@jakobm/peacekeeper 0.20.0 → 0.22.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.
- package/README.md +82 -27
- package/dist/bin/peacekeeper.js +36 -0
- package/{bin/peacekeeper.yaml → dist/cmdabra.yaml} +7 -0
- package/dist/package.json +57 -0
- package/dist/src/container.js +89 -0
- package/dist/src/modules/cli/interface.js +1 -0
- package/dist/src/modules/cli/service.js +48 -0
- package/dist/src/modules/cli/types.js +2 -0
- package/dist/src/modules/configuration/interface.js +7 -0
- package/dist/src/modules/configuration/project-config.js +114 -0
- package/dist/src/modules/configuration/update-config.js +42 -0
- package/dist/src/modules/dependencies.yaml +16 -0
- package/dist/src/modules/external.js +48 -0
- package/dist/src/modules/lifecycle/checkpoint-codex-changes.js +204 -0
- package/dist/src/modules/lifecycle/checkpoint-codex-session-start.js +23 -0
- package/dist/src/modules/lifecycle/checkpoint-codex-stop.js +69 -0
- package/dist/src/modules/lifecycle/checkpoint-instructions.js +21 -0
- package/dist/src/modules/lifecycle/cleanup-ended-session.js +265 -0
- package/dist/src/modules/lifecycle/interface.js +7 -0
- package/dist/src/modules/lifecycle/log-script-invocation.js +115 -0
- package/dist/src/modules/lifecycle/queue-merged-worktree-cleanup.js +37 -0
- package/dist/src/modules/maintenance/cleanup-merged-branches.js +298 -0
- package/dist/src/modules/maintenance/interface.js +7 -0
- package/dist/src/modules/maintenance/remove-empty-directories.js +114 -0
- package/{scripts → dist/src/modules/projects}/check-project-requirements.txt +15 -13
- package/dist/src/modules/projects/check-project.js +344 -0
- package/dist/src/modules/projects/create-project-core.js +207 -0
- package/dist/src/modules/projects/create-project.js +19 -0
- package/dist/src/modules/projects/generate-github-setup.js +60 -0
- package/dist/src/modules/projects/github-setup-prefix.sh +5 -0
- package/dist/src/modules/projects/github-setup-repository-template.sh +40 -0
- package/dist/src/modules/projects/github-setup-suffix-template.sh +5 -0
- package/dist/src/modules/projects/install-hooks.js +151 -0
- package/dist/src/modules/projects/interface.js +6 -0
- package/dist/src/modules/releases/assess-release-core.js +145 -0
- package/dist/src/modules/releases/assess-release.js +8 -0
- package/dist/src/modules/releases/github-base-protection-policy.json +46 -0
- package/dist/src/modules/releases/github-owner-approval-policy.json +35 -0
- package/dist/src/modules/releases/github-policy.js +127 -0
- package/dist/src/modules/releases/interface.js +11 -0
- package/dist/src/modules/releases/release-core.js +529 -0
- package/dist/src/modules/releases/release-protection.js +194 -0
- package/dist/src/modules/releases/release.js +23 -0
- package/dist/src/modules/releases/verify-release-core.js +44 -0
- package/dist/src/modules/releases/verify-release-protection.js +25 -0
- package/dist/src/modules/releases/verify-release-version.js +14 -0
- package/dist/src/modules/releases/verify-release.js +30 -0
- package/dist/src/modules/testing/check-test-receipt.js +46 -0
- package/dist/src/modules/testing/interface.js +5 -0
- package/dist/src/modules/testing/receipt-state.js +99 -0
- package/dist/src/modules/testing/record-test-receipt.js +29 -0
- package/dist/src/modules/testing/run-tests.js +57 -0
- package/package.json +25 -9
- package/bin/peacekeeper.js +0 -68
- package/scripts/assess-release-core.js +0 -146
- package/scripts/assess-release.js +0 -7
- package/scripts/check-project.js +0 -346
- package/scripts/check-test-receipt.js +0 -49
- package/scripts/checkpoint-codex-changes.js +0 -232
- package/scripts/checkpoint-codex-session-start.js +0 -24
- package/scripts/checkpoint-codex-stop.js +0 -86
- package/scripts/checkpoint-instructions.js +0 -19
- package/scripts/cleanup-ended-session.js +0 -318
- package/scripts/cleanup-merged-branches.js +0 -382
- package/scripts/create-project-core.js +0 -278
- package/scripts/create-project.js +0 -26
- package/scripts/install-hooks.js +0 -155
- package/scripts/log-script-invocation.js +0 -125
- package/scripts/project-config.js +0 -120
- package/scripts/queue-merged-worktree-cleanup.js +0 -58
- package/scripts/receipt-state.js +0 -91
- package/scripts/record-test-receipt.js +0 -37
- package/scripts/release-core.js +0 -530
- package/scripts/release-protection.js +0 -135
- package/scripts/release.js +0 -18
- package/scripts/remove-empty-directories.js +0 -163
- package/scripts/run-tests.js +0 -66
- package/scripts/update-config.js +0 -41
- package/scripts/verify-release-core.js +0 -39
- package/scripts/verify-release-protection.js +0 -20
- package/scripts/verify-release-version.js +0 -14
- package/scripts/verify-release.js +0 -27
- /package/{scripts → dist/src/modules/configuration}/project-config-defaults.json +0 -0
- /package/{scripts → dist/src/modules/projects}/codex-setup-prefix.sh +0 -0
- /package/{scripts → dist/src/modules/releases}/assess-release-schema.json +0 -0
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
export default ({ configuration, githubPolicy }) => {
|
|
2
|
+
const { approvalParameters, createGithubPolicy, managedRulesetMatches, requiredCheckContexts, sameMembers } = githubPolicy;
|
|
3
|
+
function requiredPolicy(cwd) {
|
|
4
|
+
const { projectConfig } = configuration;
|
|
5
|
+
const config = projectConfig(cwd).git;
|
|
6
|
+
if (!config.releaseRequiredChecks?.length) {
|
|
7
|
+
throw new Error('Configure git.releaseRequiredChecks with the CI jobs required for releases.');
|
|
8
|
+
}
|
|
9
|
+
if (!config.requiredApprover) {
|
|
10
|
+
throw new Error('Configure git.requiredApprover with the personal GitHub repository owner.');
|
|
11
|
+
}
|
|
12
|
+
return { checks: config.releaseRequiredChecks, requiredApprover: config.requiredApprover };
|
|
13
|
+
}
|
|
14
|
+
const bypassWarning = 'Cannot verify bypass users unless given write access. Run a manual check instead; available as a gist.';
|
|
15
|
+
// A missing classic protection is expected for ruleset-only repositories. All
|
|
16
|
+
// other API failures, including permission failures, must propagate.
|
|
17
|
+
function verifyProtection({ api, slug, branch, checks, requiredApprover: approver, warn }) {
|
|
18
|
+
const policy = createGithubPolicy({ branch, checks, requiredApprover: approver });
|
|
19
|
+
const base = `repos/${slug}`;
|
|
20
|
+
const repository = api(base);
|
|
21
|
+
if (repository?.delete_branch_on_merge !== policy.repository.delete_branch_on_merge) {
|
|
22
|
+
throw new Error(`Repository ${slug} must enable delete_branch_on_merge. Run gh api --method PATCH ${base} -F delete_branch_on_merge=true, then rerun.`);
|
|
23
|
+
}
|
|
24
|
+
if (repository.allow_auto_merge !== policy.repository.allow_auto_merge)
|
|
25
|
+
throw new Error('Repository must enable allow_auto_merge; this only makes auto-merge available per PR.');
|
|
26
|
+
if (repository.default_branch !== branch)
|
|
27
|
+
throw new Error(`Verify the actual default branch (${repository.default_branch}), not ${branch}.`);
|
|
28
|
+
if (repository.owner?.type !== 'User'
|
|
29
|
+
|| repository.owner.login?.toLowerCase() !== policy.requiredApprover.toLowerCase()
|
|
30
|
+
|| !Number.isInteger(repository.owner.id)) {
|
|
31
|
+
throw new Error(`git.requiredApprover (${policy.requiredApprover}) must be the personal owner of repository ${slug}.`);
|
|
32
|
+
}
|
|
33
|
+
let protection;
|
|
34
|
+
try {
|
|
35
|
+
protection = api(`${base}/branches/${encodeURIComponent(branch)}/protection`);
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (error.status !== 404)
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
const rules = [];
|
|
42
|
+
for (let page = 1;; page += 1) {
|
|
43
|
+
const batch = api(`${base}/rules/branches/${encodeURIComponent(branch)}?per_page=100&page=${page}`);
|
|
44
|
+
if (!Array.isArray(batch))
|
|
45
|
+
throw new Error('GitHub returned invalid branch rules.');
|
|
46
|
+
rules.push(...batch);
|
|
47
|
+
if (batch.length < 100)
|
|
48
|
+
break;
|
|
49
|
+
}
|
|
50
|
+
if (protection?.required_linear_history?.enabled || rules.some(rule => rule.type === 'required_linear_history')) {
|
|
51
|
+
throw new Error('Default branch must allow merge commits; disable required linear history.');
|
|
52
|
+
}
|
|
53
|
+
if (protection) {
|
|
54
|
+
if (protection.allow_deletions?.enabled === true)
|
|
55
|
+
throw new Error('Default branch must prevent deletion.');
|
|
56
|
+
if (protection.allow_force_pushes?.enabled === true)
|
|
57
|
+
throw new Error('Default branch must prevent force pushes.');
|
|
58
|
+
if (protection.enforce_admins?.enabled !== true)
|
|
59
|
+
throw new Error('Classic branch protection must include administrators.');
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
if (!rules.some(rule => rule.type === 'deletion'))
|
|
63
|
+
throw new Error('Default branch rulesets must prevent deletion.');
|
|
64
|
+
if (!rules.some(rule => rule.type === 'non_fast_forward'))
|
|
65
|
+
throw new Error('Default branch rulesets must prevent force pushes.');
|
|
66
|
+
}
|
|
67
|
+
const rulesets = new Map();
|
|
68
|
+
function rulesetFor(rule) {
|
|
69
|
+
if (!Number.isInteger(rule.ruleset_id))
|
|
70
|
+
throw new Error('GitHub did not identify the policy ruleset.');
|
|
71
|
+
if (!rulesets.has(rule.ruleset_id)) {
|
|
72
|
+
const ruleset = api(`${base}/rulesets/${rule.ruleset_id}`);
|
|
73
|
+
if (ruleset.enforcement !== 'active')
|
|
74
|
+
throw new Error('Policy rulesets must be active.');
|
|
75
|
+
if (!Array.isArray(ruleset.rules)) {
|
|
76
|
+
throw new Error('Cannot verify all rules in a policy ruleset; grant access to the complete ruleset, then rerun.');
|
|
77
|
+
}
|
|
78
|
+
if (!managedRulesetMatches(policy, ruleset)) {
|
|
79
|
+
throw new Error(`Managed ruleset ${ruleset.name} differs from Peacekeeper's generated policy. Regenerate and run the GitHub setup script.`);
|
|
80
|
+
}
|
|
81
|
+
rulesets.set(rule.ruleset_id, ruleset);
|
|
82
|
+
}
|
|
83
|
+
return rulesets.get(rule.ruleset_id);
|
|
84
|
+
}
|
|
85
|
+
for (const rule of rules.filter(rule => Number.isInteger(rule.ruleset_id)))
|
|
86
|
+
rulesetFor(rule);
|
|
87
|
+
for (const name of [policy.baseRuleset.name, policy.approvalRuleset.name]) {
|
|
88
|
+
if ([...rulesets.values()].filter(ruleset => ruleset.name === name).length > 1) {
|
|
89
|
+
throw new Error(`Default branch has multiple managed rulesets named ${name}. Remove duplicates, then rerun.`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const approvalRulesets = new Set();
|
|
93
|
+
for (const [id, ruleset] of rulesets) {
|
|
94
|
+
if (ruleset.rules.length === 1 && ruleset.rules[0].type === 'pull_request'
|
|
95
|
+
&& approvalParameters(policy, ruleset.rules[0].parameters))
|
|
96
|
+
approvalRulesets.add(id);
|
|
97
|
+
}
|
|
98
|
+
const classicReviews = protection?.required_pull_request_reviews;
|
|
99
|
+
const classicBypasses = classicReviews?.bypass_pull_request_allowances;
|
|
100
|
+
if (classicBypasses && ['users', 'teams', 'apps']
|
|
101
|
+
.some(kind => Array.isArray(classicBypasses[kind]) && classicBypasses[kind].length > 0)) {
|
|
102
|
+
throw new Error('Classic branch protection must not allow pull-request bypass actors.');
|
|
103
|
+
}
|
|
104
|
+
let requiresPullRequest = Boolean(classicReviews);
|
|
105
|
+
let branchMergeOnly = false;
|
|
106
|
+
let approvalPolicyCount = 0;
|
|
107
|
+
for (const rule of rules.filter(rule => rule.type === 'pull_request')) {
|
|
108
|
+
const ruleset = rulesetFor(rule);
|
|
109
|
+
if (approvalRulesets.has(rule.ruleset_id)) {
|
|
110
|
+
if (!approvalParameters(policy, rule.parameters)) {
|
|
111
|
+
throw new Error('The effective owner approval rule must require one code-owner approval and dismiss stale approvals.');
|
|
112
|
+
}
|
|
113
|
+
approvalPolicyCount += 1;
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
requiresPullRequest = true;
|
|
117
|
+
}
|
|
118
|
+
const methods = rule.parameters?.allowed_merge_methods;
|
|
119
|
+
if (methods && !methods.includes('merge'))
|
|
120
|
+
throw new Error('Default branch PR rules must allow merge commits.');
|
|
121
|
+
if (Array.isArray(methods) && methods.length === 1 && methods[0] === 'merge'
|
|
122
|
+
&& !approvalRulesets.has(rule.ruleset_id))
|
|
123
|
+
branchMergeOnly = true;
|
|
124
|
+
}
|
|
125
|
+
if (approvalPolicyCount !== 1 || approvalRulesets.size !== 1) {
|
|
126
|
+
throw new Error('Default branch must have exactly one owner approval ruleset requiring one code-owner approval and stale approval dismissal.');
|
|
127
|
+
}
|
|
128
|
+
let bypassUnknown = Boolean(protection);
|
|
129
|
+
for (const [id, ruleset] of rulesets) {
|
|
130
|
+
const protectsRelease = approvalRulesets.has(id)
|
|
131
|
+
|| ruleset.rules.some(rule => ['pull_request', 'required_status_checks'].includes(rule.type || ''));
|
|
132
|
+
if (!protectsRelease)
|
|
133
|
+
continue;
|
|
134
|
+
if (!Array.isArray(ruleset.bypass_actors)) {
|
|
135
|
+
bypassUnknown = true;
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
const expected = approvalRulesets.has(id)
|
|
139
|
+
? [{ actor_id: repository.owner.id, actor_type: 'User', bypass_mode: 'pull_request' }]
|
|
140
|
+
: [];
|
|
141
|
+
const actual = ruleset.bypass_actors.map(actor => ({ actor_id: actor.actor_id,
|
|
142
|
+
actor_type: actor.actor_type, bypass_mode: actor.bypass_mode }));
|
|
143
|
+
if (JSON.stringify(actual) !== JSON.stringify(expected)) {
|
|
144
|
+
throw new Error('Ruleset bypass actors do not match the generated Peacekeeper policy.');
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (bypassUnknown && warn)
|
|
148
|
+
warn(bypassWarning);
|
|
149
|
+
const strictChecks = new Set();
|
|
150
|
+
const classic = protection?.required_status_checks;
|
|
151
|
+
if (classic?.strict === true) {
|
|
152
|
+
for (const check of classic.checks || [])
|
|
153
|
+
strictChecks.add(check.context);
|
|
154
|
+
for (const context of classic.contexts || [])
|
|
155
|
+
strictChecks.add(context);
|
|
156
|
+
}
|
|
157
|
+
for (const rule of rules.filter(rule => rule.type === 'required_status_checks')) {
|
|
158
|
+
rulesetFor(rule);
|
|
159
|
+
if (rule.parameters?.strict_required_status_checks_policy !== true)
|
|
160
|
+
continue;
|
|
161
|
+
for (const check of rule.parameters.required_status_checks || [])
|
|
162
|
+
strictChecks.add(check.context);
|
|
163
|
+
}
|
|
164
|
+
const expectedChecks = requiredCheckContexts(policy);
|
|
165
|
+
const actualChecks = [...strictChecks];
|
|
166
|
+
const missing = expectedChecks.filter(check => !strictChecks.has(check));
|
|
167
|
+
const extra = actualChecks.filter(check => !expectedChecks.includes(check));
|
|
168
|
+
if (!sameMembers(actualChecks, expectedChecks)) {
|
|
169
|
+
const detail = [missing.length ? `missing: ${missing.join(', ')}` : '',
|
|
170
|
+
extra.length ? `extra: ${extra.join(', ')}` : ''].filter(Boolean).join('; ');
|
|
171
|
+
throw new Error(`Branch ${branch} must require exactly these strict status checks: ${expectedChecks.join(', ')}${detail ? ` (${detail})` : ''}. Enable strict checks, then rerun.`);
|
|
172
|
+
}
|
|
173
|
+
if (!requiresPullRequest)
|
|
174
|
+
throw new Error('Default branch must require pull requests.');
|
|
175
|
+
if (repository.allow_merge_commit !== policy.repository.allow_merge_commit || (!branchMergeOnly
|
|
176
|
+
&& (repository.allow_squash_merge !== policy.repository.allow_squash_merge
|
|
177
|
+
|| repository.allow_rebase_merge !== policy.repository.allow_rebase_merge))) {
|
|
178
|
+
throw new Error('Default branch must allow only merge commits: restrict its base pull request ruleset to merge, or disable repository squash and rebase merging.');
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function githubApi(exec, cwd, host) {
|
|
182
|
+
return endpoint => {
|
|
183
|
+
const response = exec('gh', ['api', '--hostname', host, '--method', 'GET', endpoint], { cwd });
|
|
184
|
+
if (response.status !== 0) {
|
|
185
|
+
const error = new Error(`Cannot verify GitHub release policy (${endpoint}): ${response.stderr?.trim() || 'API request failed'}. Grant the token Administration read, Contents read/write, Pull requests read and Actions read permissions, then rerun.`);
|
|
186
|
+
error.status = Number(/HTTP (\d{3})/u.exec(response.stderr || '')?.[1]);
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
return JSON.parse(response.stdout);
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
const api = { bypassWarning, githubApi, requiredPolicy, verifyProtection };
|
|
193
|
+
return api;
|
|
194
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export default ({ releaseCore, external: { clock, output, runtime, spawnSync } }) => {
|
|
2
|
+
const { release } = releaseCore;
|
|
3
|
+
async function main(bump) {
|
|
4
|
+
await release(bump, {
|
|
5
|
+
environment: runtime.env,
|
|
6
|
+
cwd: runtime.cwd(),
|
|
7
|
+
spawnSync,
|
|
8
|
+
now: clock.now,
|
|
9
|
+
sleep: clock.sleep,
|
|
10
|
+
log: (message) => output.log(`${clock.date().toTimeString().slice(0, 8)} ${message}`),
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
async function run(bump) {
|
|
14
|
+
try {
|
|
15
|
+
await main(bump);
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
output.error(`Release stopped: ${error instanceof Error ? error.message : String(error)}`);
|
|
19
|
+
runtime.exitCode = 1;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return { run };
|
|
23
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export default ({ releaseProtection }) => {
|
|
2
|
+
const { verifyProtection } = releaseProtection;
|
|
3
|
+
function list(api, endpoint, member) {
|
|
4
|
+
const items = [];
|
|
5
|
+
for (let page = 1;; page += 1) {
|
|
6
|
+
const response = api(`${endpoint}${endpoint.includes('?') ? '&' : '?'}per_page=100&page=${page}`);
|
|
7
|
+
const batch = member ? response[member] : response;
|
|
8
|
+
if (!Array.isArray(batch))
|
|
9
|
+
throw new Error(`GitHub returned an invalid list for ${endpoint}`);
|
|
10
|
+
items.push(...batch);
|
|
11
|
+
if (batch.length < 100)
|
|
12
|
+
return items;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function verifyRelease({ api, slug, sha, tag, branch, checks, requiredApprover, workflow, warn }) {
|
|
16
|
+
if (!/^v\d+\.\d+\.\d+$/u.test(tag))
|
|
17
|
+
throw new Error('Expected a stable release tag');
|
|
18
|
+
verifyProtection({ api, slug, branch, checks, requiredApprover, warn });
|
|
19
|
+
const base = `repos/${slug}`;
|
|
20
|
+
const commit = api(`${base}/commits/${encodeURIComponent(sha)}`);
|
|
21
|
+
const comparison = api(`${base}/compare/${commit.sha}...${encodeURIComponent(branch)}`);
|
|
22
|
+
if (!['ahead', 'identical'].includes(comparison.status))
|
|
23
|
+
throw new Error('Release commit must belong to the default branch');
|
|
24
|
+
const pulls = list(api, `${base}/commits/${commit.sha}/pulls`);
|
|
25
|
+
const pull = pulls.find(pr => pr.merged_at && pr.merge_commit_sha === commit.sha &&
|
|
26
|
+
pr.base.ref === branch && pr.base.repo.full_name === slug &&
|
|
27
|
+
pr.head.repo?.full_name === slug && pr.head.ref === `release/${tag}`);
|
|
28
|
+
if (!pull)
|
|
29
|
+
throw new Error('Tag must point to a merged release PR');
|
|
30
|
+
const runs = list(api, `${base}/actions/workflows/${encodeURIComponent(workflow)}/runs?event=pull_request&head_sha=${pull.head.sha}`, 'workflow_runs');
|
|
31
|
+
const run = runs.sort((a, b) => b.run_number - a.run_number)[0];
|
|
32
|
+
if (!run || run.conclusion !== 'success')
|
|
33
|
+
throw new Error('Release PR must have a successful CI run');
|
|
34
|
+
const jobs = list(api, `${base}/actions/runs/${run.id}/jobs?filter=latest`, 'jobs');
|
|
35
|
+
for (const name of checks) {
|
|
36
|
+
const matching = jobs.filter(job => job.name === name);
|
|
37
|
+
if (!matching.length || matching.some(job => job.conclusion !== 'success')) {
|
|
38
|
+
throw new Error(`Release PR requires successful ${name} check`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const api = { verifyRelease };
|
|
43
|
+
return api;
|
|
44
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export default ({ configuration, releaseCore, releaseProtection, external: { output, runtime, spawnSync, } }) => {
|
|
2
|
+
const { projectConfig } = configuration;
|
|
3
|
+
const { originRepository } = releaseCore;
|
|
4
|
+
const { githubApi, requiredPolicy, verifyProtection } = releaseProtection;
|
|
5
|
+
function main(cwd = runtime.cwd()) {
|
|
6
|
+
const config = projectConfig(cwd);
|
|
7
|
+
const remote = spawnSync('git', ['remote', 'get-url', config.git.remote], { encoding: 'utf8' });
|
|
8
|
+
if (remote.status !== 0)
|
|
9
|
+
throw new Error(remote.stderr);
|
|
10
|
+
const { host, slug } = originRepository(remote.stdout.trim());
|
|
11
|
+
const api = githubApi((command, args, options) => spawnSync(command, args, { ...options, encoding: 'utf8' }), cwd, host);
|
|
12
|
+
verifyProtection({ api, slug, branch: api(`repos/${slug}`).default_branch,
|
|
13
|
+
...requiredPolicy(cwd), warn: message => output.warn(message) });
|
|
14
|
+
}
|
|
15
|
+
function run() {
|
|
16
|
+
try {
|
|
17
|
+
main();
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
output.error(error instanceof Error ? error.message : String(error));
|
|
21
|
+
runtime.exitCode = 1;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return { run };
|
|
25
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export default ({ external: { fs, runtime } }) => {
|
|
2
|
+
function main() {
|
|
3
|
+
const manifest = JSON.parse(fs.readFileSync('package.json', 'utf8'));
|
|
4
|
+
const lockfile = JSON.parse(fs.readFileSync('package-lock.json', 'utf8'));
|
|
5
|
+
const expectedTag = `v${manifest.version}`;
|
|
6
|
+
if (runtime.env.RELEASE_TAG !== expectedTag) {
|
|
7
|
+
throw new Error(`Release tag must be ${expectedTag}, got ${runtime.env.RELEASE_TAG}`);
|
|
8
|
+
}
|
|
9
|
+
if (lockfile.version !== manifest.version || lockfile.packages[''].version !== manifest.version) {
|
|
10
|
+
throw new Error('package-lock.json version must match package.json');
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
return { run: main };
|
|
14
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export default ({ configuration, releaseCore, releaseProtection, verifyReleaseCore, verifyReleaseVersion, external: { execFileSync, output, runtime, spawnSync } }) => {
|
|
2
|
+
const { projectConfig } = configuration;
|
|
3
|
+
const { originRepository, inspectWorkflow } = releaseCore;
|
|
4
|
+
const { githubApi, requiredPolicy } = releaseProtection;
|
|
5
|
+
const { verifyRelease } = verifyReleaseCore;
|
|
6
|
+
function main() {
|
|
7
|
+
verifyReleaseVersion.run();
|
|
8
|
+
const cwd = runtime.cwd();
|
|
9
|
+
const config = projectConfig(cwd);
|
|
10
|
+
const remote = execFileSync('git', ['remote', 'get-url', config.git.remote], { encoding: 'utf8' }).trim();
|
|
11
|
+
const { host, slug } = originRepository(remote);
|
|
12
|
+
const api = githubApi((command, args, options) => spawnSync(command, args, { ...options, encoding: 'utf8' }), cwd, host);
|
|
13
|
+
const tag = runtime.env.RELEASE_TAG;
|
|
14
|
+
const sha = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
|
|
15
|
+
inspectWorkflow(cwd, tag);
|
|
16
|
+
verifyRelease({ api, slug, sha, tag, branch: config.git.defaultBranch,
|
|
17
|
+
...requiredPolicy(cwd), workflow: config.git.releaseTestWorkflow,
|
|
18
|
+
warn: message => output.warn(message) });
|
|
19
|
+
}
|
|
20
|
+
function run() {
|
|
21
|
+
try {
|
|
22
|
+
main();
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
output.error(error instanceof Error ? error.message : String(error));
|
|
26
|
+
runtime.exitCode = 1;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return { run };
|
|
30
|
+
};
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
export default ({ configuration, receiptState, external: { clock, fs, output, runtime } }) => {
|
|
2
|
+
const { ROOT, environmentFingerprint, receiptPath, snapshot } = receiptState;
|
|
3
|
+
const { projectConfig, requireTestCommands } = configuration;
|
|
4
|
+
function successMessage(root = ROOT()) {
|
|
5
|
+
const command = projectConfig(root).tests.npmTestUsesRunner
|
|
6
|
+
? 'npm test -- --force'
|
|
7
|
+
: 'node node_modules/@jakobm/peacekeeper/dist/bin/peacekeeper.js run-tests --force';
|
|
8
|
+
return `Tests already passed for this change set. In order to rerun tests anyway, use: ${command}`;
|
|
9
|
+
}
|
|
10
|
+
function matchesReceipt(receipt, root = ROOT()) {
|
|
11
|
+
const { receiptMaxAgeMinutes } = projectConfig(root).tests;
|
|
12
|
+
if (!receipt || receipt.version !== 1 || !Number.isFinite(receipt.passedAt) ||
|
|
13
|
+
clock.now() < receipt.passedAt || clock.now() - receipt.passedAt > receiptMaxAgeMinutes * 60_000 ||
|
|
14
|
+
receipt.environment !== environmentFingerprint())
|
|
15
|
+
return false;
|
|
16
|
+
const current = snapshot(root, receipt.baseCommit);
|
|
17
|
+
return JSON.stringify(current.changedFiles) === JSON.stringify(receipt.changedFiles);
|
|
18
|
+
}
|
|
19
|
+
function checkReceipt(root = ROOT()) {
|
|
20
|
+
requireTestCommands(root);
|
|
21
|
+
let receipt;
|
|
22
|
+
try {
|
|
23
|
+
receipt = JSON.parse(fs.readFileSync(receiptPath(root), 'utf8'));
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (error.code === 'ENOENT' || error instanceof SyntaxError)
|
|
27
|
+
return false;
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
return matchesReceipt(receipt, root);
|
|
31
|
+
}
|
|
32
|
+
function run() {
|
|
33
|
+
try {
|
|
34
|
+
if (!checkReceipt())
|
|
35
|
+
runtime.exitCode = 1;
|
|
36
|
+
else
|
|
37
|
+
output.log(successMessage());
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
output.error(error instanceof Error ? error.message : String(error));
|
|
41
|
+
runtime.exitCode = 1;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const api = { checkReceipt, matchesReceipt, run, successMessage };
|
|
45
|
+
return api;
|
|
46
|
+
};
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
export default ({ configuration, external: { clock, crypto, execFileSync, fs, modulesRoot, os, path, runtime, } }) => {
|
|
2
|
+
const { repositoryRoot } = configuration;
|
|
3
|
+
const ROOT = repositoryRoot;
|
|
4
|
+
const RECEIPT_DIRECTORY = 'peacekeeper-test-receipts';
|
|
5
|
+
const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
|
|
6
|
+
function git(root, args) {
|
|
7
|
+
return execFileSync('git', args, { cwd: root, maxBuffer: 10 * 1024 * 1024,
|
|
8
|
+
stdio: ['ignore', 'pipe', 'pipe'] });
|
|
9
|
+
}
|
|
10
|
+
function pathsFromOutput(output) {
|
|
11
|
+
return output.toString('utf8').split('\0').filter(Boolean);
|
|
12
|
+
}
|
|
13
|
+
function changedPaths(root, baseCommit) {
|
|
14
|
+
const tracked = pathsFromOutput(git(root, [
|
|
15
|
+
'diff', '--no-ext-diff', '--no-textconv', '--no-renames', '--name-only', '-z', baseCommit, '--',
|
|
16
|
+
]));
|
|
17
|
+
const untracked = pathsFromOutput(git(root, ['ls-files', '--others', '--exclude-standard', '-z']));
|
|
18
|
+
return [...new Set([...tracked, ...untracked])].sort();
|
|
19
|
+
}
|
|
20
|
+
function fileFingerprint(root, relative) {
|
|
21
|
+
const fullPath = path.join(root, relative);
|
|
22
|
+
let stat;
|
|
23
|
+
try {
|
|
24
|
+
stat = fs.lstatSync(fullPath);
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (error.code === 'ENOENT')
|
|
28
|
+
return 'missing';
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
31
|
+
const hash = crypto.createHash('sha256');
|
|
32
|
+
hash.update(`${stat.mode & 0o777}\0`);
|
|
33
|
+
if (stat.isSymbolicLink())
|
|
34
|
+
hash.update(fs.readlinkSync(fullPath));
|
|
35
|
+
else if (stat.isFile())
|
|
36
|
+
hash.update(fs.readFileSync(fullPath));
|
|
37
|
+
else
|
|
38
|
+
hash.update(`special:${stat.mode}`);
|
|
39
|
+
return hash.digest('hex');
|
|
40
|
+
}
|
|
41
|
+
function sharedScriptsFingerprint() {
|
|
42
|
+
const hash = crypto.createHash('sha256');
|
|
43
|
+
const scriptsRoot = modulesRoot;
|
|
44
|
+
const files = [];
|
|
45
|
+
function visit(directory) {
|
|
46
|
+
for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
|
|
47
|
+
const file = path.join(directory, entry.name);
|
|
48
|
+
if (entry.isDirectory())
|
|
49
|
+
visit(file);
|
|
50
|
+
else if (entry.isFile() && /\.(?:js|json|sh|txt|yaml)$/u.test(entry.name))
|
|
51
|
+
files.push(file);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
visit(scriptsRoot);
|
|
55
|
+
for (const file of files.sort()) {
|
|
56
|
+
const name = path.relative(scriptsRoot, file);
|
|
57
|
+
hash.update(name);
|
|
58
|
+
hash.update('\0');
|
|
59
|
+
hash.update(fs.readFileSync(file));
|
|
60
|
+
hash.update('\0');
|
|
61
|
+
}
|
|
62
|
+
return hash.digest('hex');
|
|
63
|
+
}
|
|
64
|
+
function environmentFingerprint() {
|
|
65
|
+
return JSON.stringify({
|
|
66
|
+
node: runtime.version,
|
|
67
|
+
platform: runtime.platform,
|
|
68
|
+
architecture: runtime.arch,
|
|
69
|
+
timezone: clock.timezone(),
|
|
70
|
+
sharedScripts: sharedScriptsFingerprint(),
|
|
71
|
+
environment: Object.fromEntries(['CI', 'TZ', 'LANG', 'LC_ALL', 'NODE_OPTIONS']
|
|
72
|
+
.map((name) => [name, runtime.env[name] || ''])),
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
function currentBase(root) {
|
|
76
|
+
try {
|
|
77
|
+
return git(root, ['rev-parse', '--verify', 'HEAD']).toString('utf8').trim();
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (error.status === 128)
|
|
81
|
+
return EMPTY_TREE;
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function snapshot(root = ROOT(), baseCommit = currentBase(root)) {
|
|
86
|
+
return {
|
|
87
|
+
baseCommit,
|
|
88
|
+
environment: environmentFingerprint(),
|
|
89
|
+
changedFiles: changedPaths(root, baseCommit)
|
|
90
|
+
.map((relative) => [relative, fileFingerprint(root, relative)]),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function receiptPath(root = ROOT()) {
|
|
94
|
+
const id = crypto.createHash('sha256').update(fs.realpathSync(root)).digest('hex');
|
|
95
|
+
return path.join(os.tmpdir(), RECEIPT_DIRECTORY, `${id}.git.json`);
|
|
96
|
+
}
|
|
97
|
+
const api = { ROOT, environmentFingerprint, receiptPath, snapshot };
|
|
98
|
+
return api;
|
|
99
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export default ({ configuration, receiptState, external: { clock, fs, output, path, runtime } }) => {
|
|
2
|
+
const { requireTestCommands } = configuration;
|
|
3
|
+
const { ROOT, receiptPath, snapshot } = receiptState;
|
|
4
|
+
function recordReceipt(root = ROOT(), testedSnapshot) {
|
|
5
|
+
requireTestCommands(root);
|
|
6
|
+
const current = snapshot(root, testedSnapshot?.baseCommit);
|
|
7
|
+
if (testedSnapshot && JSON.stringify(current) !== JSON.stringify(testedSnapshot)) {
|
|
8
|
+
throw new Error('Files or environment changed while tests ran; rerun tests before recording a receipt.');
|
|
9
|
+
}
|
|
10
|
+
const receipt = { version: 1, passedAt: clock.now(), ...current };
|
|
11
|
+
const destination = receiptPath(root);
|
|
12
|
+
fs.mkdirSync(path.dirname(destination), { recursive: true });
|
|
13
|
+
const temporary = `${destination}.${runtime.pid}.tmp`;
|
|
14
|
+
fs.writeFileSync(temporary, `${JSON.stringify(receipt)}\n`);
|
|
15
|
+
fs.renameSync(temporary, destination);
|
|
16
|
+
return receipt;
|
|
17
|
+
}
|
|
18
|
+
function run() {
|
|
19
|
+
try {
|
|
20
|
+
recordReceipt();
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
output.error(error instanceof Error ? error.message : String(error));
|
|
24
|
+
runtime.exitCode = 1;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const api = { recordReceipt, run };
|
|
28
|
+
return api;
|
|
29
|
+
};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
export default ({ checkTestReceipt, configuration, projects, receiptState, recordTestReceipt, external: { fs, output, runtime, spawnSync } }) => {
|
|
2
|
+
const { checkReceipt, successMessage } = checkTestReceipt;
|
|
3
|
+
const { recordReceipt } = recordTestReceipt;
|
|
4
|
+
const { projectConfig, requireTestCommands } = configuration;
|
|
5
|
+
const { receiptPath, snapshot } = receiptState;
|
|
6
|
+
function run(command, root) {
|
|
7
|
+
const result = spawnSync(command, { cwd: root, stdio: 'inherit', shell: true });
|
|
8
|
+
if (result.error)
|
|
9
|
+
throw result.error;
|
|
10
|
+
return result.status ?? 1;
|
|
11
|
+
}
|
|
12
|
+
function hasReusableReceipt() {
|
|
13
|
+
try {
|
|
14
|
+
return checkReceipt();
|
|
15
|
+
}
|
|
16
|
+
catch (error) {
|
|
17
|
+
output.error(error instanceof Error ? error.message : String(error));
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function main({ force = false } = {}) {
|
|
22
|
+
requireTestCommands();
|
|
23
|
+
const config = projectConfig();
|
|
24
|
+
runtime.exitCode = undefined;
|
|
25
|
+
projects.checkProject();
|
|
26
|
+
const projectStatus = runtime.exitCode ?? 0;
|
|
27
|
+
if (projectStatus !== 0) {
|
|
28
|
+
fs.rmSync(receiptPath(config.root), { force: true });
|
|
29
|
+
runtime.exitCode = projectStatus;
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
if (!force && !runtime.env.CI && hasReusableReceipt()) {
|
|
33
|
+
output.log(successMessage(config.root));
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
fs.rmSync(receiptPath(config.root), { force: true });
|
|
37
|
+
const testedSnapshot = snapshot(config.root);
|
|
38
|
+
for (const command of config.tests.commands) {
|
|
39
|
+
const status = run(command, config.root);
|
|
40
|
+
if (status !== 0) {
|
|
41
|
+
runtime.exitCode = status;
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
recordReceipt(config.root, testedSnapshot);
|
|
46
|
+
}
|
|
47
|
+
function runCommand(options = {}) {
|
|
48
|
+
try {
|
|
49
|
+
main(options);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
output.error(error instanceof Error ? error.message : String(error));
|
|
53
|
+
runtime.exitCode = 1;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return { run: runCommand };
|
|
57
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jakobm/peacekeeper",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.22.0",
|
|
4
4
|
"description": "Shared repository test, Git worktree, and Codex hook commands",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Jakob Mattsson",
|
|
@@ -8,32 +8,48 @@
|
|
|
8
8
|
"type": "git",
|
|
9
9
|
"url": "git+https://github.com/jakobmattsson/peacekeeper.git"
|
|
10
10
|
},
|
|
11
|
+
"type": "module",
|
|
11
12
|
"publishConfig": {
|
|
12
13
|
"access": "public",
|
|
13
14
|
"registry": "https://registry.npmjs.org/"
|
|
14
15
|
},
|
|
15
16
|
"bin": {
|
|
16
|
-
"peacekeeper": "bin/peacekeeper.js"
|
|
17
|
+
"peacekeeper": "dist/bin/peacekeeper.js"
|
|
17
18
|
},
|
|
18
19
|
"files": [
|
|
19
|
-
"bin/",
|
|
20
|
-
"
|
|
20
|
+
"dist/bin/",
|
|
21
|
+
"dist/src/",
|
|
22
|
+
"dist/cmdabra.yaml",
|
|
23
|
+
"dist/package.json"
|
|
21
24
|
],
|
|
22
25
|
"scripts": {
|
|
23
|
-
"
|
|
24
|
-
"
|
|
25
|
-
"
|
|
26
|
-
"
|
|
26
|
+
"generate:cli-types": "cmdabra generate-types cmdabra.yaml --output src/modules/cli/types.ts",
|
|
27
|
+
"check:cli-types": "cmdabra generate-types cmdabra.yaml --output src/modules/cli/types.ts --check",
|
|
28
|
+
"clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
|
|
29
|
+
"build": "npm run clean && npm run check:cli-types && tsc && tsc -p tsconfig.test.json && node dist/scripts/copy-assets.js",
|
|
30
|
+
"typecheck": "npm run check:cli-types && tsc --noEmit && tsc -p tsconfig.test.json --noEmit",
|
|
31
|
+
"test": "npm run build && node dist/bin/peacekeeper.js run-tests",
|
|
32
|
+
"prepare": "npm run build",
|
|
33
|
+
"architecture": "npm run build && portico architecture --modules dist/src/modules --output architecture",
|
|
34
|
+
"release": "node dist/bin/peacekeeper.js release",
|
|
35
|
+
"cleanup:branches": "node dist/bin/peacekeeper.js cleanup-merged-branches",
|
|
36
|
+
"cleanup:empty-directories": "node dist/bin/peacekeeper.js remove-empty-directories"
|
|
27
37
|
},
|
|
28
38
|
"engines": {
|
|
29
|
-
"node": "
|
|
39
|
+
"node": "^22.14.0"
|
|
30
40
|
},
|
|
31
41
|
"dependencies": {
|
|
32
42
|
"@iarna/toml": "^2.2.5",
|
|
33
43
|
"@jakobm/cmdabra": "^0.2.1",
|
|
44
|
+
"@jakobm/portico": "^0.7.0",
|
|
34
45
|
"semver": "^7.8.5",
|
|
35
46
|
"yaml": "^2.9.1"
|
|
36
47
|
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@types/node": "^22.20.5",
|
|
50
|
+
"@types/semver": "^7.7.1",
|
|
51
|
+
"typescript": "^6.0.3"
|
|
52
|
+
},
|
|
37
53
|
"volta": {
|
|
38
54
|
"node": "22.14.0",
|
|
39
55
|
"npm": "11.21.0"
|