Debian Codegraph @

glob/glob.go

raw symbols SCIP
1 package glob
2
3 import (
4 "bytes"
5 "fmt"
6 //"log"
7 "os"
8 gpath "path"
9 "path/filepath"
10 "regexp"
11 "strings"
12 "sync"
13 "unicode/utf8"
14
15 "github.com/MichaelTJones/walk"
16 )
17
18 const (
19 // NotSlash is any rune but path separator.
20 notSlash = "[^/]"
21 // AnyRune is zero or more non-path separators.
22 anyRune = notSlash + "*"
23 // ZeroOrMoreDirectories is used by ** patterns.
24 zeroOrMoreDirectories = `(?:[.{}\w\-\ ]+\/)*`
25 // TrailingStarStar matches everything inside directory.
26 trailingStarStar = "/**"
27 // SlashStarStarSlash maches zero or more directories.
28 slashStarStarSlash = "/**/"
29 )
30
31 // RegexpInfo contains additional info about the Regexp created by a glob pattern.
32 type RegexpInfo struct {
33 Regexp *regexp.Regexp
34 Negate bool
35 Path string
36 Glob string
37 }
38
39 // MatchString matches a string with either a regexp or direct string match
40 func (ri *RegexpInfo) MatchString(s string) bool {
41 if ri.Regexp != nil {
42 return ri.Regexp.MatchString(s)
43 } else if ri.Path != "" {
44 return strings.HasSuffix(s, ri.Path)
45 }
46 return false
47 }
48
49 // Globexp builds a regular express from from extended glob pattern and then
50 // returns a Regexp object.
51 func Globexp(glob string) *regexp.Regexp {
52 var re bytes.Buffer
53
54 re.WriteString("^")
55
56 i, inGroup, L := 0, false, len(glob)
57
58 for i < L {
59 r, w := utf8.DecodeRuneInString(glob[i:])
60
61 switch r {
62 default:
63 re.WriteRune(r)
64
65 case '\\', '$', '^', '+', '.', '(', ')', '=', '!', '|':
66 re.WriteRune('\\')
67 re.WriteRune(r)
68
69 case '/':
70 // TODO optimize later, string could be long
71 rest := glob[i:]
72 re.WriteRune('/')
73 if strings.HasPrefix(rest, "/**/") {
74 re.WriteString(zeroOrMoreDirectories)
75 w *= 4
76 } else if rest == "/**" {
77 re.WriteString(".*")
78 w *= 3
79 }
80
81 case '?':
82 re.WriteRune('.')
83
84 case '[', ']':
85 re.WriteRune(r)
86
87 case '{':
88 if i < L-1 {
89 if glob[i+1:i+2] == "{" {
90 re.WriteString("\\{")
91 w *= 2
92 break
93 }
94 }
95 inGroup = true
96 re.WriteRune('(')
97
98 case '}':
99 if inGroup {
100 inGroup = false
101 re.WriteRune(')')
102 } else {
103 re.WriteRune('}')
104 }
105
106 case ',':
107 if inGroup {
108 re.WriteRune('|')
109 } else {
110 re.WriteRune('\\')
111 re.WriteRune(r)
112 }
113
114 case '*':
115 rest := glob[i:]
116 if strings.HasPrefix(rest, "**/") {
117 re.WriteString(zeroOrMoreDirectories)
118 w *= 3
119 } else {
120 re.WriteString(anyRune)
121 }
122 }
123
124 i += w
125 }
126
127 re.WriteString("$")
128 //log.Printf("regex string %s", re.String())
129 return regexp.MustCompile(re.String())
130 }
131
132 // Glob returns files and dirctories that match patterns. Patterns must use
133 // slashes, even Windows.
134 //
135 // Special chars.
136 //
137 // /**/ - match zero or more directories
138 // {a,b} - match a or b, no spaces
139 // * - match any non-separator char
140 // ? - match a single non-separator char
141 // **/ - match any directory, start of pattern only
142 // /** - match any this directory, end of pattern only
143 // ! - removes files from resultset, start of pattern only
144 //
145 func Glob(patterns []string) ([]*FileAsset, []*RegexpInfo, error) {
146 // TODO very inefficient and unintelligent, optimize later
147
148 m := map[string]*FileAsset{}
149 regexps := []*RegexpInfo{}
150
151 for _, pattern := range patterns {
152 remove := strings.HasPrefix(pattern, "!")
153 if remove {
154 pattern = pattern[1:]
155 if hasMeta(pattern) {
156 re := Globexp(pattern)
157 regexps = append(regexps, &RegexpInfo{Regexp: re, Glob: pattern, Negate: true})
158 for path := range m {
159 if re.MatchString(path) {
160 m[path] = nil
161 }
162 }
163 } else {
164 path := gpath.Clean(pattern)
165 m[path] = nil
166 regexps = append(regexps, &RegexpInfo{Path: path, Glob: pattern, Negate: true})
167 }
168 } else {
169 if hasMeta(pattern) {
170 re := Globexp(pattern)
171 regexps = append(regexps, &RegexpInfo{Regexp: re, Glob: pattern})
172 root := PatternRoot(pattern)
173 if root == "" {
174 return nil, nil, fmt.Errorf("Cannot get root from pattern: %s", pattern)
175 }
176 fileAssets, err := walkFiles(root)
177 if err != nil {
178 return nil, nil, err
179 }
180
181 for _, file := range fileAssets {
182 if re.MatchString(file.Path) {
183 // TODO closure problem assigning &file
184 tmp := file
185 m[file.Path] = tmp
186 }
187 }
188 } else {
189 path := gpath.Clean(pattern)
190 info, err := os.Stat(path)
191 if err != nil {
192 return nil, nil, err
193 }
194 regexps = append(regexps, &RegexpInfo{Path: path, Glob: pattern, Negate: false})
195 fa := &FileAsset{Path: path, FileInfo: info}
196 m[path] = fa
197 }
198 }
199 }
200
201 //log.Printf("m %v", m)
202 keys := []*FileAsset{}
203 for _, it := range m {
204 if it != nil {
205 keys = append(keys, it)
206 }
207 }
208 return keys, regexps, nil
209 }
210
211 // hasMeta determines if a path has special chars used to build a Regexp.
212 func hasMeta(path string) bool {
213 return strings.IndexAny(path, "*?[{") >= 0
214 }
215
216 func isDir(path string) bool {
217 st, err := os.Stat(path)
218 if os.IsNotExist(err) {
219 return false
220 }
221 return st.IsDir()
222 }
223
224 // PatternRoot gets a real directory root from a pattern. The directory
225 // returned is used as the start location for globbing.
226 func PatternRoot(s string) string {
227 if isDir(s) {
228 return s
229 }
230
231 // No directory in pattern
232 parts := strings.Split(s, "/")
233 if len(parts) == 1 {
234 return "."
235 }
236 // parts returns an empty string at positio 0 if the s starts with "/"
237 root := ""
238
239 // Build path until a dirname has a char used to build regex
240 for i, part := range parts {
241 if hasMeta(part) {
242 break
243 }
244 if i > 0 {
245 root += "/"
246 }
247 root += part
248 }
249 // Default to cwd
250 if root == "" {
251 root = "."
252 }
253 return root
254 }
255
256 // walkFiles walks a directory starting at root returning all directories and files
257 // include those found in subdirectories.
258 func walkFiles(root string) ([]*FileAsset, error) {
259 fileAssets := []*FileAsset{}
260 var lock sync.Mutex
261 visitor := func(path string, info os.FileInfo, err error) error {
262 // if err != nil {
263 // fmt.Println("visitor err", err.Error(), "root", root)
264 // }
265 if err == nil {
266 lock.Lock()
267 fileAssets = append(fileAssets, &FileAsset{FileInfo: info, Path: filepath.ToSlash(path)})
268 lock.Unlock()
269 }
270 return nil
271 }
272 err := walk.Walk(root, visitor)
273 if err != nil {
274 return nil, err
275 }
276 return fileAssets, nil
277 }