-
Notifications
You must be signed in to change notification settings - Fork 12
/
source_deleter.go
91 lines (76 loc) · 2.01 KB
/
source_deleter.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
82
83
84
85
86
87
88
89
90
91
package gobuild
import (
"fmt"
"os"
"path/filepath"
"strings"
)
type SourceDeleter struct{}
func NewSourceDeleter() SourceDeleter {
return SourceDeleter{}
}
func (d SourceDeleter) Clear(path string) error {
var envGlobs []string
if val, ok := os.LookupEnv("BP_KEEP_FILES"); ok {
envGlobs = append(envGlobs, filepath.SplitList(val)...)
}
// This is logic taken from github.com/ForestEckhardt/source-removal/build.go
//
// The following constructs a set of all the file paths that are required
// from a globed file to exist and prepends the working directory onto all of
// those permutation
//
// Example:
// Input: "public/data/*"
// Output: ["path/public", "path/public/data", "path/public/data/*"]
var globs = []string{path}
for _, glob := range envGlobs {
dirs := strings.Split(glob, string(os.PathSeparator))
for i := range dirs {
globs = append(globs, filepath.Join(path, filepath.Join(dirs[:i+1]...)))
}
}
err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
match, err := matchingGlob(path, globs)
if err != nil {
return err
}
if !match {
err := os.RemoveAll(path)
if err != nil {
return err
}
if info.IsDir() {
return filepath.SkipDir
}
}
return nil
})
if err != nil {
return fmt.Errorf("failed to remove source: %w", err)
}
return nil
}
func matchingGlob(path string, globs []string) (bool, error) {
for _, glob := range globs {
match, err := filepath.Match(glob, path)
if err != nil {
return false, err
}
if match {
// filepath.SkipDir is returned here because this is a glob that
// specifies everything in a directroy. If we get a match on such
// a glob we want to ignore all other files in that directory because
// they are files we want to keep and the glob will not work
// if it enters that directory
if strings.HasSuffix(glob, fmt.Sprintf("%c*", os.PathSeparator)) {
return true, filepath.SkipDir
}
return true, nil
}
}
return false, nil
}