-
Notifications
You must be signed in to change notification settings - Fork 0
/
filepathx.go
63 lines (54 loc) · 1.19 KB
/
filepathx.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
package filepathx
import (
"io/fs"
"path/filepath"
"strings"
)
// Glob support double star and single star
func Glob(pattern string) ([]string, error) {
if !strings.Contains(pattern, "**") {
return filepath.Glob(pattern)
}
patterns := strings.Split(pattern, "**")
newPatterns := make([]string, len(patterns))
for i, p := range patterns {
p = strings.TrimRight(p, "/")
newPatterns[i] = p
}
return expand(newPatterns)
}
func expand(patterns []string) ([]string, error) {
// all matches will put in array
matches := []string{""}
for _, pattern := range patterns {
m, err := expandMatches(matches, pattern)
if err != nil {
return nil, err
}
matches = m
}
return matches, nil
}
func expandMatches(matches []string, pattern string) ([]string, error) {
var r []string
for _, match := range matches {
paths, err := filepath.Glob(match + pattern)
if err != nil {
return nil, err
}
for _, path := range paths {
// TODO: cache the result
err = filepath.Walk(path, func(path string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
r = append(r, path)
return nil
})
if err != nil {
return nil, err
}
}
}
return r, nil
}