-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathremove.go
125 lines (115 loc) · 2.4 KB
/
remove.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package building
import (
"io"
"os"
"path/filepath"
)
// Remove wraps a files and folders remove operation.
type Remove struct {
filesets []fileset
keepGoing bool
}
// Remove handles files and folders deletion.
func (b *B) Remove(paths ...string) Remove {
r := Remove{}
if len(paths) > 0 {
r.filesets = append(r.filesets, fileset{
includes: paths,
})
r.Run()
}
return r
}
// WithFiles adds a list of files and folders for deletion.
func (r Remove) WithFiles(paths ...string) Remove {
r.filesets = append(r.filesets, fileset{
includes: paths,
})
return r
}
// WithFileset adds a fileset for deletion.
func (r Remove) WithFileset(dir, includes, excludes string) Remove {
r.filesets = append(r.filesets, makeFileset(dir, includes, excludes))
return r
}
// Run performs the deletion.
func (r Remove) Run(paths ...string) {
r.filesets = append(r.filesets, fileset{
includes: paths,
})
if err := r.run(); err != nil {
b.Fatalln(err)
}
}
func (r Remove) run() error {
filesets, err := resolve(r.filesets, false)
if err != nil {
return err
}
for _, f := range filesets {
if len(f.excludes) == 0 {
if err := removeWithoutExcludes(f); err != nil {
return err
}
} else if err := removeWithExcludes(f); err != nil {
return err
}
}
return nil
}
func removeWithoutExcludes(f fileset) error {
for _, include := range f.includes {
if f.dir != "" && !filepath.IsAbs(include) {
include = filepath.Join(f.dir, include)
}
err := os.RemoveAll(include)
if err != nil {
return err
}
}
return nil
}
func removeWithExcludes(f fileset) error {
var paths []string
if err := f.walk(func(path, rel string, info os.FileInfo, err error) error {
paths = append(paths, path)
return err
}); err != nil {
return err
}
for i := len(paths); i > 0; i-- {
path := paths[i-1]
info, err := os.Stat(path)
if os.IsNotExist(err) {
b.Debugf("skipped non existing %q", path)
continue
}
if err != nil {
return err
}
if info.IsDir() {
empty, err := isEmptyDir(path)
if err != nil {
return err
}
if !empty {
b.Debugf("skipped non empty folder %q", path)
continue
}
}
if err := os.Remove(path); err != nil {
return err
}
b.Debugf("removed %q", path)
}
return nil
}
func isEmptyDir(dir string) (bool, error) {
f, err := os.Open(dir)
if err != nil {
return false, err
}
defer f.Close()
_, err = f.Readdir(1)
return err == io.EOF, nil
}