-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplan.go
427 lines (358 loc) · 9.55 KB
/
plan.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
package main
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
)
// These represent the possibilities for the $1 positional argument when
// executing rules.
const (
PhaseDeps = "deps"
PhaseExec = "exec"
)
// Walkfile is the name of the file that will be executed to plan and build
// targets.
const Walkfile = "Walkfile"
// Rule defines what a target depends on, and how to execute it.
type Rule interface {
// Dependencies returns the name of the targets that this target depends
// on.
Dependencies(context.Context) ([]string, error)
// Exec executes the target.
Exec(context.Context) error
}
// Target represents a target, which is usually built by a Rule. In general,
// targets are represented as paths to files on disk (e.g. "test/all" or
// "src/hello.o").
type Target interface {
Rule
// Name returns the name of the target.
Name() string
}
// TargetOptions are options passed to the NewTarget factory method.
type TargetOptions struct {
// The working directory that the target is relative to. The zero value
// is to use os.Getwd().
WorkingDir string
// Stdout/Stderr streams.
Stdout, Stderr io.Writer
// If true, the stdout from the targets will be attached to the Stdout
// provided above.
Verbose bool
// If true, disables prefixing of stdout/stderr
NoPrefix bool
}
// NewTarget returns a new Target instance.
func NewTarget(options TargetOptions) func(string) (Target, error) {
if options.Stdout == nil {
options.Stdout = os.Stdout
}
if options.Stderr == nil {
options.Stderr = os.Stderr
}
var err error
if options.WorkingDir == "" {
options.WorkingDir, err = os.Getwd()
}
return func(name string) (Target, error) {
if err != nil {
return nil, err
}
t := newTarget(options.WorkingDir, name)
if options.Verbose {
if options.NoPrefix {
t.stdout = options.Stdout
} else {
t.stdout = prefix(options.Stdout, t)
}
}
if options.NoPrefix {
t.stderr = options.Stderr
} else {
t.stderr = prefix(options.Stderr, t)
}
return &verboseTarget{
target: t,
stdout: options.Stdout,
}, nil
}
}
// Plan is used to build a graph of all the targets and their dependencies. It
// offers two primary methods; `Plan` and `Exec`, which correspond to the `deps`
// and `exec` phases respectively.
type Plan struct {
// NewTarget is executed when a target is discovered during Plan. This
// method should return a new Target instance, to represent the named
// target.
NewTarget func(string) (Target, error)
graph *Graph
}
// Exec is a simple helper to build and execute a target.
func Exec(ctx context.Context, semaphore Semaphore, targets ...string) error {
plan := newPlan()
err := plan.Plan(ctx, targets...)
if err != nil {
return err
}
return plan.Exec(ctx, semaphore)
}
// newPlan returns a new initialized Plan instance.
func newPlan() *Plan {
return &Plan{
NewTarget: NewTarget(TargetOptions{}),
graph: newGraph(),
}
}
// String implements the fmt.Stringer interface for Plan, which simply prints
// the targets and their dependencies.
func (p *Plan) String() string {
return p.graph.String()
}
// Plan builds the graph, starting with the given target. It recursively
// executes the "deps" phase of the targets rule, adding each dependency to the
// graph as their found.
func (p *Plan) Plan(ctx context.Context, targets ...string) error {
for _, target := range targets {
_, err := p.newTarget(ctx, target)
if err != nil {
return err
}
}
// Add a root target, with all of the given targets as it's dependency.
if err := p.addTarget(ctx, &rootTarget{deps: targets}); err != nil {
return err
}
if err := p.graph.Validate(); err != nil {
return err
}
p.graph.TransitiveReduction()
return nil
}
// addTarget adds the given Target to the graph, as well as it's dependencies,
// then connects the target to it's dependency with an edge.
func (p *Plan) addTarget(ctx context.Context, t Target) error {
p.graph.Add(t)
deps, err := t.Dependencies(ctx)
if err != nil {
return fmt.Errorf("error getting dependencies for %s: %v", t.Name(), err)
}
for _, d := range deps {
// TODO(ejholmes): Accept a semaphore and parallelize this. No
// need to perform this serially.
dep, err := p.newTarget(ctx, d)
if err != nil {
return err
}
p.graph.Connect(t, dep)
}
return nil
}
// newTarget instantiates a new Target instance using the Plan's NewTarget
// method, and adds it to the graph, if it hasn't already been added.
func (p *Plan) newTarget(ctx context.Context, target string) (Target, error) {
// Target already exists in the graph.
if t := p.graph.Target(target); t != nil {
return t, nil
}
t, err := p.NewTarget(target)
if err != nil {
return t, err
}
return t, p.addTarget(ctx, t)
}
// Exec begins walking the graph, executing the "exec" phase of each targets
// Rule. Targets Exec functions are guaranteed to be called when all of the
// Targets dependencies have been fulfilled.
func (p *Plan) Exec(ctx context.Context, semaphore Semaphore) error {
return p.graph.Walk(func(t Target) error {
semaphore.P()
defer semaphore.V()
return t.Exec(ctx)
})
}
// targetError is an error implementation that provides additional information
// about the rule that was used to build the target (if any).
type targetError struct {
target *target
err error
}
func (e *targetError) Error() string {
return fmt.Sprintf("%s: %v", e.target.Name(), e.err)
}
// target is a Target implementation, that represents a file on disk, which may
// be built by a rule.
type target struct {
// Relative path to the file.
name string
// The absolute path to the file.
path string
// path to the rulefile to use. This is determined by the RuleFile
// function.
rulefile string
// the directory to use as the working directory when executing the
// build file.
dir string
// The working directory.
wd string
stdout, stderr io.Writer
}
// newTarget initializes and returns a new target instance.
func newTarget(wd, name string) *target {
path := abs(wd, name)
rulefile := RuleFile(path)
var dir string
if rulefile != "" {
dir = filepath.Dir(path)
}
return &target{
name: name,
path: path,
rulefile: rulefile,
dir: dir,
wd: wd,
}
}
// Name implements the Target interface.
func (t *target) Name() string {
return t.name
}
// Exec executes the rule with "exec" as the first argument.
func (t *target) Exec(ctx context.Context) error {
// No .walk file, meaning it's a static dependency.
if t.rulefile == "" {
return nil
}
cmd, err := t.ruleCommand(ctx, PhaseExec)
if err != nil {
return err
}
return cmd.Run()
}
// Dependencies executes the rule with "deps" as the first argument, and parses
// out the newline delimited list of dependencies.
func (t *target) Dependencies(ctx context.Context) ([]string, error) {
// No .walk file, meaning it's a static dependency.
if t.rulefile == "" {
return nil, nil
}
b := new(bytes.Buffer)
cmd, err := t.ruleCommand(ctx, PhaseDeps)
if err != nil {
return nil, err
}
cmd.Stdout = b
if err := cmd.Run(); err != nil {
return nil, err
}
var deps []string
scanner := bufio.NewScanner(b)
for scanner.Scan() {
path := scanner.Text()
if path == "" {
continue
}
// If the path is not already and absolute path, make it one.
if !filepath.IsAbs(path) {
path = filepath.Join(t.dir, path)
}
// Make all paths relative to the working directory.
path, err := filepath.Rel(t.wd, path)
if err != nil {
return deps, err
}
deps = append(deps, path)
}
return deps, scanner.Err()
}
func (t *target) ruleCommand(ctx context.Context, phase string) (*exec.Cmd, error) {
name := filepath.Base(t.path)
cmd := exec.CommandContext(ctx, t.rulefile, phase, name)
cmd.Stdout = t.stdout
cmd.Stderr = t.stderr
cmd.Dir = t.dir
return cmd, nil
}
// verboseTarget simply wraps a target to print to to stdout when it's Exec'd.
type verboseTarget struct {
*target
stdout io.Writer
}
func (t *verboseTarget) Exec(ctx context.Context) error {
err := t.target.Exec(ctx)
prefix := "ok"
color := "32"
if err != nil {
prefix = "error"
color = "31"
}
line := fmt.Sprintf("%s\t%s", ansi(color, "%s", prefix), t.target.Name())
if err != nil {
line = fmt.Sprintf("%s\t%s", line, err)
}
if t.rulefile != "" {
fmt.Fprintf(t.stdout, "%s\n", line)
}
if err != nil {
return &targetError{t.target, err}
}
return err
}
// RuleFile is used to determine the path to an executable which will be used as
// the Rule to execute the given target. At the moment, this simply looks for an
// executable file called `Walkfile` in the same directory as the target.
func RuleFile(path string) string {
dir := filepath.Dir(path)
try := []string{
Walkfile,
}
for _, n := range try {
path := filepath.Join(dir, n)
_, err := os.Stat(path)
if err == nil {
return path
}
}
return ""
}
// prefixWriter wraps an io.Writer to append a prefix to each line written.
type prefixWriter struct {
prefix []byte
// The underlying io.Writer where prefixed lines will be written.
w io.Writer
// Buffer to hold the last line, which doesn't have a newline yet.
b []byte
}
func prefix(w io.Writer, t Target) io.Writer {
if w == nil {
return w
}
prefix := ansi("36", fmt.Sprintf("%s\t", t.Name()))
return &prefixWriter{
prefix: []byte(prefix),
w: w,
}
}
func (w *prefixWriter) Write(b []byte) (int, error) {
p := b
for {
i := bytes.IndexRune(p, '\n')
if i >= 0 {
w.b = append(w.b, p[:i+1]...)
p = p[i+1:]
_, err := w.w.Write(append(w.prefix, w.b...))
w.b = nil
if err != nil {
return len(b), err
}
continue
}
w.b = append(w.b, p...)
break
}
return len(b), nil
}