From 7470ed4117f23aea2842000ace16265063357b43 Mon Sep 17 00:00:00 2001 From: Guillaume Lours <705411+glours@users.noreply.github.com> Date: Thu, 2 Nov 2023 17:24:13 +0100 Subject: [PATCH] add public function to remove old doc files Signed-off-by: Guillaume Lours <705411+glours@users.noreply.github.com> --- clidocstool.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/clidocstool.go b/clidocstool.go index d4aeaba..e38d8e5 100644 --- a/clidocstool.go +++ b/clidocstool.go @@ -17,7 +17,9 @@ package clidocstool import ( "errors" "io" + "io/fs" "os" + "path/filepath" "strings" "github.com/spf13/cobra" @@ -76,6 +78,40 @@ func (c *Client) GenAllTree() error { return nil } +// GenAllTreeAndRemoveOldFiles creates all structured ref files for this command and +// all descendants in the directory given then removes potential old documentation files from the origin directory tree. +func (c *Client) GenAllTreeAndRemoveOldFiles() error { + if err := c.GenAllTree(); err != nil { + return err + } + filesToRemove := make(map[string]any) + filepath.WalkDir(c.source, func(path string, entry fs.DirEntry, err error) error { + return c.checkIfShouldBeRemoved(filesToRemove, path, entry, err) + }) + for file := range filesToRemove { + if err := os.Remove(file); err != nil { + return err + } + } + return nil +} + +func (c *Client) checkIfShouldBeRemoved(filesToRemove map[string]any, path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + if !entry.IsDir() { + if _, err := entry.Info(); err != nil { + return err + } + targetFile := filepath.Join(c.target, strings.ReplaceAll(path, c.source, "")) + if _, err := os.Stat(targetFile); os.IsNotExist(err) { + filesToRemove[path] = struct{}{} + } + } + return nil +} + func fileExists(f string) bool { info, err := os.Stat(f) if os.IsNotExist(err) {