summaryrefslogtreecommitdiff
path: root/internal/vfs
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2024-05-25 23:17:38 +0300
committerPaul Buetow <paul@buetow.org>2024-05-25 23:17:38 +0300
commit6e631b4ccbe71299137469a69900b874d709fe35 (patch)
tree727962808911d945ab903725d450d5101b8135da /internal/vfs
parentbee82ce126846acd815cdc51f39f5c344ca432d2 (diff)
refactor vfs into its own package
Diffstat (limited to 'internal/vfs')
-rw-r--r--internal/vfs/memoryfs.go33
-rw-r--r--internal/vfs/realfs.go44
-rw-r--r--internal/vfs/vfs.go8
3 files changed, 85 insertions, 0 deletions
diff --git a/internal/vfs/memoryfs.go b/internal/vfs/memoryfs.go
new file mode 100644
index 0000000..22b1611
--- /dev/null
+++ b/internal/vfs/memoryfs.go
@@ -0,0 +1,33 @@
+package vfs
+
+import (
+ "fmt"
+ "strings"
+)
+
+type MemoryFS map[string][]byte
+
+func (fs MemoryFS) ReadFile(filePath string) ([]byte, error) {
+ if bytes, ok := fs[filePath]; ok {
+ return bytes, nil
+ }
+ return []byte{}, fmt.Errorf("no such file path: %s", filePath)
+}
+
+func (fs MemoryFS) SaveFile(filePath string, bytes []byte) error {
+ fs[filePath] = bytes
+ return nil
+}
+
+func (fs MemoryFS) FindFiles(dataDir, suffix string) ([]string, error) {
+ var filePaths []string
+
+ for filePath := range fs {
+ if !strings.HasSuffix(filePath, suffix) {
+ continue
+ }
+ filePaths = append(filePaths, filePath)
+ }
+
+ return filePaths, nil
+}
diff --git a/internal/vfs/realfs.go b/internal/vfs/realfs.go
new file mode 100644
index 0000000..8b9c9de
--- /dev/null
+++ b/internal/vfs/realfs.go
@@ -0,0 +1,44 @@
+package vfs
+
+import (
+ "log"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+type RealFS struct{}
+
+func (RealFS) ReadFile(filePath string) ([]byte, error) {
+ return os.ReadFile(filePath)
+}
+
+func (RealFS) SaveFile(filePath string, bytes []byte) error {
+ dir := filepath.Dir(filePath)
+ if _, err := os.Stat(dir); os.IsNotExist(err) {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ return err
+ }
+ }
+ return os.WriteFile(filePath, bytes, 0644)
+}
+
+func (RealFS) FindFiles(dataDir, suffix string) ([]string, error) {
+ var filePaths []string
+
+ visit := func() filepath.WalkFunc {
+ return func(path string, info os.FileInfo, err error) error {
+ if err != nil {
+ log.Println(err)
+ return nil
+ }
+ if info.IsDir() || !strings.HasSuffix(path, suffix) {
+ return nil
+ }
+ filePaths = append(filePaths, path)
+ return nil
+ }
+ }
+
+ return filePaths, filepath.Walk(dataDir, visit())
+}
diff --git a/internal/vfs/vfs.go b/internal/vfs/vfs.go
new file mode 100644
index 0000000..0297ff9
--- /dev/null
+++ b/internal/vfs/vfs.go
@@ -0,0 +1,8 @@
+package vfs
+
+// virtual file system - useful for testing as well
+type VFS interface {
+ ReadFile(name string) ([]byte, error)
+ SaveFile(filePath string, bytes []byte) error
+ FindFiles(dataPath, suffix string) ([]string, error)
+}