@intentius/chant-lexicon-terraform 0.124.89 → 0.124.91

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,7 @@ import { type OtlpSpan, type OtlpTrace } from "@intentius/chant/otlp";
2
2
  import { type TerraformCommand, type TerraformCommandHook } from "./op/command-hook.js";
3
3
  import { type BinaryExec, type Ran } from "./state/exec.js";
4
4
  import type { TerragruntExec } from "./terragrunt/run.js";
5
- export { withTerraformCommandHook, asUpstreamCommands, type TerraformCommand, type TerraformCommandHook, type TerraformCommandResult, type TerraformCommandRun } from "./op/command-hook.js";
5
+ export { withTerraformCommandHook, asUpstreamCommands, composeCommandHooks, type TerraformCommand, type TerraformCommandHook, type TerraformCommandResult, type TerraformCommandRun } from "./op/command-hook.js";
6
6
  /** A run of the binary that blocks: `-chdir=<dir>`, `TF_IN_AUTOMATION=1`, as {@link runBinary} runs it. */
7
7
  export type BinaryExecSync = (binary: string, args: string[], dir: string, env: NodeJS.ProcessEnv) => Ran;
8
8
  /** What {@link engineRunner} takes. */
@@ -77,7 +77,9 @@ export interface CommandTraceOptions {
77
77
  * `process.command_args`) under `parent(command)`, the variables
78
78
  * {@link commandTraceEnv} gives for it, and the span ended with
79
79
  * `process.exit.code` once the command ends, failed unless it exited 0 (or 2
80
- * for a `plan`, `-detailed-exitcode`'s changes). A command timed apart from
80
+ * for a `plan`, `-detailed-exitcode`'s changes), its error the result's
81
+ * `error` when the command did not exit (a binary that could not be started,
82
+ * chant#5007), `exit <code>` otherwise. A command timed apart from
81
83
  * its call (`at`, a Terragrunt unit's plan) spans the time it ran. Pass it as
82
84
  * `engineTimings({ inner })`, so the engine's spans join the trace and reach
83
85
  * the timings' receiver.
@@ -1 +1 @@
1
- {"version":3,"file":"engine-runner.d.ts","sourceRoot":"","sources":["../src/engine-runner.ts"],"names":[],"mappings":"AAgCA,OAAO,EAAmC,KAAK,QAAQ,EAAE,KAAK,SAAS,EAAE,MAA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mBAAmB;IAClC,uBAAuB;IACvB,KAAK,EAAE,SAAS,CAAC;IACjB,gFAAgF;IAChF,MAAM,EAAE,MAAM,CAAC;IACf,oJAAoJ;IACpJ,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,gBAAgB,KAAK,QAAQ,GAAG,SAAS,CAAC;IAC7D,0IAA0I;IAC1I,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,wGAAwG;IACxG,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,mBAAmB,GAAG,oBAAoB,CAa/E"}
@@ -15,7 +15,13 @@
15
15
  * - {@link commandTrace} is a `TerraformCommandHook` that opens a span per
16
16
  * engine command under the product's span for its root, and gives the
17
17
  * command `TRACEPARENT` and the resource attributes that name the span
18
- * ({@link commandTraceEnv}). Pass it as `engineTimings({ inner })`.
18
+ * ({@link commandTraceEnv}). Pass it as `engineTimings({ inner })`, or
19
+ * beside a product's own hook through `composeCommandHooks` (chant#5007).
20
+ *
21
+ * Every run `exec` makes answers its stderr apart (`Ran.stderr`) and, for a
22
+ * binary that could not be started, the spawn error (`Ran.error`), which the
23
+ * hook's `after` gets as a null code with `error` and `commandTrace` puts on
24
+ * the span (chant#5007).
19
25
  *
20
26
  * A Terragrunt unit's plan reaches the same hook through
21
27
  * `planTerragruntWave({ onCommand })` (`./terragrunt/run.ts`).
@@ -33,7 +39,7 @@ import { FORGE_TOKEN_VARS } from "@intentius/chant/ci-handover";
33
39
  import { formatOtlpPairs, parseOtlpPairs } from "@intentius/chant/otlp";
34
40
  import { hookedBinaryExec } from "./op/command-hook.js";
35
41
  import { engineEnv, runBinary, tokenlessBinaryExec } from "./state/exec.js";
36
- export { withTerraformCommandHook, asUpstreamCommands } from "./op/command-hook.js";
42
+ export { withTerraformCommandHook, asUpstreamCommands, composeCommandHooks } from "./op/command-hook.js";
37
43
  /** Whether `p` is a file this process may run. */
38
44
  function runnable(p) {
39
45
  try {
@@ -60,7 +66,9 @@ export function engineRunner(options = {}) {
60
66
  const execSync = (binary, args, dir, given) => {
61
67
  const p = spawnSync(binary, [`-chdir=${dir}`, ...args], { encoding: "utf-8", env: { ...env(given), TF_IN_AUTOMATION: "1" }, maxBuffer: 512 * 1024 * 1024 });
62
68
  const stdout = p.stdout ?? "";
63
- return { code: p.error && p.status === null ? 127 : (p.status ?? 1), stdout, out: `${stdout}${p.stderr ?? ""}${p.error ? p.error.message : ""}` };
69
+ const stderr = p.stderr ?? "";
70
+ const error = p.error && p.status === null ? { error: p.error.message } : {};
71
+ return { code: p.error && p.status === null ? 127 : (p.status ?? 1), stdout, out: `${stdout}${stderr}${p.error ? p.error.message : ""}`, stderr, ...error };
64
72
  };
65
73
  const terragrunt = (file, args, opts) => new Promise((done) => {
66
74
  execFile(file, [...args], { cwd: opts.cwd, env: env({ ...process.env, ...opts.env }), maxBuffer: 256 * 1024 * 1024 }, (err, stdout, stderr) => {
@@ -111,7 +119,9 @@ export function commandTraceEnv(env, trace, span, options) {
111
119
  * `process.command_args`) under `parent(command)`, the variables
112
120
  * {@link commandTraceEnv} gives for it, and the span ended with
113
121
  * `process.exit.code` once the command ends, failed unless it exited 0 (or 2
114
- * for a `plan`, `-detailed-exitcode`'s changes). A command timed apart from
122
+ * for a `plan`, `-detailed-exitcode`'s changes), its error the result's
123
+ * `error` when the command did not exit (a binary that could not be started,
124
+ * chant#5007), `exit <code>` otherwise. A command timed apart from
115
125
  * its call (`at`, a Terragrunt unit's plan) spans the time it ran. Pass it as
116
126
  * `engineTimings({ inner })`, so the engine's spans join the trace and reach
117
127
  * the timings' receiver.
@@ -127,7 +137,7 @@ export function commandTrace(options) {
127
137
  if (r.at)
128
138
  span.start = BigInt(Math.round(r.at.start)) * 1000000n;
129
139
  const ok = r.code === 0 || (c.name === "plan" && r.code === 2);
130
- options.trace.end(span, { "process.exit.code": r.code ?? -1 }, ok ? undefined : `exit ${r.code}`, r.at?.end);
140
+ options.trace.end(span, { "process.exit.code": r.code ?? -1 }, ok ? undefined : r.code === null && r.error ? r.error : `exit ${r.code}`, r.at?.end);
131
141
  },
132
142
  };
133
143
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "algorithm": "sha256",
3
3
  "artifacts": {
4
- "manifest.json": "b80640df1f7db7ee804395be7c62b0c61385a8378fa126ec2b8e3d020edbf0ca",
4
+ "manifest.json": "489304dceb998fa1c77edf1d30daf01115814ac8b18e05ee9b9bbbb8d31e4090",
5
5
  "meta.json": "ca3d163bab055381827226140568f3bef7eaac187cebd76878e0b63e9e442356",
6
6
  "types/index.d.ts": "022927e6a7b351cc4cf52d5f973f60ccd140e5810e17b32fb8868965aa1db161",
7
7
  "rules/plan-before-apply.ts": "7c10245b2c3335253b48ee7d8b075d89f43116bde20313a5d1031b343fef1282",
@@ -59,5 +59,5 @@
59
59
  "rules/tf047.ts": "bfa86f85c4c5efff297280fc2f15104d6319fa96dfc444a31829fb7353224092",
60
60
  "skills/chant-terraform.md": "53dd11c7b289652f92fdaf2c03766abda46d8964e31fe709e8b142ced4f19c50"
61
61
  },
62
- "composite": "c8d1a67d1fa734dea44c7de54f1054e3db52613eb24c60ebfb83373a70833e5d"
62
+ "composite": "1e560c2022f2261c669dce21b07ce73d1538817e3d947fd0b0b3ceefef782f87"
63
63
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "terraform",
3
- "version": "0.124.89",
3
+ "version": "0.124.91",
4
4
  "chantVersion": ">=0.1.0",
5
5
  "namespace": "Terraform"
6
6
  }
@@ -47,6 +47,12 @@ export interface TerraformCommandResult {
47
47
  start: number;
48
48
  end: number;
49
49
  };
50
+ /**
51
+ * Why the command did not exit on its own, when `code` is null (chant#5007):
52
+ * the spawn error's message for a binary that could not be started, the
53
+ * error a run threw, or why a Terragrunt unit did not run.
54
+ */
55
+ error?: string;
50
56
  }
51
57
  /** What a {@link TerraformCommandHook} answers for one command (chant#4865). */
52
58
  export interface TerraformCommandRun {
@@ -93,6 +99,18 @@ export declare function scopedCommand(scope: CommandScope): Pick<TerraformComman
93
99
  * the exit code, time and output. Outside a scope, `exec` as it is.
94
100
  */
95
101
  export declare function hookedBinaryExec(exec: BinaryExec): BinaryExec;
102
+ /**
103
+ * Several command hooks as one (chant#5007), such as a product's own timing
104
+ * hook and `commandTrace`, for a step that takes one `onCommand`. Each is
105
+ * called in turn and sees the command with the variables the hooks before
106
+ * it answered laid over its `env`, so a hook that reads the command's
107
+ * `OTEL_RESOURCE_ATTRIBUTES` keeps what an earlier one set; the variables
108
+ * they answer are laid over each other in the same order. Once the command
109
+ * ends every `after` is called in the same order, all of them even when
110
+ * one throws, and the first error is thrown after the last. An undefined
111
+ * hook is left out.
112
+ */
113
+ export declare function composeCommandHooks(...hooks: Array<TerraformCommandHook | undefined>): TerraformCommandHook;
96
114
  /** The words of a command line the builders here wrote: plain words, and `quoteArg`'s single-quoted ones. */
97
115
  export declare function commandWords(line: string): string[];
98
116
  //# sourceMappingURL=command-hook.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"command-hook.d.ts","sourceRoot":"","sources":["../../src/op/command-hook.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,UAAU,EAAO,MAAM,eAAe,CAAC;AAErD;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B,4CAA4C;IAC5C,IAAI,EAAE,MAAM,CAAC;IACb,kGAAkG;IAClG,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,4EAA4E;IAC5E,MAAM,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,MAAM,EAAE,MAAM,CAAC;IACf,sIAAsI;IACtI,IAAI,EAAE,MAAM,CAAC;IACb,gDAAgD;IAChD,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,6CAA6C;IAC7C,IAAI,EAAE,MAAM,CAAC;IACb,gCAAgC;IAChC,GAAG,EAAE,MAAM,C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C,CAGvJ;AAED,mJAAmJ;AACnJ,wBAAgB,kBAAkB,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAGxF;AAED,0EAA0E;AAC1E,wBAAgB,mBAAmB,IAAI,YAAY,GAAG,SAAS,CAE9D;AAED,yEAAyE;AACzE,wBAAgB,aAAa,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,CAAC,gBAAgB,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,GAAG,QAAQ,CAAC,CAOrH;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,UAAU,GAAG,UAAU,CAgC7D;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,KAAK,EAAE,KAAK,CAAC,oBAAoB,GAAG,SAAS,CAAC,GAAG,oBAAoB,CA0B3G;AAKD,6GAA6G;AAC7G,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAqBnD"}
@@ -74,15 +74,60 @@ export function hookedBinaryExec(exec) {
74
74
  ran = await exec(binary, args, dir, given.env ? { ...env, ...given.env } : env, io);
75
75
  }
76
76
  catch (err) {
77
- await given.after?.({ code: null, seconds: (performance.now() - start) / 1000, stdout: "", stderr: err instanceof Error ? err.message : String(err) });
77
+ const message = err instanceof Error ? err.message : String(err);
78
+ await given.after?.({ code: null, seconds: (performance.now() - start) / 1000, stdout: "", stderr: message, error: message });
78
79
  throw err;
79
80
  }
80
- // `out` holds stdout and stderr together, as they came; stderr alone is what is left once stdout is taken out of it.
81
- const stderr = ran.out.startsWith(ran.stdout) ? ran.out.slice(ran.stdout.length) : ran.out;
82
- await given.after?.({ code: ran.code, seconds: (performance.now() - start) / 1000, stdout: ran.stdout, stderr });
81
+ // `out` holds stdout and stderr together, as they came; an exec that does not keep stderr apart leaves what is left once stdout is taken out of it.
82
+ const stderr = ran.stderr ?? (ran.out.startsWith(ran.stdout) ? ran.out.slice(ran.stdout.length) : ran.out);
83
+ // A binary that could not be started did not exit (chant#5007): its code is the hook's null, with the spawn error's message.
84
+ const failed = ran.error !== undefined ? { code: null, error: ran.error } : { code: ran.code };
85
+ await given.after?.({ ...failed, seconds: (performance.now() - start) / 1000, stdout: ran.stdout, stderr });
83
86
  return ran;
84
87
  };
85
88
  }
89
+ /**
90
+ * Several command hooks as one (chant#5007), such as a product's own timing
91
+ * hook and `commandTrace`, for a step that takes one `onCommand`. Each is
92
+ * called in turn and sees the command with the variables the hooks before
93
+ * it answered laid over its `env`, so a hook that reads the command's
94
+ * `OTEL_RESOURCE_ATTRIBUTES` keeps what an earlier one set; the variables
95
+ * they answer are laid over each other in the same order. Once the command
96
+ * ends every `after` is called in the same order, all of them even when
97
+ * one throws, and the first error is thrown after the last. An undefined
98
+ * hook is left out.
99
+ */
100
+ export function composeCommandHooks(...hooks) {
101
+ const list = hooks.filter((h) => h !== undefined);
102
+ return async (command) => {
103
+ const runs = [];
104
+ let env = {};
105
+ for (const hook of list) {
106
+ const run = (await hook(Object.keys(env).length > 0 ? { ...command, env: { ...command.env, ...env } } : command)) ?? {};
107
+ runs.push(run);
108
+ if (run.env)
109
+ env = { ...env, ...run.env };
110
+ }
111
+ if (runs.every((r) => !r.env && !r.after))
112
+ return;
113
+ return {
114
+ ...(Object.keys(env).length > 0 ? { env } : {}),
115
+ after: async (result) => {
116
+ let first;
117
+ for (const run of runs) {
118
+ try {
119
+ await run.after?.(result);
120
+ }
121
+ catch (error) {
122
+ first ?? (first = { error });
123
+ }
124
+ }
125
+ if (first)
126
+ throw first.error;
127
+ },
128
+ };
129
+ };
130
+ }
86
131
  /** A word single-quoted for a shell, as `quoteArg` writes it. */
87
132
  const quoteWord = (w) => `'${w.replace(/'/g, `'\\''`)}'`;
88
133
  /** The words of a command line the builders here wrote: plain words, and `quoteArg`'s single-quoted ones. */
@@ -0,0 +1,76 @@
1
+ /**
2
+ * What a change reaches (#4984), beside ./changed-roots.ts: the roots,
3
+ * Terragrunt units, Atmos instances or synthesized roots a change from
4
+ * `from` to `to` reaches, read from git alone. Moved from terragucci's
5
+ * `reachedRoots`, `reachedUnits`, `reachedInstances` and
6
+ * `reachedSynthesized` (comment-apply.ts), for a product's reach line
7
+ * (`productPlan.reach`, #4979): the lock job and the decision before merge
8
+ * run it at the target branch's commit, so none of the change's code runs.
9
+ *
10
+ * Each follows what reads a reached target: a root that reads a reached
11
+ * root's state, a unit that names a reached unit in a `dependency` or
12
+ * `dependencies` block, an instance that depends on a reached one, followed
13
+ * through. The product hands the reads it knows (terragucci's
14
+ * `terraform_remote_state` edges and `waves.after`, Atmos's dependencies);
15
+ * the Terragrunt unit reads are parsed here, at both ends of the range.
16
+ * Markdown files reach nothing. When a change can reach anything, or git
17
+ * cannot diff the range, every target is reached and `every` says why.
18
+ */
19
+ /** Git in a checkout: an argv after `git`, and what it answered. */
20
+ export type ReachGit = (args: string[]) => {
21
+ status: number | null;
22
+ stdout: string;
23
+ stderr: string;
24
+ };
25
+ /** What a change reaches, sorted, and why it is every target when it is. */
26
+ export interface Reach {
27
+ targets: string[];
28
+ every?: string;
29
+ }
30
+ /** The targets each target reads, so a change to one of those reaches it too. */
31
+ export type ReachReads = ReadonlyMap<string, ReadonlySet<string>>;
32
+ /** Changed files that reach nothing: documentation. */
33
+ export declare const READS_NOTHING: RegExp;
34
+ /** The files the change from `from` to `to` changes (`git diff --name-only from...to`), or undefined when git cannot say. */
35
+ export declare function changedFilesBetween(git: ReachGit, from: string, to: string): string[] | undefined;
36
+ /** Add to `selected` every target that reads a selected one, followed through. */
37
+ export declare function followReads(selected: Set<string>, reads: ReachReads | undefined): void;
38
+ /**
39
+ * The plain roots a change reaches: the roots whose files it changes, by
40
+ * chant's path rules (./changed-roots.ts: a root's directory, the local
41
+ * modules it calls, its var files), and every root that reads one of those.
42
+ * Every root when git cannot diff the range.
43
+ */
44
+ export declare function reachedRoots(repo: string, git: ReachGit, from: string, to: string, roots: readonly string[], reads?: ReachReads): Reach;
45
+ /**
46
+ * The paths a unit's `terragrunt.hcl` names in its `dependency` blocks'
47
+ * `config_path` and its `dependencies` block's `paths`, when each is a plain
48
+ * string. A path built with a function or an interpolation is not read:
49
+ * only Terragrunt can evaluate it, and no Terragrunt runs on a change's
50
+ * files before a review.
51
+ */
52
+ export declare function literalTerragruntDependencies(text: string): string[];
53
+ /**
54
+ * The Terragrunt units a change reaches. A unit is reached when a file
55
+ * under its directory changes (the deepest unit holding the file), and so
56
+ * is every unit that names a reached one with a plain path, at either end
57
+ * of the range. A changed file under no unit's directory (`root.hcl`, a
58
+ * module, a stack template) may change any unit, so it reaches every one.
59
+ */
60
+ export declare function reachedUnits(git: ReachGit, from: string, to: string, units: readonly string[]): Reach;
61
+ /**
62
+ * The Atmos instances a change reaches. `componentOf` names each instance's
63
+ * component directory. A changed file under one reaches that component's
64
+ * instances; any other file (a stack manifest, a catalog, `atmos.yaml`) can
65
+ * change any instance's vars or backend, so it reaches every instance.
66
+ * Instances that read a reached one follow.
67
+ */
68
+ export declare function reachedInstances(git: ReachGit, from: string, to: string, instances: readonly string[], componentOf: ReadonlyMap<string, string | undefined>, reads?: ReachReads): Reach;
69
+ /**
70
+ * The roots a change reaches when a command writes them (`synth`, CDK
71
+ * Terrain's stacks). The roots are not in git, so no diff names them, and
72
+ * the command is the change's own code: any changed file that is not
73
+ * Markdown can change any root.
74
+ */
75
+ export declare function reachedSynthesized(git: ReachGit, from: string, to: string, roots: readonly string[]): Reach;
76
+ //# sourceMappingURL=reach.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reach.d.ts","sourceRoot":"","sources":["../src/reach.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAKH,oEAAoE;AACpE,MAAM,MAAM,QAAQ,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK;IAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAA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S,MAAM,EAAE,EAAE,WAAW,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,EAAE,KAAK,CAAC,EAAE,UAAU,GAAG,KAAK,CAgBvL;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,KAAK,CAO3G"}
package/dist/reach.js ADDED
@@ -0,0 +1,193 @@
1
+ /**
2
+ * What a change reaches (#4984), beside ./changed-roots.ts: the roots,
3
+ * Terragrunt units, Atmos instances or synthesized roots a change from
4
+ * `from` to `to` reaches, read from git alone. Moved from terragucci's
5
+ * `reachedRoots`, `reachedUnits`, `reachedInstances` and
6
+ * `reachedSynthesized` (comment-apply.ts), for a product's reach line
7
+ * (`productPlan.reach`, #4979): the lock job and the decision before merge
8
+ * run it at the target branch's commit, so none of the change's code runs.
9
+ *
10
+ * Each follows what reads a reached target: a root that reads a reached
11
+ * root's state, a unit that names a reached unit in a `dependency` or
12
+ * `dependencies` block, an instance that depends on a reached one, followed
13
+ * through. The product hands the reads it knows (terragucci's
14
+ * `terraform_remote_state` edges and `waves.after`, Atmos's dependencies);
15
+ * the Terragrunt unit reads are parsed here, at both ends of the range.
16
+ * Markdown files reach nothing. When a change can reach anything, or git
17
+ * cannot diff the range, every target is reached and `every` says why.
18
+ */
19
+ import { posix } from "node:path";
20
+ import { changedRoots } from "./changed-roots.js";
21
+ /** Changed files that reach nothing: documentation. */
22
+ export const READS_NOTHING = /\.md$/i;
23
+ /** The files the change from `from` to `to` changes (`git diff --name-only from...to`), or undefined when git cannot say. */
24
+ export function changedFilesBetween(git, from, to) {
25
+ const diff = git(["diff", "--name-only", "--no-renames", `${from}...${to}`]);
26
+ if (diff.status !== 0)
27
+ return undefined;
28
+ return diff.stdout.split("\n").map((l) => l.trim()).filter(Boolean);
29
+ }
30
+ /** Add to `selected` every target that reads a selected one, followed through. */
31
+ export function followReads(selected, reads) {
32
+ if (!reads)
33
+ return;
34
+ for (let grew = true; grew;) {
35
+ grew = false;
36
+ for (const [target, from] of reads) {
37
+ if (!selected.has(target) && [...from].some((d) => selected.has(d))) {
38
+ selected.add(target);
39
+ grew = true;
40
+ }
41
+ }
42
+ }
43
+ }
44
+ const sorted = (xs) => [...new Set(xs)].sort();
45
+ /**
46
+ * The plain roots a change reaches: the roots whose files it changes, by
47
+ * chant's path rules (./changed-roots.ts: a root's directory, the local
48
+ * modules it calls, its var files), and every root that reads one of those.
49
+ * Every root when git cannot diff the range.
50
+ */
51
+ export function reachedRoots(repo, git, from, to, roots, reads) {
52
+ const all = sorted(roots);
53
+ const files = changedFilesBetween(git, from, to);
54
+ if (files === undefined)
55
+ return { targets: all, every: "git could not list the files it changes" };
56
+ const selected = new Set(changedRoots(repo, Object.fromEntries(all.map((r) => [r, { dir: r }])), files));
57
+ followReads(selected, reads);
58
+ return { targets: [...selected].filter((r) => all.includes(r)).sort() };
59
+ }
60
+ /** The body of each top-level `<keyword> ... {` block in HCL text, braces matched, strings skipped. */
61
+ function hclBlocks(text, keyword) {
62
+ const out = [];
63
+ const head = new RegExp(`^\\s*${keyword}\\b[^{\\n]*\\{`, "gm");
64
+ for (let m = head.exec(text); m; m = head.exec(text)) {
65
+ let depth = 1;
66
+ let i = m.index + m[0].length;
67
+ const start = i;
68
+ for (let quoted = false; i < text.length && depth > 0; i++) {
69
+ const c = text[i];
70
+ if (quoted) {
71
+ if (c === "\\")
72
+ i++;
73
+ else if (c === '"')
74
+ quoted = false;
75
+ }
76
+ else if (c === '"')
77
+ quoted = true;
78
+ else if (c === "{")
79
+ depth++;
80
+ else if (c === "}")
81
+ depth--;
82
+ }
83
+ out.push(text.slice(start, i - 1));
84
+ head.lastIndex = i;
85
+ }
86
+ return out;
87
+ }
88
+ /**
89
+ * The paths a unit's `terragrunt.hcl` names in its `dependency` blocks'
90
+ * `config_path` and its `dependencies` block's `paths`, when each is a plain
91
+ * string. A path built with a function or an interpolation is not read:
92
+ * only Terragrunt can evaluate it, and no Terragrunt runs on a change's
93
+ * files before a review.
94
+ */
95
+ export function literalTerragruntDependencies(text) {
96
+ const clean = text.replace(/(^|[^:"$])(#|\/\/).*$/gm, "$1");
97
+ const plain = /^"([^"$]*)"$/;
98
+ const out = [];
99
+ for (const b of hclBlocks(clean, "dependency")) {
100
+ const m = /^\s*config_path\s*=\s*("[^"\n]*")\s*$/m.exec(b);
101
+ const p = m && plain.exec(m[1]);
102
+ if (p)
103
+ out.push(p[1]);
104
+ }
105
+ for (const b of hclBlocks(clean, "dependencies")) {
106
+ const m = /\bpaths\s*=\s*\[([^\]]*)\]/.exec(b);
107
+ for (const item of m ? m[1].split(",").map((x) => x.trim()).filter(Boolean) : []) {
108
+ const p = plain.exec(item);
109
+ if (p)
110
+ out.push(p[1]);
111
+ }
112
+ }
113
+ return out;
114
+ }
115
+ /**
116
+ * The Terragrunt units a change reaches. A unit is reached when a file
117
+ * under its directory changes (the deepest unit holding the file), and so
118
+ * is every unit that names a reached one with a plain path, at either end
119
+ * of the range. A changed file under no unit's directory (`root.hcl`, a
120
+ * module, a stack template) may change any unit, so it reaches every one.
121
+ */
122
+ export function reachedUnits(git, from, to, units) {
123
+ const all = sorted(units);
124
+ const files0 = changedFilesBetween(git, from, to);
125
+ if (files0 === undefined)
126
+ return { targets: all, every: "git could not list the files it changes" };
127
+ const files = files0.filter((f) => !READS_NOTHING.test(f));
128
+ const deepest = [...all].sort((a, b) => b.length - a.length);
129
+ const selected = new Set();
130
+ for (const f of files) {
131
+ const u = deepest.find((d) => f.startsWith(`${d}/`));
132
+ if (!u)
133
+ return { targets: all, every: `it changes \`${f}\`, which is in no unit's directory` };
134
+ selected.add(u);
135
+ }
136
+ const reads = new Map();
137
+ for (const u of all) {
138
+ const deps = new Set();
139
+ for (const ref of [from, to]) {
140
+ const shown = git(["show", `${ref}:${u}/terragrunt.hcl`]);
141
+ if (shown.status !== 0)
142
+ continue;
143
+ for (const p of literalTerragruntDependencies(shown.stdout))
144
+ deps.add(posix.normalize(posix.join(u, p)).replace(/\/+$/, ""));
145
+ }
146
+ reads.set(u, deps);
147
+ }
148
+ followReads(selected, reads);
149
+ return { targets: [...selected].sort() };
150
+ }
151
+ /**
152
+ * The Atmos instances a change reaches. `componentOf` names each instance's
153
+ * component directory. A changed file under one reaches that component's
154
+ * instances; any other file (a stack manifest, a catalog, `atmos.yaml`) can
155
+ * change any instance's vars or backend, so it reaches every instance.
156
+ * Instances that read a reached one follow.
157
+ */
158
+ export function reachedInstances(git, from, to, instances, componentOf, reads) {
159
+ const all = sorted(instances);
160
+ const files0 = changedFilesBetween(git, from, to);
161
+ if (files0 === undefined)
162
+ return { targets: all, every: "git could not list the files it changes" };
163
+ const files = files0.filter((f) => !READS_NOTHING.test(f));
164
+ const selected = new Set();
165
+ for (const f of files) {
166
+ const owners = all.filter((r) => {
167
+ const c = componentOf.get(r)?.replace(/\/+$/, "");
168
+ return c !== undefined && f.startsWith(`${c}/`);
169
+ });
170
+ if (owners.length === 0)
171
+ return { targets: all, every: `it changes \`${f}\`, which can change any Atmos instance` };
172
+ for (const r of owners)
173
+ selected.add(r);
174
+ }
175
+ followReads(selected, reads);
176
+ return { targets: [...selected].sort() };
177
+ }
178
+ /**
179
+ * The roots a change reaches when a command writes them (`synth`, CDK
180
+ * Terrain's stacks). The roots are not in git, so no diff names them, and
181
+ * the command is the change's own code: any changed file that is not
182
+ * Markdown can change any root.
183
+ */
184
+ export function reachedSynthesized(git, from, to, roots) {
185
+ const all = sorted(roots);
186
+ const files = changedFilesBetween(git, from, to);
187
+ if (files === undefined)
188
+ return { targets: all, every: "git could not list the files it changes" };
189
+ const file = files.find((f) => !READS_NOTHING.test(f));
190
+ if (file === undefined)
191
+ return { targets: [] };
192
+ return { targets: all, every: `it changes \`${file}\`, and the synth command writes every root from the repo's files` };
193
+ }
@@ -3,6 +3,10 @@ export interface Ran {
3
3
  stdout: string;
4
4
  /** stdout and stderr together, as they came. */
5
5
  out: string;
6
+ /** stderr alone, less the lines `io.stderr` took (chant#5007). {@link runBinary} sets it; an exec of a product's or a test's may leave it out. */
7
+ stderr?: string;
8
+ /** Why the binary did not run, when it could not be started: the spawn error's message (chant#5007). `code` is then 127. */
9
+ error?: string;
6
10
  }
7
11
  /** What a run of the binary hands back while it runs: `stderr` sees each line of stderr as it arrives, and a line it takes (true) is left out of `out`. */
8
12
  export interface BinaryIo {
@@ -1 +1 @@
1
- {"version":3,"file":"exec.d.ts","sourceRoot":"","sources":["../../src/state/exec.ts"],"names":[],"mappings":"AAUA,MAAM,WAAW,GAAG;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,GAAG,EAAE,MAAM,CAAC;CACb;AAED,2JAA2J;AAC3J,MAAM,WAAW,QAAQ;IACvB,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;CACpC;AAED,uEAAuE;AACvE,MAAM,MAAM,UAAU,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,UAAU,EAAE,EAAE,CAAC,EAAE,QAAQ,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;AAE9H,mEAAmE;AACnE,eAAO,MAAM,SAAS,EAAE,UA2CpB,CAAC;AAEL;;;;;;;;;;;;GAYG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,GAAE,SAAS,MAAM,EAAO,GAAG,MAAM,CAAC,UAAU,CAUnG;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,GAAE,SAAS,MAAM,EAAO,EAAE,IAAI,GAAE,UAAsB,GAAG,UAAU,CAE5G;AAED,mGAAmG;AACnG,MAAM,WAAW,SAAS;IACxB,OAAO,EAAE,MAAM,CA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AO,CAAC;CACtB;AAED,wEAAwE;AACxE,eAAO,MAAM,SAAS,MAAO,MAAM,iBAAU,MAAgE,CAAC;AAE9G,yEAAyE;AACzE,wBAAsB,SAAS,CAAC,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,CAc9I"}
@@ -11,6 +11,7 @@ import { FORGE_TOKEN_VARS } from "@intentius/chant/ci-handover";
11
11
  export const runBinary = (binary, args, dir, env, io) => new Promise((done) => {
12
12
  const child = spawn(binary, [`-chdir=${dir}`, ...args], { env: { ...env, TF_IN_AUTOMATION: "1" }, stdio: ["ignore", "pipe", "pipe"] });
13
13
  let stdout = "";
14
+ let stderr = "";
14
15
  let out = "";
15
16
  let partial = "";
16
17
  const stderrLine = (line) => {
@@ -21,8 +22,10 @@ export const runBinary = (binary, args, dir, env, io) => new Promise((done) => {
21
22
  catch {
22
23
  taken = false;
23
24
  }
24
- if (!taken)
25
+ if (!taken) {
25
26
  out += `${line}\n`;
27
+ stderr += `${line}\n`;
28
+ }
26
29
  };
27
30
  child.stdout.on("data", (d) => {
28
31
  stdout += d;
@@ -34,6 +37,7 @@ export const runBinary = (binary, args, dir, env, io) => new Promise((done) => {
34
37
  child.stderr.on("data", (d) => {
35
38
  if (!io?.stderr) {
36
39
  out += d;
40
+ stderr += d;
37
41
  return;
38
42
  }
39
43
  partial += d;
@@ -49,11 +53,11 @@ export const runBinary = (binary, args, dir, env, io) => new Promise((done) => {
49
53
  };
50
54
  child.on("error", (e) => {
51
55
  rest();
52
- done({ code: 127, stdout, out: `${out}${e.message}` });
56
+ done({ code: 127, stdout, out: `${out}${e.message}`, stderr, error: e.message });
53
57
  });
54
58
  child.on("close", (code) => {
55
59
  rest();
56
- done({ code: code ?? 1, stdout, out });
60
+ done({ code: code ?? 1, stdout, out, stderr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AgB,8BAA8B,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAErE;AAED,MAAM,WAAW,wBAAyB,SAAQ,oBAAoB;IACpE,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IACzB,mEAAmE;IACnE,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;;;;;;;GASG;AACH,wBAAsB,wBAAwB,CAAC,KAAK,EAAE,wBAAwB,GAAG,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAiD7G;AAED,MAAM,WAAW,kBAAkB;IACjC,qFAAqF;IACrF,KAAK,EAAE,aAAa,EAAE,CAAC;IACvB,2CAA2C;IAC3C,WAAW,EAAE,OAAO,CAAC;IACrB,OAAO,EAAE,oBAAoB,EAAE,CAAC;IAChC,8BAA8B;IAC9B,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,4CAA4C;IAC5C,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,kBAAkB,CAAC,KAAK,EAAE,sBAAsB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAwDnG;AAED,MAAM,WAAW,mBAAmB;IAClC,OAAO,EAAE,oBAAoB,EAAE,CAAC;IAChC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;;GAKG;AACH,wBAAsB,mBAAmB,CAAC,KAAK,EAAE,sBAAsB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CA6BrG"}
@@ -180,6 +180,7 @@ async function unitCommandRuns(hook, input, work, outDir, waveArgs) {
180
180
  seconds: timed ? (end - start) / 1000 : 0,
181
181
  stdout: "",
182
182
  stderr: row ? why : "not in Terragrunt's run report, so it did not run",
183
+ ...(row ? {} : { error: "not in Terragrunt's run report, so it did not run" }),
183
184
  ...(timed ? { at: { start, end } } : {}),
184
185
  });
185
186
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/chant-lexicon-terraform",
3
- "version": "0.124.89",
3
+ "version": "0.124.91",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "src/",
@@ -93,7 +93,7 @@
93
93
  "access": "public"
94
94
  },
95
95
  "peerDependencies": {
96
- "@intentius/chant": "^0.124.89",
96
+ "@intentius/chant": "^0.124.91",
97
97
  "zod": "^4.3.6"
98
98
  },
99
99
  "description": "terraform lexicon for chant, existing Terraform root modules as declarable entities",
@@ -12,7 +12,7 @@ import { tmpdir } from "node:os";
12
12
  import { dirname, join } from "node:path";
13
13
  import { describe, expect, test } from "vitest";
14
14
  import { OtlpTrace } from "@intentius/chant/otlp";
15
- import { commandTrace, commandTraceEnv, engineRunner, withTerraformCommandHook, type TerraformCommand, type TerraformCommandResult } from "./engine-runner";
15
+ import { commandTrace, commandTraceEnv, composeCommandHooks, engineRunner, withTerraformCommandHook, type TerraformCommand, type TerraformCommandHook, type TerraformCommandResult } from "./engine-runner";
16
16
  import { engineTimings } from "./engine-timings";
17
17
  import type { BinaryExec } from "./state/exec";
18
18
  import { planTerragruntWave, terragruntUnitWrapper, type TerragruntExec } from "./terragrunt/run";
@@ -253,9 +253,95 @@ describe("a Terragrunt unit's plan", () => {
253
253
  return { code: 0, stdout: "", stderr: "" };
254
254
  };
255
255
  await planTerragruntWave({ dir, units: ["live/a"], workDir: "w", binary: bin, provisional: true, exec, onCommand: () => ({ after: (r) => void after.push(r) }) });
256
- expect(after).toMatchObject([{ code: null, seconds: 0 }]);
256
+ expect(after).toMatchObject([{ code: null, seconds: 0, error: "not in Terragrunt's run report, so it did not run" }]);
257
257
  let called = false;
258
258
  await planTerragruntWave({ dir, units: ["live/a"], workDir: "w2", provisional: true, exec, onCommand: () => void (called = true) });
259
259
  expect(called).toBe(false);
260
260
  });
261
261
  });
262
+
263
+ describe("what a product's own command trace read (chant#5007)", () => {
264
+ test("exec answers stderr apart, and a binary that could not be started as the spawn error", async () => {
265
+ const dir = tmp();
266
+ const bin = script(join(dir, "bin/tofu"), "echo out\necho err >&2\nexit 1");
267
+ const runner = engineRunner();
268
+ const ran = await runner.exec(bin, ["init"], dir, { ...JOB });
269
+ expect(ran).toMatchObject({ code: 1, stdout: "out\n", stderr: "err\n" });
270
+ expect(ran.error).toBeUndefined();
271
+ const missing = await runner.exec(join(dir, "missing"), ["init"], dir, { ...JOB });
272
+ expect(missing.code).toBe(127);
273
+ expect(missing.error).toMatch(/ENOENT/);
274
+ const sync = runner.execSync(bin, ["init"], dir, { ...JOB });
275
+ expect(sync).toMatchObject({ code: 1, stdout: "out\n", stderr: "err\n" });
276
+ expect(runner.execSync(join(dir, "missing"), ["init"], dir, { ...JOB }).error).toMatch(/ENOENT/);
277
+ });
278
+
279
+ test("a stage's own run is traced once, as the product's trace was: span, attributes, variables, exit and error", async () => {
280
+ const dir = tmp();
281
+ const record = join(dir, "env");
282
+ const bin = script(join(dir, "bin/tofu"), `echo "$TRACEPARENT $OTEL_RESOURCE_ATTRIBUTES $OTEL_TRACES_EXPORTER" >> '${record}'\n[ "$1" = "-chdir=${dir}" ] || exit 9\n[ "$2" = plan ] && exit 2\nexit 0`);
283
+ const trace = new OtlpTrace();
284
+ const root = trace.start("root roots/a", undefined, { "terragucci.root": "roots/a" });
285
+ const results: TerraformCommandResult[] = [];
286
+ // The product's own timing half, beside chant's trace.
287
+ const timing: TerraformCommandHook = () => ({ after: (r) => void results.push(r) });
288
+ const hook = composeCommandHooks(timing, commandTrace({ trace, prefix: "terragucci", parent: () => root, env: { OTEL_RESOURCE_ATTRIBUTES: "team=infra" } }));
289
+ const runner = engineRunner({ tokens: ["TG_TOKEN"] });
290
+ await withTerraformCommandHook(hook, { root: "roots/a", method: "plan" }, async () => {
291
+ expect((await runner.exec(bin, ["init", "-input=false"], dir, { ...JOB })).code).toBe(0);
292
+ expect((await runner.exec(bin, ["plan", "-out=p"], dir, { ...JOB })).code).toBe(2);
293
+ expect((await runner.exec(join(dir, "missing"), ["show"], dir, { ...JOB })).code).toBe(127);
294
+ });
295
+ const spans = trace.spans.filter((s) => s !== root);
296
+ expect(spans.map((s) => [s.name, s.parentSpanId, s.kind, s.attributes["process.executable.name"], s.attributes["process.command_args"], s.attributes["process.exit.code"]])).toEqual([
297
+ [`${bin} init`, root.spanId, 3, bin, "init -input=false", 0],
298
+ [`${bin} plan`, root.spanId, 3, bin, "plan -out=p", 2],
299
+ [`${join(dir, "missing")} show`, root.spanId, 3, join(dir, "missing"), "show", -1],
300
+ ]);
301
+ expect(spans[0]!.error).toBeUndefined();
302
+ expect(spans[1]!.error).toBeUndefined();
303
+ expect(spans[2]!.error).toMatch(/ENOENT/);
304
+ const lines = readFileSync(record, "utf-8").trim().split("\n");
305
+ expect(lines).toHaveLength(2);
306
+ expect(lines[0]).toContain(trace.traceparent(spans[0]!));
307
+ expect(lines[0]).toContain("team=infra");
308
+ expect(lines[0]).toContain(`terragucci.span_id=${spans[0]!.spanId}`);
309
+ expect(lines[0]).toContain("terragucci.root=roots%2Fa");
310
+ expect(lines[0]!.endsWith(" otlp")).toBe(true);
311
+ expect(results.map((r) => [r.code, r.error === undefined ? undefined : /ENOENT/.test(r.error)])).toEqual([
312
+ [0, undefined],
313
+ [2, undefined],
314
+ [null, true],
315
+ ]);
316
+ });
317
+
318
+ test("composeCommandHooks calls each hook in turn over the variables before it, and every after even when one throws", async () => {
319
+ const order: string[] = [];
320
+ const seenEnv: Array<Record<string, string>> = [];
321
+ const hook = composeCommandHooks(
322
+ (c) => {
323
+ seenEnv.push({ ...c.env });
324
+ return { env: { A: "1", OTEL_RESOURCE_ATTRIBUTES: "first=1" }, after: () => void order.push("first") };
325
+ },
326
+ undefined,
327
+ (c) => {
328
+ seenEnv.push({ ...c.env });
329
+ return {
330
+ env: { B: "2" },
331
+ after: () => {
332
+ order.push("second");
333
+ throw new Error("second failed");
334
+ },
335
+ };
336
+ },
337
+ () => ({ after: () => void order.push("third") }),
338
+ );
339
+ const base: TerraformCommand = { root: "r", method: "plan", binary: "tofu", name: "plan", args: ["plan"], line: "tofu plan", cwd: "/w", env: { TF_IN_AUTOMATION: "1" } };
340
+ const run = await hook(base);
341
+ expect(seenEnv).toEqual([{ TF_IN_AUTOMATION: "1" }, { TF_IN_AUTOMATION: "1", A: "1", OTEL_RESOURCE_ATTRIBUTES: "first=1" }]);
342
+ expect(run?.env).toEqual({ A: "1", OTEL_RESOURCE_ATTRIBUTES: "first=1", B: "2" });
343
+ await expect(run!.after!({ code: 0, seconds: 1, stdout: "", stderr: "" })).rejects.toThrow("second failed");
344
+ expect(order).toEqual(["first", "second", "third"]);
345
+ expect(await composeCommandHooks(() => undefined)(base)).toBeUndefined();
346
+ });
347
+ });
@@ -15,7 +15,13 @@
15
15
  * - {@link commandTrace} is a `TerraformCommandHook` that opens a span per
16
16
  * engine command under the product's span for its root, and gives the
17
17
  * command `TRACEPARENT` and the resource attributes that name the span
18
- * ({@link commandTraceEnv}). Pass it as `engineTimings({ inner })`.
18
+ * ({@link commandTraceEnv}). Pass it as `engineTimings({ inner })`, or
19
+ * beside a product's own hook through `composeCommandHooks` (chant#5007).
20
+ *
21
+ * Every run `exec` makes answers its stderr apart (`Ran.stderr`) and, for a
22
+ * binary that could not be started, the spawn error (`Ran.error`), which the
23
+ * hook's `after` gets as a null code with `error` and `commandTrace` puts on
24
+ * the span (chant#5007).
19
25
  *
20
26
  * A Terragrunt unit's plan reaches the same hook through
21
27
  * `planTerragruntWave({ onCommand })` (`./terragrunt/run.ts`).
@@ -35,7 +41,7 @@ import { hookedBinaryExec, type TerraformCommand, type TerraformCommandHook } fr
35
41
  import { engineEnv, runBinary, tokenlessBinaryExec, type BinaryExec, type Ran } from "./state/exec";
36
42
  import type { TerragruntExec } from "./terragrunt/run";
37
43
 
38
- export { withTerraformCommandHook, asUpstreamCommands, type TerraformCommand, type TerraformCommandHook, type TerraformCommandResult, type TerraformCommandRun } from "./op/command-hook";
44
+ export { withTerraformCommandHook, asUpstreamCommands, composeCommandHooks, type TerraformCommand, type TerraformCommandHook, type TerraformCommandResult, type TerraformCommandRun } from "./op/command-hook";
39
45
 
40
46
  /** A run of the binary that blocks: `-chdir=<dir>`, `TF_IN_AUTOMATION=1`, as {@link runBinary} runs it. */
41
47
  export type BinaryExecSync = (binary: string, args: string[], dir: string, env: NodeJS.ProcessEnv) => Ran;
@@ -102,7 +108,9 @@ export function engineRunner(options: EngineRunnerOptions = {}): EngineRunner {
102
108
  const execSync: BinaryExecSync = (binary, args, dir, given) => {
103
109
  const p = spawnSync(binary, [`-chdir=${dir}`, ...args], { encoding: "utf-8", env: { ...env(given), TF_IN_AUTOMATION: "1" }, maxBuffer: 512 * 1024 * 1024 });
104
110
  const stdout = p.stdout ?? "";
105
- return { code: p.error && p.status === null ? 127 : (p.status ?? 1), stdout, out: `${stdout}${p.stderr ?? ""}${p.error ? p.error.message : ""}` };
111
+ const stderr = p.stderr ?? "";
112
+ const error = p.error && p.status === null ? { error: p.error.message } : {};
113
+ return { code: p.error && p.status === null ? 127 : (p.status ?? 1), stdout, out: `${stdout}${stderr}${p.error ? p.error.message : ""}`, stderr, ...error };
106
114
  };
107
115
  const terragrunt: TerragruntExec = (file, args, opts) =>
108
116
  new Promise((done) => {
@@ -170,7 +178,9 @@ export interface CommandTraceOptions {
170
178
  * `process.command_args`) under `parent(command)`, the variables
171
179
  * {@link commandTraceEnv} gives for it, and the span ended with
172
180
  * `process.exit.code` once the command ends, failed unless it exited 0 (or 2
173
- * for a `plan`, `-detailed-exitcode`'s changes). A command timed apart from
181
+ * for a `plan`, `-detailed-exitcode`'s changes), its error the result's
182
+ * `error` when the command did not exit (a binary that could not be started,
183
+ * chant#5007), `exit <code>` otherwise. A command timed apart from
174
184
  * its call (`at`, a Terragrunt unit's plan) spans the time it ran. Pass it as
175
185
  * `engineTimings({ inner })`, so the engine's spans join the trace and reach
176
186
  * the timings' receiver.
@@ -184,7 +194,7 @@ export function commandTrace(options: CommandTraceOptions): TerraformCommandHook
184
194
  after: (r) => {
185
195
  if (r.at) span.start = BigInt(Math.round(r.at.start)) * 1_000_000n;
186
196
  const ok = r.code === 0 || (c.name === "plan" && r.code === 2);
187
- options.trace.end(span, { "process.exit.code": r.code ?? -1 }, ok ? undefined : `exit ${r.code}`, r.at?.end);
197
+ options.trace.end(span, { "process.exit.code": r.code ?? -1 }, ok ? undefined : r.code === null && r.error ? r.error : `exit ${r.code}`, r.at?.end);
188
198
  },
189
199
  };
190
200
  };
@@ -55,6 +55,12 @@ export interface TerraformCommandResult {
55
55
  * from the hook's call to its `after`.
56
56
  */
57
57
  at?: { start: number; end: number };
58
+ /**
59
+ * Why the command did not exit on its own, when `code` is null (chant#5007):
60
+ * the spawn error's message for a binary that could not be started, the
61
+ * error a run threw, or why a Terragrunt unit did not run.
62
+ */
63
+ error?: string;
58
64
  }
59
65
 
60
66
  /** What a {@link TerraformCommandHook} answers for one command (chant#4865). */
@@ -151,16 +157,58 @@ export function hookedBinaryExec(exec: BinaryExec): BinaryExec {
151
157
  try {
152
158
  ran = await exec(binary, args, dir, given.env ? { ...env, ...given.env } : env, io);
153
159
  } catch (err) {
154
- await given.after?.({ code: null, seconds: (performance.now() - start) / 1000, stdout: "", stderr: err instanceof Error ? err.message : String(err) });
160
+ const message = err instanceof Error ? err.message : String(err);
161
+ await given.after?.({ code: null, seconds: (performance.now() - start) / 1000, stdout: "", stderr: message, error: message });
155
162
  throw err;
156
163
  }
157
- // `out` holds stdout and stderr together, as they came; stderr alone is what is left once stdout is taken out of it.
158
- const stderr = ran.out.startsWith(ran.stdout) ? ran.out.slice(ran.stdout.length) : ran.out;
159
- await given.after?.({ code: ran.code, seconds: (performance.now() - start) / 1000, stdout: ran.stdout, stderr });
164
+ // `out` holds stdout and stderr together, as they came; an exec that does not keep stderr apart leaves what is left once stdout is taken out of it.
165
+ const stderr = ran.stderr ?? (ran.out.startsWith(ran.stdout) ? ran.out.slice(ran.stdout.length) : ran.out);
166
+ // A binary that could not be started did not exit (chant#5007): its code is the hook's null, with the spawn error's message.
167
+ const failed = ran.error !== undefined ? { code: null, error: ran.error } : { code: ran.code };
168
+ await given.after?.({ ...failed, seconds: (performance.now() - start) / 1000, stdout: ran.stdout, stderr });
160
169
  return ran;
161
170
  };
162
171
  }
163
172
 
173
+ /**
174
+ * Several command hooks as one (chant#5007), such as a product's own timing
175
+ * hook and `commandTrace`, for a step that takes one `onCommand`. Each is
176
+ * called in turn and sees the command with the variables the hooks before
177
+ * it answered laid over its `env`, so a hook that reads the command's
178
+ * `OTEL_RESOURCE_ATTRIBUTES` keeps what an earlier one set; the variables
179
+ * they answer are laid over each other in the same order. Once the command
180
+ * ends every `after` is called in the same order, all of them even when
181
+ * one throws, and the first error is thrown after the last. An undefined
182
+ * hook is left out.
183
+ */
184
+ export function composeCommandHooks(...hooks: Array<TerraformCommandHook | undefined>): TerraformCommandHook {
185
+ const list = hooks.filter((h): h is TerraformCommandHook => h !== undefined);
186
+ return async (command) => {
187
+ const runs: TerraformCommandRun[] = [];
188
+ let env: Record<string, string> = {};
189
+ for (const hook of list) {
190
+ const run = (await hook(Object.keys(env).length > 0 ? { ...command, env: { ...command.env, ...env } } : command)) ?? {};
191
+ runs.push(run);
192
+ if (run.env) env = { ...env, ...run.env };
193
+ }
194
+ if (runs.every((r) => !r.env && !r.after)) return;
195
+ return {
196
+ ...(Object.keys(env).length > 0 ? { env } : {}),
197
+ after: async (result) => {
198
+ let first: { error: unknown } | undefined;
199
+ for (const run of runs) {
200
+ try {
201
+ await run.after?.(result);
202
+ } catch (error) {
203
+ first ??= { error };
204
+ }
205
+ }
206
+ if (first) throw first.error;
207
+ },
208
+ };
209
+ };
210
+ }
211
+
164
212
  /** A word single-quoted for a shell, as `quoteArg` writes it. */
165
213
  const quoteWord = (w: string): string => `'${w.replace(/'/g, `'\\''`)}'`;
166
214
 
@@ -0,0 +1,72 @@
1
+ /**
2
+ * What a change reaches (#4984), moved from terragucci's comment-apply.ts:
3
+ * roots with the reads the product hands, Terragrunt units from their
4
+ * plain dependency paths at both ends of the range, Atmos instances by
5
+ * component, and synthesized roots.
6
+ */
7
+
8
+ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { join } from "node:path";
11
+ import { describe, expect, test } from "vitest";
12
+ import { literalTerragruntDependencies, reachedInstances, reachedRoots, reachedSynthesized, reachedUnits, type ReachGit } from "./reach";
13
+
14
+ /** Git that answers the diff with `files` and each `show <ref>:<path>` from `shows`. */
15
+ const fakeGit = (files: string[] | null, shows: Record<string, string> = {}): ReachGit => (args) => {
16
+ if (args[0] === "diff") return files === null ? { status: 128, stdout: "", stderr: "bad range" } : { status: 0, stdout: files.join("\n"), stderr: "" };
17
+ if (args[0] === "show") {
18
+ const text = shows[args[1]!.replace(/^[^:]*:/, "")];
19
+ return text === undefined ? { status: 128, stdout: "", stderr: "no such path" } : { status: 0, stdout: text, stderr: "" };
20
+ }
21
+ return { status: 1, stdout: "", stderr: "unexpected" };
22
+ };
23
+
24
+ describe("reachedRoots", () => {
25
+ const repo = mkdtempSync(join(tmpdir(), "chant-reach-"));
26
+ for (const r of ["net", "app", "dns"]) {
27
+ mkdirSync(join(repo, r), { recursive: true });
28
+ writeFileSync(join(repo, r, "main.tf"), "");
29
+ }
30
+ const reads = new Map([["app", new Set(["net"])], ["dns", new Set(["app"])]]);
31
+
32
+ test("a changed root, and every root that reads it, followed through", () => {
33
+ expect(reachedRoots(repo, fakeGit(["net/main.tf"]), "a", "b", ["net", "app", "dns"], reads)).toEqual({ targets: ["app", "dns", "net"] });
34
+ expect(reachedRoots(repo, fakeGit(["dns/main.tf"]), "a", "b", ["net", "app", "dns"], reads)).toEqual({ targets: ["dns"] });
35
+ });
36
+
37
+ test("every root when git cannot diff the range", () => {
38
+ expect(reachedRoots(repo, fakeGit(null), "a", "b", ["net", "app"])).toEqual({ targets: ["app", "net"], every: "git could not list the files it changes" });
39
+ });
40
+ });
41
+
42
+ describe("reachedUnits", () => {
43
+ const hcl = (dep: string) => `dependency "up" {\n config_path = "${dep}"\n}\n`;
44
+
45
+ test("a changed unit and the units that name it, at either end of the range", () => {
46
+ const git = fakeGit(["live/vpc/main.tf"], { "live/app/terragrunt.hcl": hcl("../vpc"), "live/vpc/terragrunt.hcl": "" });
47
+ expect(reachedUnits(git, "a", "b", ["live/vpc", "live/app", "live/dns"])).toEqual({ targets: ["live/app", "live/vpc"] });
48
+ });
49
+
50
+ test("a file in no unit's directory reaches every unit, and Markdown reaches nothing", () => {
51
+ expect(reachedUnits(fakeGit(["root.hcl"]), "a", "b", ["x", "y"])).toEqual({ targets: ["x", "y"], every: "it changes `root.hcl`, which is in no unit's directory" });
52
+ expect(reachedUnits(fakeGit(["README.md"]), "a", "b", ["x", "y"])).toEqual({ targets: [] });
53
+ });
54
+
55
+ test("only plain dependency paths are read", () => {
56
+ expect(literalTerragruntDependencies(`${'dependency "a" {\n config_path = "../a"\n}\n'}dependencies {\n paths = ["../b", "\${local.c}"]\n}\n# dependency "z" { config_path = "../z" }`)).toEqual(["../a", "../b"]);
57
+ });
58
+ });
59
+
60
+ describe("reachedInstances and reachedSynthesized", () => {
61
+ test("an instance by its component, the ones that read it, and a manifest that reaches every one", () => {
62
+ const componentOf = new Map([["vpc-prod", "components/terraform/vpc"], ["app-prod", "components/terraform/app"]]);
63
+ const reads = new Map([["app-prod", new Set(["vpc-prod"])]]);
64
+ expect(reachedInstances(fakeGit(["components/terraform/vpc/main.tf"]), "a", "b", ["vpc-prod", "app-prod"], componentOf, reads)).toEqual({ targets: ["app-prod", "vpc-prod"] });
65
+ expect(reachedInstances(fakeGit(["stacks/prod.yaml"]), "a", "b", ["vpc-prod", "app-prod"], componentOf).every).toBe("it changes `stacks/prod.yaml`, which can change any Atmos instance");
66
+ });
67
+
68
+ test("synthesized roots: any file but Markdown reaches every root", () => {
69
+ expect(reachedSynthesized(fakeGit(["docs/a.md"]), "a", "b", ["s1", "s2"])).toEqual({ targets: [] });
70
+ expect(reachedSynthesized(fakeGit(["main.ts"]), "a", "b", ["s2", "s1"])).toEqual({ targets: ["s1", "s2"], every: "it changes `main.ts`, and the synth command writes every root from the repo's files" });
71
+ });
72
+ });
package/src/reach.ts ADDED
@@ -0,0 +1,196 @@
1
+ /**
2
+ * What a change reaches (#4984), beside ./changed-roots.ts: the roots,
3
+ * Terragrunt units, Atmos instances or synthesized roots a change from
4
+ * `from` to `to` reaches, read from git alone. Moved from terragucci's
5
+ * `reachedRoots`, `reachedUnits`, `reachedInstances` and
6
+ * `reachedSynthesized` (comment-apply.ts), for a product's reach line
7
+ * (`productPlan.reach`, #4979): the lock job and the decision before merge
8
+ * run it at the target branch's commit, so none of the change's code runs.
9
+ *
10
+ * Each follows what reads a reached target: a root that reads a reached
11
+ * root's state, a unit that names a reached unit in a `dependency` or
12
+ * `dependencies` block, an instance that depends on a reached one, followed
13
+ * through. The product hands the reads it knows (terragucci's
14
+ * `terraform_remote_state` edges and `waves.after`, Atmos's dependencies);
15
+ * the Terragrunt unit reads are parsed here, at both ends of the range.
16
+ * Markdown files reach nothing. When a change can reach anything, or git
17
+ * cannot diff the range, every target is reached and `every` says why.
18
+ */
19
+
20
+ import { posix } from "node:path";
21
+ import { changedRoots } from "./changed-roots";
22
+
23
+ /** Git in a checkout: an argv after `git`, and what it answered. */
24
+ export type ReachGit = (args: string[]) => { status: number | null; stdout: string; stderr: string };
25
+
26
+ /** What a change reaches, sorted, and why it is every target when it is. */
27
+ export interface Reach {
28
+ targets: string[];
29
+ every?: string;
30
+ }
31
+
32
+ /** The targets each target reads, so a change to one of those reaches it too. */
33
+ export type ReachReads = ReadonlyMap<string, ReadonlySet<string>>;
34
+
35
+ /** Changed files that reach nothing: documentation. */
36
+ export const READS_NOTHING = /\.md$/i;
37
+
38
+ /** The files the change from `from` to `to` changes (`git diff --name-only from...to`), or undefined when git cannot say. */
39
+ export function changedFilesBetween(git: ReachGit, from: string, to: string): string[] | undefined {
40
+ const diff = git(["diff", "--name-only", "--no-renames", `${from}...${to}`]);
41
+ if (diff.status !== 0) return undefined;
42
+ return diff.stdout.split("\n").map((l) => l.trim()).filter(Boolean);
43
+ }
44
+
45
+ /** Add to `selected` every target that reads a selected one, followed through. */
46
+ export function followReads(selected: Set<string>, reads: ReachReads | undefined): void {
47
+ if (!reads) return;
48
+ for (let grew = true; grew; ) {
49
+ grew = false;
50
+ for (const [target, from] of reads) {
51
+ if (!selected.has(target) && [...from].some((d) => selected.has(d))) {
52
+ selected.add(target);
53
+ grew = true;
54
+ }
55
+ }
56
+ }
57
+ }
58
+
59
+ const sorted = (xs: Iterable<string>): string[] => [...new Set(xs)].sort();
60
+
61
+ /**
62
+ * The plain roots a change reaches: the roots whose files it changes, by
63
+ * chant's path rules (./changed-roots.ts: a root's directory, the local
64
+ * modules it calls, its var files), and every root that reads one of those.
65
+ * Every root when git cannot diff the range.
66
+ */
67
+ export function reachedRoots(repo: string, git: ReachGit, from: string, to: string, roots: readonly string[], reads?: ReachReads): Reach {
68
+ const all = sorted(roots);
69
+ const files = changedFilesBetween(git, from, to);
70
+ if (files === undefined) return { targets: all, every: "git could not list the files it changes" };
71
+ const selected = new Set(changedRoots(repo, Object.fromEntries(all.map((r) => [r, { dir: r }])), files));
72
+ followReads(selected, reads);
73
+ return { targets: [...selected].filter((r) => all.includes(r)).sort() };
74
+ }
75
+
76
+ /** The body of each top-level `<keyword> ... {` block in HCL text, braces matched, strings skipped. */
77
+ function hclBlocks(text: string, keyword: string): string[] {
78
+ const out: string[] = [];
79
+ const head = new RegExp(`^\\s*${keyword}\\b[^{\\n]*\\{`, "gm");
80
+ for (let m = head.exec(text); m; m = head.exec(text)) {
81
+ let depth = 1;
82
+ let i = m.index + m[0].length;
83
+ const start = i;
84
+ for (let quoted = false; i < text.length && depth > 0; i++) {
85
+ const c = text[i];
86
+ if (quoted) {
87
+ if (c === "\\") i++;
88
+ else if (c === '"') quoted = false;
89
+ } else if (c === '"') quoted = true;
90
+ else if (c === "{") depth++;
91
+ else if (c === "}") depth--;
92
+ }
93
+ out.push(text.slice(start, i - 1));
94
+ head.lastIndex = i;
95
+ }
96
+ return out;
97
+ }
98
+
99
+ /**
100
+ * The paths a unit's `terragrunt.hcl` names in its `dependency` blocks'
101
+ * `config_path` and its `dependencies` block's `paths`, when each is a plain
102
+ * string. A path built with a function or an interpolation is not read:
103
+ * only Terragrunt can evaluate it, and no Terragrunt runs on a change's
104
+ * files before a review.
105
+ */
106
+ export function literalTerragruntDependencies(text: string): string[] {
107
+ const clean = text.replace(/(^|[^:"$])(#|\/\/).*$/gm, "$1");
108
+ const plain = /^"([^"$]*)"$/;
109
+ const out: string[] = [];
110
+ for (const b of hclBlocks(clean, "dependency")) {
111
+ const m = /^\s*config_path\s*=\s*("[^"\n]*")\s*$/m.exec(b);
112
+ const p = m && plain.exec(m[1]!);
113
+ if (p) out.push(p[1]!);
114
+ }
115
+ for (const b of hclBlocks(clean, "dependencies")) {
116
+ const m = /\bpaths\s*=\s*\[([^\]]*)\]/.exec(b);
117
+ for (const item of m ? m[1]!.split(",").map((x) => x.trim()).filter(Boolean) : []) {
118
+ const p = plain.exec(item);
119
+ if (p) out.push(p[1]!);
120
+ }
121
+ }
122
+ return out;
123
+ }
124
+
125
+ /**
126
+ * The Terragrunt units a change reaches. A unit is reached when a file
127
+ * under its directory changes (the deepest unit holding the file), and so
128
+ * is every unit that names a reached one with a plain path, at either end
129
+ * of the range. A changed file under no unit's directory (`root.hcl`, a
130
+ * module, a stack template) may change any unit, so it reaches every one.
131
+ */
132
+ export function reachedUnits(git: ReachGit, from: string, to: string, units: readonly string[]): Reach {
133
+ const all = sorted(units);
134
+ const files0 = changedFilesBetween(git, from, to);
135
+ if (files0 === undefined) return { targets: all, every: "git could not list the files it changes" };
136
+ const files = files0.filter((f) => !READS_NOTHING.test(f));
137
+ const deepest = [...all].sort((a, b) => b.length - a.length);
138
+ const selected = new Set<string>();
139
+ for (const f of files) {
140
+ const u = deepest.find((d) => f.startsWith(`${d}/`));
141
+ if (!u) return { targets: all, every: `it changes \`${f}\`, which is in no unit's directory` };
142
+ selected.add(u);
143
+ }
144
+ const reads = new Map<string, Set<string>>();
145
+ for (const u of all) {
146
+ const deps = new Set<string>();
147
+ for (const ref of [from, to]) {
148
+ const shown = git(["show", `${ref}:${u}/terragrunt.hcl`]);
149
+ if (shown.status !== 0) continue;
150
+ for (const p of literalTerragruntDependencies(shown.stdout)) deps.add(posix.normalize(posix.join(u, p)).replace(/\/+$/, ""));
151
+ }
152
+ reads.set(u, deps);
153
+ }
154
+ followReads(selected, reads);
155
+ return { targets: [...selected].sort() };
156
+ }
157
+
158
+ /**
159
+ * The Atmos instances a change reaches. `componentOf` names each instance's
160
+ * component directory. A changed file under one reaches that component's
161
+ * instances; any other file (a stack manifest, a catalog, `atmos.yaml`) can
162
+ * change any instance's vars or backend, so it reaches every instance.
163
+ * Instances that read a reached one follow.
164
+ */
165
+ export function reachedInstances(git: ReachGit, from: string, to: string, instances: readonly string[], componentOf: ReadonlyMap<string, string | undefined>, reads?: ReachReads): Reach {
166
+ const all = sorted(instances);
167
+ const files0 = changedFilesBetween(git, from, to);
168
+ if (files0 === undefined) return { targets: all, every: "git could not list the files it changes" };
169
+ const files = files0.filter((f) => !READS_NOTHING.test(f));
170
+ const selected = new Set<string>();
171
+ for (const f of files) {
172
+ const owners = all.filter((r) => {
173
+ const c = componentOf.get(r)?.replace(/\/+$/, "");
174
+ return c !== undefined && f.startsWith(`${c}/`);
175
+ });
176
+ if (owners.length === 0) return { targets: all, every: `it changes \`${f}\`, which can change any Atmos instance` };
177
+ for (const r of owners) selected.add(r);
178
+ }
179
+ followReads(selected, reads);
180
+ return { targets: [...selected].sort() };
181
+ }
182
+
183
+ /**
184
+ * The roots a change reaches when a command writes them (`synth`, CDK
185
+ * Terrain's stacks). The roots are not in git, so no diff names them, and
186
+ * the command is the change's own code: any changed file that is not
187
+ * Markdown can change any root.
188
+ */
189
+ export function reachedSynthesized(git: ReachGit, from: string, to: string, roots: readonly string[]): Reach {
190
+ const all = sorted(roots);
191
+ const files = changedFilesBetween(git, from, to);
192
+ if (files === undefined) return { targets: all, every: "git could not list the files it changes" };
193
+ const file = files.find((f) => !READS_NOTHING.test(f));
194
+ if (file === undefined) return { targets: [] };
195
+ return { targets: all, every: `it changes \`${file}\`, and the synth command writes every root from the repo's files` };
196
+ }
package/src/state/exec.ts CHANGED
@@ -13,6 +13,10 @@ export interface Ran {
13
13
  stdout: string;
14
14
  /** stdout and stderr together, as they came. */
15
15
  out: string;
16
+ /** stderr alone, less the lines `io.stderr` took (chant#5007). {@link runBinary} sets it; an exec of a product's or a test's may leave it out. */
17
+ stderr?: string;
18
+ /** Why the binary did not run, when it could not be started: the spawn error's message (chant#5007). `code` is then 127. */
19
+ error?: string;
16
20
  }
17
21
 
18
22
  /** What a run of the binary hands back while it runs: `stderr` sees each line of stderr as it arrives, and a line it takes (true) is left out of `out`. */
@@ -28,6 +32,7 @@ export const runBinary: BinaryExec = (binary, args, dir, env, io) =>
28
32
  new Promise((done) => {
29
33
  const child = spawn(binary, [`-chdir=${dir}`, ...args], { env: { ...env, TF_IN_AUTOMATION: "1" }, stdio: ["ignore", "pipe", "pipe"] });
30
34
  let stdout = "";
35
+ let stderr = "";
31
36
  let out = "";
32
37
  let partial = "";
33
38
  const stderrLine = (line: string): void => {
@@ -37,7 +42,10 @@ export const runBinary: BinaryExec = (binary, args, dir, env, io) =>
37
42
  } catch {
38
43
  taken = false;
39
44
  }
40
- if (!taken) out += `${line}\n`;
45
+ if (!taken) {
46
+ out += `${line}\n`;
47
+ stderr += `${line}\n`;
48
+ }
41
49
  };
42
50
  child.stdout.on("data", (d) => {
43
51
  stdout += d;
@@ -48,6 +56,7 @@ export const runBinary: BinaryExec = (binary, args, dir, env, io) =>
48
56
  child.stderr.on("data", (d) => {
49
57
  if (!io?.stderr) {
50
58
  out += d;
59
+ stderr += d;
51
60
  return;
52
61
  }
53
62
  partial += d;
@@ -61,11 +70,11 @@ export const runBinary: BinaryExec = (binary, args, dir, env, io) =>
61
70
  };
62
71
  child.on("error", (e) => {
63
72
  rest();
64
- done({ code: 127, stdout, out: `${out}${e.message}` });
73
+ done({ code: 127, stdout, out: `${out}${e.message}`, stderr, error: e.message });
65
74
  });
66
75
  child.on("close", (code) => {
67
76
  rest();
68
- done({ code: code ?? 1, stdout, out });
77
+ done({ code: code ?? 1, stdout, out, stderr });
69
78
  });
70
79
  });
71
80
 
@@ -290,6 +290,7 @@ async function unitCommandRuns(
290
290
  seconds: timed ? (end - start) / 1000 : 0,
291
291
  stdout: "",
292
292
  stderr: row ? why : "not in Terragrunt's run report, so it did not run",
293
+ ...(row ? {} : { error: "not in Terragrunt's run report, so it did not run" }),
293
294
  ...(timed ? { at: { start, end } } : {}),
294
295
  });
295
296
  }