From eb1b7d7d9149114eb6b4287b7cb40c49dccfb26e Mon Sep 17 00:00:00 2001 From: Gabriel Arakaki Giovanini Date: Sun, 16 Oct 2022 19:13:41 +0200 Subject: feat: Add storage interface With this is easier to interact with storage layers. --- storage/storage_fs.go | 86 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 83 insertions(+), 3 deletions(-) (limited to 'storage/storage_fs.go') diff --git a/storage/storage_fs.go b/storage/storage_fs.go index 35ce58b..16bf8e8 100644 --- a/storage/storage_fs.go +++ b/storage/storage_fs.go @@ -1,22 +1,38 @@ package storage import ( + "errors" + "fmt" + "io" + "io/ioutil" "os" "path/filepath" + "porg/pipe" ) type FileSystem struct { - root string } -func WalkFolder(folder string, walkMode WalkMode) <-chan string { +func NewFileSystem() *FileSystem { + return &FileSystem{} +} + +func (fs *FileSystem) Get(path string) (io.Reader, error) { + return os.Open(path) +} + +func (fs *FileSystem) Walk(folder string, walkMode WalkMode) <-chan string { c := make(chan string) go func(folder string, c chan string) { filepath.Walk(folder, func(path string, info os.FileInfo, err error) error { file, _ := os.Open(path) defer file.Close() - fileInfo, _ := file.Stat() + fileInfo, err := file.Stat() + if err != nil { + fmt.Println("@@@@ ", err.Error()) + return nil + } switch walkMode { case Folder: @@ -38,3 +54,67 @@ func WalkFolder(folder string, walkMode WalkMode) <-chan string { return c } + +func (fs *FileSystem) Put(path string, f io.Reader) error { + fo, err := os.Create(path) + if err != nil { + return err + } + + if _, err := io.Copy(fo, f); err != nil { + return err + } + + return nil +} + +func (fs *FileSystem) List(path string) ([]string, error) { + files, err := ioutil.ReadDir(path) + if err != err { + return nil, err + } + + findPath := func(f os.FileInfo) string { + return path + "/" + f.Name() + } + return pipe.Map(findPath, files), nil +} + +func (fs *FileSystem) Move(src string, dst string) error { + return os.Rename(src, dst) +} + +func (fs *FileSystem) Copy(src string, dst string) error { + in, err := os.Open(src) + if err != nil { + return err + } + defer in.Close() + + out, err := os.Create(dst) + if err != nil { + return err + } + defer out.Close() + + _, err = io.Copy(out, in) + if err != nil { + return err + } + return out.Close() +} + +func (fs *FileSystem) Exists(path string) (bool, error) { + _, err := os.Stat(path) + if err == nil { + return true, nil + } + if errors.Is(err, os.ErrNotExist) { + return false, nil + } + return false, err +} + +func (fs *FileSystem) Mkdir(path string) error { + return os.MkdirAll(path, 0777) +} -- cgit v1.2.3