-
Notifications
You must be signed in to change notification settings - Fork 0
/
filesystem.go
81 lines (65 loc) · 1.45 KB
/
filesystem.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package shared
import (
"io/fs"
"os"
"path"
)
type FileSystem interface {
ReadDir(relativePath string) ([]os.DirEntry, error)
ReadFile(relativePath string) ([]byte, error)
}
type S = string
/*
Embedded file system
*/
type FSReader struct {
FS fs.FS
root string
}
func (fr *FSReader) ReadFile(relativePath string) ([]byte, error) {
return fs.ReadFile(fr.FS, path.Join(fr.root, relativePath))
}
func (fr *FSReader) ReadDir(relativePath string) ([]os.DirEntry, error) {
return fs.ReadDir(fr.FS, path.Join(fr.root, relativePath))
}
func Embed(fsys fs.FS) *FSReader {
return &FSReader{FS: fsys}
}
func (fr *FSReader) At(root string) *FSReader {
fr.root = root
return fr
}
func (fr *FSReader) Copy(relativePath string, destination string) error {
content, err := fr.ReadFile(path.Join(fr.root, relativePath))
if err != nil {
return err
}
err = os.WriteFile(destination, content, 0600)
if err != nil {
return err
}
return nil
}
/*
Local file system
*/
type DirReader struct {
root string
}
func NewDirReader() *DirReader {
return &DirReader{}
}
func (dr *DirReader) At(root string) *DirReader {
dr.root = root
return dr
}
func (dr *DirReader) ReadDir(relativePath string) ([]os.DirEntry, error) {
return os.ReadDir(path.Join(dr.root, relativePath))
}
func (dr *DirReader) ReadFile(relativePath string) ([]byte, error) {
content, err := os.ReadFile(path.Join(dr.root, relativePath))
if err != nil {
return nil, err
}
return content, nil
}