forked from cookieo9/resources-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
104 lines (84 loc) · 1.8 KB
/
file.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
package resources
import (
"io"
"os"
"path/filepath"
)
type fsResource struct {
base string
path string
}
func (f *fsResource) real_path() string {
return filepath.Join(f.base, filepath.FromSlash(f.path))
}
func (f *fsResource) Path() string {
return f.path
}
func (f *fsResource) Stat() (os.FileInfo, error) {
return os.Stat(f.real_path())
}
func (f *fsResource) Open() (io.ReadCloser, error) {
return os.Open(f.real_path())
}
func (f *fsResource) String() string {
return f.path
}
type fsBundle struct {
base string
}
func OpenFS(base_dir string) Bundle {
base, err := filepath.Abs(filepath.Clean(base_dir))
if err != nil {
panic(err)
}
return &fsBundle{base: base}
}
func (fb *fsBundle) Close() error {
return nil
}
func (fb *fsBundle) file(path string) Resource {
return &fsResource{
base: fb.base,
path: path,
}
}
func (fb *fsBundle) Open(path string) (io.ReadCloser, error) {
if err := CheckPath(path); err != nil {
return nil, err
}
return fb.file(path).Open()
}
func (fb *fsBundle) Find(path string) (Resource, error) {
if err := CheckPath(path); err != nil {
return nil, err
}
f := fb.file(path)
if _, err := f.Stat(); err != nil {
if os.IsNotExist(err) {
return nil, ErrNotFound
}
return nil, err
}
return f, nil
}
func (fb *fsBundle) Glob(pattern string) ([]Resource, error) {
if err := CheckPath(pattern); err != nil {
return nil, err
}
pattern = filepath.Clean(filepath.FromSlash(pattern))
pattern = fb.file(pattern).(*fsResource).real_path()
matches, err := filepath.Glob(pattern)
if err != nil {
return nil, err
}
rsrcs := make([]Resource, len(matches))
for i := range rsrcs {
rel, err := filepath.Rel(fb.base, matches[i])
if err != nil {
return nil, err
}
path := filepath.ToSlash(rel)
rsrcs[i] = fb.file(path)
}
return rsrcs, nil
}