@intentius/chant-lexicon-terraform 0.124.87 → 0.124.89

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.
Files changed (82) hide show
  1. package/dist/action-ops.d.ts.map +1 -1
  2. package/dist/action-ops.js +3 -1
  3. package/dist/chant-floors.d.ts +30 -0
  4. package/dist/chant-floors.d.ts.map +1 -0
  5. package/dist/chant-floors.js +29 -0
  6. package/dist/components/capability-plugin.d.ts +15 -1
  7. package/dist/components/capability-plugin.d.ts.map +1 -1
  8. package/dist/components/capability-plugin.js +13 -5
  9. package/dist/components/compose-group.d.ts +5 -1
  10. package/dist/components/compose-group.d.ts.map +1 -1
  11. package/dist/components/compose-group.js +7 -4
  12. package/dist/engine-runner.d.ts +86 -0
  13. package/dist/engine-runner.d.ts.map +1 -0
  14. package/dist/engine-runner.js +134 -0
  15. package/dist/engine-timings.d.ts +249 -0
  16. package/dist/engine-timings.d.ts.map +1 -0
  17. package/dist/engine-timings.js +569 -0
  18. package/dist/integrity.json +2 -2
  19. package/dist/live-roots.d.ts +143 -0
  20. package/dist/live-roots.d.ts.map +1 -0
  21. package/dist/live-roots.js +304 -0
  22. package/dist/manifest.json +1 -1
  23. package/dist/migration-history.d.ts +105 -0
  24. package/dist/migration-history.d.ts.map +1 -0
  25. package/dist/migration-history.js +159 -0
  26. package/dist/module-catalog/index.d.ts +1 -0
  27. package/dist/module-catalog/index.d.ts.map +1 -1
  28. package/dist/module-catalog/index.js +3 -1
  29. package/dist/op/activities/live-detect.d.ts +15 -0
  30. package/dist/op/activities/live-detect.d.ts.map +1 -1
  31. package/dist/op/activities/live-detect.js +94 -0
  32. package/dist/op/activities/terraform.d.ts +1 -65
  33. package/dist/op/activities/terraform.d.ts.map +1 -1
  34. package/dist/op/activities/terraform.js +4 -54
  35. package/dist/op/command-hook.d.ts +98 -0
  36. package/dist/op/command-hook.d.ts.map +1 -0
  37. package/dist/op/command-hook.js +115 -0
  38. package/dist/registry/index.d.ts +1 -0
  39. package/dist/registry/index.d.ts.map +1 -1
  40. package/dist/registry/index.js +1 -0
  41. package/dist/state/exec.d.ts +23 -0
  42. package/dist/state/exec.d.ts.map +1 -1
  43. package/dist/state/exec.js +38 -0
  44. package/dist/state-ops.d.ts.map +1 -1
  45. package/dist/state-ops.js +3 -1
  46. package/dist/terragrunt/index.d.ts +3 -1
  47. package/dist/terragrunt/index.d.ts.map +1 -1
  48. package/dist/terragrunt/index.js +3 -1
  49. package/dist/terragrunt/place.d.ts +27 -0
  50. package/dist/terragrunt/place.d.ts.map +1 -0
  51. package/dist/terragrunt/place.js +52 -0
  52. package/dist/terragrunt/run.d.ts +23 -0
  53. package/dist/terragrunt/run.d.ts.map +1 -1
  54. package/dist/terragrunt/run.js +107 -3
  55. package/package.json +2 -2
  56. package/src/action-ops.ts +3 -1
  57. package/src/chant-floors.ts +32 -0
  58. package/src/components/capability-plugin.ts +27 -6
  59. package/src/components/compose-group.test.ts +29 -0
  60. package/src/components/compose-group.ts +12 -5
  61. package/src/components/terraform-apply-command-hook.test.ts +43 -0
  62. package/src/engine-runner.test.ts +261 -0
  63. package/src/engine-runner.ts +191 -0
  64. package/src/engine-timings.test.ts +203 -0
  65. package/src/engine-timings.ts +718 -0
  66. package/src/live-record-store.test.ts +76 -0
  67. package/src/live-roots.test.ts +80 -0
  68. package/src/live-roots.ts +347 -0
  69. package/src/migration-history.test.ts +83 -0
  70. package/src/migration-history.ts +199 -0
  71. package/src/module-catalog/index.ts +4 -1
  72. package/src/op/activities/live-detect.ts +87 -0
  73. package/src/op/activities/terraform.ts +12 -111
  74. package/src/op/command-hook.ts +189 -0
  75. package/src/registry/index.ts +1 -0
  76. package/src/state/engine-env.test.ts +18 -0
  77. package/src/state/exec.ts +38 -0
  78. package/src/state-ops.ts +3 -1
  79. package/src/terragrunt/index.ts +3 -1
  80. package/src/terragrunt/place.test.ts +42 -0
  81. package/src/terragrunt/place.ts +75 -0
  82. package/src/terragrunt/run.ts +128 -4
package/src/state/exec.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  * `BinaryExec`, `runBinary`, `StateFile`, `StateResource` and `pullState`.
7
7
  */
8
8
  import { spawn } from "node:child_process";
9
+ import { FORGE_TOKEN_VARS } from "@intentius/chant/ci-handover";
9
10
 
10
11
  export interface Ran {
11
12
  code: number;
@@ -68,6 +69,43 @@ export const runBinary: BinaryExec = (binary, args, dir, env, io) =>
68
69
  });
69
70
  });
70
71
 
72
+ /**
73
+ * `env` without the forge's tokens, for the engine (chant#4910): the
74
+ * providers, modules and external data sources the binary runs are the
75
+ * change's own code, and none of it needs the forge's API. Left out: chant's
76
+ * {@link FORGE_TOKEN_VARS}, the product's own token variables (`tokens`,
77
+ * such as terragucci's `TG_TOKEN` and `TG_MERGE_TOKEN`), and any other
78
+ * variable holding the same value as one of them (GitLab's `GITLAB_TOKEN`
79
+ * set from the product's, or a variable a product's `token_env` names). A
80
+ * variable whose name starts with `TF_` is passed as set, so a backend
81
+ * password or a `TF_VAR_` given to the binary on purpose still reaches it.
82
+ *
83
+ * Lifted from terragucci's `binaryEnv` (binary-env.ts).
84
+ */
85
+ export function engineEnv(env: NodeJS.ProcessEnv, tokens: readonly string[] = []): NodeJS.ProcessEnv {
86
+ const names = new Set<string>([...FORGE_TOKEN_VARS, ...tokens]);
87
+ const secrets = new Set([...names].map((n) => env[n]).filter((v): v is string => typeof v === "string" && v.length > 0));
88
+ const out: NodeJS.ProcessEnv = {};
89
+ for (const [k, v] of Object.entries(env)) {
90
+ if (names.has(k)) continue;
91
+ if (v !== undefined && secrets.has(v) && !k.startsWith("TF_")) continue;
92
+ out[k] = v;
93
+ }
94
+ return out;
95
+ }
96
+
97
+ /**
98
+ * {@link runBinary} with the forge's tokens left out of the binary's
99
+ * environment ({@link engineEnv}), `tokens` naming the product's own
100
+ * (chant#4910). A product that ran the binary through its own wrapper over
101
+ * `runBinary` passes this one wherever a `BinaryExec` is taken. `runBinary`
102
+ * itself still passes the environment as given, since a project's provider
103
+ * may read a forge token on purpose (the GitHub provider reads `GITHUB_TOKEN`).
104
+ */
105
+ export function tokenlessBinaryExec(tokens: readonly string[] = [], exec: BinaryExec = runBinary): BinaryExec {
106
+ return (binary, args, dir, env, io) => exec(binary, args, dir, engineEnv(env, tokens), io);
107
+ }
108
+
71
109
  /** A state file as `state pull` prints it (format version 4); only what a run touches is named. */
72
110
  export interface StateFile {
73
111
  version: number;
package/src/state-ops.ts CHANGED
@@ -52,6 +52,7 @@ import { gitlabStore, shownUrl, type GitLabFetch } from "./state/gitlab";
52
52
  import type { StoreFetch } from "./state/object-store";
53
53
  import { stateStore } from "./state/store";
54
54
  import { gitlabVersionSource, stateVersionSource } from "./state/versions";
55
+ import { actorFromEnv } from "@intentius/chant/actor";
55
56
 
56
57
  /** The ops the gated requests of this module wait at, one per kind, as terragucci named them. */
57
58
  export const STATE_OPS = {
@@ -377,7 +378,8 @@ export interface CopyStepInput {
377
378
  lockTimeout?: string | false;
378
379
  }
379
380
 
380
- const actorOf = (env: NodeJS.ProcessEnv): string => env.GITHUB_ACTOR || env.GITLAB_USER_LOGIN || env.USER || env.USERNAME || "unknown";
381
+ /** Who asks when the caller names nobody: core's actor fallback (#4911). */
382
+ const actorOf = (env: NodeJS.ProcessEnv): string => actorFromEnv(env);
381
383
 
382
384
  const dirOf = (cwd: string | undefined, input: { root: string; dir?: string }): string => input.dir ?? join(cwd ?? process.cwd(), input.root);
383
385
 
@@ -2,7 +2,8 @@
2
2
  * Terragrunt units as roots (#3414). `./units`, `./wave` and `./mocks` are pure and
3
3
  * bundle without TypeScript; `./run` spawns `terragrunt`. `./affected` picks
4
4
  * the units a git range touches (#3415). `./capability` is `terragrunt-apply`,
5
- * the units as an op wave's step (#4842).
5
+ * the units as an op wave's step (#4842). `./place` is where a unit's binary runs
6
+ * as Terragrunt prepares it (#4910).
6
7
  */
7
8
 
8
9
  export * from "./units";
@@ -11,3 +12,4 @@ export * from "./mocks";
11
12
  export * from "./run";
12
13
  export * from "./affected";
13
14
  export * from "./capability";
15
+ export * from "./place";
@@ -0,0 +1,42 @@
1
+ /**
2
+ * chant#4910: where a Terragrunt unit's binary runs, as Terragrunt prepares
3
+ * it. The fake Terragrunt runs the `TG_TF_PATH` wrapper itself, in a working
4
+ * directory of its own and with an input as a `TF_VAR_`, as Terragrunt does;
5
+ * the binary the wrapper then runs is `true`. No Terragrunt is installed.
6
+ */
7
+ import { spawnSync } from "node:child_process";
8
+ import { mkdirSync, mkdtempSync, realpathSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { join } from "node:path";
11
+ import { describe, expect, test } from "vitest";
12
+ import { terragruntUnitPlace, UnitPlaceError } from "./place";
13
+ import type { TerragruntExec } from "./run";
14
+
15
+ const tmp = (): string => realpathSync(mkdtempSync(join(tmpdir(), "chant-tg-place-")));
16
+
17
+ describe("terragruntUnitPlace (chant#4910)", () => {
18
+ test("the unit's working directory, and the variables Terragrunt adds, from the wrapper's record", async () => {
19
+ const project = tmp();
20
+ const cache = join(project, ".terragrunt-cache", "abc", "unit");
21
+ mkdirSync(cache, { recursive: true });
22
+ const seen: Array<{ file: string; args: readonly string[]; cwd: string }> = [];
23
+ const exec: TerragruntExec = async (file, args, o) => {
24
+ seen.push({ file, args, cwd: o.cwd });
25
+ const r = spawnSync(o.env.TG_TF_PATH!, ["init"], { cwd: cache, env: { ...o.env, TF_VAR_region: "eu-west-1" }, encoding: "utf-8" });
26
+ return { code: r.status, stdout: r.stdout, stderr: r.stderr };
27
+ };
28
+ const place = await terragruntUnitPlace({ projectDir: project, unit: "live/queues", binary: "true", env: { PATH: process.env.PATH, JOB: "1" }, work: tmp(), exec });
29
+ expect(seen[0]).toMatchObject({ file: "terragrunt", cwd: project });
30
+ expect(seen[0]!.args).toEqual(["run", "--non-interactive", "--no-color", "--working-dir", "live/queues", "--", "init", "-input=false", "-no-color"]);
31
+ expect(place.dir).toBe(cache);
32
+ expect(place.env).toMatchObject({ JOB: "1", TF_VAR_region: "eu-west-1", TG_NON_INTERACTIVE: "true" });
33
+ expect(place.env.TG_TF_PATH).toBeUndefined();
34
+ });
35
+
36
+ test("a failed init, or one that never runs the binary, is refused with why", async () => {
37
+ const failed: TerragruntExec = async () => ({ code: 1, stdout: "", stderr: "ERROR no such unit" });
38
+ await expect(terragruntUnitPlace({ projectDir: tmp(), unit: "u", binary: "tofu", env: {}, work: tmp(), exec: failed })).rejects.toThrow(new UnitPlaceError("terragrunt could not prepare u (init failed): ERROR no such unit"));
39
+ const skipped: TerragruntExec = async () => ({ code: 0, stdout: "", stderr: "" });
40
+ await expect(terragruntUnitPlace({ projectDir: tmp(), unit: "u", binary: "tofu", env: {}, work: tmp(), exec: skipped })).rejects.toThrow(/without running tofu/);
41
+ });
42
+ });
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Where a Terragrunt unit's binary runs (chant#4910): its working directory
3
+ * and environment as Terragrunt prepares them, so a reader or writer of the
4
+ * unit's state (a state migration, an export, an ephemeral environment) runs
5
+ * the binary there as for a plain root.
6
+ *
7
+ * `terragrunt run -- init` in the unit, with `TG_TF_PATH` a wrapper that
8
+ * records the directory and the environment Terragrunt runs the binary in
9
+ * (its working directory, in Terragrunt's cache when the unit names a
10
+ * source, with backend.tf and provider.tf generated, and its inputs as
11
+ * `TF_VAR_` variables) and then runs the binary. The wrapper records with
12
+ * the running Node (`process.execPath`), so it needs nothing on `PATH`.
13
+ *
14
+ * Lifted from terragucci's `unitPlace` (migrate.ts), so terragucci deletes
15
+ * its copy.
16
+ */
17
+ import { chmodSync, existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
18
+ import { basename, join } from "node:path";
19
+ import { defaultTerragruntExec, type TerragruntExec } from "./run";
20
+
21
+ /** Where a unit's binary runs: its directory, and the job's environment with what Terragrunt adds. */
22
+ export interface UnitPlace {
23
+ dir: string;
24
+ env: NodeJS.ProcessEnv;
25
+ }
26
+
27
+ /** A unit Terragrunt could not prepare. */
28
+ export class UnitPlaceError extends Error {
29
+ constructor(message: string) {
30
+ super(message);
31
+ this.name = "UnitPlaceError";
32
+ }
33
+ }
34
+
35
+ export interface UnitPlaceInput {
36
+ /** The directory Terragrunt runs in; `unit` is relative to it. */
37
+ projectDir: string;
38
+ unit: string;
39
+ /** The binary Terragrunt calls through the wrapper. */
40
+ binary: string;
41
+ env: NodeJS.ProcessEnv;
42
+ /** A directory of the caller's, which the wrapper and its record go under. */
43
+ work: string;
44
+ /** The `terragrunt` executable. Default `terragrunt` on `PATH`. */
45
+ terragrunt?: string;
46
+ /** How Terragrunt runs. Default {@link defaultTerragruntExec}. */
47
+ exec?: TerragruntExec;
48
+ }
49
+
50
+ /** The variables of the wrapper's own run that are not Terragrunt's additions. */
51
+ const SHELL_VARS = new Set(["TG_TF_PATH", "PWD", "OLDPWD", "SHLVL", "_"]);
52
+
53
+ /** The unit's place, as Terragrunt prepares it. Throws {@link UnitPlaceError} when its init fails or never runs the binary. */
54
+ export async function terragruntUnitPlace(input: UnitPlaceInput): Promise<UnitPlace> {
55
+ const { unit, binary, env } = input;
56
+ const capture = mkdtempSync(join(input.work, "unit-"));
57
+ const file = join(capture, "place.json");
58
+ const wrapper = join(capture, basename(binary) || "tofu");
59
+ const q = (x: string): string => `'${x.replace(/'/g, `'\\''`)}'`;
60
+ const record = `require("fs").writeFileSync(process.argv[1], JSON.stringify({ dir: process.cwd(), env: process.env }))`;
61
+ writeFileSync(wrapper, `#!/bin/sh\n${q(process.execPath)} -e ${q(record)} ${q(file)}\nexec ${q(binary)} "$@"\n`);
62
+ chmodSync(wrapper, 0o755);
63
+ const run = await (input.exec ?? defaultTerragruntExec)(input.terragrunt ?? "terragrunt", ["run", "--non-interactive", "--no-color", "--working-dir", unit, "--", "init", "-input=false", "-no-color"], {
64
+ cwd: input.projectDir,
65
+ env: { ...(env as Record<string, string>), TG_TF_PATH: wrapper, TG_NON_INTERACTIVE: "true" },
66
+ });
67
+ if (run.code !== 0) throw new UnitPlaceError(`terragrunt could not prepare ${unit} (init failed): ${lastLines(run.stderr || run.stdout)}`);
68
+ if (!existsSync(file)) throw new UnitPlaceError(`terragrunt prepared ${unit} without running ${binary}, so where it runs is not known`);
69
+ const got = JSON.parse(readFileSync(file, "utf-8")) as { dir: string; env: Record<string, string> };
70
+ // The binary's own variables from Terragrunt: the unit's inputs, and any credentials an iam_role gave it.
71
+ const added = Object.fromEntries(Object.entries(got.env).filter(([k, v]) => env[k] !== v && !SHELL_VARS.has(k)));
72
+ return { dir: got.dir, env: { ...env, ...added } };
73
+ }
74
+
75
+ const lastLines = (s: string, n = 4): string => s.trim().split("\n").slice(-n).join(" ").slice(0, 400);
@@ -7,9 +7,10 @@
7
7
  */
8
8
 
9
9
  import { execFile } from "node:child_process";
10
- import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
11
- import { dirname, join, resolve } from "node:path";
10
+ import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
11
+ import { basename, dirname, join, resolve } from "node:path";
12
12
  import type { ChangeSetPart, ChangeSetPlanner } from "@intentius/chant/change-set";
13
+ import type { TerraformCommand, TerraformCommandHook, TerraformCommandRun } from "../op/command-hook";
13
14
  import { plannerForBinary } from "../change-set";
14
15
  import {
15
16
  parseTerragruntFind,
@@ -42,6 +43,7 @@ import {
42
43
  terragruntUnitResults,
43
44
  terragruntWaveArgs,
44
45
  terragruntWaveParts,
46
+ type TerragruntReportRow,
45
47
  type TerragruntUnitResult,
46
48
  } from "./wave";
47
49
 
@@ -180,6 +182,119 @@ export interface TerragruntWaveRunInput extends TerragruntRunOptions {
180
182
  * the plan, which fails the unit with its report row as before.
181
183
  */
182
184
  initTurn?: <T>(fn: () => Promise<T>) => Promise<T>;
185
+ /**
186
+ * The product's hook around each unit's plan (chant#4954), the
187
+ * `TerraformCommandHook` `terraform-apply` takes as `onCommand`, such as
188
+ * `engineTimings().onCommand`. Terragrunt runs the binary itself, so the
189
+ * hook is asked for every unit of the wave before `run --all`, as a `plan`
190
+ * command for that unit (`root` is the unit's path, `method` is `plan`).
191
+ * The variables it answers reach that unit's plan alone, through a
192
+ * `TG_TF_PATH` wrapper that matches the `-out` path Terragrunt gives it.
193
+ * Once the wave ends, each unit's `after` gets its time (`at`) and result
194
+ * from the run report. Needs `binary`: without it Terragrunt picks the
195
+ * binary per unit, and the hook is not called.
196
+ */
197
+ onCommand?: TerraformCommandHook;
198
+ }
199
+
200
+ /** A word single-quoted for `sh`. */
201
+ const shq = (s: string): string => `'${s.replace(/'/g, `'\\''`)}'`;
202
+
203
+ /**
204
+ * The `TG_TF_PATH` wrapper for one wave (chant#4954): a shell script that
205
+ * runs `binary` with the variables of the unit whose plan it runs.
206
+ * Terragrunt hands each unit's plan `-out=<out-dir>/<unit>/tfplan.tfplan`,
207
+ * which names the unit; every other call (init, show, output, version) runs
208
+ * the binary as it is. `outDirs` are the wave's plan directory as given and
209
+ * as its real path. Lifted from terragucci's `unitWrapper` (report/stage.ts).
210
+ */
211
+ export function terragruntUnitWrapper(binary: string, outDirs: readonly string[], units: ReadonlyMap<string, Record<string, string>>): string {
212
+ const lines = [
213
+ "#!/bin/sh",
214
+ "# chant: each unit's plan runs with the variables its command hook answered. Written for one wave.",
215
+ 'out=""',
216
+ 'prev=""',
217
+ 'for a in "$@"; do',
218
+ ' case "$a" in -out=*|--out=*) out="${a#*=}" ;; esac',
219
+ ' if [ "$prev" = "-out" ] || [ "$prev" = "--out" ]; then out="$a"; fi',
220
+ ' prev="$a"',
221
+ "done",
222
+ 'case "$out" in',
223
+ ];
224
+ for (const [unit, vars] of units) {
225
+ const set = Object.entries(vars).filter(([k]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(k));
226
+ if (set.length === 0) continue;
227
+ const patterns = [...new Set(outDirs.map((d) => join(d, unit, "tfplan.tfplan")))].map(shq).join(" | ");
228
+ lines.push(` ${patterns}) export ${set.map(([k, v]) => `${k}=${shq(v)}`).join(" ")} ;;`);
229
+ }
230
+ lines.push("esac", `exec ${shq(binary)} "$@"`);
231
+ return lines.join("\n") + "\n";
232
+ }
233
+
234
+ /**
235
+ * Ask `hook` for each unit's plan before the wave runs (chant#4954), and
236
+ * write the wrapper that hands each its variables when any has some.
237
+ * Answers the variables the run adds and what to call once the run report
238
+ * is read.
239
+ */
240
+ async function unitCommandRuns(
241
+ hook: TerraformCommandHook,
242
+ input: TerragruntWaveRunInput & { binary: string },
243
+ work: string,
244
+ outDir: string,
245
+ waveArgs: readonly string[],
246
+ ): Promise<{ env: Record<string, string>; done: (report: Map<string, TerragruntReportRow>) => Promise<void> }> {
247
+ const units = [...new Set(input.units)].sort();
248
+ const args = waveArgs.slice(waveArgs.indexOf("--") + 1);
249
+ const runs = new Map<string, TerraformCommandRun>();
250
+ for (const unit of units) {
251
+ const command: TerraformCommand = {
252
+ root: unit,
253
+ method: "plan",
254
+ binary: input.binary,
255
+ name: "plan",
256
+ args: [...args],
257
+ line: [input.binary, ...args].map((w) => (/^[\w@%+=:,./-]+$/.test(w) ? w : shq(w))).join(" "),
258
+ cwd: resolve(input.dir, unit),
259
+ env: {},
260
+ };
261
+ runs.set(unit, (await hook(command)) ?? {});
262
+ }
263
+ const vars = new Map([...runs].map(([unit, run]) => [unit, run.env ?? {}] as const));
264
+ let env: Record<string, string> = {};
265
+ if ([...vars.values()].some((v) => Object.keys(v).length > 0)) {
266
+ let real = outDir;
267
+ try {
268
+ real = join(realpathSync(work), "plans");
269
+ } catch {
270
+ // The path as given is matched alone.
271
+ }
272
+ const bin = join(work, "unit-bin");
273
+ mkdirSync(bin, { recursive: true });
274
+ // The wrapper carries the binary's name, which Terragrunt prefixes its log lines with.
275
+ const wrapper = join(bin, basename(input.binary) || "tofu");
276
+ writeFileSync(wrapper, terragruntUnitWrapper(input.binary, [outDir, real], vars));
277
+ chmodSync(wrapper, 0o755);
278
+ env = { TG_TF_PATH: wrapper };
279
+ }
280
+ const done = async (report: Map<string, TerragruntReportRow>): Promise<void> => {
281
+ for (const [unit, run] of runs) {
282
+ if (!run.after) continue;
283
+ const row = report.get(unit);
284
+ const start = row?.started ? Date.parse(row.started) : NaN;
285
+ const end = row?.ended ? Date.parse(row.ended) : NaN;
286
+ const timed = Number.isFinite(start) && Number.isFinite(end) && end >= start;
287
+ const why = row && row.result !== "succeeded" ? [row.result, row.reason, row.cause].filter(Boolean).join(": ") : "";
288
+ await run.after({
289
+ code: row ? (row.result === "succeeded" ? 0 : 1) : null,
290
+ seconds: timed ? (end - start) / 1000 : 0,
291
+ stdout: "",
292
+ stderr: row ? why : "not in Terragrunt's run report, so it did not run",
293
+ ...(timed ? { at: { start, end } } : {}),
294
+ });
295
+ }
296
+ };
297
+ return { env, done };
183
298
  }
184
299
 
185
300
  /**
@@ -345,8 +460,17 @@ export async function planTerragruntWave(input: TerragruntWaveRunInput): Promise
345
460
  ...(input.destroy ? { destroy: true } : {}),
346
461
  ...(input.parallelism !== undefined ? { parallelism: input.parallelism } : {}),
347
462
  });
348
- const r = await exec(tg, args, { cwd: input.dir, env: terragruntEnv(input.binary) });
349
- const report = existsSync(reportFile) ? parseTerragruntReport(readFileSync(reportFile, "utf8")) : new Map();
463
+ // chant#4954: each unit's plan goes through the product's hook, its variables through a TG_TF_PATH wrapper.
464
+ const units = input.onCommand && input.binary ? await unitCommandRuns(input.onCommand, { ...input, binary: input.binary }, work, outDir, args) : undefined;
465
+ let r: ExecResult;
466
+ try {
467
+ r = await exec(tg, args, { cwd: input.dir, env: { ...terragruntEnv(input.binary), ...(units?.env ?? {}) } });
468
+ } catch (err) {
469
+ await units?.done(new Map());
470
+ throw err;
471
+ }
472
+ const report = existsSync(reportFile) ? parseTerragruntReport(readFileSync(reportFile, "utf8")) : new Map<string, TerragruntReportRow>();
473
+ await units?.done(report);
350
474
  const planFor = (unit: string): unknown => {
351
475
  const f = join(jsonOutDir, unit, "tfplan.json");
352
476
  return existsSync(f) ? (JSON.parse(readFileSync(f, "utf8")) as unknown) : undefined;