...
1
2
3
4 package filepathx
5
6 import (
7 "os"
8 "path/filepath"
9 "strings"
10 )
11
12
13 type Globs []string
14
15
16
17 func Glob(pattern string) ([]string, error) {
18 if !strings.Contains(pattern, "**") {
19
20 return filepath.Glob(pattern)
21 }
22 return Globs(strings.Split(pattern, "**")).Expand()
23 }
24
25
26 func (globs Globs) Expand() ([]string, error) {
27 var matches = []string{""}
28 for _, glob := range globs {
29 var hits []string
30 var hitMap = map[string]bool{}
31 for _, match := range matches {
32 paths, err := filepath.Glob(match + glob)
33 if err != nil {
34 return nil, err
35 }
36 for _, path := range paths {
37 err = filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
38 if err != nil {
39 return err
40 }
41
42 if _, ok := hitMap[path]; !ok {
43 hits = append(hits, path)
44 hitMap[path] = true
45 }
46 return nil
47 })
48 if err != nil {
49 return nil, err
50 }
51 }
52 }
53 matches = hits
54 }
55
56
57 if globs == nil && len(matches) > 0 && matches[0] == "" {
58 matches = matches[1:]
59 }
60
61 return matches, nil
62 }
63
View as plain text