forked from gobuffalo/buffalo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recursive.go
65 lines (61 loc) · 1.81 KB
/
recursive.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
package resolvers
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
// RecursiveResolver will walk the tree of the specified RootPath
// to resolve the given file name to the a path on disk. It is recommended
// to scope this as tight as possible as it is possibly quite slow
// the first time a file is requested. Once a file is found it's resolved
// path is cached to prevent further slow resolutions.
type RecursiveResolver struct {
Path string
cache map[string]string
}
// Resolve will walk the tree of the specified RootPath
// to resolve the given file name to the a path on disk. It is recommended
// to scope this as tight as possible as it is possibly quite slow
// the first time a file is requested. Once a file is found it's resolved
// path is cached to prevent further slow resolutions.
func (r *RecursiveResolver) Resolve(name string) (string, error) {
if r.cache == nil {
r.cache = map[string]string{}
}
if p, ok := r.cache[name]; ok {
return p, nil
}
var p string
var err error
var found bool
err = filepath.Walk(r.Path, func(path string, info os.FileInfo, err error) error {
if strings.HasSuffix(path, name) {
found = true
r.cache[name] = path
p = path
return err
}
return nil
})
if err != nil {
return p, err
}
if !found {
return p, fmt.Errorf("could not find file %s", name)
}
return p, nil
}
// Read will walk the tree of the specified RootPath
// to resolve the given file name to the a path on disk. It is recommended
// to scope this as tight as possible as it is possibly quite slow
// the first time a file is requested. Once a file is found it's resolved
// path is cached to prevent further slow resolutions.
func (r *RecursiveResolver) Read(name string) ([]byte, error) {
p, err := r.Resolve(name)
if err != nil {
return nil, err
}
return ioutil.ReadFile(p)
}