-
Notifications
You must be signed in to change notification settings - Fork 28
/
fs.go
110 lines (91 loc) · 1.82 KB
/
fs.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package resource
import (
"io"
"io/ioutil"
"os"
"path"
"github.com/spf13/afero"
)
type File interface {
io.Closer
io.Reader
io.ReaderAt
io.Seeker
Name() string
Stat() (os.FileInfo, error)
// Readdir does not follow symlinks, use Readdirnames instead to avoid surprises.
Readdir(count int) ([]os.FileInfo, error)
Readdirnames(n int) ([]string, error)
}
type FsLevel int
const (
FsLevelBuiltin FsLevel = iota + 1
FsLevelCustom
FsLevelApp
)
type Fs interface {
Open(name string) (File, error)
Stat(name string) (os.FileInfo, error)
GetFsLevel() FsLevel
}
type LeveledAferoFs struct {
Fs afero.Fs
FsLevel FsLevel
}
func (f LeveledAferoFs) Open(name string) (File, error) {
return f.Fs.Open(name)
}
func (f LeveledAferoFs) Stat(name string) (os.FileInfo, error) {
return f.Fs.Stat(name)
}
func (f LeveledAferoFs) GetFsLevel() FsLevel {
return f.FsLevel
}
func ReadLocation(location Location) ([]byte, error) {
file, err := location.Fs.Open(location.Path)
if err != nil {
return nil, err
}
defer file.Close()
return ioutil.ReadAll(file)
}
func readDirNames(fs Fs, dir string) ([]string, error) {
f, err := fs.Open(dir)
if err != nil {
return nil, err
}
defer f.Close()
return f.Readdirnames(0)
}
func EnumerateAllLocations(fs Fs) ([]Location, error) {
var locations []Location
var list func(dir string) error
list = func(dir string) error {
files, err := readDirNames(fs, dir)
if err != nil {
return err
}
for _, f := range files {
p := path.Join(dir, f)
f, err := fs.Stat(p)
if err != nil {
return err
}
if f.IsDir() {
if err := list(p); err != nil {
return err
}
continue
}
locations = append(locations, Location{
Fs: fs,
Path: p,
})
}
return nil
}
if err := list(""); err != nil {
return nil, err
}
return locations, nil
}