-
Notifications
You must be signed in to change notification settings - Fork 0
/
filesystem.go
76 lines (62 loc) · 1.4 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
// Content managed by Project Forge, see [projectforge.md] for details.
package filesystem
import (
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
)
var (
DirectoryMode = os.FileMode(0o755)
DefaultMode = os.FileMode(0o644)
)
type FileSystem struct {
root string
}
var _ FileLoader = (*FileSystem)(nil)
func NewFileSystem(root string) *FileSystem {
return &FileSystem{root: root}
}
func (f *FileSystem) getPath(ss ...string) string {
s := filepath.Join(ss...)
if strings.HasPrefix(s, f.root) {
return s
}
return filepath.Join(f.root, s)
}
func (f *FileSystem) Root() string {
return f.root
}
func (f *FileSystem) Clone() FileLoader {
return NewFileSystem(f.root)
}
func (f *FileSystem) Stat(path string) (os.FileInfo, error) {
p := f.getPath(path)
s, err := os.Stat(p)
if err == nil {
return s, nil
}
return nil, err
}
func (f *FileSystem) SetMode(path string, mode os.FileMode) error {
p := f.getPath(path)
return os.Chmod(p, mode)
}
func (f *FileSystem) Exists(path string) bool {
x, _ := f.Stat(path)
return x != nil
}
func (f *FileSystem) IsDir(path string) bool {
s, err := f.Stat(path)
if s == nil || err != nil {
return false
}
return s.IsDir()
}
func (f *FileSystem) CreateDirectory(path string) error {
p := f.getPath(path)
if err := os.MkdirAll(p, DirectoryMode); err != nil {
return errors.Wrapf(err, "unable to create data directory [%s]", p)
}
return nil
}