-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunner.go
More file actions
1215 lines (1160 loc) · 34.4 KB
/
Copy pathrunner.go
File metadata and controls
1215 lines (1160 loc) · 34.4 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
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package taskrun
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/gookit/taskrun/internal/data"
)
type executionMode int
const (
modeRun executionMode = iota
modeInspect
)
// callState is the isolated state of one task call. Every call has its own
// identifier, arguments, directory and deadline, and rebuilds its variables and
// environment from the definition defaults and the Request instead of
// inheriting the caller's local values.
type callState struct {
id string
task Task
args []string
depth int
dir string
}
// varScope resolves static and dynamic variables for one task call or step.
type varScope struct {
s *runState
ctx context.Context
task string
callID string
step string
dir string
env map[string]string
// taskEnv is the rendered task level environment, kept so a step scope can
// rebuild the final environment without re-rendering the task level.
taskEnv map[string]string
// paths lists the EnvPaths directories already prepended to PATH.
paths []string
args []string
run map[string]any
vars map[string]any
dyn map[string]DynamicVar
values map[string]any
}
func (v *varScope) lookup(name string) (any, bool, error) {
if value, ok := v.vars[name]; ok {
return value, true, nil
}
if v.values != nil {
if value, ok := v.values[name]; ok {
return value, true, nil
}
}
spec, ok := v.dyn[name]
if !ok {
return nil, false, nil
}
if v.s.mode == modeInspect {
return nil, false, errDeferred
}
value, err := v.s.evalDynamicVar(v, name, spec)
if err != nil {
return nil, false, err
}
if v.values == nil {
v.values = map[string]any{}
}
v.values[name] = value
return value, true, nil
}
func (v *varScope) deferredNames() []string {
if len(v.dyn) == 0 {
return nil
}
names := make([]string, 0, len(v.dyn))
for name := range v.dyn {
names = append(names, name)
}
data.SortStrings(names)
return names
}
func (v *varScope) renderVars() renderVars {
return renderVars{
Vars: v.vars,
Env: v.env,
Args: v.args,
Host: v.s.host,
Run: v.run,
Dynamic: v.lookup,
DeferredNames: v.deferredNames(),
}
}
// visibleVars returns static plus already resolved dynamic values for handlers.
func (v *varScope) visibleVars() map[string]any {
return data.Merge(v.vars, v.values)
}
type runState struct {
r *Runner
mode executionMode
ctx context.Context
req Request
host map[string]any
defVars map[string]any
// defEnv holds only the rendered definition level Env values; the base
// environment is merged later so CleanEnv can still drop it.
defEnv map[string]string
defEnvPaths []string
baseDir string
callSeq int
calls int
ignored bool
skipped bool
result *Result
plan *Plan
}
func newRunState(ctx context.Context, r *Runner, req Request, mode executionMode) (*runState, error) {
s := &runState{
r: r,
mode: mode,
ctx: ctx,
req: req,
host: data.CloneMap(req.HostData),
result: &Result{
Task: req.Task,
},
}
if s.host == nil {
s.host = map[string]any{}
}
s.baseDir = r.def.BaseDir
if req.Dir != "" {
s.baseDir = resolveDir(r.def.BaseDir, req.Dir)
}
baseView := renderVars{
Env: s.r.cfg.baseEnv,
Args: req.Args,
Host: s.host,
Run: s.runMeta("", "", s.baseDir),
}
vars, err := resolveVarLevel(r.def.Vars, baseView)
if err != nil {
return nil, err
}
s.defVars = data.Merge(vars, req.Vars)
// Environment values may reference variables, so they are rendered once the
// definition variables are known.
view := baseView
view.Vars = s.defVars
renderedEnv, err := s.renderEnvMap(r.def.Env, view)
if err != nil {
return nil, err
}
s.defEnv = renderedEnv
renderedPaths, err := s.renderPaths(r.def.EnvPaths, view)
if err != nil {
return nil, err
}
s.defEnvPaths = renderedPaths
if mode == modeInspect {
s.plan = &Plan{Task: req.Task}
}
return s, nil
}
func (s *runState) runMeta(task, callID, dir string) map[string]any {
return map[string]any{
"task": task,
"call": callID,
"dir": dir,
"os": runtime.GOOS,
"arch": runtime.GOARCH,
}
}
func (s *runState) nextCallID(name string) string {
s.callSeq++
return fmt.Sprintf("%s#%d", name, s.callSeq)
}
// visibleEnv returns the environment visible for rendering at a given level:
// the base snapshot plus the definition defaults, or only the definition
// defaults for a task with CleanEnv.
func (s *runState) visibleEnv(cleanEnv bool) map[string]string {
if cleanEnv {
return data.CloneStringMap(s.defEnv)
}
return mergeStringMaps(s.r.cfg.baseEnv, s.defEnv)
}
// composeEnv merges the effective environment in priority order (base,
// definition, task, step, Request) and replaces PATH with the EnvPaths
// directories in front of the inherited value. A task with CleanEnv drops only
// the base environment snapshot.
func (s *runState) composeEnv(cleanEnv bool, taskEnv, stepEnv, reqEnv map[string]string, paths []string) map[string]string {
parts := []map[string]string{}
if !cleanEnv {
parts = append(parts, s.r.cfg.baseEnv)
}
parts = append(parts, s.defEnv, taskEnv, stepEnv, reqEnv)
out := mergeStringMaps(parts...)
if len(paths) > 0 {
existing, _ := lookupEnv(out, "PATH")
for key := range out {
if data.EnvKey(key) == data.EnvKey("PATH") {
delete(out, key)
}
}
joined := strings.Join(paths, string(os.PathListSeparator))
if existing != "" {
joined += string(os.PathListSeparator) + existing
}
out["PATH"] = joined
}
return out
}
// envView builds the read view used to render Env values and EnvPaths at one
// level. Dynamic variables must never decide the process environment, so a
// dynamic reference is an error while running and a deferred field while
// inspecting.
func (s *runState) envView(call *callState, dir string, vars map[string]any, visible map[string]string, dyn map[string]DynamicVar) renderVars {
view := renderVars{
Vars: vars,
Env: visible,
Args: call.args,
Host: s.host,
Run: s.runMeta(call.task.Name, call.id, dir),
}
if len(dyn) == 0 {
return view
}
names := make([]string, 0, len(dyn))
for name := range dyn {
names = append(names, name)
}
data.SortStrings(names)
view.DeferredNames = names
view.Dynamic = func(name string) (any, bool, error) {
if _, declared := dyn[name]; !declared {
return nil, false, nil
}
if s.mode == modeInspect {
return nil, false, errDeferred
}
return nil, false, invalidDef("environment values must not depend on the dynamic variable %q: dynamic variables cannot decide the process environment", name)
}
return view
}
func (s *runState) renderEnvMap(env map[string]string, view renderVars) (map[string]string, error) {
if len(env) == 0 {
return nil, nil
}
out := make(map[string]string, len(env))
for _, key := range data.SortedKeys(env) {
value, err := renderTemplate(env[key], view)
if err != nil {
if errors.Is(err, errDeferred) && s.mode == modeInspect {
s.deferPlan("environment %s depends on a dynamic variable", key)
out[key] = env[key]
continue
}
return nil, err
}
out[key] = value
}
return out, nil
}
func (s *runState) renderPaths(list []string, view renderVars) ([]string, error) {
if len(list) == 0 {
return nil, nil
}
out := make([]string, 0, len(list))
for _, item := range list {
rendered, err := renderTemplate(item, view)
if err != nil {
if errors.Is(err, errDeferred) && s.mode == modeInspect {
s.deferPlan("env_paths entry depends on a dynamic variable")
out = append(out, item)
continue
}
return nil, err
}
out = append(out, rendered)
}
return out, nil
}
// resolveLevelVars resolves one variable level. While inspecting, a level that
// depends on a dynamic variable is reported as deferred instead of failing.
func (s *runState) resolveLevelVars(where string, level map[string]any, view renderVars) (map[string]any, error) {
vars, err := resolveVarLevel(level, view)
if err != nil {
if errors.Is(err, errDeferred) && s.mode == modeInspect {
s.deferPlan("%s variables depend on a dynamic variable", where)
return nil, nil
}
return nil, err
}
return vars, nil
}
// Run executes the requested task in an isolated state. A returned error is
// always a *RunError and its kind matches the Result status.
func (r *Runner) Run(ctx context.Context, req Request) (*Result, error) {
if ctx == nil {
return nil, &RunError{Kind: ErrKindInvalidRequest, Task: req.Task, Err: errf("ctx is nil")}
}
if err := req.validate(); err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, &RunError{Kind: ErrKindCanceled, Task: req.Task, Err: err}
}
req = newRequest(req)
if req.DryRun {
plan, err := r.Inspect(ctx, req)
if err != nil {
return nil, err
}
now := time.Now()
return &Result{Status: StatusDryRun, Task: req.Task, Plan: &plan, StartedAt: now, EndedAt: now}, nil
}
root, err := r.Lookup(req.Task)
if err != nil {
return nil, err
}
started := time.Now()
s, err := newRunState(ctx, r, req, modeRun)
if err != nil {
return nil, err
}
call := &callState{
id: s.nextCallID(root.Name),
task: root,
args: data.CloneStrings(req.Args),
depth: 1,
dir: s.baseDir,
}
s.emit(Event{Kind: EventRunStarted, Task: root.Name, CallID: call.id, Depth: call.depth, Dir: s.baseDir, Time: started})
runErr := s.runTask(ctx, call)
s.result.StartedAt = started
s.result.EndedAt = time.Now()
s.result.Status = s.finalStatus(runErr)
s.emit(Event{
Kind: EventRunFinished, Task: root.Name, CallID: call.id, Depth: call.depth,
Status: s.result.Status, Err: runErr, Time: s.result.EndedAt,
})
return s.result, runErr
}
func (s *runState) finalStatus(runErr error) Status {
if runErr == nil {
switch {
case s.ignored:
return StatusSucceededWithWarnings
case s.skipped:
return StatusSkipped
default:
return StatusSucceeded
}
}
var classified *RunError
if errors.As(runErr, &classified) {
switch classified.Kind {
case ErrKindCanceled:
return StatusCanceled
case ErrKindTimedOut:
return StatusTimedOut
}
}
return StatusFailed
}
// runTask executes one task call: platform and condition gates, dependencies,
// then steps, each with its own deadline.
func (s *runState) runTask(parent context.Context, call *callState) (err error) {
s.calls++
if s.calls > s.r.cfg.maxExpansions {
return &RunError{Kind: ErrKindExpansionLimit, Task: call.task.Name, CallID: call.id,
Err: errf("%w: more than %d task calls", ErrExpansionLimit, s.r.cfg.maxExpansions)}
}
record := func(status Status, reason string, err error, startedAt time.Time) {
s.result.Tasks = append(s.result.Tasks, TaskResult{
Name: call.task.Name, CallID: call.id, Status: status, Reason: reason, Err: err,
StartedAt: startedAt, EndedAt: time.Now(),
})
}
startedAt := time.Now()
task := call.task
// Task started/skipped/finished events are emitted on every exit path.
skipped := false
defer func() {
if skipped {
return
}
status := StatusSucceeded
if err != nil {
status = statusForKind(kindOf(err))
}
s.emit(Event{
Kind: EventTaskFinished, Task: task.Name, CallID: call.id, Depth: call.depth,
Status: status, Dir: call.dir, Err: err, Time: time.Now(),
})
}()
if !platformMatches(task.Platform, runtime.GOOS) {
s.skipped = s.skipped || call.depth == 1
reason := fmt.Sprintf("platform %s not in %v", runtime.GOOS, task.Platform)
record(StatusSkipped, reason, nil, startedAt)
s.note("task %s skipped: platform %s", task.Name, runtime.GOOS)
skipped = true
s.emit(Event{Kind: EventTaskSkipped, Task: task.Name, CallID: call.id, Depth: call.depth, Status: StatusSkipped, Reason: reason, Dir: call.dir, Time: time.Now()})
return nil
}
ctx, cancel := withBudget(parent, task.Timeout)
defer cancel()
call.dir = resolveDir(call.dir, task.Dir)
scope, err := s.newTaskScope(ctx, call)
if err != nil {
return s.fail(err, call, "")
}
evaluator, err := compileCondition(task.If, scope.renderVars())
if err != nil {
if errors.Is(err, errDeferred) {
s.deferPlan("task condition %s: %s", task.Name, task.If)
evaluator = func() (bool, error) { return true, nil }
} else {
return s.fail(err, call, "")
}
}
ok, err := evaluator()
if err != nil {
return s.fail(err, call, "")
}
if !ok {
s.skipped = s.skipped || call.depth == 1
record(StatusSkipped, "condition false", nil, startedAt)
s.note("task %s skipped: condition false", task.Name)
skipped = true
s.emit(Event{Kind: EventTaskSkipped, Task: task.Name, CallID: call.id, Depth: call.depth, Status: StatusSkipped, Reason: "condition false", Dir: call.dir, Time: time.Now()})
return nil
}
// started means the call really runs its dependencies and steps.
s.emit(Event{Kind: EventTaskStarted, Task: task.Name, CallID: call.id, Depth: call.depth, Dir: call.dir, Time: time.Now()})
for _, dep := range task.Deps {
child, err := s.childCall(call, dep, call.args)
if err != nil {
return s.fail(err, call, "")
}
if err := s.runTask(ctx, child); err != nil {
return err
}
}
for index, step := range task.Steps {
if err := s.runStep(ctx, call, scope, index, step); err != nil {
return err
}
}
record(StatusSucceeded, "", nil, startedAt)
return nil
}
// childCall builds an isolated call for a dependency or a task call. The child
// rebuilds its variables and environment from the definition defaults and the
// Request, so the caller's local values never leak in.
func (s *runState) childCall(parent *callState, name string, args []string) (*callState, error) {
task, ok := s.r.def.Tasks[name]
if !ok {
return nil, invalidDef("task %s calls unknown task %s", parent.task.Name, name)
}
return &callState{
id: s.nextCallID(name),
task: cloneTask(task),
args: data.CloneStrings(args),
depth: parent.depth + 1,
dir: s.baseDir,
}, nil
}
// newTaskScope resolves the variables, environment and EnvPaths of one task
// call. Variables are resolved before the environment, because environment
// values may reference them, and the environment is visible to conditions and
// actions but never to the variables of the same level.
func (s *runState) newTaskScope(ctx context.Context, call *callState) (*varScope, error) {
task := call.task
dir := call.dir
visible := s.visibleEnv(task.CleanEnv)
scope := &varScope{
s: s,
ctx: ctx,
task: task.Name,
callID: call.id,
dir: dir,
args: call.args,
run: s.runMeta(task.Name, call.id, dir),
vars: data.Merge(s.defVars),
dyn: task.DynamicVars,
env: visible,
}
varsView := scope.renderVars()
varsView.Env = visible
vars, err := s.resolveLevelVars("task "+task.Name, task.Vars, varsView)
if err != nil {
return nil, err
}
scope.vars = data.Merge(s.defVars, vars)
envView := s.envView(call, dir, scope.vars, visible, scope.dyn)
taskEnv, err := s.renderEnvMap(task.Env, envView)
if err != nil {
return nil, err
}
taskPaths, err := s.renderPaths(task.EnvPaths, envView)
if err != nil {
return nil, err
}
// The Request environment applies to the whole run, so it is visible to the
// task condition as well as to the steps.
requestEnv, err := s.renderEnvMap(s.req.Env, envView)
if err != nil {
return nil, err
}
scope.taskEnv = taskEnv
scope.paths = append(taskPaths, s.defEnvPaths...)
scope.env = s.composeEnv(task.CleanEnv, taskEnv, nil, requestEnv, scope.paths)
return scope, nil
}
// newStepScope resolves the variables, environment and EnvPaths of one step on
// top of its task scope and adds the Request environment, which has the highest
// priority.
func (s *runState) newStepScope(ctx context.Context, call *callState, taskScope *varScope, index int, step Step) (*varScope, error) {
dir := resolveDir(call.dir, step.Dir)
scope := &varScope{
s: s,
ctx: ctx,
task: call.task.Name,
callID: call.id,
step: stepLabel(step, index),
dir: dir,
args: call.args,
run: s.runMeta(call.task.Name, call.id, dir),
vars: taskScope.vars,
dyn: mergeDynamicVars(taskScope.dyn, step.DynamicVars),
env: taskScope.env,
}
varsView := scope.renderVars()
varsView.Env = taskScope.env
vars, err := s.resolveLevelVars("step "+scope.step, step.Vars, varsView)
if err != nil {
return nil, err
}
scope.vars = data.Merge(taskScope.vars, vars)
envView := s.envView(call, dir, scope.vars, taskScope.env, scope.dyn)
stepEnv, err := s.renderEnvMap(step.Env, envView)
if err != nil {
return nil, err
}
requestEnv, err := s.renderEnvMap(s.req.Env, envView)
if err != nil {
return nil, err
}
stepPaths, err := s.renderPaths(step.EnvPaths, envView)
if err != nil {
return nil, err
}
scope.taskEnv = taskScope.taskEnv
scope.paths = append(stepPaths, taskScope.paths...)
scope.env = s.composeEnv(call.task.CleanEnv, taskScope.taskEnv, stepEnv, requestEnv, scope.paths)
return scope, nil
}
// runStep evaluates and executes a single step.
func (s *runState) runStep(parent context.Context, call *callState, taskScope *varScope, index int, step Step) (err error) {
ctx, cancel := withBudget(parent, step.Timeout)
defer cancel()
label := stepLabel(step, index)
actionKind := step.actionKind()
// The effective step directory is deterministic, so it is available even when
// building the scope fails.
stepDir := resolveDir(call.dir, step.Dir)
skipped := false
defer func() {
if skipped {
return
}
// The recorded step result is authoritative, so ignored failures and
// handler results keep their status.
status := StatusSucceeded
var exitCode *int
var stepErr error
if last := s.lastStepResult(call.id, label); last != nil {
status = last.Status
exitCode = last.ExitCode
stepErr = last.Err
}
if err != nil {
status = statusForKind(kindOf(err))
stepErr = err
}
s.emit(Event{
Kind: EventStepFinished, Task: call.task.Name, CallID: call.id, Step: label,
ActionKind: actionKind, Depth: call.depth, Status: status, ExitCode: exitCode,
Dir: stepDir, Err: stepErr, Time: time.Now(),
})
}()
if !platformMatches(step.Platform, runtime.GOOS) {
reason := fmt.Sprintf("platform %s not in %v", runtime.GOOS, step.Platform)
s.recordStep(call, step, StepResult{Status: StatusSkipped, Err: nil})
s.note("task %s step %s skipped: platform %s", call.task.Name, label, runtime.GOOS)
skipped = true
s.emit(Event{Kind: EventStepSkipped, Task: call.task.Name, CallID: call.id, Step: label,
ActionKind: actionKind, Depth: call.depth, Status: StatusSkipped, Reason: reason,
Dir: stepDir, Time: time.Now()})
return nil
}
scope, err := s.newStepScope(ctx, call, taskScope, index, step)
if err != nil {
return s.fail(err, call, label)
}
evaluator, err := compileCondition(step.If, scope.renderVars())
if err != nil {
if errors.Is(err, errDeferred) {
s.deferPlan("step condition %s/%s: %s", call.task.Name, scope.step, step.If)
evaluator = func() (bool, error) { return true, nil }
} else {
return s.fail(err, call, scope.step)
}
}
ok, err := evaluator()
if err != nil {
return s.fail(err, call, scope.step)
}
if !ok {
s.recordStep(call, step, StepResult{Status: StatusSkipped})
s.note("task %s step %s skipped: condition false", call.task.Name, scope.step)
skipped = true
s.emit(Event{Kind: EventStepSkipped, Task: call.task.Name, CallID: call.id, Step: label,
ActionKind: actionKind, Depth: call.depth, Status: StatusSkipped, Reason: "condition false",
Dir: stepDir, Time: time.Now()})
return nil
}
s.emit(Event{Kind: EventStepStarted, Task: call.task.Name, CallID: call.id, Step: label,
ActionKind: actionKind, Depth: call.depth, Dir: stepDir, Time: time.Now()})
switch actionKind {
case "task":
return s.runTaskCall(ctx, call, scope, step)
case "host":
return s.runHost(ctx, call, scope, step)
default:
return s.runExternal(ctx, call, scope, step)
}
}
func (s *runState) runTaskCall(ctx context.Context, call *callState, scope *varScope, step Step) error {
args := step.Task.Args
if args == nil {
args = call.args
} else {
rendered, err := renderStrings(args, scope.renderVars())
if err != nil {
return s.fail(err, call, scope.step)
}
args = rendered
}
if step.Task.ForwardArgs {
args = append(data.CloneStrings(args), s.req.Args...)
}
child, err := s.childCall(call, step.Task.Name, args)
if err != nil {
return s.fail(err, call, scope.step)
}
if s.mode == modeInspect {
return s.planTaskCall(ctx, child)
}
if err := s.runTask(ctx, child); err != nil {
return err
}
s.recordStep(call, step, StepResult{Kind: "task", Status: StatusSucceeded})
return nil
}
// planTaskCall expands a called task while inspecting.
func (s *runState) planTaskCall(ctx context.Context, call *callState) error {
return s.runTask(ctx, call)
}
func (s *runState) runHost(ctx context.Context, call *callState, scope *varScope, step Step) error {
handler := s.r.cfg.handlers[step.Host.Name]
if s.mode == modeInspect {
s.planAction(PlannedAction{
Task: call.task.Name, CallID: call.id, Step: scope.step, Kind: "host",
Program: step.Host.Name, Dir: scope.dir, EnvKeys: data.SortedKeys(scope.env), Status: StatusPlanned,
})
return nil
}
args := make([]any, len(step.Host.Args))
for i, arg := range step.Host.Args {
if text, ok := arg.(string); ok {
rendered, err := renderTemplate(text, scope.renderVars())
if err != nil {
return s.fail(err, call, scope.step)
}
args[i] = rendered
continue
}
args[i] = data.Clone(arg)
}
hostCall := HostCall{
Name: step.Host.Name,
Args: args,
Vars: scope.visibleVars(),
Env: data.CloneStringMap(scope.env),
Dir: scope.dir,
}
result, err := invokeHandler(ctx, handler, hostCall)
if err != nil {
classified := s.classify(err, call, scope.step, ErrKindHandler)
if step.IgnoreError {
s.ignored = true
classified.Kind = ErrKindHandler
s.recordStep(call, step, StepResult{Kind: "host", Status: StatusIgnoredFailure, Started: true, Err: classified})
return nil
}
return s.fail(classified, call, scope.step)
}
s.recordStep(call, step, StepResult{
Kind: "host", Status: StatusSucceeded, Started: true,
ExitCode: result.ExitCode, Output: result.Output, ErrorOutput: result.ErrorOutput, Truncated: result.Truncated,
})
return nil
}
func invokeHandler(ctx context.Context, handler Handler, call HostCall) (result ActionResult, err error) {
defer func() {
if recovered := recover(); recovered != nil {
err = &RunError{Kind: ErrKindHandler, Err: errf("handler %s panicked: %v", call.Name, recovered)}
}
}()
return handler(ctx, call)
}
func (s *runState) runExternal(ctx context.Context, call *callState, scope *varScope, step Step) error {
action, err := s.prepareAction(scope, step)
if err != nil {
if errors.Is(err, errDeferred) && s.mode == modeInspect {
s.deferPlan("action %s/%s depends on a dynamic variable", call.task.Name, scope.step)
s.planDeferredAction(call, scope, step)
return nil
}
return s.fail(err, call, scope.step)
}
if s.mode == modeInspect {
s.planAction(PlannedAction{
Task: call.task.Name, CallID: call.id, Step: scope.step, Kind: action.Kind,
Program: action.Program, Args: action.Args, Script: action.Script,
Dir: action.Dir, EnvKeys: data.SortedKeys(scope.env), Status: StatusPlanned,
})
return nil
}
started := time.Now()
result, execErr := s.r.cfg.engine.Execute(ctx, action, s.req.IO)
stepResult := StepResult{
Kind: action.Kind, Started: result.Started, ExitCode: result.ExitCode,
Output: result.Output, ErrorOutput: result.ErrorOutput, Truncated: result.Truncated,
StartedAt: started, EndedAt: time.Now(),
}
if execErr != nil {
classified := s.classify(execErr, call, scope.step, ErrKindExit)
stepResult.Err = classified
if step.IgnoreError && toleratedFailure(classified.Kind) {
s.ignored = true
stepResult.Status = StatusIgnoredFailure
s.recordStep(call, step, stepResult)
return nil
}
stepResult.Status = statusForKind(classified.Kind)
s.recordStep(call, step, stepResult)
return classified
}
stepResult.Status = StatusSucceeded
s.recordStep(call, step, stepResult)
return nil
}
// toleratedFailure reports whether ignore_error may absorb a failure kind.
func toleratedFailure(kind ErrorKind) bool {
return kind == ErrKindExit || kind == ErrKindHandler
}
func statusForKind(kind ErrorKind) Status {
switch kind {
case ErrKindCanceled:
return StatusCanceled
case ErrKindTimedOut:
return StatusTimedOut
default:
return StatusFailed
}
}
// prepareAction renders and validates an external action.
func (s *runState) prepareAction(scope *varScope, step Step) (PreparedAction, error) {
rv := scope.renderVars()
action := PreparedAction{Dir: scope.dir, Env: data.EnvList(scope.env)}
switch {
case step.Exec != nil:
program, err := renderTemplate(step.Exec.Program, rv)
if err != nil {
return action, err
}
args, err := renderStrings(step.Exec.Args, rv)
if err != nil {
return action, err
}
if strings.TrimSpace(program) == "" {
return action, invalidDef("step %s has an empty exec program", scope.step)
}
action.Kind = "exec"
action.Program = program
action.Args = args
case step.Shell != nil:
script, err := renderTemplate(step.Shell.Script, rv)
if err != nil {
return action, err
}
action.Kind = "shell"
action.Program = normalizeShellName(step.Shell.Name)
action.Script = script
if len(step.Shell.PrefixArgs) > 0 {
args, err := renderStrings(step.Shell.PrefixArgs, rv)
if err != nil {
return action, err
}
action.Args = args
}
case step.File != nil:
file, ok := s.r.def.Files[step.File.Name]
if !ok {
return action, invalidDef("step %s references unknown script file %q", scope.step, step.File.Name)
}
program, err := renderTemplate(file.Interpreter.Program, rv)
if err != nil {
return action, err
}
args, err := renderStrings(file.Interpreter.PrefixArgs, rv)
if err != nil {
return action, err
}
args = append(args, file.Path)
extra, err := renderStrings(step.File.Args, rv)
if err != nil {
return action, err
}
args = append(args, extra...)
if file.Dir != "" {
action.Dir = resolveDir(scope.dir, file.Dir)
}
if len(file.Env) > 0 {
action.Env = data.EnvList(mergeStringMaps(scope.env, file.Env))
}
action.Kind = "file"
action.Program = program
action.Args = args
default:
return action, invalidDef("step %s has no external action", scope.step)
}
return action, nil
}
// prepareDynamicAction builds the command that produces a dynamic variable.
func (s *runState) prepareDynamicAction(scope *varScope, spec DynamicVar) (PreparedAction, error) {
rv := scope.renderVars()
action := PreparedAction{Dir: scope.dir, Env: data.EnvList(scope.env)}
switch {
case spec.Exec != nil:
program, err := renderTemplate(spec.Exec.Program, rv)
if err != nil {
return action, err
}
args, err := renderStrings(spec.Exec.Args, rv)
if err != nil {
return action, err
}
action.Kind = "exec"
action.Program = program
action.Args = args
case spec.Shell != nil:
script, err := renderTemplate(spec.Shell.Script, rv)
if err != nil {
return action, err
}
action.Kind = "shell"
action.Program = normalizeShellName(spec.Shell.Name)
action.Script = script
case spec.File != nil:
file, ok := s.r.def.Files[spec.File.Name]
if !ok {
return action, invalidDef("dynamic variable references unknown script file %q", spec.File.Name)
}
program, err := renderTemplate(file.Interpreter.Program, rv)
if err != nil {
return action, err
}
args, err := renderStrings(file.Interpreter.PrefixArgs, rv)
if err != nil {
return action, err
}
args = append(args, file.Path)
action.Kind = "file"
action.Program = program
action.Args = args
default:
return action, invalidDef("dynamic variable has no action")
}
return action, nil
}
func (s *runState) evalDynamicVar(scope *varScope, name string, spec DynamicVar) (any, error) {
action, err := s.prepareDynamicAction(scope, spec)
if err != nil {
return nil, s.classify(err, nil, scope.step, ErrKindInvalidDefinition)
}
result, err := s.r.cfg.engine.Execute(scope.ctx, action, IO{CaptureLimit: s.r.cfg.dynamicLimit})
if err != nil {
return nil, s.classify(err, nil, scope.step, ErrKindExit)
}
if result.Truncated {
return nil, &RunError{Kind: ErrKindOutputLimit, Task: scope.task, CallID: scope.callID, Step: scope.step,
Err: errf("%w: dynamic variable %q output exceeded %d bytes", ErrOutputLimit, name, s.r.cfg.dynamicLimit)}
}
return strings.TrimRight(string(result.Output), "\r\n"), nil
}
// classify converts any error into a RunError carrying run coordinates.
func (s *runState) classify(err error, call *callState, step string, fallback ErrorKind) *RunError {
if err == nil {
return nil
}
var existing *RunError
if errors.As(err, &existing) {
out := *existing
if out.Task == "" && call != nil {
out.Task = call.task.Name
}
if out.CallID == "" && call != nil {
out.CallID = call.id
}
if out.Step == "" {
out.Step = step
}
if out.Source == "" {
out.Source = s.sourceName()
}
if out.Err == nil {
out.Err = err
}
return &out
}
kind := fallback
var procErr *ProcessError
switch {
case errors.Is(err, context.Canceled):
kind = ErrKindCanceled
case errors.Is(err, context.DeadlineExceeded):
kind = ErrKindTimedOut
case errors.As(err, &procErr):
kind = procErr.Kind
}
out := &RunError{Kind: kind, Step: step, Source: s.sourceName(), Err: err}
if call != nil {
out.Task = call.task.Name
out.CallID = call.id
}
return out
}
// lastStepResult returns the recorded result of the most recent step with the
// given call and label, which is the authoritative status for events.
func (s *runState) lastStepResult(callID, label string) *StepResult {
for i := len(s.result.Steps) - 1; i >= 0; i-- {
step := s.result.Steps[i]
if step.CallID == callID && step.Name == label {