-
Notifications
You must be signed in to change notification settings - Fork 0
/
glob.go
73 lines (67 loc) · 1.48 KB
/
glob.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
64
65
66
67
68
69
70
71
72
73
package main
import (
"log"
"os"
"path/filepath"
"strings"
)
// GlobMany takes a search pattern and returns absolute file paths that mach that
// pattern.
// - targets : list of paths to glob
// - mask : GlobDirs or GlobFiles
// - onErr : callback function to call when there's an error.
// can be nil.
func GlobMany(targets []string, onErr func(string, error)) []string {
rv := make([]string, 0, 20)
addFile := func(path string, fi os.FileInfo, err error) error {
if err != nil {
log.Println(err.Error())
return err
}
rv = append(rv, path)
return err
}
for _, p := range targets {
// "p" is a wildcard pattern? expand it:
if strings.Contains(p, "*") {
matches, err := filepath.Glob(p)
if err == nil {
// walk each match:
for _, p := range matches {
filepath.Walk(p, addFile)
}
}
// path is not a wildcard, walk it:
} else {
filepath.Walk(p, addFile)
}
}
return rv
}
// CommonHome takes an array of aboluste file paths and returns a common home
// directory for them
func CommonHome(paths []string) (home string) {
if len(paths) == 0 {
return ""
}
// first path in list:
first := paths[0]
// function returns 'true' if all paths begin with s
parentForAll := func(s string) bool {
for _, p := range paths {
if !strings.HasPrefix(p, s) {
return false
}
}
return true
}
for i := 1; i < len(first); i++ {
s := first[:i]
if parentForAll(s) {
home = s
} else {
break
}
}
return home
}