forked from cloudfoundry/bosh-softlayer-cpi-release
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dir.go
81 lines (64 loc) · 1.65 KB
/
dir.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
74
75
76
77
78
79
80
81
package glob
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
type Dir interface {
Glob(patterns ...string) (filePaths []string, err error)
}
type dir struct {
path string
}
func NewDir(path string) (d Dir) {
return dir{path: path}
}
func (d dir) Glob(patterns ...string) (filePaths []string, err error) {
for _, pattern := range patterns {
var newFiles []string
newFiles, err = d.glob(pattern)
if err != nil {
err = wrapError(err, "Finding files matching pattern %s", pattern)
return
}
filePaths = append(filePaths, newFiles...)
}
return
}
func (d dir) glob(pattern string) (files []string, err error) {
globPattern := filepath.Join(d.path, pattern)
glob, err := CompileGlob(globPattern)
if err != nil {
err = wrapError(err, "Compiling glob for pattern %s", pattern)
return
}
filepath.Walk(d.path, func(path string, info os.FileInfo, inErr error) (err error) {
if inErr != nil {
err = inErr
return
}
if glob.Match(path) {
files = append(files, strings.Replace(path, d.path+"/", "", 1))
}
return
})
// Ruby Dir.glob will include *.log when looking for **/*.log
// Our glob implementation will not do it automatically
if strings.Contains(pattern, "**/*") {
var extraFiles []string
updatedPattern := strings.Replace(pattern, "**/*", "*", 1)
extraFiles, err = d.glob(updatedPattern)
if err != nil {
err = wrapError(err, "Recursing into pattern %s", updatedPattern)
return
}
files = append(files, extraFiles...)
}
return
}
func wrapError(err error, msg string, args ...interface{}) (newErr error) {
msg = fmt.Sprintf(msg, args...)
return errors.New(fmt.Sprintf("%s: %s", msg, err.Error()))
}