| 1 |
// Package filepathx adds double-star globbing support to the Glob function from the core path/filepath package. |
| 2 |
// You might recognize "**" recursive globs from things like your .gitignore file, and zsh. |
| 3 |
// The "**" glob represents a recursive wildcard matching zero-or-more directory levels deep. |
| 4 |
package filepathx |
| 5 |
|
| 6 |
import ( |
| 7 |
"os" |
| 8 |
"path/filepath" |
| 9 |
"strings" |
| 10 |
) |
| 11 |
|
| 12 |
// Globs represents one filepath glob, with its elements joined by "**". |
| 13 |
type Globs []string |
| 14 |
|
| 15 |
// Glob adds double-star support to the core path/filepath Glob function. |
| 16 |
// It's useful when your globs might have double-stars, but you're not sure. |
| 17 |
func Glob(pattern string) ([]string, error) { |
| 18 |
if !strings.Contains(pattern, "**") { |
| 19 |
// passthru to core package if no double-star |
| 20 |
return filepath.Glob(pattern) |
| 21 |
} |
| 22 |
return Globs(strings.Split(pattern, "**")).Expand() |
| 23 |
} |
| 24 |
|
| 25 |
// Expand finds matches for the provided Globs. |
| 26 |
func (globs Globs) Expand() ([]string, error) { |
| 27 |
var matches = []string{""} // accumulate here |
| 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 |
// save deduped match from current iteration |
| 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 |
// fix up return value for nil input |
| 57 |
if globs == nil && len(matches) > 0 && matches[0] == "" { |
| 58 |
matches = matches[1:] |
| 59 |
} |
| 60 |
|
| 61 |
return matches, nil |
| 62 |
} |