78 lines
1.3 KiB
Go
78 lines
1.3 KiB
Go
package utils
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
)
|
|
|
|
func ExpandGlob(patterns []string) ([]string, error) {
|
|
var result []string
|
|
seen := make(map[string]struct{})
|
|
|
|
for _, pattern := range patterns {
|
|
|
|
if pattern == "*" {
|
|
filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
if info.IsDir() {
|
|
return nil
|
|
}
|
|
add(path, seen, &result)
|
|
return nil
|
|
})
|
|
continue
|
|
}
|
|
|
|
isRecursive := strings.Contains(pattern, "**")
|
|
|
|
if isRecursive {
|
|
root := strings.Split(pattern, "**")[0]
|
|
if root == "" {
|
|
root = "."
|
|
}
|
|
|
|
filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
|
|
if err != nil || info.IsDir() {
|
|
return nil
|
|
}
|
|
|
|
matched, _ := filepath.Match(
|
|
strings.Replace(pattern, "**", "*", 1),
|
|
path,
|
|
)
|
|
|
|
if matched {
|
|
add(path, seen, &result)
|
|
}
|
|
return nil
|
|
})
|
|
continue
|
|
}
|
|
|
|
matches, err := filepath.Glob(pattern)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
for _, m := range matches {
|
|
info, err := os.Stat(m)
|
|
if err != nil || info.IsDir() {
|
|
continue
|
|
}
|
|
add(m, seen, &result)
|
|
}
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
func add(path string, seen map[string]struct{}, result *[]string) {
|
|
if _, ok := seen[path]; ok {
|
|
return
|
|
}
|
|
seen[path] = struct{}{}
|
|
*result = append(*result, path)
|
|
} |