summaryrefslogtreecommitdiff
path: root/internal/oi
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2024-09-21 15:54:11 +0300
committerPaul Buetow <paul@buetow.org>2024-09-21 15:54:11 +0300
commitd38f93fc4fdb54687c425b8866bc99cbd9ad7935 (patch)
treeca5e5b3c582ea373aa6b9193d2e047e2fb06c2f5 /internal/oi
parentdff4d455e07d639b82a0bed814f41d0656e9b6d0 (diff)
initial revamp
Diffstat (limited to 'internal/oi')
-rw-r--r--internal/oi/oi.go87
1 files changed, 87 insertions, 0 deletions
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
+}