-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexec.go
More file actions
295 lines (258 loc) · 6.87 KB
/
exec.go
File metadata and controls
295 lines (258 loc) · 6.87 KB
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
// Copyright 2026 The mk Authors
// SPDX-License-Identifier: Apache-2.0
package mk
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
)
// Executor runs build recipes.
type Executor struct {
graph *Graph
state *BuildState
vars *Vars
verbose bool
force bool // -B: unconditional rebuild
dryRun bool // -n: print commands without executing
jobs int // max concurrent recipes (0 = unlimited)
mu sync.Mutex
building map[string]*buildResult // singleflight dedup
sem chan struct{} // recipe concurrency limiter; nil = unlimited
outputMu sync.Mutex // serializes buffered output flushes
cache *HashCache // file content hash cache
}
// buildResult tracks the in-progress or completed build of a target.
// Multiple targets from the same multi-output rule share one buildResult.
type buildResult struct {
done chan struct{}
err error
}
func NewExecutor(graph *Graph, state *BuildState, vars *Vars, verbose, force, dryRun bool, jobs int) *Executor {
if jobs < 0 {
jobs = runtime.NumCPU()
}
var sem chan struct{}
if jobs > 0 {
sem = make(chan struct{}, jobs)
}
// jobs == 0: sem stays nil → unlimited concurrency
return &Executor{
graph: graph,
state: state,
vars: vars,
verbose: verbose,
force: force,
dryRun: dryRun,
jobs: jobs,
building: make(map[string]*buildResult),
sem: sem,
cache: NewHashCache(),
}
}
// Build builds the given target and all its dependencies.
// Safe to call concurrently from multiple goroutines.
func (e *Executor) Build(target string) error {
e.mu.Lock()
if res, ok := e.building[target]; ok {
e.mu.Unlock()
<-res.done
return res.err
}
// Resolve rule under lock to discover co-targets for multi-output dedup.
// Graph.Resolve is read-only and safe to call here.
rule, err := e.graph.Resolve(target)
if err != nil {
e.mu.Unlock()
return err
}
res := &buildResult{done: make(chan struct{})}
for _, t := range rule.targets {
e.building[t] = res
}
e.mu.Unlock()
err = e.doBuild(target, rule)
res.err = err
close(res.done)
return err
}
func (e *Executor) doBuild(target string, rule *resolvedRule) error {
// Build all prerequisites concurrently
allPrereqs := make([]string, 0, len(rule.prereqs)+len(rule.orderOnlyPrereqs))
allPrereqs = append(allPrereqs, rule.prereqs...)
allPrereqs = append(allPrereqs, rule.orderOnlyPrereqs...)
errs := make([]error, len(allPrereqs))
var wg sync.WaitGroup
for i, p := range allPrereqs {
wg.Add(1)
go func(idx int, prereq string) {
defer wg.Done()
errs[idx] = e.Build(prereq)
}(i, p)
}
wg.Wait()
// Check for prereq errors
for i, err := range errs {
if err != nil {
return fmt.Errorf("building %q for %q: %w", allPrereqs[i], target, err)
}
}
// No recipe = leaf node or prerequisite-only rule
if len(rule.recipe) == 0 {
return nil
}
// Check staleness (only normal prereqs affect staleness)
recipeText := e.expandRecipe(rule)
fingerprint := e.expandFingerprint(rule)
if !rule.isTask && !e.force && !e.state.IsStale(rule.targets, rule.prereqs, recipeText, fingerprint, e.cache) {
if e.verbose {
e.outputMu.Lock()
fmt.Fprintf(os.Stderr, "mk: %q is up to date\n", rule.target)
e.outputMu.Unlock()
}
return nil
}
// Acquire semaphore slot to limit concurrent recipes
if e.sem != nil {
e.sem <- struct{}{}
defer func() { <-e.sem }()
}
return e.executeRecipe(rule, recipeText, fingerprint)
}
func (e *Executor) executeRecipe(rule *resolvedRule, recipeText, fingerprint string) error {
// Auto-create parent directories for all targets
if !rule.isTask {
for _, t := range rule.targets {
dir := filepath.Dir(t)
if dir != "." && dir != "" {
if !e.dryRun {
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("creating directory %q: %w", dir, err)
}
}
}
}
}
// Build banner
var banner strings.Builder
fmt.Fprintf(&banner, "mk: building %q\n", rule.target)
if e.verbose || e.dryRun {
for _, line := range strings.Split(recipeText, "\n") {
fmt.Fprintf(&banner, " %s\n", line)
}
}
if e.dryRun {
e.outputMu.Lock()
fmt.Fprint(os.Stderr, banner.String())
e.outputMu.Unlock()
return nil
}
// Determine output mode: serial streams directly, parallel buffers
serial := e.sem != nil && cap(e.sem) == 1
var stdout, stderr io.Writer
var outBuf, errBuf bytes.Buffer
if serial {
// Serial mode: stream banner and output directly
e.outputMu.Lock()
fmt.Fprint(os.Stderr, banner.String())
e.outputMu.Unlock()
stdout = os.Stdout
stderr = os.Stderr
} else {
// Parallel mode: buffer output, flush atomically on completion
stdout = &outBuf
stderr = &errBuf
}
// Execute recipe
fullScript := "set -e\n" + recipeText
cmd := exec.Command("sh", "-c", fullScript)
cmd.Stdout = stdout
cmd.Stderr = stderr
cmd.Env = e.vars.Environ()
err := cmd.Run()
if !serial {
// Flush buffered output atomically
e.outputMu.Lock()
fmt.Fprint(os.Stderr, banner.String())
outBuf.WriteTo(os.Stdout)
errBuf.WriteTo(os.Stderr)
e.outputMu.Unlock()
}
if err != nil {
// Delete partial output on failure (for file targets), unless [keep]
if !rule.isTask && !rule.keep {
for _, t := range rule.targets {
os.Remove(t)
}
}
return fmt.Errorf("recipe for %q failed: %w", rule.target, err)
}
// Record successful build for all outputs
if !rule.isTask {
e.state.Record(rule.targets, rule.prereqs, recipeText, fingerprint, e.cache)
}
return nil
}
func (e *Executor) expandFingerprint(rule *resolvedRule) string {
if rule.fingerprint == "" {
return ""
}
vars := e.vars.Clone()
vars.Set("target", rule.target)
if len(rule.prereqs) > 0 {
vars.Set("input", rule.prereqs[0])
}
vars.Set("inputs", strings.Join(rule.prereqs, " "))
if rule.stem != "" {
vars.Set("stem", rule.stem)
}
return vars.Expand(rule.fingerprint)
}
func (e *Executor) expandRecipe(rule *resolvedRule) string {
vars := e.vars.Clone()
vars.Set("target", rule.target)
if len(rule.prereqs) > 0 {
vars.Set("input", rule.prereqs[0])
}
vars.Set("inputs", strings.Join(rule.prereqs, " "))
// Set stem if available from pattern match
if rule.stem != "" {
vars.Set("stem", rule.stem)
}
// Find changed prerequisites (only normal prereqs)
var changed []string
ts := e.state.GetTarget(rule.target)
for _, p := range rule.prereqs {
if ts == nil {
changed = append(changed, p)
continue
}
h, err := e.cache.Hash(p)
if err != nil || ts.InputHashes[p] != h {
changed = append(changed, p)
}
}
vars.Set("changed", strings.Join(changed, " "))
var lines []string
for _, line := range rule.recipe {
ignoreErr := false
l := line
for len(l) > 0 && (l[0] == '@' || l[0] == '-') {
if l[0] == '-' {
ignoreErr = true
}
l = l[1:]
}
expanded := vars.Expand(l)
if ignoreErr {
expanded += " || true"
}
lines = append(lines, expanded)
}
return strings.Join(lines, "\n")
}