From 0eead333b733c80d79b6e6424b12c8ae0f105e74 Mon Sep 17 00:00:00 2001 From: Arsen Musayelyan Date: Mon, 29 Aug 2022 14:22:02 -0700 Subject: [PATCH] Add RemoveAll() and MkdirAll() to the filesystem implementation --- blefs/all.go | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 blefs/all.go diff --git a/blefs/all.go b/blefs/all.go new file mode 100644 index 0000000..a29719c --- /dev/null +++ b/blefs/all.go @@ -0,0 +1,73 @@ +package blefs + +import ( + "fmt" + "path/filepath" + "strings" +) + +func (blefs *FS) RemoveAll(path string) error { + if path == "" { + return nil + } + + if filepath.Clean(path) == "/" { + return ErrNoRemoveRoot + } + + fi, err := blefs.Stat(path) + if err != nil { + return nil + } + + if fi.IsDir() { + return blefs.removeAllChildren(path) + } else { + err = blefs.Remove(path) + if err != nil && err.(FSError).Code != -2 { + return err + } + } + + return nil +} + +func (blefs *FS) removeAllChildren(path string) error { + list, err := blefs.ReadDir(path) + if err != nil { + return err + } + + for _, entry := range list { + if entry.IsDir() { + err = blefs.removeAllChildren(filepath.Join(path, entry.Name())) + } else { + err = blefs.Remove(path) + } + if err != nil { + return err + } + } + + return nil +} + +func (blefs *FS) MkdirAll(path string) error { + if path == "" || path == "/" { + return nil + } + + splitPath := strings.Split(path, "/") + fmt.Println("p", path, splitPath) + for i := 1; i < len(splitPath); i++ { + curPath := strings.Join(splitPath[0:i], "/") + fmt.Println("cp", curPath) + + err := blefs.Mkdir(curPath) + if err != nil && err.(FSError).Code != -17 { + return err + } + } + + return nil +}