@intentius/chant-lexicon-terraform 0.124.89 → 0.124.90

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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "algorithm": "sha256",
3
3
  "artifacts": {
4
- "manifest.json": "b80640df1f7db7ee804395be7c62b0c61385a8378fa126ec2b8e3d020edbf0ca",
4
+ "manifest.json": "214cf8ced5b52ba25016f9d9221fa826357931365c2b0aee9bee4d6b897d2901",
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": "4cc20a5426a9c3aa740be85866c49d15634406d55463a57ba6359cf57a9974f8"
63
63
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "terraform",
3
- "version": "0.124.89",
3
+ "version": "0.124.90",
4
4
  "chantVersion": ">=0.1.0",
5
5
  "namespace": "Terraform"
6
6
  }
@@ -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;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAErG,4EAA4E;AAC5E,MAAM,WAAW,KAAK;IACpB,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,iFAAiF;AACjF,MAAM,MAAM,UAAU,GAAG,WAAW,CAAC,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;AAElE,uDAAuD;AACvD,eAAO,MAAM,aAAa,QAAW,CAAC;AAEtC,6HAA6H;AAC7H,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAIjG;AAED,kFAAkF;AAClF,wBAAgB,WAAW,CAAC,QAAQ,EAAE,GAAG,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,UAAU,GAAG,SAAS,GAAG,IAAI,CAWtF;AAID;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,MAAM,EAAE,EAAE,KAAK,CAAC,EAAE,UAAU,GAAG,KAAK,CAOvI;AAyBD;;;;;;GAMG;AACH,wBAAgB,6BAA6B,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAiBpE;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,KAAK,CAwBrG;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,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
+ }
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.90",
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.90",
97
97
  "zod": "^4.3.6"
98
98
  },
99
99
  "description": "terraform lexicon for chant, existing Terraform root modules as declarable entities",
@@ -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
+ }