From d38f93fc4fdb54687c425b8866bc99cbd9ad7935 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Sat, 21 Sep 2024 15:54:11 +0300 Subject: initial revamp --- internal/oi/oi.go | 87 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 internal/oi/oi.go (limited to 'internal/oi') diff --git a/internal/oi/oi.go b/internal/oi/oi.go new file mode 100644 index 0000000..00b4dd5 --- /dev/null +++ b/internal/oi/oi.go @@ -0,0 +1,87 @@ +package oi + +import ( + "fmt" + "io" + "os" + "path/filepath" +) + +func EnsureDirExists(dir string) error { + if _, err := os.Stat(dir); os.IsNotExist(err) { + return os.MkdirAll(dir, os.ModePerm) + } + return nil +} + +func ReadDirFilter(dir string, filter func(file os.DirEntry) bool) (chan string, error) { + ch := make(chan string) + + if err := EnsureDirExists(dir); err != nil { + return ch, err + } + + files, err := os.ReadDir(dir) + if err != nil { + return ch, err + } + + go func() { + defer close(ch) + for _, file := range files { + if filter(file) { + ch <- filepath.Join(dir, file.Name()) + } + } + }() + + return ch, nil +} + +func ReadDirSlurp(dir string, filter func(file os.DirEntry) bool) ([]string, error) { + var files []string + + ch, err := ReadDirFilter(dir, filter) + if err != err { + return files, err + } + + for file := range ch { + files = append(files, file) + } + + return files, nil +} + +func IsRegular(path string) bool { + stat, err := os.Stat(path) + if err != nil { + return false + } + return stat.Mode().IsRegular() +} + +func CopyFile(srcPath, dstPath string) error { + if !IsRegular(srcPath) { + return fmt.Errorf("%s is not a regular file", srcPath) + } + + source, err := os.Open(srcPath) + if err != nil { + return err + } + defer source.Close() + + if err := EnsureDirExists(dstPath); err != nil { + return err + } + + destination, err := os.Create(dstPath) + if err != nil { + return err + } + defer destination.Close() + + _, err = io.Copy(destination, source) + return err +} -- cgit v1.2.3