@jakobm/peacekeeper 0.25.2 → 0.27.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 (40) hide show
  1. package/README.md +464 -89
  2. package/dist/cmdabra.yaml +174 -110
  3. package/dist/package.json +6 -5
  4. package/dist/src/modules/cli/legacy-commands.js +37 -0
  5. package/dist/src/modules/cli/service.js +48 -39
  6. package/dist/src/modules/configuration/convention-rules.js +93 -0
  7. package/dist/src/modules/configuration/facade.js +1 -0
  8. package/dist/src/modules/configuration/project-config-defaults.json +5 -1
  9. package/dist/src/modules/configuration/project-config.js +28 -9
  10. package/dist/src/modules/configuration/update-config.js +16 -2
  11. package/dist/src/modules/dependencies.yaml +4 -4
  12. package/dist/src/modules/external.js +5 -0
  13. package/dist/src/modules/lifecycle/checkpoint-instructions.js +1 -1
  14. package/dist/src/modules/lifecycle/cleanup-ended-session.js +1 -1
  15. package/dist/src/modules/maintenance/cleanup-merged-branches.js +4 -4
  16. package/dist/src/modules/maintenance/initialize-codex-worktree.js +1 -1
  17. package/dist/src/modules/maintenance/remove-empty-directories.js +1 -1
  18. package/dist/src/modules/projects/check-project-requirements.txt +32 -31
  19. package/dist/src/modules/projects/check-project.js +16 -16
  20. package/dist/src/modules/projects/codex-setup-prefix.sh +2 -2
  21. package/dist/src/modules/projects/create-project-core.js +13 -28
  22. package/dist/src/modules/projects/generate-github-setup.js +16 -55
  23. package/dist/src/modules/projects/github-setup-prefix.sh +29 -2
  24. package/dist/src/modules/projects/github-setup-repository-template.sh +1 -40
  25. package/dist/src/modules/projects/github-setup-suffix-template.sh +7 -5
  26. package/dist/src/modules/projects/install-hooks.js +6 -5
  27. package/dist/src/modules/releases/configure-github.js +57 -0
  28. package/dist/src/modules/releases/facade.js +3 -2
  29. package/dist/src/modules/releases/github-configuration.js +166 -0
  30. package/dist/src/modules/releases/github-policy.js +45 -11
  31. package/dist/src/modules/releases/github-remote.js +230 -0
  32. package/dist/src/modules/testing/check-conventions.js +41 -0
  33. package/dist/src/modules/testing/check-test-receipt.js +17 -22
  34. package/dist/src/modules/testing/conventions.js +168 -0
  35. package/dist/src/modules/testing/facade.js +2 -1
  36. package/dist/src/modules/testing/receipt-state.js +27 -1
  37. package/dist/src/modules/testing/record-test-receipt.js +14 -13
  38. package/dist/src/modules/testing/run-tests.js +23 -14
  39. package/dist/src/modules/testing/types.js +1 -0
  40. package/package.json +6 -5
@@ -0,0 +1,230 @@
1
+ export default ({ configuration, githubPolicy, external: { buffer: Buffer, projectConfigDefaults, spawnSync, structuredClone, YAML, } }) => {
2
+ const { canonical, normalizeRuleset } = githubPolicy;
3
+ const shaPattern = /^[a-f0-9]{40}$/u;
4
+ function request(endpoint, method = 'GET', body) {
5
+ const args = ['api', '--hostname', 'github.com', '--method', method, endpoint];
6
+ if (body !== undefined)
7
+ args.push('--input', '-');
8
+ const result = spawnSync('gh', args, { encoding: 'utf8',
9
+ ...(body === undefined ? {} : { input: JSON.stringify(body) }) });
10
+ if (result.error || result.status !== 0)
11
+ throw new Error(`GitHub ${method} ${endpoint}: ${result.error?.message || result.stderr?.trim() || `exit ${result.status}`}`);
12
+ if (method === 'DELETE' && !result.stdout?.trim())
13
+ return undefined;
14
+ let response;
15
+ try {
16
+ response = JSON.parse(result.stdout);
17
+ }
18
+ catch {
19
+ throw new Error(`GitHub returned invalid JSON for ${endpoint}.`);
20
+ }
21
+ if (response?.errors?.length)
22
+ throw new Error(`GitHub ${endpoint}: ${response.errors.map(error => error.message).join('; ')}`);
23
+ return response;
24
+ }
25
+ function graphql(query, variables) {
26
+ const result = request('graphql', 'POST', { query, variables });
27
+ if (!result?.data)
28
+ throw new Error('GitHub returned incomplete GraphQL data.');
29
+ return result.data;
30
+ }
31
+ function repositorySlug(value) {
32
+ if (typeof value !== 'string' || !/^[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+$/u.test(value)
33
+ || ['.', '..'].includes(value.split('/')[1]))
34
+ throw new Error('--repository must be OWNER/REPO on github.com.');
35
+ return value;
36
+ }
37
+ function commitSha(value) {
38
+ if (typeof value !== 'string' || !shaPattern.test(value))
39
+ throw new Error('GitHub did not return an exact commit SHA.');
40
+ return value;
41
+ }
42
+ function readTree(slug, sha) {
43
+ const response = request(`repos/${slug}/git/trees/${sha}`);
44
+ if (!Array.isArray(response?.tree) || response.truncated !== false)
45
+ throw new Error('Cannot completely inspect the policy source tree.');
46
+ return response.tree;
47
+ }
48
+ function readBlob(slug, sha, name, tree, basename = name) {
49
+ const entry = tree.find(item => item.path === basename);
50
+ if (!entry)
51
+ return undefined;
52
+ if (entry.type !== 'blob' || !['100644', '100755'].includes(entry.mode))
53
+ throw new Error(`${name} must be a regular file.`);
54
+ const file = request(`repos/${slug}/contents/${name}?ref=${sha}`);
55
+ if (file?.type !== 'file' || file.encoding !== 'base64' || typeof file.content !== 'string' || file.sha !== entry.sha) {
56
+ throw new Error(`GitHub returned invalid policy file contents for ${name}.`);
57
+ }
58
+ return Buffer.from(file.content, 'base64').toString('utf8');
59
+ }
60
+ function loadSource({ repository, policyPr, sourceRef }) {
61
+ const slug = repositorySlug(repository);
62
+ if (sourceRef !== undefined && !shaPattern.test(sourceRef))
63
+ throw new Error('--source-ref must be a full lowercase commit SHA.');
64
+ const metadata = request(`repos/${slug}`);
65
+ if (!Number.isSafeInteger(metadata?.id) || typeof metadata.full_name !== 'string'
66
+ || metadata.full_name.toLowerCase() !== slug.toLowerCase()
67
+ || typeof metadata.default_branch !== 'string' || !metadata.default_branch
68
+ || !Number.isSafeInteger(metadata.owner?.id) || typeof metadata.owner.login !== 'string') {
69
+ throw new Error('GitHub returned incomplete repository metadata.');
70
+ }
71
+ const base = `repos/${metadata.full_name}`;
72
+ const defaultSha = commitSha(request(`${base}/commits/${encodeURIComponent(metadata.default_branch)}`).sha);
73
+ let sha = defaultSha;
74
+ let number;
75
+ if (policyPr !== undefined) {
76
+ if (!/^[1-9][0-9]*$/u.test(String(policyPr)) || !Number.isSafeInteger(Number(policyPr)))
77
+ throw new Error('--policy-pr must be a positive PR number.');
78
+ number = Number(policyPr);
79
+ const pr = request(`${base}/pulls/${number}`);
80
+ if (pr?.number !== number || pr.state !== 'open' || pr.base?.repo?.id !== metadata.id
81
+ || pr.head?.repo?.id !== metadata.id || pr.base?.ref !== metadata.default_branch) {
82
+ throw new Error('Policy PR must be open, originate in this repository and target its current default branch.');
83
+ }
84
+ sha = commitSha(pr.head.sha);
85
+ }
86
+ if (sourceRef !== undefined && sourceRef !== sha)
87
+ throw new Error('Policy source moved from --source-ref; create a new plan.');
88
+ const root = readTree(metadata.full_name, sha);
89
+ const contents = readBlob(metadata.full_name, sha, 'peacekeeper.config.yaml', root);
90
+ let config;
91
+ if (contents === undefined) {
92
+ if (root.some(item => item.path === 'peacekeeper.config.json'))
93
+ throw new Error('Rename legacy peacekeeper.config.json to peacekeeper.config.yaml and convert it to YAML.');
94
+ config = structuredClone(projectConfigDefaults);
95
+ }
96
+ else {
97
+ try {
98
+ config = YAML.parse(contents);
99
+ }
100
+ catch (error) {
101
+ throw new Error(`peacekeeper.config.yaml: ${error instanceof Error ? error.message : String(error)}`);
102
+ }
103
+ }
104
+ configuration.validateConfig(config, `${metadata.full_name}/peacekeeper.config.yaml`);
105
+ const requiredApprover = config.git.requiredApprover || metadata.owner.login;
106
+ const blockers = [];
107
+ if (metadata.owner.type !== 'User' || requiredApprover.toLowerCase() !== metadata.owner.login.toLowerCase()) {
108
+ blockers.push('git.requiredApprover must be the personal GitHub repository owner.');
109
+ }
110
+ const github = root.find(item => item.path === '.github');
111
+ if (github && github.type !== 'tree')
112
+ throw new Error('.github must be a directory in the policy source.');
113
+ const tree = github ? readTree(metadata.full_name, github.sha) : [];
114
+ const codeowners = readBlob(metadata.full_name, sha, '.github/CODEOWNERS', tree, 'CODEOWNERS');
115
+ const codeownersError = configuration.codeownersError(codeowners, requiredApprover);
116
+ if (codeownersError)
117
+ blockers.push(codeownersError);
118
+ const source = { kind: number === undefined ? 'default-branch' : 'pull-request',
119
+ sha, defaultBranch: metadata.default_branch, defaultSha, ...(number === undefined ? {} : { policyPr: number }) };
120
+ return { metadata, config, requiredApprover, blockers, source,
121
+ configSource: contents === undefined ? 'defaults' : 'remote' };
122
+ }
123
+ function restPages(endpoint) {
124
+ const all = [];
125
+ for (let page = 1;; page += 1) {
126
+ const batch = request(`${endpoint}${endpoint.includes('?') ? '&' : '?'}per_page=100&page=${page}`);
127
+ if (!Array.isArray(batch))
128
+ throw new Error(`Cannot completely inventory ${endpoint}.`);
129
+ all.push(...batch);
130
+ if (batch.length < 100)
131
+ return all;
132
+ }
133
+ }
134
+ function connectionPages(read) {
135
+ let cursor = null;
136
+ const cursors = new Set();
137
+ const result = [];
138
+ for (;;) {
139
+ const connection = read(cursor);
140
+ if (!Array.isArray(connection?.nodes) || connection.nodes.some(node => !node)
141
+ || typeof connection.pageInfo?.hasNextPage !== 'boolean')
142
+ throw new Error('Cannot completely inventory GitHub protection rules.');
143
+ result.push(...connection.nodes);
144
+ if (!connection.pageInfo.hasNextPage)
145
+ return result;
146
+ cursor = connection.pageInfo.endCursor;
147
+ if (!cursor || cursors.has(cursor))
148
+ throw new Error('GitHub returned invalid protection pagination.');
149
+ cursors.add(cursor);
150
+ }
151
+ }
152
+ const protectionFields = `id pattern allowsDeletions allowsForcePushes blocksCreations
153
+ dismissesStaleReviews isAdminEnforced lockAllowsFetchAndMerge lockBranch requireLastPushApproval
154
+ requiredApprovingReviewCount requiredDeploymentEnvironments requiredStatusCheckContexts
155
+ requiredStatusChecks { context app { id } }
156
+ requiresApprovingReviews requiresCodeOwnerReviews requiresCommitSignatures
157
+ requiresConversationResolution requiresDeployments requiresLinearHistory requiresStatusChecks
158
+ requiresStrictStatusChecks restrictsPushes restrictsReviewDismissals`;
159
+ function classicProtections(slug) {
160
+ const [owner, name] = slug.split('/');
161
+ const query = `query PeacekeeperProtections($owner:String!,$name:String!,$cursor:String) {
162
+ repository(owner:$owner,name:$name) { branchProtectionRules(first:100,after:$cursor) {
163
+ nodes { ${protectionFields} } pageInfo { hasNextPage endCursor }
164
+ } }
165
+ }`;
166
+ const rules = connectionPages(cursor => graphql(query, { owner, name, cursor }).repository?.branchProtectionRules);
167
+ if (new Set(rules.map(rule => rule.id)).size !== rules.length)
168
+ throw new Error('Duplicate classic protection IDs in inventory.');
169
+ for (const rule of rules) {
170
+ if (typeof rule.id !== 'string' || !rule.id || typeof rule.pattern !== 'string')
171
+ throw new Error('GitHub returned invalid classic protection.');
172
+ for (const field of ['pushAllowances', 'reviewDismissalAllowances', 'bypassPullRequestAllowances', 'bypassForcePushAllowances']) {
173
+ const allowances = connectionPages(cursor => graphql(`query PeacekeeperAllowances($id:ID!,$cursor:String) {
174
+ node(id:$id) { ... on BranchProtectionRule { ${field}(first:100,after:$cursor) {
175
+ nodes { actor { __typename ... on Node { id } } } pageInfo { hasNextPage endCursor }
176
+ } } }
177
+ }`, { id: rule.id, cursor }).node?.[field]);
178
+ if (allowances.some(item => typeof item.actor?.id !== 'string'))
179
+ throw new Error('Cannot inspect classic protection allowance actors.');
180
+ rule[field] = allowances;
181
+ }
182
+ }
183
+ return canonical(rules);
184
+ }
185
+ function readRuleset(base, summary) {
186
+ if (!Number.isSafeInteger(summary.id))
187
+ throw new Error('GitHub returned invalid ruleset identity.');
188
+ const ruleset = request(`${base}/rulesets/${summary.id}`);
189
+ if (ruleset?.id !== summary.id || ruleset.target !== 'branch'
190
+ || ruleset.source !== summary.source || ruleset.source_type !== summary.source_type
191
+ || typeof ruleset.name !== 'string' || !['active', 'disabled', 'evaluate'].includes(ruleset.enforcement)
192
+ || !Array.isArray(ruleset.rules) || !Array.isArray(ruleset.bypass_actors)
193
+ || !ruleset.conditions?.ref_name || !Array.isArray(ruleset.conditions.ref_name.include)
194
+ || !Array.isArray(ruleset.conditions.ref_name.exclude))
195
+ throw new Error(`Cannot fully inspect branch ruleset ${summary.id}, including bypass actors.`);
196
+ return { id: summary.id, policy: normalizeRuleset(ruleset) };
197
+ }
198
+ function inventory(metadata, repositoryFields) {
199
+ const base = `repos/${metadata.full_name}`;
200
+ const repository = Object.fromEntries(Object.keys(repositoryFields).map(key => {
201
+ if (typeof metadata[key] !== 'boolean')
202
+ throw new Error(`Cannot inspect repository setting ${key}.`);
203
+ return [key, metadata[key]];
204
+ }));
205
+ const owned = restPages(`${base}/rulesets?includes_parents=false`);
206
+ const all = restPages(`${base}/rulesets?includes_parents=true`);
207
+ if (owned.some(rule => rule.source_type !== 'Repository' || rule.source !== metadata.full_name)) {
208
+ throw new Error('Cannot determine repository ruleset ownership.');
209
+ }
210
+ if (owned.some(rule => !['branch', 'tag', 'push'].includes(rule.target)))
211
+ throw new Error('Cannot determine ruleset target.');
212
+ if (all.some(rule => !['branch', 'tag', 'push'].includes(rule.target)
213
+ || !['Repository', 'Organization', 'Enterprise'].includes(rule.source_type)))
214
+ throw new Error('Cannot determine inherited ruleset ownership.');
215
+ const ownedIds = owned.filter(rule => rule.target === 'branch').map(rule => rule.id);
216
+ const allOwnedIds = all.filter(rule => rule.target === 'branch' && rule.source_type === 'Repository'
217
+ && rule.source === metadata.full_name).map(rule => rule.id);
218
+ if (new Set(all.map(rule => rule.id)).size !== all.length
219
+ || !githubPolicy.same(ownedIds, allOwnedIds))
220
+ throw new Error('Ruleset inventory changed between requests; create a new plan.');
221
+ const rulesets = owned.filter(rule => rule.target === 'branch').map(rule => readRuleset(base, rule));
222
+ const inheritedRulesets = all.filter(rule => rule.target === 'branch'
223
+ && (rule.source_type !== 'Repository' || rule.source !== metadata.full_name))
224
+ .map(rule => ({ ...readRuleset(base, rule), source: rule.source }));
225
+ if (new Set(rulesets.map(rule => rule.id)).size !== rulesets.length)
226
+ throw new Error('Duplicate ruleset IDs in inventory.');
227
+ return canonical({ repository, rulesets, inheritedRulesets, classicProtections: classicProtections(metadata.full_name) });
228
+ }
229
+ return { request, graphql, repositorySlug, loadSource, inventory };
230
+ };
@@ -0,0 +1,41 @@
1
+ export default ({ configuration, conventions, external: { output, runtime, test } }) => {
2
+ function name(rule) {
3
+ switch (rule.check) {
4
+ case 'allowed-files':
5
+ case 'file-names': return `${rule.check}: ${rule.files}`;
6
+ case 'corresponding-files': return `${rule.check}: ${rule.from} -> ${rule.to}`;
7
+ case 'sorted-yaml-lists': return `${rule.check}: ${rule.file}`;
8
+ case 'document-links': return `${rule.check}: ${rule.document} -> ${rule.files}`;
9
+ case 'generated-files': return `${rule.check}: ${rule.expected}`;
10
+ }
11
+ }
12
+ async function run({ update = false } = {}) {
13
+ try {
14
+ const config = configuration.projectConfig();
15
+ if (!config.conventions.rules.length) {
16
+ output.log('No convention rules configured.');
17
+ return;
18
+ }
19
+ await test('repository conventions', async (context) => {
20
+ for (const rule of config.conventions.rules) {
21
+ await context.test(name(rule), () => {
22
+ try {
23
+ const violations = conventions.checkRule(config.root, rule, update);
24
+ if (violations.length)
25
+ throw new Error(violations.join('\n'));
26
+ }
27
+ catch (error) {
28
+ runtime.exitCode = 1;
29
+ throw error;
30
+ }
31
+ });
32
+ }
33
+ });
34
+ }
35
+ catch (error) {
36
+ output.error(error instanceof Error ? error.message : String(error));
37
+ runtime.exitCode = 1;
38
+ }
39
+ }
40
+ return { run };
41
+ };
@@ -1,40 +1,35 @@
1
- export default ({ configuration, receiptState, external: { clock, fs, output, runtime } }) => {
2
- const { ROOT, environmentFingerprint, receiptPath, snapshot } = receiptState;
1
+ // --- Implementation ---
2
+ export default ({ configuration, receiptState, external: { clock, output, runtime } }) => {
3
+ const { ROOT, environmentFingerprint, readReceipts, snapshot } = receiptState;
3
4
  const { projectConfig, requireTestCommands } = configuration;
4
- function successMessage(root = ROOT()) {
5
+ function successMessage(root = ROOT(), checkpoint = false) {
5
6
  const command = projectConfig(root).tests.npmTestUsesRunner
6
- ? 'npm test -- --force'
7
- : 'node node_modules/@jakobm/peacekeeper/dist/bin/peacekeeper.js run-tests --force';
7
+ ? `npm test -- --force${checkpoint ? ' --checkpoint' : ''}`
8
+ : `node node_modules/@jakobm/peacekeeper/dist/bin/peacekeeper.js test run --force${checkpoint ? ' --checkpoint' : ''}`;
8
9
  return `Tests already passed for this change set. In order to rerun tests anyway, use: ${command}`;
9
10
  }
10
11
  function matchesReceipt(receipt, root = ROOT()) {
11
12
  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())
13
+ if (!receipt || typeof receipt.command !== 'string' || typeof receipt.baseCommit !== 'string'
14
+ || !Array.isArray(receipt.changedFiles) || !Number.isFinite(receipt.passedAt)
15
+ || clock.now() < receipt.passedAt || clock.now() - receipt.passedAt > receiptMaxAgeMinutes * 60_000
16
+ || receipt.environment !== environmentFingerprint())
15
17
  return false;
16
18
  const current = snapshot(root, receipt.baseCommit);
17
19
  return JSON.stringify(current.changedFiles) === JSON.stringify(receipt.changedFiles);
18
20
  }
19
- function checkReceipt(root = ROOT()) {
21
+ function checkReceipt(root = ROOT(), commands = projectConfig(root).tests.all) {
20
22
  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);
23
+ const receipts = readReceipts(root);
24
+ return commands.every(command => receipts.some(receipt => receipt?.command === command && matchesReceipt(receipt, root)));
31
25
  }
32
- function run() {
26
+ function run({ checkpoint = false } = {}) {
33
27
  try {
34
- if (!checkReceipt())
28
+ const config = projectConfig();
29
+ if (!checkReceipt(config.root, config.tests[checkpoint ? 'checkpoint' : 'all']))
35
30
  runtime.exitCode = 1;
36
31
  else
37
- output.log(successMessage());
32
+ output.log(successMessage(config.root, checkpoint));
38
33
  }
39
34
  catch (error) {
40
35
  output.error(error instanceof Error ? error.message : String(error));
@@ -0,0 +1,168 @@
1
+ export default ({ external: { fs, os, spawnSync, path, globSync, hasMagic, runtime, YAML } }) => {
2
+ function selectedFiles(root, pattern) {
3
+ return globSync(pattern, {
4
+ cwd: root, nodir: true, dot: true, follow: false,
5
+ ignore: {
6
+ childrenIgnored: entry => entry.isSymbolicLink(),
7
+ ignored: entry => entry.isSymbolicLink()
8
+ && !fs.statSync(entry.fullpath(), { throwIfNoEntry: false })?.isFile(),
9
+ },
10
+ })
11
+ .map((fileName) => fileName.split(path.sep).join('/')).sort();
12
+ }
13
+ function selectionDirectory(pattern) {
14
+ const segments = pattern.split('/');
15
+ const firstPattern = segments.findIndex((segment) => hasMagic(`./${segment}`, { magicalBraces: true }));
16
+ return segments.slice(0, firstPattern === -1 ? -1 : firstPattern).join('/') || '.';
17
+ }
18
+ function missingDirectory(root, pattern) {
19
+ const directory = selectionDirectory(pattern);
20
+ return fs.existsSync(path.join(root, directory)) && fs.statSync(path.join(root, directory)).isDirectory()
21
+ ? [] : [`Selection directory does not exist: ${directory}`];
22
+ }
23
+ function allowedFiles(root, rule) {
24
+ const violations = missingDirectory(root, rule.files);
25
+ if (violations.length === 0) {
26
+ const allowed = new Set(rule.allow.flatMap((pattern) => selectedFiles(root, pattern)));
27
+ for (const fileName of selectedFiles(root, rule.files)) {
28
+ if (!allowed.has(fileName))
29
+ violations.push(`Unexpected file: ${fileName}`);
30
+ }
31
+ }
32
+ return violations;
33
+ }
34
+ function fileNames(root, rule) {
35
+ const pattern = new RegExp(rule.match, 'u');
36
+ const violations = missingDirectory(root, rule.files);
37
+ if (violations.length === 0) {
38
+ for (const fileName of selectedFiles(root, rule.files)) {
39
+ if (!pattern.test(path.posix.basename(fileName))) {
40
+ violations.push(`Unexpected file name: ${fileName} (expected ${rule.match})`);
41
+ }
42
+ }
43
+ }
44
+ return violations;
45
+ }
46
+ function correspondingFiles(root, rule) {
47
+ const [prefix, suffix] = rule.from.split('{path}');
48
+ const directory = path.posix.dirname(`${prefix}placeholder`);
49
+ const pattern = directory === '.' ? '**/*' : `${directory}/**/*`;
50
+ const violations = missingDirectory(root, pattern);
51
+ if (violations.length === 0) {
52
+ for (const fileName of selectedFiles(root, pattern)) {
53
+ if (!fileName.startsWith(prefix) || !fileName.endsWith(suffix) ||
54
+ fileName.length <= prefix.length + suffix.length)
55
+ continue;
56
+ const captured = fileName.slice(prefix.length, suffix.length === 0 ? undefined : -suffix.length);
57
+ const counterpart = rule.to.replace('{path}', () => captured);
58
+ const destination = path.join(root, counterpart);
59
+ if (!fs.existsSync(destination) || !fs.statSync(destination).isFile()) {
60
+ violations.push(`Missing corresponding file: ${fileName} -> ${counterpart}`);
61
+ }
62
+ }
63
+ }
64
+ return violations;
65
+ }
66
+ function sortedYamlLists(root, rule) {
67
+ const violations = [];
68
+ function visit(value, location) {
69
+ if (Array.isArray(value)) {
70
+ if (value.every((entry) => typeof entry === 'string')) {
71
+ const sorted = [...value].sort();
72
+ if (value.some((entry, index) => entry !== sorted[index])) {
73
+ violations.push(`Unsorted list: ${rule.file} at ${location}`);
74
+ }
75
+ }
76
+ else {
77
+ value.forEach((entry, index) => visit(entry, `${location}[${index}]`));
78
+ }
79
+ }
80
+ else if (value !== null && typeof value === 'object') {
81
+ for (const [key, entry] of Object.entries(value))
82
+ visit(entry, `${location}.${key}`);
83
+ }
84
+ }
85
+ visit(YAML.parse(fs.readFileSync(path.join(root, rule.file), 'utf8')), '$');
86
+ return violations;
87
+ }
88
+ function documentLinks(root, rule) {
89
+ const document = fs.readFileSync(path.join(root, rule.document), 'utf8');
90
+ const links = new Set();
91
+ for (const match of document.matchAll(/\]\(([^\s)]+)(?:\s+"[^"\n]*")?\)/gu)) {
92
+ const target = match[1].split(/[?#]/u)[0];
93
+ if (!target || /^(?:[a-z][a-z\d+.-]*:|\/)/iu.test(target))
94
+ continue;
95
+ links.add(path.resolve(root, path.dirname(rule.document), decodeURIComponent(target)));
96
+ }
97
+ const violations = missingDirectory(root, rule.files);
98
+ if (violations.length === 0) {
99
+ for (const fileName of selectedFiles(root, rule.files)) {
100
+ if (!links.has(path.resolve(root, fileName))) {
101
+ violations.push(`Missing document link: ${rule.document} -> ${fileName}`);
102
+ }
103
+ }
104
+ }
105
+ return violations;
106
+ }
107
+ function generatedFiles(root, rule, update) {
108
+ const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'conventions-generated-'));
109
+ const output = path.join(temporary, 'output');
110
+ const expected = path.join(root, rule.expected);
111
+ const violations = [];
112
+ try {
113
+ // Updating through a directory symlink could replace files outside this repository.
114
+ let target = root;
115
+ for (const segment of rule.expected.split('/')) {
116
+ target = path.join(target, segment);
117
+ if (fs.lstatSync(target, { throwIfNoEntry: false })?.isSymbolicLink()) {
118
+ throw new Error(`Generated output path must not contain symbolic links: ${rule.expected}`);
119
+ }
120
+ }
121
+ fs.mkdirSync(output);
122
+ const result = spawnSync(rule.run.replaceAll('{output}', () => output), {
123
+ cwd: root, shell: true, encoding: 'utf8',
124
+ env: { ...runtime.env, PATH: path.join(root, 'node_modules/.bin') + path.delimiter + (runtime.env.PATH ?? '') },
125
+ });
126
+ if (result.error)
127
+ throw result.error;
128
+ if (result.status !== 0) {
129
+ violations.push(`Generation failed (exit ${result.status}, signal ${result.signal}): ${result.stdout}${result.stderr}`);
130
+ }
131
+ else if (update) {
132
+ fs.rmSync(expected, { recursive: true, force: true });
133
+ fs.cpSync(output, expected, { recursive: true });
134
+ }
135
+ else if (!fs.existsSync(expected) || !fs.statSync(expected).isDirectory()) {
136
+ violations.push(`Missing expected directory: ${rule.expected}`);
137
+ }
138
+ else {
139
+ const generated = new Set(selectedFiles(output, '**/*'));
140
+ const committed = new Set(selectedFiles(expected, '**/*'));
141
+ for (const name of [...new Set([...generated, ...committed])].sort()) {
142
+ if (!generated.has(name))
143
+ violations.push(`Unexpected expected file: ${rule.expected}/${name}`);
144
+ else if (!committed.has(name))
145
+ violations.push(`Missing expected file: ${rule.expected}/${name}`);
146
+ else if (!fs.readFileSync(path.join(output, name)).equals(fs.readFileSync(path.join(expected, name)))) {
147
+ violations.push(`Generated file differs: ${rule.expected}/${name}`);
148
+ }
149
+ }
150
+ }
151
+ }
152
+ finally {
153
+ fs.rmSync(temporary, { recursive: true, force: true });
154
+ }
155
+ return violations;
156
+ }
157
+ function checkRule(root, rule, update) {
158
+ switch (rule.check) {
159
+ case 'generated-files': return generatedFiles(root, rule, update);
160
+ case 'allowed-files': return allowedFiles(root, rule);
161
+ case 'corresponding-files': return correspondingFiles(root, rule);
162
+ case 'sorted-yaml-lists': return sortedYamlLists(root, rule);
163
+ case 'document-links': return documentLinks(root, rule);
164
+ case 'file-names': return fileNames(root, rule);
165
+ }
166
+ }
167
+ return { checkRule };
168
+ };
@@ -1,4 +1,5 @@
1
- export const porticoFacade = ({ checkTestReceipt, recordTestReceipt, runTests }) => ({
1
+ export const porticoFacade = ({ checkConventions, checkTestReceipt, recordTestReceipt, runTests }) => ({
2
+ checkConventions: checkConventions.run,
2
3
  checkTestReceipt: checkTestReceipt.run,
3
4
  recordTestReceipt: recordTestReceipt.run,
4
5
  runTests: runTests.run,
@@ -1,3 +1,4 @@
1
+ // --- Implementation ---
1
2
  export default ({ configuration, external: { clock, crypto, execFileSync, fs, modulesRoot, os, path, runtime, } }) => {
2
3
  const { repositoryRoot } = configuration;
3
4
  const ROOT = repositoryRoot;
@@ -94,6 +95,31 @@ export default ({ configuration, external: { clock, crypto, execFileSync, fs, mo
94
95
  const id = crypto.createHash('sha256').update(fs.realpathSync(root)).digest('hex');
95
96
  return path.join(os.tmpdir(), RECEIPT_DIRECTORY, `${id}.git.json`);
96
97
  }
97
- const api = { ROOT, environmentFingerprint, receiptPath, snapshot };
98
+ function readReceipts(root = ROOT()) {
99
+ try {
100
+ const stored = JSON.parse(fs.readFileSync(receiptPath(root), 'utf8'));
101
+ return stored?.version === 2 && Array.isArray(stored.receipts) ? stored.receipts : [];
102
+ }
103
+ catch (error) {
104
+ if (error.code === 'ENOENT' || error instanceof SyntaxError)
105
+ return [];
106
+ throw error;
107
+ }
108
+ }
109
+ function writeReceipts(root, receipts) {
110
+ const destination = receiptPath(root);
111
+ if (!receipts.length) {
112
+ fs.rmSync(destination, { force: true });
113
+ return;
114
+ }
115
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
116
+ const temporary = `${destination}.${runtime.pid}.tmp`;
117
+ fs.writeFileSync(temporary, `${JSON.stringify({ version: 2, receipts })}\n`);
118
+ fs.renameSync(temporary, destination);
119
+ }
120
+ function invalidateReceipts(root = ROOT(), commands) {
121
+ writeReceipts(root, commands ? readReceipts(root).filter(receipt => !commands.includes(receipt?.command)) : []);
122
+ }
123
+ const api = { ROOT, environmentFingerprint, receiptPath, snapshot, readReceipts, writeReceipts, invalidateReceipts };
98
124
  return api;
99
125
  };
@@ -1,23 +1,24 @@
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) {
1
+ // --- Implementation ---
2
+ export default ({ configuration, receiptState, external: { clock, output, runtime } }) => {
3
+ const { projectConfig, requireTestCommands } = configuration;
4
+ const { ROOT, readReceipts, writeReceipts, snapshot } = receiptState;
5
+ function recordReceipt(root = ROOT(), testedSnapshot, commands = projectConfig(root).tests.all) {
5
6
  requireTestCommands(root);
6
7
  const current = snapshot(root, testedSnapshot?.baseCommit);
7
8
  if (testedSnapshot && JSON.stringify(current) !== JSON.stringify(testedSnapshot)) {
8
9
  throw new Error('Files or environment changed while tests ran; rerun tests before recording a receipt.');
9
10
  }
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;
11
+ const receipts = [...new Set(commands)].map(command => ({ command, passedAt: clock.now(), ...current }));
12
+ writeReceipts(root, [
13
+ ...readReceipts(root).filter(receipt => !commands.includes(receipt?.command)),
14
+ ...receipts,
15
+ ]);
16
+ return receipts[0];
17
17
  }
18
- function run() {
18
+ function run({ checkpoint = false } = {}) {
19
19
  try {
20
- recordReceipt();
20
+ const config = projectConfig();
21
+ recordReceipt(config.root, undefined, config.tests[checkpoint ? 'checkpoint' : 'all']);
21
22
  }
22
23
  catch (error) {
23
24
  output.error(error instanceof Error ? error.message : String(error));
@@ -1,48 +1,57 @@
1
- export default ({ checkTestReceipt, configuration, projects, receiptState, recordTestReceipt, external: { fs, output, runtime, spawnSync } }) => {
1
+ // --- Implementation ---
2
+ export default ({ checkTestReceipt, configuration, projects, receiptState, recordTestReceipt, external: { output, runtime, spawnSync } }) => {
2
3
  const { checkReceipt, successMessage } = checkTestReceipt;
3
4
  const { recordReceipt } = recordTestReceipt;
4
5
  const { projectConfig, requireTestCommands } = configuration;
5
- const { receiptPath, snapshot } = receiptState;
6
+ const { invalidateReceipts, snapshot } = receiptState;
6
7
  function run(command, root) {
7
8
  const result = spawnSync(command, { cwd: root, stdio: 'inherit', shell: true });
8
9
  if (result.error)
9
10
  throw result.error;
10
11
  return result.status ?? 1;
11
12
  }
12
- function hasReusableReceipt() {
13
+ function hasReusableReceipt(root, command) {
13
14
  try {
14
- return checkReceipt();
15
+ return checkReceipt(root, [command]);
15
16
  }
16
17
  catch (error) {
17
18
  output.error(error instanceof Error ? error.message : String(error));
18
19
  return false;
19
20
  }
20
21
  }
21
- function main({ force = false } = {}) {
22
+ function main({ force = false, checkpoint = false } = {}) {
22
23
  requireTestCommands();
23
24
  const config = projectConfig();
25
+ const commands = [...new Set(config.tests[checkpoint ? 'checkpoint' : 'all'])];
24
26
  runtime.exitCode = undefined;
25
27
  projects.checkProject();
26
28
  const projectStatus = runtime.exitCode ?? 0;
27
29
  if (projectStatus !== 0) {
28
- fs.rmSync(receiptPath(config.root), { force: true });
30
+ invalidateReceipts(config.root);
29
31
  runtime.exitCode = projectStatus;
30
32
  return;
31
33
  }
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) {
34
+ const bypassReceipts = force || Boolean(runtime.env.CI);
35
+ if (bypassReceipts)
36
+ invalidateReceipts(config.root, commands);
37
+ let ran = false;
38
+ for (const command of commands) {
39
+ if (!bypassReceipts && hasReusableReceipt(config.root, command)) {
40
+ output.log(`Skipping previously passed command: ${command}`);
41
+ continue;
42
+ }
43
+ invalidateReceipts(config.root, [command]);
44
+ const testedSnapshot = snapshot(config.root);
39
45
  const status = run(command, config.root);
40
46
  if (status !== 0) {
41
47
  runtime.exitCode = status;
42
48
  return;
43
49
  }
50
+ recordReceipt(config.root, testedSnapshot, [command]);
51
+ ran = true;
44
52
  }
45
- recordReceipt(config.root, testedSnapshot);
53
+ if (commands.length && !ran)
54
+ output.log(successMessage(config.root, checkpoint));
46
55
  }
47
56
  function runCommand(options = {}) {
48
57
  try {