@intentius/chant 0.124.91 → 0.124.93

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 (108) hide show
  1. package/dist/__golden__/notify-defaults-plain.json +52 -0
  2. package/dist/__golden__/notify-defaults-relay.json +92 -0
  3. package/dist/ci-comment-commands.d.ts +11 -1
  4. package/dist/ci-comment-commands.d.ts.map +1 -1
  5. package/dist/ci-comment-commands.js +10 -3
  6. package/dist/ci-job-guard.d.ts +22 -8
  7. package/dist/ci-job-guard.d.ts.map +1 -1
  8. package/dist/ci-job-guard.js +93 -49
  9. package/dist/ci-jobs.d.ts +22 -0
  10. package/dist/ci-jobs.d.ts.map +1 -1
  11. package/dist/ci-jobs.js +23 -0
  12. package/dist/ci-product.d.ts +42 -1
  13. package/dist/ci-product.d.ts.map +1 -1
  14. package/dist/ci-product.js +44 -3
  15. package/dist/cli/handlers/pr-comment.d.ts.map +1 -1
  16. package/dist/cli/handlers/pr-comment.js +15 -2
  17. package/dist/cli/handlers/pr.d.ts.map +1 -1
  18. package/dist/cli/handlers/pr.js +4 -1
  19. package/dist/components/pr-pipeline.d.ts +4 -2
  20. package/dist/components/pr-pipeline.d.ts.map +1 -1
  21. package/dist/components/pr-pipeline.js +7 -4
  22. package/dist/components/product-pipeline.d.ts +71 -7
  23. package/dist/components/product-pipeline.d.ts.map +1 -1
  24. package/dist/components/product-pipeline.js +84 -22
  25. package/dist/components/product-plan.d.ts +7 -0
  26. package/dist/components/product-plan.d.ts.map +1 -1
  27. package/dist/components/product-plan.js +1 -0
  28. package/dist/floor-table.data.d.ts.map +1 -1
  29. package/dist/floor-table.data.js +15 -5
  30. package/dist/lexicon.d.ts +59 -1
  31. package/dist/lexicon.d.ts.map +1 -1
  32. package/dist/notify.d.ts +8 -0
  33. package/dist/notify.d.ts.map +1 -1
  34. package/dist/notify.js +8 -3
  35. package/dist/op/before-merge-decide.d.ts +2 -0
  36. package/dist/op/before-merge-decide.d.ts.map +1 -1
  37. package/dist/op/before-merge.d.ts +8 -0
  38. package/dist/op/before-merge.d.ts.map +1 -1
  39. package/dist/op/before-merge.js +6 -0
  40. package/dist/op/index.d.ts +1 -1
  41. package/dist/op/index.d.ts.map +1 -1
  42. package/dist/op/index.js +1 -1
  43. package/dist/op/op-waves-evidence-jobs.d.ts +3 -2
  44. package/dist/op/op-waves-evidence-jobs.d.ts.map +1 -1
  45. package/dist/op/op-waves-evidence-jobs.js +4 -3
  46. package/dist/op/op-waves-follow-on.d.ts +2 -0
  47. package/dist/op/op-waves-follow-on.d.ts.map +1 -1
  48. package/dist/op/op-waves-follow-on.js +8 -2
  49. package/dist/op/op-waves-names.d.ts +145 -0
  50. package/dist/op/op-waves-names.d.ts.map +1 -0
  51. package/dist/op/op-waves-names.js +201 -0
  52. package/dist/op/op-waves-run.d.ts +2 -0
  53. package/dist/op/op-waves-run.d.ts.map +1 -1
  54. package/dist/op/op-waves-run.js +2 -2
  55. package/dist/op/op-waves-stand-down.d.ts +9 -1
  56. package/dist/op/op-waves-stand-down.d.ts.map +1 -1
  57. package/dist/op/op-waves-stand-down.js +14 -2
  58. package/dist/op/op-waves.d.ts +12 -1
  59. package/dist/op/op-waves.d.ts.map +1 -1
  60. package/dist/op/op-waves.js +2 -0
  61. package/dist/pr-forge-job.d.ts +8 -0
  62. package/dist/pr-forge-job.d.ts.map +1 -1
  63. package/dist/pr-forge-job.js +13 -0
  64. package/dist/pr-plan-record.d.ts +3 -1
  65. package/dist/pr-plan-record.d.ts.map +1 -1
  66. package/dist/pr-plan-record.js +1 -1
  67. package/dist/pr-post.d.ts +9 -3
  68. package/dist/pr-post.d.ts.map +1 -1
  69. package/dist/pr-post.js +5 -2
  70. package/dist/release-floors.d.ts +1 -1
  71. package/dist/release-floors.d.ts.map +1 -1
  72. package/dist/release-floors.js +4 -4
  73. package/dist/wave-runtime.mjs +305 -305
  74. package/package.json +1 -1
  75. package/src/__golden__/notify-defaults-plain.json +52 -0
  76. package/src/__golden__/notify-defaults-relay.json +92 -0
  77. package/src/ci-comment-commands.test.ts +19 -5
  78. package/src/ci-comment-commands.ts +18 -3
  79. package/src/ci-job-guard.default-branch.test.ts +125 -0
  80. package/src/ci-job-guard.ts +64 -10
  81. package/src/ci-jobs.ts +26 -0
  82. package/src/ci-product.ts +54 -3
  83. package/src/cli/handlers/pr-comment.ts +12 -2
  84. package/src/cli/handlers/pr.ts +4 -1
  85. package/src/components/pr-pipeline.ts +7 -4
  86. package/src/components/product-job-names.test.ts +176 -0
  87. package/src/components/product-pipeline.ts +143 -31
  88. package/src/components/product-plan.ts +8 -0
  89. package/src/floor-table.data.ts +15 -5
  90. package/src/lexicon.ts +59 -1
  91. package/src/notify-bundle.test.ts +3 -2
  92. package/src/notify-relay-name.test.ts +72 -0
  93. package/src/notify.ts +16 -3
  94. package/src/op/before-merge-decide.ts +2 -0
  95. package/src/op/before-merge.ts +12 -0
  96. package/src/op/index.ts +1 -1
  97. package/src/op/op-waves-evidence-jobs.ts +4 -3
  98. package/src/op/op-waves-follow-on.ts +10 -2
  99. package/src/op/op-waves-names.test.ts +131 -0
  100. package/src/op/op-waves-names.ts +289 -0
  101. package/src/op/op-waves-run.ts +4 -2
  102. package/src/op/op-waves-stand-down.ts +15 -2
  103. package/src/op/op-waves.ts +13 -1
  104. package/src/pr-forge-job.ts +13 -0
  105. package/src/pr-plan-record.ts +4 -2
  106. package/src/pr-post-head.test.ts +116 -0
  107. package/src/pr-post.ts +15 -5
  108. package/src/release-floors.ts +4 -4
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/chant",
3
- "version": "0.124.91",
3
+ "version": "0.124.93",
4
4
  "description": "Declarative infrastructure-as-code toolkit — TypeScript on Node.js",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://intentius.io/chant",
@@ -0,0 +1,52 @@
1
+ [
2
+ {
3
+ "type": "message",
4
+ "attachments": [
5
+ {
6
+ "contentType": "application/vnd.microsoft.card.adaptive",
7
+ "contentUrl": null,
8
+ "content": {
9
+ "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
10
+ "type": "AdaptiveCard",
11
+ "version": "1.4",
12
+ "body": [
13
+ {
14
+ "type": "TextBlock",
15
+ "text": "terragucci: wave 1 (wave-1) of tf-apply waits for an approval",
16
+ "weight": "Bolder",
17
+ "wrap": true
18
+ },
19
+ {
20
+ "type": "FactSet",
21
+ "facts": [
22
+ {
23
+ "title": "Targets",
24
+ "value": "network"
25
+ },
26
+ {
27
+ "title": "Digest",
28
+ "value": "jcs1-sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
29
+ },
30
+ {
31
+ "title": "Approve",
32
+ "value": "terragucci approve tf-apply wave-1 --plan jcs1-sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
33
+ },
34
+ {
35
+ "title": "Run",
36
+ "value": "https://github.com/acme/db/actions/runs/42"
37
+ }
38
+ ]
39
+ }
40
+ ],
41
+ "actions": [
42
+ {
43
+ "type": "Action.OpenUrl",
44
+ "title": "Open the run",
45
+ "url": "https://github.com/acme/db/actions/runs/42"
46
+ }
47
+ ]
48
+ }
49
+ }
50
+ ]
51
+ }
52
+ ]
@@ -0,0 +1,92 @@
1
+ [
2
+ {
3
+ "text": "*terragucci: wave 1 (wave-1) of tf-apply waits for an approval*\nTargets: network\nDigest: `jcs1-sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`\nApprove: `terragucci approve tf-apply wave-1 --plan jcs1-sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`\nRun: <https://github.com/acme/db/actions/runs/42>",
4
+ "blocks": [
5
+ {
6
+ "type": "section",
7
+ "text": {
8
+ "type": "mrkdwn",
9
+ "text": "*terragucci: wave 1 (wave-1) of tf-apply waits for an approval*\nTargets: network\nDigest: `jcs1-sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`\nApprove: `terragucci approve tf-apply wave-1 --plan jcs1-sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`\nRun: <https://github.com/acme/db/actions/runs/42>"
10
+ }
11
+ },
12
+ {
13
+ "type": "actions",
14
+ "elements": [
15
+ {
16
+ "type": "button",
17
+ "text": {
18
+ "type": "plain_text",
19
+ "text": "Approve"
20
+ },
21
+ "action_id": "chant-approve",
22
+ "value": "eyJ2IjoxLCJpZCI6ImQ0MDM4OWRjOWM2ZDAzZDUxYTU3MDE5NzQ4OTMyMWU5N2Q0NWNjMGJkODg0NmExMGM1N2I5MDQ2YTMxMmI4YjIiLCJzb3VyY2UiOiJ0ZXJyYWd1Y2NpIiwiYXQiOiIyMDI2LTEwLTExVDEyOjAwOjAwLjAwMFoiLCJnYXRlIjoid2F2ZS0xIiwiZGlnZXN0IjoiamNzMS1zaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSJ9.6122dfab74cb9b2729f23dae8546cf5948d4b01cc34fdb33dfa128c1a6772437",
23
+ "style": "primary"
24
+ },
25
+ {
26
+ "type": "button",
27
+ "text": {
28
+ "type": "plain_text",
29
+ "text": "Decline"
30
+ },
31
+ "action_id": "chant-decline",
32
+ "value": "eyJ2IjoxLCJpZCI6ImQ0MDM4OWRjOWM2ZDAzZDUxYTU3MDE5NzQ4OTMyMWU5N2Q0NWNjMGJkODg0NmExMGM1N2I5MDQ2YTMxMmI4YjIiLCJzb3VyY2UiOiJ0ZXJyYWd1Y2NpIiwiYXQiOiIyMDI2LTEwLTExVDEyOjAwOjAwLjAwMFoiLCJnYXRlIjoid2F2ZS0xIiwiZGlnZXN0IjoiamNzMS1zaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSJ9.6122dfab74cb9b2729f23dae8546cf5948d4b01cc34fdb33dfa128c1a6772437"
33
+ }
34
+ ]
35
+ }
36
+ ]
37
+ },
38
+ {
39
+ "type": "message",
40
+ "attachments": [
41
+ {
42
+ "contentType": "application/vnd.microsoft.card.adaptive",
43
+ "contentUrl": null,
44
+ "content": {
45
+ "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
46
+ "type": "AdaptiveCard",
47
+ "version": "1.4",
48
+ "body": [
49
+ {
50
+ "type": "TextBlock",
51
+ "text": "terragucci: wave 1 (wave-1) of tf-apply waits for an approval",
52
+ "weight": "Bolder",
53
+ "wrap": true
54
+ },
55
+ {
56
+ "type": "FactSet",
57
+ "facts": [
58
+ {
59
+ "title": "Targets",
60
+ "value": "network"
61
+ },
62
+ {
63
+ "title": "Digest",
64
+ "value": "jcs1-sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
65
+ },
66
+ {
67
+ "title": "Approve",
68
+ "value": "terragucci approve tf-apply wave-1 --plan jcs1-sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
69
+ },
70
+ {
71
+ "title": "Run",
72
+ "value": "https://github.com/acme/db/actions/runs/42"
73
+ },
74
+ {
75
+ "title": "Approve in chat",
76
+ "value": "mention the relay and reply: approve eyJ2IjoxLCJpZCI6ImQ0MDM4OWRjOWM2ZDAzZDUxYTU3MDE5NzQ4OTMyMWU5N2Q0NWNjMGJkODg0NmExMGM1N2I5MDQ2YTMxMmI4YjIiLCJzb3VyY2UiOiJ0ZXJyYWd1Y2NpIiwiYXQiOiIyMDI2LTEwLTExVDEyOjAwOjAwLjAwMFoiLCJnYXRlIjoid2F2ZS0xIiwiZGlnZXN0IjoiamNzMS1zaGEyNTY6YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYSJ9.6122dfab74cb9b2729f23dae8546cf5948d4b01cc34fdb33dfa128c1a6772437"
77
+ }
78
+ ]
79
+ }
80
+ ],
81
+ "actions": [
82
+ {
83
+ "type": "Action.OpenUrl",
84
+ "title": "Open the run",
85
+ "url": "https://github.com/acme/db/actions/runs/42"
86
+ }
87
+ ]
88
+ }
89
+ }
90
+ ]
91
+ }
92
+ ]
@@ -380,6 +380,23 @@ describe("the comment job's apply before merge on the waves (#4984)", () => {
380
380
  const jobs: CommentJobs = { applyOnMerge: true, waves: { op: "tf-apply", count: 2 }, wavesBeforeMerge: bm };
381
381
 
382
382
  test("an open pull request's apply is decided, and the waves workflow dispatched on the default branch with the decided head", async () => {
383
+ const { sent, stops, got, posted, head, digest } = await decideAndDispatch(jobs);
384
+ expect(sent).toEqual([["tf-apply.yml", "main", { pr: "12", head, digest }]]);
385
+ expect(stops).toEqual([[head, 1]]);
386
+ expect(got).toMatchObject({ command: "apply", ran: true, replied: true });
387
+ expect(posted).toEqual([`terragucci: started the waves of tf-apply on pull request 12's head ${head.slice(0, 8)} through wave 1 for alice; each wave's gate decides, and the run says when the head applied`]);
388
+ });
389
+
390
+ test("#5022: a product's workflow is dispatched with the product's input names", async () => {
391
+ const named: CommentJobs = { ...jobs, wavesBeforeMerge: { ...bm, workflow: "terragucci.yml", inputs: { pr: "apply_pr", head: "apply_head", digest: "apply_digest" } } };
392
+ expect(commentJobsFromEnv(JSON.stringify(named))).toEqual(named);
393
+ expect(() => commentJobsFromEnv(JSON.stringify({ ...jobs, wavesBeforeMerge: { ...bm, inputs: { wave: "w" } } }))).toThrow("inputs names the inputs pr, head and digest");
394
+ expect(() => commentJobsFromEnv(JSON.stringify({ ...jobs, wavesBeforeMerge: { ...bm, inputs: { pr: "a b" } } }))).toThrow("inputs names the inputs pr, head and digest");
395
+ const { sent, head, digest } = await decideAndDispatch(named);
396
+ expect(sent).toEqual([["terragucci.yml", "main", { apply_pr: "12", apply_head: head, apply_digest: digest }]]);
397
+ });
398
+
399
+ async function decideAndDispatch(jobs: CommentJobs) {
383
400
  const { spawnSync } = await import("node:child_process");
384
401
  const { mkdtempSync, writeFileSync } = await import("node:fs");
385
402
  const { tmpdir } = await import("node:os");
@@ -424,11 +441,8 @@ describe("the comment job's apply before merge on the waves (#4984)", () => {
424
441
  },
425
442
  });
426
443
  const digest = beforeMergeDigest("tf-apply", { pr: 12, head, base: baseSha, through: 1, at, by: "alice" });
427
- expect(sent).toEqual([["tf-apply.yml", "main", { pr: "12", head, digest }]]);
428
- expect(stops).toEqual([[head, 1]]);
429
- expect(got).toMatchObject({ command: "apply", ran: true, replied: true });
430
- expect(s.posted).toEqual([`terragucci: started the waves of tf-apply on pull request 12's head ${head.slice(0, 8)} through wave 1 for alice; each wave's gate decides, and the run says when the head applied`]);
431
- });
444
+ return { sent, stops, got, posted: s.posted, head, digest };
445
+ }
432
446
 
433
447
  test("CHANT_COMMENT_JOBS carries the waves before merge, each field checked", () => {
434
448
  expect(commentJobsFromEnv(JSON.stringify(jobs))).toEqual(jobs);
@@ -57,7 +57,7 @@ import { ForgeApiError, type ForgeFetch, type PrForge } from "./pr-forge";
57
57
  import type { ForgeReads, PullRequestDetail } from "./pr-forge-reads";
58
58
  import type { DecideBeforeMergeInput, WavesBeforeMergeJobs } from "./op/before-merge-decide";
59
59
 
60
- /** The comment job's name in a generated workflow (#4946). */
60
+ /** The comment job's name in a generated workflow (#4946), unless the product names it (#5027: the product pipeline's `commentJob.jobName`, such as terragucci's `apply-comment`). */
61
61
  export const PR_COMMENT_JOB = "comment";
62
62
 
63
63
  /** The variable the comment job reads the pipeline's jobs from, as JSON ({@link CommentJobs}), written by the generator (#4946). */
@@ -102,6 +102,14 @@ export interface CommentJobs extends Omit<ChantNoteJobs, "members"> {
102
102
  * `chant/lifecycle`, and dispatches the waves workflow for it.
103
103
  */
104
104
  wavesBeforeMerge?: WavesBeforeMergeJobs;
105
+ /**
106
+ * The waves' apply jobs by the names the product gave them (#5027, the
107
+ * Op waves generator's `jobNames`, such as terragucci's `apply-wave-<k>`,
108
+ * `apply-wave-<k>-share-<n>`, its group jobs and `apply-rest`). A re-run
109
+ * of a merged pull request's apply looks for these. Absent:
110
+ * {@link RERUN_APPLY_JOBS}.
111
+ */
112
+ applyJobs?: readonly string[];
105
113
  }
106
114
 
107
115
  /** What the decision before merge reads and writes with (#4984), the comment job's handler's. */
@@ -117,6 +125,12 @@ export type CommentWaveStops = (op: string, sha: string, stop: { through: number
117
125
  */
118
126
  export const RERUN_APPLY_JOBS = /^(?:wave-([1-9][0-9]*)-[a-z0-9][a-z0-9_-]*|(?:[a-z0-9][a-z0-9-]*-)?apply(?:-wave-([1-9][0-9]*)(?:-share-[1-9][0-9]*)?)?)$/;
119
127
 
128
+ /** The apply jobs a re-run looks for (#5027): exactly `jobs.applyJobs` when the product named them, else {@link RERUN_APPLY_JOBS}. */
129
+ export function rerunApplyJobs(jobs: Pick<CommentJobs, "applyJobs">): RegExp {
130
+ if (!jobs.applyJobs?.length) return RERUN_APPLY_JOBS;
131
+ return new RegExp(`^(?:${jobs.applyJobs.map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})$`);
132
+ }
133
+
120
134
  /** The writes a re-run makes, with the job's token. */
121
135
  export interface CommentRuns {
122
136
  /** GitHub: `POST /repos/{repo}/actions/runs/{run}/rerun-failed-jobs`. */
@@ -327,7 +341,8 @@ export async function answerProductComment(o: AnswerCommentOptions): Promise<Com
327
341
  count: o.jobs.waves.count,
328
342
  jobs: bm,
329
343
  words: o.words,
330
- start: (r) => o.runs.dispatch(workflow, o.base, { pr: String(r.pr), head: r.head, digest: r.digest }),
344
+ // #5022: under the waves workflow's input names, the product's when it renamed them.
345
+ start: (r) => o.runs.dispatch(workflow, o.base, { [bm.inputs?.pr ?? "pr"]: String(r.pr), [bm.inputs?.head ?? "head"]: r.head, [bm.inputs?.digest ?? "digest"]: r.digest }),
331
346
  });
332
347
  if (done.kind === "fail") return broke(done.reason, command);
333
348
  return reply(done.text, done.kind === "ran", done.kind === "ran" ? done.url : undefined);
@@ -359,7 +374,7 @@ export async function answerProductComment(o: AnswerCommentOptions): Promise<Com
359
374
  return start(run, jobs, ctx);
360
375
  }
361
376
  : start;
362
- const done = await retryApply({ reads: o.reads, forge: o.poster, words: o.words, base: o.base }, o.forge, pr, user, { kind: "retry", sha: mergeCommit, jobs: RERUN_APPLY_JOBS }, rerun);
377
+ const done = await retryApply({ reads: o.reads, forge: o.poster, words: o.words, base: o.base }, o.forge, pr, user, { kind: "retry", sha: mergeCommit, jobs: rerunApplyJobs(o.jobs) }, rerun);
363
378
  if (done.kind === "fail") return broke(done.reason, command);
364
379
  const stopped = done.kind === "ran" && wave !== undefined && waves && wave < waves.count ? `; it stops after \`wave-${wave}\`, and the waves after it wait until \`/${o.words.product} ${typedApply(o.words)}\` runs it again` : "";
365
380
  return reply(`${done.text}${stopped}`, done.kind === "ran", done.kind === "ran" ? done.url : undefined);
@@ -0,0 +1,125 @@
1
+ /**
2
+ * #5032: a waves job that runs from the repository's default branch, by
3
+ * the name the forge gives it at run time, with or without named branches
4
+ * beside it. The default branch here is `trunk`, never `main`.
5
+ */
6
+ import { describe, expect, test } from "vitest";
7
+ import { spawnSync } from "node:child_process";
8
+ import { CHANT_EXIT } from "./exit-codes";
9
+ import {
10
+ checkJob,
11
+ describeJobGuard,
12
+ JOB_DEFAULT_BRANCH_ENV,
13
+ JOB_GUARD_DEFAULT_BRANCH_JS,
14
+ JOB_GUARD_ENV,
15
+ JOB_GUARD_JS,
16
+ jobGuardLine,
17
+ jobGuardSpec,
18
+ jobSeen,
19
+ parseJobGuardSpec,
20
+ type JobGuardSpec,
21
+ } from "./ci-job-guard";
22
+ import { opWaveDefaultBranch, tipAppliesTargets } from "./op/op-waves-stand-down";
23
+ import { githubWavesBranchIf, gitlabWavesBranches, wavesNamedBranches } from "./ci-jobs";
24
+ import type { OpWavesSpec } from "./op/op-waves";
25
+
26
+ const noFetch = (() => Promise.reject(new Error("no fetch"))) as unknown as typeof fetch;
27
+ const program = (spec: JobGuardSpec, env: Record<string, string>) =>
28
+ spawnSync(process.execPath, ["-e", JOB_GUARD_DEFAULT_BRANCH_JS], { env: { PATH: process.env.PATH ?? "", [JOB_GUARD_ENV]: JSON.stringify(spec), ...env }, encoding: "utf-8" });
29
+
30
+ describe("the guard on the default branch (#5032)", () => {
31
+ test("the spec says so only when asked, and parses back", () => {
32
+ expect(jobGuardSpec({ forge: "github", job: "w", branches: [] , defaultBranch: true })).toEqual({ forge: "github", job: "w", branches: [], defaultBranch: true });
33
+ expect(jobGuardSpec({ forge: "github", job: "w", branches: ["main"] })).not.toHaveProperty("defaultBranch");
34
+ expect(parseJobGuardSpec(JSON.stringify({ forge: "gitlab", job: "w", branches: [], defaultBranch: true })).defaultBranch).toBe(true);
35
+ expect(() => parseJobGuardSpec(JSON.stringify({ forge: "gitlab", job: "w", branches: [], defaultBranch: "main" }))).toThrow(/defaultBranch is true or absent/);
36
+ });
37
+
38
+ const github: JobGuardSpec = { forge: "github", job: "wave 1 (wave-1) of tf-apply", product: "terragucci", branches: [], defaultBranch: true };
39
+ const forgejo: JobGuardSpec = { ...github, forge: "forgejo", branches: ["release"] };
40
+ const gitlab: JobGuardSpec = { forge: "gitlab", job: "wave 1 (wave-1) of tf-apply", branches: ["release"], defaultBranch: true };
41
+
42
+ test("GitHub admits the default branch the event names, and refuses main when it is not that", async () => {
43
+ const at = (ref: string, def?: string) => ({ GITHUB_REF: ref, ...(def !== undefined ? { [JOB_DEFAULT_BRANCH_ENV]: def } : {}) });
44
+ expect(checkJob(github, await jobSeen(github, at("refs/heads/trunk", "trunk"), noFetch)).problems).toEqual([]);
45
+ expect(checkJob(github, await jobSeen(github, at("refs/heads/main", "trunk"), noFetch)).problems).toEqual(["ref: expected refs/heads/trunk, found refs/heads/main"]);
46
+ expect(checkJob(github, await jobSeen(github, at("refs/heads/trunk"), noFetch)).problems).toEqual([`ref: the job runs from the default branch, and the forge names none (no ${JOB_DEFAULT_BRANCH_ENV})`]);
47
+ });
48
+
49
+ test("Forgejo admits the default branch and the named one beside it", async () => {
50
+ const seen = (ref: string) => jobSeen(forgejo, { GITHUB_REF: ref, [JOB_DEFAULT_BRANCH_ENV]: "trunk" }, noFetch);
51
+ expect(checkJob(forgejo, await seen("refs/heads/trunk")).checked).toContain("ref refs/heads/trunk");
52
+ expect(checkJob(forgejo, await seen("refs/heads/release")).checked).toContain("ref refs/heads/release");
53
+ expect(checkJob(forgejo, await seen("refs/heads/dev")).problems).toEqual(["ref: expected refs/heads/trunk or refs/heads/release, found refs/heads/dev"]);
54
+ });
55
+
56
+ test("GitLab reads CI_DEFAULT_BRANCH, and still asks for a protected ref", async () => {
57
+ const env = (ref: string, prot = "true") => ({ CI_COMMIT_REF_NAME: ref, CI_COMMIT_REF_PROTECTED: prot, CI_DEFAULT_BRANCH: "trunk" });
58
+ expect(checkJob(gitlab, await jobSeen(gitlab, env("trunk"), noFetch)).problems).toEqual([]);
59
+ expect(checkJob(gitlab, await jobSeen(gitlab, env("release"), noFetch)).problems).toEqual([]);
60
+ expect(checkJob(gitlab, await jobSeen(gitlab, env("main"), noFetch)).problems).toEqual(["ref: expected trunk or release, found main"]);
61
+ expect(checkJob(gitlab, await jobSeen(gitlab, env("trunk", "false"), noFetch)).problems).toEqual(["ref: expected a protected ref (CI_COMMIT_REF_PROTECTED true), found false"]);
62
+ });
63
+
64
+ test("a spec without defaultBranch reads no default branch", async () => {
65
+ const plain: JobGuardSpec = { forge: "gitlab", job: "w", branches: ["main"] };
66
+ expect(await jobSeen(plain, { CI_COMMIT_REF_NAME: "trunk", CI_DEFAULT_BRANCH: "trunk" }, noFetch)).not.toHaveProperty("defaultBranch");
67
+ expect(checkJob(plain, await jobSeen(plain, { CI_COMMIT_REF_NAME: "trunk", CI_COMMIT_REF_PROTECTED: "true", CI_DEFAULT_BRANCH: "trunk" }, noFetch)).problems).toEqual(["ref: expected main, found trunk"]);
68
+ });
69
+
70
+ const cases: Array<[string, JobGuardSpec, Record<string, string>]> = [
71
+ ["GitHub on the default branch", github, { GITHUB_REF: "refs/heads/trunk", [JOB_DEFAULT_BRANCH_ENV]: "trunk" }],
72
+ ["GitHub on main, which is not it", github, { GITHUB_REF: "refs/heads/main", [JOB_DEFAULT_BRANCH_ENV]: "trunk" }],
73
+ ["GitHub with no default branch named", github, { GITHUB_REF: "refs/heads/trunk" }],
74
+ ["Forgejo on the named branch", forgejo, { GITHUB_REF: "refs/heads/release", [JOB_DEFAULT_BRANCH_ENV]: "trunk" }],
75
+ ["Forgejo elsewhere", forgejo, { GITHUB_REF: "refs/heads/dev", [JOB_DEFAULT_BRANCH_ENV]: "trunk" }],
76
+ ["GitLab on the default branch", gitlab, { CI_COMMIT_REF_NAME: "trunk", CI_COMMIT_REF_PROTECTED: "true", CI_DEFAULT_BRANCH: "trunk" }],
77
+ ["GitLab on main, which is not it", gitlab, { CI_COMMIT_REF_NAME: "main", CI_COMMIT_REF_PROTECTED: "true", CI_DEFAULT_BRANCH: "trunk" }],
78
+ ["GitLab with only the named branch to go by", { ...gitlab }, { CI_COMMIT_REF_NAME: "release", CI_COMMIT_REF_PROTECTED: "true" }],
79
+ ];
80
+ for (const [name, spec, env] of cases) {
81
+ test(`the node -e program agrees with checkJob: ${name}`, async () => {
82
+ const r = program(spec, env);
83
+ const want = describeJobGuard(spec, checkJob(spec, await jobSeen(spec, env, noFetch)));
84
+ expect(r.status).toBe(want.ok ? 0 : CHANT_EXIT.misplaced);
85
+ expect(r.stdout.trim().split("\n").filter(Boolean)).toEqual(want.out);
86
+ expect(r.stderr.trim().split("\n").filter(Boolean)).toEqual(want.err);
87
+ });
88
+ }
89
+
90
+ test("the program holds no single quote, and a job without defaultBranch keeps the program it had", () => {
91
+ expect(JOB_GUARD_DEFAULT_BRANCH_JS).not.toContain("'");
92
+ expect(JOB_GUARD_JS).not.toContain(JOB_DEFAULT_BRANCH_ENV);
93
+ expect(jobGuardLine()).toBe(`(cd / && node -e '${JOB_GUARD_JS}')`);
94
+ expect(jobGuardLine({})).toBe(jobGuardLine());
95
+ expect(jobGuardLine({ defaultBranch: true })).toBe(`(cd / && node -e '${JOB_GUARD_DEFAULT_BRANCH_JS}')`);
96
+ });
97
+ });
98
+
99
+ describe("the branches a waves spec runs from (#5032)", () => {
100
+ test("named alone, or beside the default branch", () => {
101
+ expect(wavesNamedBranches({})).toEqual(["main"]);
102
+ expect(wavesNamedBranches({ defaultBranch: true })).toEqual([]);
103
+ expect(wavesNamedBranches({ defaultBranch: true, branches: ["release"] })).toEqual(["release"]);
104
+ expect(githubWavesBranchIf({ defaultBranch: true, branches: ["release"] })).toBe("github.ref == format('refs/heads/{0}', github.event.repository.default_branch) || github.ref == 'refs/heads/release'");
105
+ expect(gitlabWavesBranches({ defaultBranch: true, branches: ["release"] }).map((b) => b.operand)).toEqual(["$CI_DEFAULT_BRANCH", '"release"']);
106
+ expect(gitlabWavesBranches({ branches: ["main"] }).map((b) => b.operand)).toEqual(['"main"']);
107
+ });
108
+ });
109
+
110
+ describe("the stand-down on the default branch (#5032)", () => {
111
+ const atTip = { name: "tf-apply", op: "tf-apply", defaultBranch: true, waves: [{ name: "wave-1", runs: [{ target: "network" }] }] } as unknown as OpWavesSpec;
112
+ test("a newer commit on the default branch, by its run-time name, makes the wave stand down", () => {
113
+ expect(tipAppliesTargets(atTip, "trunk", "wave-1", ["network"], "trunk")).toBe(true);
114
+ expect(tipAppliesTargets(atTip, "main", "wave-1", ["network"], "trunk")).toBe(false);
115
+ expect(tipAppliesTargets(atTip, "trunk", "wave-1", ["network"])).toBe(false);
116
+ expect(tipAppliesTargets({ ...atTip, branches: ["release"] }, "release", "wave-1", ["network"], "trunk")).toBe(true);
117
+ // Without defaultBranch the spec runs on main, as before.
118
+ expect(tipAppliesTargets({ ...atTip, defaultBranch: undefined } as unknown as OpWavesSpec, "main", "wave-1", ["network"], "trunk")).toBe(true);
119
+ });
120
+ test("the job's environment names it: CHANT_DEFAULT_BRANCH, else GitLab's CI_DEFAULT_BRANCH", () => {
121
+ expect(opWaveDefaultBranch({ CHANT_DEFAULT_BRANCH: "trunk" })).toBe("trunk");
122
+ expect(opWaveDefaultBranch({ CI_DEFAULT_BRANCH: "trunk" })).toBe("trunk");
123
+ expect(opWaveDefaultBranch({ CHANT_DEFAULT_BRANCH: " " })).toBeUndefined();
124
+ });
125
+ });
@@ -17,7 +17,12 @@
17
17
  * ref GitHub and Forgejo: GITHUB_REF is refs/heads/<branch>
18
18
  * for one of the branches the waves apply from. GitLab:
19
19
  * CI_COMMIT_REF_NAME is one of them, and
20
- * CI_COMMIT_REF_PROTECTED is "true".
20
+ * CI_COMMIT_REF_PROTECTED is "true". With
21
+ * `defaultBranch` (#5032) the repository's default
22
+ * branch is one of them, by the name the forge gives
23
+ * at run time: GitLab's CI_DEFAULT_BRANCH, and on
24
+ * GitHub and Forgejo CHANT_DEFAULT_BRANCH, which the
25
+ * job sets from github.event.repository.default_branch.
21
26
  * runner GitLab: CI_RUNNER_TAGS holds each of the job's tags.
22
27
  * GitHub and Forgejo expose no labels, only whether the
23
28
  * runner is self-hosted: when the job's labels include
@@ -80,6 +85,16 @@ import { followOnPath, followOnProblems, followOnRecordProblems, followOnRunFrom
80
85
  /** The variable the generated step carries its expectation in. */
81
86
  export const JOB_GUARD_ENV = "CHANT_JOB_GUARD";
82
87
 
88
+ /**
89
+ * The variable a GitHub or Forgejo job carries the repository's default
90
+ * branch in (#5032), from `github.event.repository.default_branch`. GitLab
91
+ * sets `CI_DEFAULT_BRANCH` itself.
92
+ */
93
+ export const JOB_DEFAULT_BRANCH_ENV = "CHANT_DEFAULT_BRANCH";
94
+
95
+ /** The job variable that sets {@link JOB_DEFAULT_BRANCH_ENV} on GitHub and Forgejo (#5032). */
96
+ export const GITHUB_DEFAULT_BRANCH_ENV: Record<string, string> = { [JOB_DEFAULT_BRANCH_ENV]: "${{ github.event.repository.default_branch }}" };
97
+
83
98
  /** The audience of the token the guard requests on GitHub, which no cloud role should trust. */
84
99
  export const JOB_GUARD_AUDIENCE = "chant-check-job";
85
100
 
@@ -96,6 +111,8 @@ export interface JobGuardSpec {
96
111
  forgeEnvironment?: string;
97
112
  /** The branches the job may run from. */
98
113
  branches: string[];
114
+ /** The job may also run from the repository's default branch, by the name the forge gives at run time (#5032). */
115
+ defaultBranch?: true;
99
116
  /** GitLab: the tags the job's runner must carry. */
100
117
  runnerTags?: string[];
101
118
  /** GitHub and Forgejo: the runner must be self-hosted. */
@@ -114,6 +131,8 @@ export interface JobSeen {
114
131
  forgeEnvironmentError?: string;
115
132
  ref?: string;
116
133
  refProtected?: string;
134
+ /** The repository's default branch, as the forge names it (#5032). Read only when the spec has `defaultBranch`. */
135
+ defaultBranch?: string;
117
136
  runnerTags?: string[];
118
137
  runnerEnvironment?: string;
119
138
  /** The decision the run names (#4984), from its variables. */
@@ -148,6 +167,8 @@ export interface JobGuardInput {
148
167
  environment?: string;
149
168
  /** The branches the job runs from. */
150
169
  branches: readonly string[];
170
+ /** The job also runs from the repository's default branch, whatever the forge calls it (#5032). */
171
+ defaultBranch?: boolean;
151
172
  /** The job's runner, as the spec gives it. */
152
173
  runner?: CiRunner;
153
174
  /** GitHub: the job may request an OIDC token (`id-token: write`), so the guard can read its environment. */
@@ -171,6 +192,7 @@ export function jobGuardSpec(input: JobGuardInput): JobGuardSpec {
171
192
  ...(input.product && input.product !== "chant" ? { product: input.product } : {}),
172
193
  ...(input.environment !== undefined && readsEnvironment ? { forgeEnvironment: input.environment } : {}),
173
194
  branches: [...input.branches],
195
+ ...(input.defaultBranch === true ? { defaultBranch: true as const } : {}),
174
196
  ...(input.forge === "gitlab" && labels.length > 0 ? { runnerTags: labels } : {}),
175
197
  ...(input.forge !== "gitlab" && labels.includes("self-hosted") ? { selfHosted: true } : {}),
176
198
  ...(input.beforeMerge ? { beforeMerge: { op: input.beforeMerge.op } } : {}),
@@ -192,6 +214,7 @@ export function parseJobGuardSpec(raw: string | undefined): JobGuardSpec {
192
214
  if (o.forge !== "github" && o.forge !== "gitlab" && o.forge !== "forgejo") throw new Error(`${JOB_GUARD_ENV}.forge is ${JSON.stringify(o.forge)}; give github, gitlab or forgejo`);
193
215
  if (typeof o.job !== "string" || o.job === "") throw new Error(`${JOB_GUARD_ENV}.job names no job`);
194
216
  if (!Array.isArray(o.branches) || o.branches.some((b) => typeof b !== "string")) throw new Error(`${JOB_GUARD_ENV}.branches is not a list of branches`);
217
+ if (o.defaultBranch !== undefined && o.defaultBranch !== true) throw new Error(`${JOB_GUARD_ENV}.defaultBranch is true or absent`);
195
218
  if (o.forgeEnvironment !== undefined && typeof o.forgeEnvironment !== "string") throw new Error(`${JOB_GUARD_ENV}.forgeEnvironment is not a name`);
196
219
  if (o.runnerTags !== undefined && (!Array.isArray(o.runnerTags) || o.runnerTags.some((t) => typeof t !== "string"))) throw new Error(`${JOB_GUARD_ENV}.runnerTags is not a list of tags`);
197
220
  if (o.beforeMerge !== undefined && (typeof o.beforeMerge !== "object" || o.beforeMerge === null || typeof o.beforeMerge.op !== "string")) throw new Error(`${JOB_GUARD_ENV}.beforeMerge is { op }`);
@@ -201,6 +224,9 @@ export function parseJobGuardSpec(raw: string | undefined): JobGuardSpec {
201
224
 
202
225
  const shown = (v: string | null | undefined): string => (v === undefined || v === null || v === "" ? "none" : v);
203
226
 
227
+ /** The variable the guard reads the default branch from (#5032). */
228
+ const defaultBranchVar = (forge: JobGuardForge): string => (forge === "gitlab" ? "CI_DEFAULT_BRANCH" : JOB_DEFAULT_BRANCH_ENV);
229
+
204
230
  /** The tags CI_RUNNER_TAGS lists: a JSON array, or a comma-separated list. */
205
231
  export function runnerTagsOf(raw: string | undefined): string[] | undefined {
206
232
  if (raw === undefined) return undefined;
@@ -237,8 +263,11 @@ export function checkJob(expect: JobGuardSpec, seen: JobSeen): JobGuardResult {
237
263
  else out.checked.push(`forge environment ${fe}`);
238
264
  }
239
265
 
240
- const branches = expect.branches.filter((b) => b !== "");
241
- if (branches.length === 0) out.problems.push("ref: the job names no branch to run from");
266
+ // #5032: the repository's default branch, by the name the forge gives this run, beside the named ones.
267
+ const named = expect.branches.filter((b) => b !== "");
268
+ const def = expect.defaultBranch ? (seen.defaultBranch ?? "").trim() : "";
269
+ const branches = def !== "" && !named.includes(def) ? [def, ...named] : named;
270
+ if (branches.length === 0) out.problems.push(expect.defaultBranch ? `ref: the job runs from the default branch, and the forge names none (no ${defaultBranchVar(expect.forge)})` : "ref: the job names no branch to run from");
242
271
  else if (expect.forge === "gitlab") {
243
272
  if (!seen.ref || !branches.includes(seen.ref)) out.problems.push(`ref: expected ${branches.join(" or ")}, found ${shown(seen.ref)}`);
244
273
  else out.checked.push(`ref ${seen.ref}`);
@@ -373,15 +402,19 @@ export const lifecycleFileByGit: LifecycleFileReader = (forge, env, path) => {
373
402
 
374
403
  /** What the forge's own variables and token say, before the decision is read. */
375
404
  async function forgeSeen(expect: JobGuardSpec, env: NodeJS.ProcessEnv, fetchFn: typeof fetch): Promise<JobSeen> {
405
+ // #5032: the default branch, read only when the spec runs from it.
406
+ const def = expect.defaultBranch ? env[defaultBranchVar(expect.forge)] : undefined;
407
+ const defaultBranch = def !== undefined && def.trim() !== "" ? { defaultBranch: def.trim() } : {};
376
408
  if (expect.forge === "gitlab") {
377
409
  return {
410
+ ...defaultBranch,
378
411
  forgeEnvironment: env.CI_ENVIRONMENT_NAME || null,
379
412
  ...(env.CI_COMMIT_REF_NAME !== undefined ? { ref: env.CI_COMMIT_REF_NAME } : {}),
380
413
  ...(env.CI_COMMIT_REF_PROTECTED !== undefined ? { refProtected: env.CI_COMMIT_REF_PROTECTED } : {}),
381
414
  ...(env.CI_RUNNER_TAGS !== undefined ? { runnerTags: runnerTagsOf(env.CI_RUNNER_TAGS) } : {}),
382
415
  };
383
416
  }
384
- const seen: JobSeen = { ...(env.GITHUB_REF !== undefined ? { ref: env.GITHUB_REF } : {}) };
417
+ const seen: JobSeen = { ...(env.GITHUB_REF !== undefined ? { ref: env.GITHUB_REF } : {}), ...defaultBranch };
385
418
  let claims: Record<string, unknown> | undefined;
386
419
  if (expect.forge === "github" && expect.forgeEnvironment !== undefined) {
387
420
  try {
@@ -478,8 +511,19 @@ const FOLLOW_ON_JS = [
478
511
  * Exits chant's `misplaced` (9) with one line per value that differs, and
479
512
  * when the variable holds no spec it can read. A test runs it against
480
513
  * {@link checkJob} so the two stay the same.
514
+ *
515
+ * `defaultBranch` (#5032) gives the program that also reads the default
516
+ * branch, for a spec with `defaultBranch`; a job without it carries the
517
+ * program as it was.
481
518
  */
482
- export const JOB_GUARD_JS = [
519
+ function jobGuardProgram(defaultBranch: boolean): string {
520
+ const branchLines = defaultBranch
521
+ ? [
522
+ `const b=x.branches.filter((v)=>v!=="");const DV=x.forge==="gitlab"?"CI_DEFAULT_BRANCH":${JSON.stringify(JOB_DEFAULT_BRANCH_ENV)};const D=x.defaultBranch?String(E[DV]||"").trim():"";if(D!==""&&!b.includes(D))b.unshift(D);`,
523
+ 'if(b.length===0)P.push(x.defaultBranch?"ref: the job runs from the default branch, and the forge names none (no "+DV+")":"ref: the job names no branch to run from");',
524
+ ]
525
+ : ['const b=x.branches.filter((v)=>v!=="");', 'if(b.length===0)P.push("ref: the job names no branch to run from");'];
526
+ return [
483
527
  '"use strict";',
484
528
  `const E=process.env,A=${JSON.stringify(JOB_GUARD_AUDIENCE)};`,
485
529
  "const shown=(v)=>v===undefined||v===null||v===\"\"?\"none\":v;",
@@ -502,8 +546,7 @@ export const JOB_GUARD_JS = [
502
546
  "seenOf().then((s)=>{const P=[],C=[],S=[];const fe=x.forgeEnvironment;",
503
547
  'if(x.forge==="forgejo")S.push("forge environment (Forgejo has none)");',
504
548
  'else if(fe!==undefined){if(s.forgeEnvironmentError!==undefined)P.push("forge environment: expected "+fe+", and it could not be read: "+s.forgeEnvironmentError);else if(s.forgeEnvironment!==fe)P.push("forge environment: expected "+fe+", found "+shown(s.forgeEnvironment));else C.push("forge environment "+fe)}',
505
- 'const b=x.branches.filter((v)=>v!=="");',
506
- 'if(b.length===0)P.push("ref: the job names no branch to run from");',
549
+ ...branchLines,
507
550
  'else if(x.forge==="gitlab"){if(!s.ref||!b.includes(s.ref))P.push("ref: expected "+b.join(" or ")+", found "+shown(s.ref));else C.push("ref "+s.ref);',
508
551
  'if(s.refProtected!=="true")P.push("ref: expected a protected ref (CI_COMMIT_REF_PROTECTED true), found "+shown(s.refProtected));else C.push("protected ref")}',
509
552
  'else{const refs=b.map((v)=>"refs/heads/"+v);if(!s.ref||!refs.includes(s.ref))P.push("ref: expected "+refs.join(" or ")+", found "+shown(s.ref));else C.push("ref "+s.ref)}',
@@ -521,10 +564,21 @@ export const JOB_GUARD_JS = [
521
564
  'console.log(at+": "+(C.length?C.join(", "):"nothing to check")+(S.length?"; not checked: "+S.join(", "):""))',
522
565
  "}).catch((e)=>fail(e&&e.message?e.message:String(e)));",
523
566
  ].join("");
567
+ }
568
+
569
+ /** The guard as one `node -e` program; see {@link jobGuardProgram}. */
570
+ export const JOB_GUARD_JS = jobGuardProgram(false);
571
+
572
+ /** The same program for a spec with `defaultBranch` (#5032), which also reads the default branch. */
573
+ export const JOB_GUARD_DEFAULT_BRANCH_JS = jobGuardProgram(true);
524
574
 
525
- /** The shell line of the guard step: `node -e` from `/`, so no file of the checkout is in reach. */
526
- export function jobGuardLine(): string {
527
- return `(cd / && node -e '${JOB_GUARD_JS}')`;
575
+ /**
576
+ * The shell line of the guard step: `node -e` from `/`, so no file of the
577
+ * checkout is in reach. #5032: a spec with `defaultBranch` gets the program
578
+ * that reads the default branch.
579
+ */
580
+ export function jobGuardLine(spec?: Pick<JobGuardSpec, "defaultBranch">): string {
581
+ return `(cd / && node -e '${spec?.defaultBranch ? JOB_GUARD_DEFAULT_BRANCH_JS : JOB_GUARD_JS}')`;
528
582
  }
529
583
 
530
584
  /** How the guard's lines name an op-wave job: `wave 2 (prod) of deploy`, `share 1 of job group eu of wave 2 (prod) of deploy`. */
package/src/ci-jobs.ts CHANGED
@@ -60,6 +60,32 @@ export function pushBranches(branches: readonly string[] | undefined): string[]
60
60
  return branches && branches.length > 0 ? [...branches] : [DEFAULT_BRANCH];
61
61
  }
62
62
 
63
+ /**
64
+ * The branches an Op waves spec names (#5032): with `defaultBranch` its
65
+ * `branches` alone, beside the repository's default branch that the forge
66
+ * names at run time; without it {@link pushBranches}'.
67
+ */
68
+ export function wavesNamedBranches(spec: { branches?: readonly string[]; defaultBranch?: boolean }): string[] {
69
+ return spec.defaultBranch === true ? [...(spec.branches ?? [])] : pushBranches(spec.branches);
70
+ }
71
+
72
+ /** GitHub and Forgejo: the `if:` expression for a ref the waves run from (#5032), the default branch first. */
73
+ export function githubWavesBranchIf(spec: { branches?: readonly string[]; defaultBranch?: boolean }): string {
74
+ const quoted = (b: string): string => `'refs/heads/${b.replace(/'/g, "''")}'`;
75
+ return [
76
+ ...(spec.defaultBranch === true ? ["github.ref == format('refs/heads/{0}', github.event.repository.default_branch)"] : []),
77
+ ...wavesNamedBranches(spec).map((b) => `github.ref == ${quoted(b)}`),
78
+ ].join(" || ");
79
+ }
80
+
81
+ /** GitLab: each branch a waves spec runs from as a rule's operand (#5032): `$CI_DEFAULT_BRANCH`, then each named one quoted. */
82
+ export function gitlabWavesBranches(spec: { branches?: readonly string[]; defaultBranch?: boolean }): Array<{ branch: string; operand: string }> {
83
+ return [
84
+ ...(spec.defaultBranch === true ? [{ branch: "", operand: "$CI_DEFAULT_BRANCH" }] : []),
85
+ ...wavesNamedBranches(spec).map((b) => ({ branch: b, operand: JSON.stringify(b) })),
86
+ ];
87
+ }
88
+
63
89
  /**
64
90
  * The branches a trigger filters on: a `pull_request` trigger's list, or
65
91
  * undefined for every branch; a `push` trigger's, with {@link pushBranches}'