blueprint-shared-templates 0.1.0-0 → 0.2.0

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 (100) hide show
  1. package/base/.github/CODEOWNERS.example +10 -0
  2. package/base/.github/ISSUE_TEMPLATE/bug.yml +15 -0
  3. package/base/.github/ISSUE_TEMPLATE/feature.yml +19 -0
  4. package/base/.github/ISSUE_TEMPLATE/hotfix.yml +17 -0
  5. package/base/.github/PULL_REQUEST_TEMPLATE.md +13 -0
  6. package/base/.github/actions/setup-workspace/action.yml +54 -0
  7. package/base/.github/version-control.md +22 -0
  8. package/base/.github/workflows/auto-merge.yml +138 -0
  9. package/base/.github/workflows/ci.yml +274 -0
  10. package/base/.github/workflows/main-commit-check.yml +42 -0
  11. package/base/.github/workflows/pr-message.yml +64 -0
  12. package/base/.gitignore +356 -0
  13. package/base/.oxlintrc.json +14 -0
  14. package/base/LICENSE +21 -0
  15. package/base/releases/release-plan.md +39 -0
  16. package/base/scripts/ci/affected.sh +15 -0
  17. package/base/scripts/ci/ai-attribution-list.txt +68 -0
  18. package/base/scripts/ci/check-commit-body.sh +110 -0
  19. package/base/scripts/ci/check-main-commits.sh +31 -0
  20. package/base/scripts/ci/check-pr-title.sh +10 -0
  21. package/base/scripts/ci/ci-scope.conf +23 -0
  22. package/base/scripts/ci/ci-scope.sh +106 -0
  23. package/base/scripts/ci/native-build.sh +40 -0
  24. package/base/scripts/ci/run-affected.sh +48 -0
  25. package/base/scripts/ci/run-units.sh +33 -0
  26. package/base/scripts/hooks/commit-msg +38 -0
  27. package/base/scripts/hooks/pre-push +63 -0
  28. package/base/scripts/lib/common.sh +233 -0
  29. package/base/scripts/lib/retry.mjs +178 -0
  30. package/base/scripts/merge/decide.mjs +130 -0
  31. package/base/scripts/setup/git-hooks.sh +16 -0
  32. package/base/scripts/setup/github-repo-settings.json +8 -0
  33. package/base/scripts/setup/github-repo-settings.sh +110 -0
  34. package/deploy/.github/workflows/deploy-prerelease.yml +157 -0
  35. package/deploy/.github/workflows/deploy-production.yml +173 -0
  36. package/deploy/scripts/deploy/build-bundle.sh +49 -0
  37. package/deploy/scripts/deploy/clone-ops.sh +14 -0
  38. package/deploy/scripts/deploy/plan-production.sh +43 -0
  39. package/deploy/scripts/deploy/promote.sh +35 -0
  40. package/deploy/scripts/deploy/publish-bundle.sh +21 -0
  41. package/deploy/scripts/deploy/route-tag.sh +65 -0
  42. package/deploy/scripts/deploy/run-prerelease.sh +49 -0
  43. package/deploy/scripts/deploy/run-production.sh +51 -0
  44. package/deploy/scripts/deploy/writeback-ops.sh +53 -0
  45. package/deploy/scripts/lib/bundle.sh +52 -0
  46. package/facts-describes.ts +53 -0
  47. package/facts-skeleton.mjs +84 -0
  48. package/hub/.github/workflows/open-release-lines.yml +63 -0
  49. package/hub/scripts/deploy/clone-ops.sh +14 -0
  50. package/hub/scripts/release/dispatch-release-lines.sh +54 -0
  51. package/hub/scripts/release/snapshot-members.sh +85 -0
  52. package/infra/.github/workflows/deploy-prerelease.yml +157 -0
  53. package/infra/.github/workflows/deploy-production.yml +173 -0
  54. package/infra/scripts/deploy/apply-infra.sh +46 -0
  55. package/infra/scripts/deploy/apply-prerelease.sh +22 -0
  56. package/infra/scripts/deploy/apply-production.sh +33 -0
  57. package/infra/scripts/deploy/route-tag.sh +65 -0
  58. package/ops/.github/workflows/ops-deploy.yml +88 -0
  59. package/ops/scripts/deploy/apply-ops.sh +100 -0
  60. package/ops/scripts/deploy/healthz.sh +16 -0
  61. package/ops/scripts/deploy/ops-run.sh +41 -0
  62. package/ops/scripts/deploy/smoke.sh +49 -0
  63. package/ops/scripts/lib/bundle.sh +52 -0
  64. package/package.json +21 -4
  65. package/publish/.github/workflows/publish.yml +299 -0
  66. package/publish/scripts/release/cleanup-private-packages.mjs +107 -0
  67. package/publish/scripts/release/mirror-units.sh +167 -0
  68. package/publish/scripts/release/publish-units.sh +489 -0
  69. package/release/.github/workflows/nightly.yml +93 -0
  70. package/release/.github/workflows/open-release-line.yml +70 -0
  71. package/release/.github/workflows/release-line-finalize.yml +101 -0
  72. package/release/.github/workflows/release-please.yml +148 -0
  73. package/release/release-please-config.json +39 -0
  74. package/release/release-policy.json +38 -0
  75. package/release/schemas/release-policy.schema.json +151 -0
  76. package/release/scripts/ci/check-facts-describes.sh +63 -0
  77. package/release/scripts/ci/check-facts.sh +46 -0
  78. package/release/scripts/ci/check-release-policy-schema.sh +59 -0
  79. package/release/scripts/ci/check-release-policy.sh +123 -0
  80. package/release/scripts/ci/pin-train.sh +29 -0
  81. package/release/scripts/ci/release-train.sh +39 -0
  82. package/release/scripts/ci/validate-json-schema.mjs +17 -0
  83. package/release/scripts/lib/docs.sh +71 -0
  84. package/release/scripts/lib/facts.sh +146 -0
  85. package/release/scripts/lib/release-plan.sh +128 -0
  86. package/release/scripts/lib/release-pr.sh +106 -0
  87. package/release/scripts/lib/release-stages.sh +903 -0
  88. package/release/scripts/release/advance-release.sh +86 -0
  89. package/release/scripts/release/cut-release.sh +313 -0
  90. package/release/scripts/release/dispatch-publish.sh +34 -0
  91. package/release/scripts/release/ensure-stage-deploys.sh +56 -0
  92. package/release/scripts/release/finalize-release.sh +351 -0
  93. package/release/scripts/release/merge-release-pr.sh +233 -0
  94. package/release/scripts/release/open-release-line.sh +22 -0
  95. package/release/scripts/release/plan.sh +45 -0
  96. package/release/scripts/release/snapshot.sh +57 -0
  97. package/release/scripts/release/verify-production.sh +63 -0
  98. package/transform.mjs +64 -0
  99. package/verify/.github/workflows/verify-production.yml +71 -0
  100. package/verify/scripts/release/verify-ops.sh +41 -0
@@ -0,0 +1,178 @@
1
+ // The one place that asks again after a transient error of GitHub (decision transient-error-shared-retry).
2
+ // A transient error is HTTP 500, 502, 503 or 504 (gh and git word it differently) and a connect timeout. Nothing else counts: another
3
+ // 5xx, a 4xx, a refused write and a dropped credential do not get better by asking again.
4
+ //
5
+ // transientOf(text) "HTTP 502" | "Connect Timeout" | null
6
+ // retryMove(...) the pure rule: after a failure, retry, stop or check first. Every caller decides through it.
7
+ // retryTransient the async loop around retryMove; retryTransientSync is the same loop for a caller that cannot await
8
+ // CLI node retry.mjs <read|push|merge> -- <cmd> [args...]
9
+ //
10
+ // What each kind retries (a failure of any other text stops at once, with the error as it was):
11
+ // read a transient error, and what the caller adds through `also` (local.mjs adds the HTTP 404 of a run that was just dispatched)
12
+ // push a transient error, and never a force or a delete (--force, -f, --force-with-lease, --force-if-includes, --delete, -d, +refspec,
13
+ // :ref, --mirror, --prune): the retry of a write that rewrites or removes history is a decision, not a reflex
14
+ // merge a transient error and "Base branch was modified" (the base moved between the pull request being opened and merged)
15
+ // dispatch a transient error, but first `exists()` asks whether the dispatch made its run; a run that is there is returned and the
16
+ // dispatch is not made again. Without a nonce `exists` cannot be written, so such a dispatch is not retried at all.
17
+ // The pause between rounds is the caller's (`pause`): this file sleeps only in the CLI, whose interval is RETRY_SLEEP seconds.
18
+ import { spawnSync } from "node:child_process";
19
+ import { resolve } from "node:path";
20
+ import { fileURLToPath } from "node:url";
21
+
22
+ export const ROUNDS = 5;
23
+ export const SLEEP_SECONDS = 5;
24
+ export const KINDS = ["read", "push", "merge", "dispatch"];
25
+ export const CLI_KINDS = ["read", "push", "merge"];
26
+
27
+ const CODES = ["500", "502", "503", "504"];
28
+ export function transientOf(text) {
29
+ const s = String(text ?? "");
30
+ const codes = [...s.matchAll(/\bHTTP\/?\s*(\d{3})\b/gi), ...s.matchAll(/requested URL returned error:\s*(\d{3})\b/gi)].map((m) => m[1]);
31
+ const code = codes.find((c) => CODES.includes(c));
32
+ if (code) return `HTTP ${code}`;
33
+ if (/Connect Timeout|connect: connection timed out|Connection timed out/i.test(s)) return "Connect Timeout";
34
+ return null;
35
+ }
36
+
37
+ export const BASE_MODIFIED = "Base branch was modified";
38
+
39
+ const LONG_REWRITE = /^--(?:force(?:-with-lease|-if-includes)?|delete|mirror|prune)(?:=.*)?$/;
40
+ const SHORT_REWRITE = /^-[A-Za-z]*[fd][A-Za-z]*$/;
41
+ // true when the command line of a git push rewrites or removes something on the remote
42
+ export function rewritesRemote(argv = []) {
43
+ const at = argv.indexOf("push");
44
+ const args = at >= 0 ? argv.slice(at + 1) : argv;
45
+ return args.some((a) => LONG_REWRITE.test(a) || SHORT_REWRITE.test(a) || a.startsWith("+") || /^:[^:]/.test(a));
46
+ }
47
+
48
+ /**
49
+ * The rule after a failure. Pure: it reads the text of the failure and the round, nothing else.
50
+ * @param {object} p
51
+ * @param {"read"|"push"|"merge"|"dispatch"} p.kind
52
+ * @param {string} p.text the text of the failure (message, stderr, stdout)
53
+ * @param {number} p.round the round that just failed, from 1
54
+ * @param {number} [p.rounds]
55
+ * @param {string[]} [p.argv] the command line, for push
56
+ * @param {(text:string) => string|null} [p.also] an extra reason to retry a read, as text, or null
57
+ * @returns {{move:"retry"|"stop"|"check", reason:string|null, why?:"not-transient"|"force"|"exhausted", final?:boolean}}
58
+ * check (dispatch only): ask exists() before anything else; `final` says this was the last round, so a missing run ends it
59
+ */
60
+ export function retryMove({ kind, text, round, rounds = ROUNDS, argv = [], also = null }) {
61
+ if (!KINDS.includes(kind)) throw new Error(`retry kind ${kind}: expected ${KINDS.join(", ")}`);
62
+ let reason = transientOf(text);
63
+ if (reason === null && kind === "merge" && new RegExp(BASE_MODIFIED, "i").test(String(text ?? ""))) reason = BASE_MODIFIED;
64
+ if (reason === null && kind === "read" && also) reason = also(String(text ?? "")) ?? null;
65
+ if (reason === null) return { move: "stop", reason: null, why: "not-transient" };
66
+ if (kind === "push" && rewritesRemote(argv)) return { move: "stop", reason, why: "force" };
67
+ if (kind === "dispatch") return { move: "check", reason, final: round >= rounds };
68
+ if (round >= rounds) return { move: "stop", reason, why: "exhausted" };
69
+ return { move: "retry", reason };
70
+ }
71
+
72
+ // the failure that ended a retry loop because the rounds were used up
73
+ export class RetryExhausted extends Error {
74
+ constructor(cause, tries, reason) {
75
+ super(`${cause?.message ?? cause}(試了 ${tries} 次,最後的理由 ${reason})`);
76
+ Object.assign(this, { cause, tries, reason });
77
+ }
78
+ }
79
+
80
+ export const errorText = (e) => [e?.message ?? e, e?.stderr, e?.stdout].filter((x) => x !== undefined && x !== null && x !== "").join("\n");
81
+
82
+ // What a failure leads to, shared by the async and the sync loop: { done } (return it), { fail } (throw it) or { wait } (pause, go on)
83
+ function settle(error, round, { kind, also, rounds, argv }, found) {
84
+ const move = retryMove({ kind, text: errorText(error), round, rounds, argv, also });
85
+ if (move.move === "stop") return { fail: move.why === "exhausted" ? new RetryExhausted(error, round, move.reason) : error };
86
+ if (move.move === "check") {
87
+ if (found) return { done: found.value };
88
+ return move.final ? { fail: new RetryExhausted(error, round, move.reason) } : { wait: move.reason };
89
+ }
90
+ return { wait: move.reason };
91
+ }
92
+ const need = (kind, exists) => { if (kind === "dispatch" && typeof exists !== "function") throw new Error("retry kind dispatch needs exists(): a dispatch that cannot be looked up is not retried"); };
93
+ const isCheck = (error, round, o) => retryMove({ kind: o.kind, text: errorText(error), round, rounds: o.rounds, argv: o.argv, also: o.also }).move === "check";
94
+
95
+ /**
96
+ * Runs attempt(round) until it returns, asking retryMove after each failure.
97
+ * @param {object} p
98
+ * @param {string} p.kind read | push | merge | dispatch
99
+ * @param {(round:number) => Promise<any>} p.attempt
100
+ * @param {() => Promise<any>} [p.exists] dispatch: the run the dispatch made, or null (a falsy answer means none)
101
+ * @param {(text:string) => string|null} [p.also]
102
+ * @param {number} [p.rounds]
103
+ * @param {(round:number, reason:string) => Promise<void>} [p.pause] called between two rounds; the default does not wait
104
+ * @param {string[]} [p.argv]
105
+ */
106
+ export async function retryTransient({ kind, attempt, exists, also = null, rounds = ROUNDS, pause = async () => {}, argv = [] }) {
107
+ need(kind, exists);
108
+ const o = { kind, exists, also, rounds, argv };
109
+ for (let round = 1; ; round++) {
110
+ let error;
111
+ try { return await attempt(round); } catch (e) { error = e; }
112
+ const found = isCheck(error, round, o) ? { value: await exists() } : null;
113
+ const s = settle(error, round, o, found?.value ? found : null);
114
+ if ("done" in s) return s.done;
115
+ if (s.fail) throw s.fail;
116
+ await pause(round, s.wait);
117
+ }
118
+ }
119
+
120
+ // The same for a caller that cannot await (the scenario world runs its commands with spawnSync): attempt, exists and pause are sync.
121
+ export function retryTransientSync({ kind, attempt, exists, also = null, rounds = ROUNDS, pause = () => {}, argv = [] }) {
122
+ need(kind, exists);
123
+ const o = { kind, exists, also, rounds, argv };
124
+ for (let round = 1; ; round++) {
125
+ let error;
126
+ try { return attempt(round); } catch (e) { error = e; }
127
+ const found = isCheck(error, round, o) ? { value: exists() } : null;
128
+ const s = settle(error, round, o, found?.value ? found : null);
129
+ if ("done" in s) return s.done;
130
+ if (s.fail) throw s.fail;
131
+ pause(round, s.wait);
132
+ }
133
+ }
134
+
135
+ // --- CLI ---------------------------------------------------------------------------------------------------------------------
136
+ class CommandFailed extends Error {
137
+ constructor(r) {
138
+ super(`exit status ${r.status ?? 1}`);
139
+ Object.assign(this, { status: r.status ?? 1, stdout: r.stdout ?? "", stderr: r.stderr ?? "" });
140
+ }
141
+ }
142
+
143
+ // Runs the command, prints what it printed as it was, and asks again after a failure the kind retries. The exit status is the status
144
+ // of the last run. `sleep` is how the CLI waits (seconds); the default really waits.
145
+ export async function main(args, { env = process.env, out = process.stdout, err = process.stderr, sleep = (s) => new Promise((r) => setTimeout(r, s * 1000)) } = {}) {
146
+ const [kind, sep, ...cmd] = args;
147
+ if (!CLI_KINDS.includes(kind) || sep !== "--" || cmd.length === 0) {
148
+ err.write(`usage: node retry.mjs <${CLI_KINDS.join("|")}> -- <cmd> [args...]\n`);
149
+ return 2;
150
+ }
151
+ const seconds = Number(env.RETRY_SLEEP ?? SLEEP_SECONDS);
152
+ const attempt = async () => {
153
+ const r = spawnSync(cmd[0], cmd.slice(1), { encoding: "utf8", stdio: ["inherit", "pipe", "pipe"], maxBuffer: 256 * 1024 * 1024, env });
154
+ if (r.error) throw new CommandFailed({ status: 127, stderr: `${cmd[0]}: ${r.error.message}\n` });
155
+ out.write(r.stdout ?? "");
156
+ err.write(r.stderr ?? "");
157
+ if (r.status !== 0) throw new CommandFailed(r);
158
+ return r;
159
+ };
160
+ try {
161
+ await retryTransient({
162
+ kind, attempt, argv: cmd,
163
+ pause: async (round, reason) => {
164
+ err.write(`! 第 ${round} 次失敗(${reason}),${seconds} 秒後重試\n`);
165
+ await sleep(seconds);
166
+ },
167
+ });
168
+ return 0;
169
+ } catch (e) {
170
+ const failed = e instanceof RetryExhausted ? e.cause : e;
171
+ if (e instanceof RetryExhausted) err.write(`✗ 重試 ${e.tries} 次仍失敗,最後的理由:${e.reason}\n`);
172
+ return failed?.status ?? 1;
173
+ }
174
+ }
175
+
176
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
177
+ process.exitCode = await main(process.argv.slice(2));
178
+ }
@@ -0,0 +1,130 @@
1
+ // Decides what the auto-merge workflow does with one pull request. It only reads the facts of the pull request and
2
+ // of its checks, and prints the decision; the workflow runs `gh` and does the merge, so this file stays testable
3
+ // without a network.
4
+ //
5
+ // usage: node scripts/merge/decide.mjs --input <file|-> [--config scripts/merge/merge-config.json]
6
+ // input JSON { pr, checkedSha, checks, changedFiles }
7
+ // pr from `gh pr view --json number,state,isDraft,headRefOid,headRefName,baseRefName,isCrossRepository,labels`,
8
+ // read last, just before this decision
9
+ // checkedSha the head commit of the pull request when the checks were read
10
+ // checks from `gh pr checks --json name,bucket`; bucket is pass, fail, pending, skipping or cancel
11
+ // changedFiles the paths the pull request changes (only used for the checks in config.pathFiltered)
12
+ // config JSON { label, requiredChecks, pathFiltered, reviewPaths, syncPr }, written when the repository is composed
13
+ // from blueprint-shared.merge.required-checks. pathFiltered maps a check name to the path globs of the workflow that
14
+ // has a path filter: when none of the changed files matches, that workflow did not run and the check
15
+ // counts as skipped. reviewPaths are the CODEOWNERS style paths (blueprint-shared.git-flow.review-paths) that need
16
+ // a review; empty or missing means no pull request needs one here. syncPr is { author, branch }: the
17
+ // pull request that blueprint opens in a demo repository (blueprint.sync.pull-request), which needs no review.
18
+ // pr also needs author ({ login, is_bot }) and latestReviews ([{ state }]) from `gh pr view --json`.
19
+ // Output: one JSON line { action, reason, ... }. action is "merge", "merge-release-pr" or "skip". A skip because a
20
+ // required check failed also lists those checks in failed.
21
+ // Exit status: 0 whenever a decision was made, 2 when the input or the config is unusable.
22
+ import { readFileSync } from "node:fs";
23
+ import { matchesGlob, resolve } from "node:path";
24
+ import { fileURLToPath } from "node:url";
25
+
26
+ const RELEASE_PR_HEAD = "release-please--";
27
+ const RELEASE_LINE = /^release\/v(\d+\.\d+)$/;
28
+
29
+ const skip = (reason, extra = {}) => ({ action: "skip", reason, ...extra });
30
+
31
+ // A sync pull request is made by the GitHub App on the sync branch, both at once. The branch name alone is not
32
+ // enough: anyone who can push can open a pull request from a branch of the same name. gh prints the App as
33
+ // "app/<slug>", the REST API as "<slug>[bot]"; the bare slug is a user account and does not count.
34
+ export function isSyncPr(pr, syncPr) {
35
+ if (!syncPr?.author || !syncPr?.branch) return false;
36
+ const slug = syncPr.author.replace(/\[bot\]$/, "");
37
+ const login = pr.author?.login;
38
+ return pr.headRefName === syncPr.branch && (login === `${slug}[bot]` || login === `app/${slug}`) && pr.author?.is_bot !== false;
39
+ }
40
+
41
+ // CODEOWNERS style: "/dir/" is everything under dir, "/file*.json" a file at the root.
42
+ const reviewGlob = (path) => (path.endsWith("/") ? `${path.replace(/^\//, "")}**` : path.replace(/^\//, ""));
43
+ export const touchesReviewPath = (files, paths = []) => files.some((f) => paths.some((p) => matchesGlob(f, reviewGlob(p))));
44
+
45
+ // "fail" for a failed or cancelled check, "pending" for a running one, "pass" for a successful or skipped one.
46
+ // A skipped check passes: the scope job of ci.yml skips the others when nothing in the diff needs checking.
47
+ function stateOf(entries) {
48
+ const buckets = entries.map((e) => e.bucket);
49
+ if (buckets.some((b) => b === "fail" || b === "cancel")) return "fail";
50
+ if (buckets.some((b) => b === "pending")) return "pending";
51
+ return "pass";
52
+ }
53
+
54
+ export function decide({ pr, checkedSha, checks = [], changedFiles = [] }, config) {
55
+ const { label, requiredChecks, pathFiltered = {} } = config;
56
+ const number = pr.number;
57
+ if (pr.state !== "OPEN") return skip(`the pull request is ${pr.state}, not OPEN`, { pr: number });
58
+ if (pr.isCrossRepository) return skip("the pull request comes from a fork and cannot get the App token", { pr: number });
59
+ const labels = (pr.labels ?? []).map((l) => (typeof l === "string" ? l : l.name));
60
+ if (!labels.includes(label)) return skip(`the pull request has no ${label} label`, { pr: number });
61
+ if (pr.isDraft) return skip("the pull request is a draft", { pr: number });
62
+ if (checkedSha !== pr.headRefOid) {
63
+ return skip(`a commit was pushed after the checks were read (checked ${checkedSha}, head now ${pr.headRefOid})`, { pr: number });
64
+ }
65
+
66
+ const failed = [];
67
+ const pending = [];
68
+ const missing = [];
69
+ for (const name of requiredChecks) {
70
+ const entries = checks.filter((c) => c.name === name);
71
+ if (entries.length === 0) {
72
+ const globs = pathFiltered[name];
73
+ const filteredOut = globs !== undefined && !changedFiles.some((file) => globs.some((glob) => matchesGlob(file, glob)));
74
+ if (!filteredOut) missing.push(name);
75
+ continue;
76
+ }
77
+ const state = stateOf(entries);
78
+ if (state === "fail") failed.push(name);
79
+ else if (state === "pending") pending.push(name);
80
+ }
81
+ if (failed.length > 0) return skip(`required check failed: ${failed.join(", ")}`, { pr: number, failed });
82
+ if (pending.length > 0) return skip(`required check still running: ${pending.join(", ")}`, { pr: number });
83
+ if (missing.length > 0) return skip(`required check has not run: ${missing.join(", ")}`, { pr: number });
84
+
85
+ const release = pr.headRefName.startsWith(RELEASE_PR_HEAD);
86
+ // A change to a review path needs an approving review, except a sync pull request (blueprint.merge.sync-pr-review-exempt)
87
+ // and a Release PR, which merge-release-pr.sh merges on a machine. The required checks above still have to pass for all of them.
88
+ if (!release && !isSyncPr(pr, config.syncPr) && touchesReviewPath(changedFiles, config.reviewPaths)) {
89
+ const states = (pr.latestReviews ?? []).map((r) => r.state);
90
+ if (states.includes("CHANGES_REQUESTED")) return skip("a review asks for changes on a pull request that changes a review path", { pr: number });
91
+ if (!states.includes("APPROVED")) return skip("the pull request changes a review path and has no approving review yet", { pr: number });
92
+ }
93
+
94
+ // A Release PR is not merged by this workflow. It waits for release-please to settle and its facts have to be pinned first, so a person
95
+ // merges it on their machine with merge-release-pr.sh (git-flow-template docs/versioning.md:28), and the real run of the demos does it
96
+ // in its pin and merge steps (decision real-run-local-orchestration).
97
+ if (release) {
98
+ if (!RELEASE_LINE.test(pr.baseRefName)) return skip(`a Release PR must target release/vX.Y, this one targets ${pr.baseRefName}`, { pr: number });
99
+ return skip("a Release PR is merged with merge-release-pr.sh on a machine, not by this workflow", { pr: number });
100
+ }
101
+ return {
102
+ action: "merge",
103
+ reason: "all required checks passed or were skipped",
104
+ pr: number,
105
+ sha: checkedSha,
106
+ command: ["gh", "pr", "merge", String(number), "--squash", "--match-head-commit", checkedSha, "--delete-branch"],
107
+ };
108
+ }
109
+
110
+ const read = (p) => readFileSync(p === "-" ? 0 : p, "utf8");
111
+
112
+ function main(argv) {
113
+ const opt = (k, d) => (argv.includes(`--${k}`) ? argv[argv.indexOf(`--${k}`) + 1] : d);
114
+ const input = opt("input");
115
+ if (!input) throw new Error("missing --input <file|->");
116
+ const config = JSON.parse(read(opt("config", "scripts/merge/merge-config.json")));
117
+ if (typeof config.label !== "string" || !Array.isArray(config.requiredChecks) || config.requiredChecks.length === 0) {
118
+ throw new Error("the config needs a label and a non-empty requiredChecks");
119
+ }
120
+ console.log(JSON.stringify(decide(JSON.parse(read(input)), config)));
121
+ }
122
+
123
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
124
+ try {
125
+ main(process.argv.slice(2));
126
+ } catch (e) {
127
+ console.error(`decide.mjs: ${e.message}`);
128
+ process.exit(2);
129
+ }
130
+ }
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env bash
2
+ # Point git at the repository's hooks (scripts/hooks), which guard the local lane into main. Runs from
3
+ # pnpm's prepare on every install, so a fresh clone is guarded without a separate step. A repository that
4
+ # only takes changes through PRs drops the prepare script from package.json and runs
5
+ # git config --unset core.hooksPath.
6
+ #
7
+ # Also sets commit.cleanup scissors. Messages use "## " section headings (docs/git-flow.md, commit 與 PR
8
+ # 訊息格式); when a message is written in the editor, git's default cleanup (strip) deletes every line
9
+ # starting with "#", headings included. scissors keeps them and drops only git's help text, which it
10
+ # places below a scissors line. Messages given with -m or -F are not edited and keep "#" lines either way.
11
+ # usage: git-hooks.sh
12
+ set -euo pipefail
13
+ git rev-parse --is-inside-work-tree >/dev/null 2>&1 || exit 0 # a packed tarball has no git
14
+ git config core.hooksPath scripts/hooks
15
+ git config commit.cleanup scissors
16
+ printf '%s\n' "git hooks → scripts/hooks(commit-msg、pre-push);commit.cleanup → scissors"
@@ -0,0 +1,8 @@
1
+ {
2
+ "squash": true,
3
+ "deleteBranchOnMerge": true,
4
+ "retentionDays": 7,
5
+ "autoMergeLabel": "auto-merge",
6
+ "autoMergeLabelColor": "bfdadc",
7
+ "autoMergeLabelDescription": "必要檢查通過後由 GitHub App 自動合併"
8
+ }
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env bash
2
+ # Lock repositories to squash-merge so release-please reads exactly what ci.yml checked, and set the
3
+ # repository-level retention of Actions artifacts and logs.
4
+ #
5
+ # allow_merge_commit / allow_rebase_merge = false
6
+ # A merge commit or a rebase lands every branch commit on main, while ci.yml checks only the PR title.
7
+ # squash_merge_commit_title = PR_TITLE
8
+ # The default COMMIT_OR_PR_TITLE takes the commit message when the branch has one commit, which
9
+ # bypasses the title check.
10
+ # squash_merge_commit_message = PR_BODY
11
+ # Puts Closes #N and the BREAKING CHANGE: footer into the commit body.
12
+ # delete_branch_on_merge = true
13
+ # The merge flow runs `gh pr merge --squash` without `--delete-branch`, and agents may not delete
14
+ # remote branches, so this setting is what removes the remote branch.
15
+ # artifact-and-log-retention days
16
+ # Applies only to what is created afterwards, so set it before the first real run.
17
+ # auto-merge label
18
+ # decide.mjs skips every pull request that has no auto-merge label, so without it the auto merge never
19
+ # takes effect. The label is created (or updated with --force) when it is missing or its color or
20
+ # description differ.
21
+ #
22
+ # The values of squash, delete-branch, days and the label come from github-repo-settings.json next to this script,
23
+ # a copy of blueprint-shared.merge.method and blueprint-shared.retention.repository-days (tests/repo-settings.test.mjs
24
+ # fails when they drift).
25
+ #
26
+ # Reads the current values first and sends only the requests that change something. A failing repository
27
+ # does not stop the others; the failed ones are listed at the end and the exit status is 1.
28
+ # External write (modify) → confirmation + audit.
29
+ # usage: github-repo-settings.sh [--yes] [--dry-run] [<owner/repo>...] (no repository: the current one)
30
+ set -euo pipefail
31
+ source "$(dirname "$0")/../lib/common.sh"
32
+
33
+ repos=()
34
+ while [[ $# -gt 0 ]]; do
35
+ case "$1" in
36
+ --yes) ASSUME_YES=1; export ASSUME_YES; shift ;;
37
+ --dry-run) DRY_RUN=1; shift ;;
38
+ -*) die "unknown argument: $1" ;;
39
+ *) repos+=("$1"); shift ;;
40
+ esac
41
+ done
42
+ if (( ${#repos[@]} == 0 )); then repos=("$(gh repo view --json nameWithOwner --jq .nameWithOwner)"); fi
43
+
44
+ settings="$(dirname "$0")/github-repo-settings.json"
45
+ squash="$(jq -r '.squash' "$settings")"
46
+ delete_branch="$(jq -r '.deleteBranchOnMerge' "$settings")"
47
+ days="$(jq -r '.retentionDays' "$settings")"
48
+ label="$(jq -r '.autoMergeLabel' "$settings")"
49
+ label_color="$(jq -r '.autoMergeLabelColor' "$settings")"
50
+ label_desc="$(jq -r '.autoMergeLabelDescription' "$settings")"
51
+ [[ -n "$label" && "$label" != null && "$label_color" =~ ^[0-9a-fA-F]{6}$ && -n "$label_desc" && "$label_desc" != null ]] || die "invalid $settings"
52
+ [[ "$squash" == true && "$delete_branch" == true && "$days" =~ ^[0-9]+$ ]] || die "invalid $settings"
53
+
54
+ # field=value pairs of the merge settings; -F makes true/false booleans, -f keeps strings
55
+ merge_args=(-F "allow_squash_merge=$squash" -F allow_merge_commit=false -F allow_rebase_merge=false
56
+ -f squash_merge_commit_title=PR_TITLE -f squash_merge_commit_message=PR_BODY -F "delete_branch_on_merge=$delete_branch")
57
+ merge_filter='.allow_squash_merge == true and .allow_merge_commit == false and .allow_rebase_merge == false
58
+ and .squash_merge_commit_title == "PR_TITLE" and .squash_merge_commit_message == "PR_BODY"
59
+ and .delete_branch_on_merge == true'
60
+
61
+ apply_repo() { # apply_repo <owner/repo>; returns 1 when a request failed
62
+ local repo="$1" current current_days
63
+ log "repo ${repo}:只允許 squash 合併,artifact 與 log 保留 ${days} 天"
64
+ if (( DRY_RUN )); then
65
+ external "github.com/$repo" gh api -X PATCH "repos/$repo" "${merge_args[@]}" || return 1
66
+ external "github.com/$repo" gh api -X PUT "repos/$repo/actions/permissions/artifact-and-log-retention" -F "days=$days" || return 1
67
+ external "github.com/$repo" gh label create "$label" -R "$repo" --color "$label_color" --description "$label_desc" --force || return 1
68
+ return 0
69
+ fi
70
+ current="$(gh api "repos/$repo")" || return 1
71
+ if jq -e "$merge_filter" <<<"$current" >/dev/null; then
72
+ info "合併設定已是只開 squash,不送"
73
+ else
74
+ external "github.com/$repo" gh api -X PATCH "repos/$repo" "${merge_args[@]}" || return 1
75
+ fi
76
+ current_days="$(gh api "repos/$repo/actions/permissions/artifact-and-log-retention" --jq .days)" || return 1
77
+ if [[ "$current_days" == "$days" ]]; then
78
+ info "已是 ${days} 天,不送"
79
+ else
80
+ external "github.com/$repo" gh api -X PUT "repos/$repo/actions/permissions/artifact-and-log-retention" -F "days=$days" || return 1
81
+ fi
82
+ local lab_err lab_json
83
+ lab_err="$(mktemp)"
84
+ if lab_json="$(gh api "repos/$repo/labels/$label" 2>"$lab_err")"; then
85
+ if jq -e --arg c "$(tr 'A-F' 'a-f' <<<"$label_color")" --arg d "$label_desc" '(.color | ascii_downcase) == $c and .description == $d' <<<"$lab_json" >/dev/null; then
86
+ info "標籤 ${label} 已存在且相同,不送"
87
+ rm -f "$lab_err"; return 0
88
+ fi
89
+ elif ! grep -q 'HTTP 404' "$lab_err"; then
90
+ cat "$lab_err" >&2; rm -f "$lab_err"; return 1
91
+ fi
92
+ rm -f "$lab_err"
93
+ external "github.com/$repo" gh label create "$label" -R "$repo" --color "$label_color" --description "$label_desc" --force || return 1
94
+ }
95
+
96
+ failed=()
97
+ for repo in "${repos[@]}"; do
98
+ if ! apply_repo "$repo"; then
99
+ warn "repo ${repo}:失敗"
100
+ failed+=("$repo")
101
+ fi
102
+ done
103
+
104
+ if (( ${#failed[@]} )); then
105
+ printf '\n%s\n' "✗ ${#failed[@]} 個倉失敗:" >&2
106
+ printf ' - %s\n' "${failed[@]}" >&2
107
+ exit 1
108
+ fi
109
+ printf '\n'
110
+ info "核對:gh api repos/<repo> --jq '{allow_squash_merge, allow_merge_commit, allow_rebase_merge, squash_merge_commit_title, squash_merge_commit_message, delete_branch_on_merge}'"
@@ -0,0 +1,157 @@
1
+ name: deploy-prerelease
2
+
3
+ # 這份檔在 deploy 與 infra 兩個角色的目錄各有一份,內容相同。倉有哪個角色,就留下那個角色的 job(compose 的角色區塊 # @if),
4
+ # 所以只有 deploy 角色的倉沒有 apply job,只有 infra 角色的倉沒有 bundle job,兩個角色都有的倉(monorepo)兩個都有。
5
+ # 預發布階段逐單元處理:每個 prerelease tag({unit}/vX.Y.Z-<階段>.N)依階段處理到對應環境,
6
+ # 階段與去處的對應寫在政策檔 release-policy.json 的 targets 與各單元的 targets
7
+ # (GA 由 deploy-production.yml 處理,單元的正式 tag 不處理)。
8
+ # 單元沒有該階段的去處時略過,原因寫進 job summary:單元的 wrangler.toml 要有該環境的 [env.<環境>]。判斷集中在
9
+ # scripts/deploy/route-tag.sh。route 依單元所在的目錄決定 kind:apps/、services/ 下的單元是 service,由 bundle job 處理,
10
+ # infra/ 下的單元是 infra,由 apply job 處理。同一個 tag 只會跑其中一個 job。
11
+ # @if deploy
12
+ # bundle job 只建置:建置 bundle、算雜湊、掛在這個 tag 的 GitHub Release,再把版號、bundle 位置與雜湊寫進 ops 宣告。
13
+ # monorepo 寫自己的 ops/ 並派送 ops-deploy.yml,poly 寫 poly-ops(repository variable OPS_REPO)並由它上線。
14
+ # 這個 job 不呼叫 wrangler,也不讀 Cloudflare 的憑證。
15
+ # @end
16
+ # @if infra
17
+ # apply job 不建置 bundle,也不寫 ops 宣告,而是用 wrangler 在環境裡建立單元宣告的 R2 bucket(scripts/deploy/apply-infra.sh)。
18
+ # 只有這個 job 與 deploy-production.yml 的 infra job 讀 Cloudflare 的憑證。
19
+ # 只合併到預設分支不套用,套用跟著單元自己的 tag(decision infra-apply-on-tag)。
20
+ # 同一個倉的 infra 與 api 同時打預發布 tag 時,兩個 run 的順序不保證。ops-deploy 若先於 bucket 建立而失敗,用 workflow_dispatch 重跑
21
+ # (decision monorepo-release-align)。
22
+ # @end
23
+ # 產品層的統一上線閘門在 deploy-production.yml,不在這裡。
24
+
25
+ on:
26
+ push:
27
+ tags: ["*/v*"]
28
+ workflow_dispatch:
29
+ inputs:
30
+ tag:
31
+ description: "unit tag, e.g. blueprint-monorepo-web/v1.4.0-beta.2"
32
+ required: true
33
+ type: string
34
+
35
+ permissions:
36
+ contents: read
37
+
38
+ defaults:
39
+ run:
40
+ shell: bash
41
+
42
+ env:
43
+ # a loop of a template script asks twice at most and the CI gate asks twice (decision self-hosted-job-no-wait)
44
+ POLL_TRIES: "2"
45
+ CI_GATE_TRIES: "2"
46
+ CI_GATE_QUEUE_TRIES: "0"
47
+
48
+ jobs:
49
+ route:
50
+ runs-on: self-hosted-linux
51
+ timeout-minutes: 5
52
+ outputs:
53
+ unit: ${{ steps.p.outputs.unit }}
54
+ version: ${{ steps.p.outputs.version }}
55
+ stage: ${{ steps.p.outputs.stage }}
56
+ env: ${{ steps.p.outputs.env }}
57
+ kind: ${{ steps.p.outputs.kind }}
58
+ skip: ${{ steps.p.outputs.skip }}
59
+ steps:
60
+ - uses: actions/checkout@v7
61
+ with:
62
+ persist-credentials: false
63
+ - id: p
64
+ env:
65
+ TAG: ${{ inputs.tag || github.ref_name }}
66
+ run: |
67
+ bash scripts/deploy/route-tag.sh "$TAG" | tee -a "$GITHUB_OUTPUT" > route.txt
68
+ {
69
+ echo "### $TAG"
70
+ sed 's/^/- /' route.txt
71
+ } >> "$GITHUB_STEP_SUMMARY"
72
+
73
+ # @if deploy
74
+ bundle:
75
+ needs: route
76
+ if: needs.route.outputs.skip == 'false' && needs.route.outputs.kind == 'service'
77
+ runs-on: self-hosted-linux
78
+ timeout-minutes: 15
79
+ # 掛 Release 與回寫同倉的 ops 宣告都要寫入權限;read 會讓 push 失敗
80
+ permissions:
81
+ contents: write
82
+ actions: write
83
+ concurrency:
84
+ group: deploy-${{ needs.route.outputs.env }}-${{ needs.route.outputs.unit }}
85
+ steps:
86
+ - uses: actions/checkout@v7
87
+ with:
88
+ ref: ${{ inputs.tag || github.ref_name }}
89
+ - uses: ./.github/actions/setup-workspace
90
+ with:
91
+ restore-from-default: "scripts"
92
+ # poly 的 app 與 service 把宣告寫進 poly-ops,要 GitHub App 的權杖。monorepo 沒設 OPS_REPO,這一步略過。
93
+ - id: ops-name
94
+ if: vars.OPS_REPO != ''
95
+ env:
96
+ OPS_REPO: ${{ vars.OPS_REPO }}
97
+ run: echo "name=${OPS_REPO#*/}" >> "$GITHUB_OUTPUT"
98
+ - id: app-token
99
+ if: vars.OPS_REPO != ''
100
+ uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
101
+ with:
102
+ client-id: ${{ vars.@@clientIdVariable@@ }}
103
+ private-key: ${{ secrets.@@privateKeySecret@@ }}
104
+ owner: ${{ github.repository_owner }}
105
+ repositories: ${{ steps.ops-name.outputs.name }}
106
+ - name: 建置 bundle、掛 Release、寫入 ops 宣告
107
+ run: |
108
+ if [[ -n "$OPS_TOKEN" ]]; then
109
+ export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0="http.${GITHUB_SERVER_URL}/.extraheader"
110
+ GIT_CONFIG_VALUE_0="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$OPS_TOKEN" | base64 | tr -d '\n')"
111
+ export GIT_CONFIG_VALUE_0
112
+ fi
113
+ bash scripts/deploy/run-prerelease.sh "$TAG"
114
+ env:
115
+ TAG: ${{ inputs.tag || github.ref_name }}
116
+ GH_TOKEN: ${{ github.token }}
117
+ OPS_TOKEN: ${{ steps.app-token.outputs.token }}
118
+ OPS_REPO: ${{ vars.OPS_REPO }}
119
+ DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
120
+ DEPLOY_LOG_DIR: ${{ runner.temp }}/deploy-log
121
+ BUNDLE_DIR: ${{ runner.temp }}/bundles
122
+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
123
+ with:
124
+ name: deploy-${{ needs.route.outputs.env }}-${{ needs.route.outputs.unit }}-${{ needs.route.outputs.version }}
125
+ path: ${{ runner.temp }}/deploy-log
126
+ retention-days: 7
127
+ # @end
128
+ # @if infra
129
+ apply:
130
+ needs: route
131
+ if: needs.route.outputs.skip == 'false' && needs.route.outputs.kind == 'infra' && vars.DEPLOY_ENABLED == 'true'
132
+ runs-on: self-hosted-linux
133
+ timeout-minutes: 15
134
+ concurrency:
135
+ group: apply-${{ needs.route.outputs.env }}-${{ needs.route.outputs.unit }}
136
+ steps:
137
+ - uses: actions/checkout@v7
138
+ with:
139
+ ref: ${{ inputs.tag || github.ref_name }}
140
+ - uses: ./.github/actions/setup-workspace
141
+ with:
142
+ restore-from-default: "scripts"
143
+ - name: 套用單元宣告的 R2 bucket
144
+ run: bash scripts/deploy/apply-prerelease.sh "$TAG"
145
+ env:
146
+ TAG: ${{ inputs.tag || github.ref_name }}
147
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
148
+ CLOUDFLARE_ACCOUNT_ID: ${{ vars.CLOUDFLARE_ACCOUNT_ID }}
149
+ DEPLOY_LOG_DIR: ${{ runner.temp }}/deploy-log
150
+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
151
+ if: always()
152
+ with:
153
+ name: apply-${{ needs.route.outputs.env }}-${{ needs.route.outputs.unit }}-${{ needs.route.outputs.version }}
154
+ path: ${{ runner.temp }}/deploy-log
155
+ if-no-files-found: ignore
156
+ retention-days: 7
157
+ # @end