-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclean.go
352 lines (321 loc) · 8.13 KB
/
clean.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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package nin
import (
"fmt"
"os"
)
// Cleaner cleans a build directory.
type Cleaner struct {
state *State
config *BuildConfig
dyndepLoader DyndepLoader
removed map[string]struct{}
cleaned map[*Node]struct{}
cleanedFilesCount int // Number of files cleaned.
di DiskInterface
status int
}
// NewCleaner returns an initialized cleaner.
func NewCleaner(state *State, config *BuildConfig, di DiskInterface) *Cleaner {
return &Cleaner{
state: state,
config: config,
dyndepLoader: NewDyndepLoader(state, di),
removed: map[string]struct{}{},
cleaned: map[*Node]struct{}{},
di: di,
}
}
// @return whether the cleaner is in verbose mode.
func (c *Cleaner) isVerbose() bool {
return c.config.Verbosity != Quiet && (c.config.Verbosity == Verbose || c.config.DryRun)
}
// @returns whether the file @a path exists.
func (c *Cleaner) fileExists(path string) bool {
mtime, err := c.di.Stat(path)
if mtime == -1 {
errorf("%s", err)
}
return mtime > 0 // Treat Stat() errors as "file does not exist".
}
func (c *Cleaner) report(path string) {
// TODO(maruel): Move this out to the caller.
c.cleanedFilesCount++
if c.isVerbose() {
fmt.Printf("Remove %s\n", path)
}
}
// Remove the given @a path file only if it has not been already removed.
func (c *Cleaner) remove(path string) {
if _, ok := c.removed[path]; !ok {
c.removed[path] = struct{}{}
if c.config.DryRun {
if c.fileExists(path) {
c.report(path)
}
} else {
if err := c.di.RemoveFile(path); err == nil {
c.report(path)
} else if !os.IsNotExist(err) {
c.status = 1
}
}
}
}
// Remove the depfile and rspfile for an Edge.
func (c *Cleaner) removeEdgeFiles(edge *Edge) {
depfile := edge.GetUnescapedDepfile()
if len(depfile) != 0 {
c.remove(depfile)
}
rspfile := edge.GetUnescapedRspfile()
if len(rspfile) != 0 {
c.remove(rspfile)
}
}
func (c *Cleaner) printHeader() {
if c.config.Verbosity == Quiet {
return
}
fmt.Printf("Cleaning...")
if c.isVerbose() {
fmt.Printf("\n")
} else {
fmt.Printf(" ")
}
// TODO(maruel): fflush(stdout)
}
func (c *Cleaner) printFooter() {
if c.config.Verbosity == Quiet {
return
}
fmt.Printf("%d files.\n", c.cleanedFilesCount)
}
// CleanAll cleans all built files, except for files created by generator rules.
//
// If generator is set, also clean files created by generator rules.
//
// Return non-zero if an error occurs.
func (c *Cleaner) CleanAll(generator bool) int {
c.Reset()
c.printHeader()
c.loadDyndeps()
for _, e := range c.state.Edges {
// Do not try to remove phony targets
if e.Rule == PhonyRule {
continue
}
// Do not remove generator's files unless generator specified.
if !generator && e.GetBinding("generator") != "" {
continue
}
for _, outNode := range e.Outputs {
c.remove(outNode.Path)
}
c.removeEdgeFiles(e)
}
c.printFooter()
return c.status
}
// CleanDead cleans the files produced by previous builds that are no longer in
// the manifest.
//
// Returns non-zero if an error occurs.
func (c *Cleaner) CleanDead(entries map[string]*LogEntry) int {
c.Reset()
c.printHeader()
for k := range entries {
n := c.state.Paths[k]
// Detecting stale outputs works as follows:
//
// - If it has no Node, it is not in the build graph, or the deps log
// anymore, hence is stale.
//
// - If it isn't an output or input for any edge, it comes from a stale
// entry in the deps log, but no longer referenced from the build
// graph.
//
if n == nil || (n.InEdge == nil && len(n.OutEdges) == 0) {
c.remove(k)
}
}
c.printFooter()
return c.status
}
// Helper recursive method for cleanTarget().
func (c *Cleaner) doCleanTarget(target *Node) {
if e := target.InEdge; e != nil {
// Do not try to remove phony targets
if e.Rule != PhonyRule {
c.remove(target.Path)
c.removeEdgeFiles(e)
}
for _, next := range e.Inputs {
// call doCleanTarget recursively if this node has not been visited
if _, ok := c.cleaned[next]; !ok {
c.doCleanTarget(next)
}
}
}
// mark this target to be cleaned already
c.cleaned[target] = struct{}{}
}
// Clean the given target @a target.
// @return non-zero if an error occurs.
// Clean the given @a target and all the file built for it.
// @return non-zero if an error occurs.
func (c *Cleaner) cleanTargetNode(target *Node) int {
if target == nil {
panic("oops")
}
c.Reset()
c.printHeader()
c.loadDyndeps()
c.doCleanTarget(target)
c.printFooter()
return c.status
}
// Clean the given target @a target.
// @return non-zero if an error occurs.
// Clean the given @a target and all the file built for it.
// @return non-zero if an error occurs.
func (c *Cleaner) cleanTarget(target string) int {
if target == "" {
panic("oops")
}
c.Reset()
node := c.state.Paths[target]
if node != nil {
c.cleanTargetNode(node)
} else {
errorf("unknown target '%s'", target)
c.status = 1
}
return c.status
}
// CleanTargets cleans the given target targets.
//
// Return non-zero if an error occurs.
func (c *Cleaner) CleanTargets(targets []string) int {
// TODO(maruel): Not unit tested.
c.Reset()
c.printHeader()
c.loadDyndeps()
for _, targetName := range targets {
if targetName == "" {
errorf("failed to canonicalize '': empty path")
c.status = 1
continue
}
targetName = CanonicalizePath(targetName)
target := c.state.Paths[targetName]
if target != nil {
if c.isVerbose() {
fmt.Printf("Target %s\n", targetName)
}
c.doCleanTarget(target)
} else {
errorf("unknown target '%s'", targetName)
c.status = 1
}
}
c.printFooter()
return c.status
}
func (c *Cleaner) doCleanRule(rule *Rule) {
if rule == nil {
panic("oops")
}
for _, e := range c.state.Edges {
if e.Rule.Name == rule.Name {
for _, outNode := range e.Outputs {
c.remove(outNode.Path)
c.removeEdgeFiles(e)
}
}
}
}
// CleanRule cleans the file produced by the given rule.
//
// Returns non-zero if an error occurs.
func (c *Cleaner) CleanRule(rule *Rule) int {
c.Reset()
c.printHeader()
c.loadDyndeps()
c.doCleanRule(rule)
c.printFooter()
return c.status
}
// CleanRuleName cleans the file produced by the given rule.
//
// Returns non-zero if an error occurs.
func (c *Cleaner) CleanRuleName(rule string) int {
if rule == "" {
panic("oops")
}
c.Reset()
r := c.state.Bindings.LookupRule(rule)
if r != nil {
c.CleanRule(r)
} else {
errorf("unknown rule '%s'", rule)
c.status = 1
}
return c.status
}
// CleanRules cleans the file produced by the given rules.
//
// Returns non-zero if an error occurs.
func (c *Cleaner) CleanRules(rules []string) int {
// TODO(maruel): Not unit tested.
if len(rules) == 0 {
panic("oops")
}
c.Reset()
c.printHeader()
c.loadDyndeps()
for _, ruleName := range rules {
rule := c.state.Bindings.LookupRule(ruleName)
if rule != nil {
if c.isVerbose() {
fmt.Printf("Rule %s\n", ruleName)
}
c.doCleanRule(rule)
} else {
errorf("unknown rule '%s'", ruleName)
c.status = 1
}
}
c.printFooter()
return c.status
}
// Reset reinitializes the cleaner stats.
func (c *Cleaner) Reset() {
c.status = 0
c.cleanedFilesCount = 0
c.removed = map[string]struct{}{}
c.cleaned = map[*Node]struct{}{}
}
// Load dependencies from dyndep bindings.
func (c *Cleaner) loadDyndeps() {
// Load dyndep files that exist, before they are cleaned.
for _, e := range c.state.Edges {
if e.Dyndep != nil {
// Capture and ignore errors loading the dyndep file.
// We clean as much of the graph as we know.
_ = c.dyndepLoader.LoadDyndeps(e.Dyndep, DyndepFile{})
}
}
}