-
Notifications
You must be signed in to change notification settings - Fork 11
/
glob.go
80 lines (72 loc) · 1.54 KB
/
glob.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
package ik
import (
"net/http"
"path"
"strings"
)
type globMatcherContext struct {
fs http.FileSystem
path string
restOfComponents []string
resultCollector func(string) error
}
func doMatch(context globMatcherContext) error {
if len(context.restOfComponents) == 0 {
return context.resultCollector(context.path)
}
f, err := context.fs.Open(context.path)
if err != nil {
return err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return err
}
if !info.IsDir() {
return nil
}
entries, err := f.Readdir(-1)
if err != nil {
return err
}
for _, entry := range entries {
name := entry.Name()
matched, err := path.Match(context.restOfComponents[0], name)
if err != nil {
return err
}
if matched {
err := doMatch(globMatcherContext{
fs: context.fs,
path: path.Join(context.path, name),
restOfComponents: context.restOfComponents[1:],
resultCollector: context.resultCollector,
})
if err != nil {
return err
}
}
}
return nil
}
func Glob(fs http.FileSystem, pattern string) ([]string, error) {
retval := make([]string, 0)
components := strings.Split(pattern, "/")
var path_ string
if len(components) > 0 && components[0] == "" {
path_ = "/"
components = components[1:]
} else {
path_ = "."
}
return retval, doMatch(globMatcherContext{
fs: fs,
path: path_,
restOfComponents: components,
resultCollector: func(match string) error {
retval = append(retval, match)
return nil
},
})
}