tslaws 0.7.0 → 0.9.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 +8 -1
- package/dist/check.js +87 -17
- package/dist/cli.js +43 -3
- package/dist/coverage.d.ts +8 -0
- package/dist/coverage.js +18 -1
- package/dist/github.d.ts +123 -0
- package/dist/github.js +276 -0
- package/dist/githubCli.d.ts +53 -0
- package/dist/githubCli.js +535 -0
- package/dist/lock.d.ts +23 -0
- package/dist/lock.js +84 -0
- package/dist/propertyRun.d.ts +11 -0
- package/dist/propertyRun.js +23 -0
- package/dist/reporters.d.ts +3 -0
- package/dist/reporters.js +17 -0
- package/dist/smt.d.ts +16 -0
- package/dist/smt.js +43 -1
- package/dist/solvers.d.ts +31 -0
- package/dist/solvers.js +121 -0
- package/dist/symbolic.js +2 -2
- package/dist/types.d.ts +17 -0
- package/package.json +7 -7
|
@@ -0,0 +1,535 @@
|
|
|
1
|
+
// `tslaws github <report|command|merge|verify>`: the GitHub side of accepting laws. See github.ts for the policy.
|
|
2
|
+
//
|
|
3
|
+
// report pull_request: runs every law (proposals included), flags each proposal on its line, keeps one sticky
|
|
4
|
+
// comment up to date, and fails when an accepted law fails, a proposal fails, or (comment mode) a proposal
|
|
5
|
+
// waits for an accept. Advisory: it runs the pull request's code, so it decides nothing about the lock.
|
|
6
|
+
// command issue_comment: reads `/tslaws accept|reject ...`, checks the commenter may accept, and records the
|
|
7
|
+
// fingerprints accepted in a comment of the bot's. Reads the pull request's files as data; runs none of it.
|
|
8
|
+
// merge push to the configured branch: runs the laws on the merged code, accepts what passes (and, in comment
|
|
9
|
+
// mode, what was accepted for that exact version) and commits tsc-laws.lock through the API as the bot.
|
|
10
|
+
// The only place the lock is written.
|
|
11
|
+
// verify pull_request_target: fails when a commit in the pull request that the bot did not make (with a signature
|
|
12
|
+
// GitHub verified) touches tsc-laws.lock, or when the pull request changes the "github" section of
|
|
13
|
+
// tslaws.json or a protected path. Reads the base branch's config, never the pull request's.
|
|
14
|
+
import { readFileSync, writeFileSync, appendFileSync, existsSync } from 'node:fs';
|
|
15
|
+
import { createHash } from 'node:crypto';
|
|
16
|
+
import { execFileSync } from 'node:child_process';
|
|
17
|
+
import { join } from 'node:path';
|
|
18
|
+
import { check, exemptionsOf } from "./check.js";
|
|
19
|
+
import { readConfig } from "./coverage.js";
|
|
20
|
+
import { readManifest } from "./compile.js";
|
|
21
|
+
import { acceptedFingerprints, inert, recordComment, decide, parseCommands, isSharedBot, parseGithubConfig, proposalsOf, pullRequestVerdict, readApprovals, renderSticky, resolveNames, stickyMarkerFor, } from "./github.js";
|
|
22
|
+
import { classifyLawFile, lockLevels } from "./lawKinds.js";
|
|
23
|
+
import { acceptChanges, lockChanges, readLock, writeLockValue } from "./lock.js";
|
|
24
|
+
import { escapeGithubData, escapeGithubProperty } from "./reporters.js";
|
|
25
|
+
/** A project-relative file as the repository names it: the project's prefix, then the path. */
|
|
26
|
+
function repoPath(ctx, file) {
|
|
27
|
+
const prefix = (ctx.projectPath ?? '').replace(/^\/+|\/+$/g, '');
|
|
28
|
+
const clean = file.replaceAll('\\', '/');
|
|
29
|
+
return prefix === '' ? clean : `${prefix}/${clean}`;
|
|
30
|
+
}
|
|
31
|
+
/** `--project-path`, else where `cwd` sits inside its git repository (`git rev-parse --show-prefix`), else ''. */
|
|
32
|
+
export function projectPathOf(cwd, flag) {
|
|
33
|
+
let raw = typeof flag === 'string' ? flag : '';
|
|
34
|
+
if (typeof flag !== 'string') {
|
|
35
|
+
try {
|
|
36
|
+
raw = execFileSync('git', ['-C', cwd, 'rev-parse', '--show-prefix'], {
|
|
37
|
+
encoding: 'utf8',
|
|
38
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
raw = '';
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return raw
|
|
46
|
+
.trim()
|
|
47
|
+
.replaceAll('\\', '/')
|
|
48
|
+
.replace(/^(\.\/)+/, '')
|
|
49
|
+
.replace(/^\/+|\/+$/g, '');
|
|
50
|
+
}
|
|
51
|
+
function restApi(env) {
|
|
52
|
+
const base = env.GITHUB_API_URL ?? 'https://api.github.com';
|
|
53
|
+
const token = env.GITHUB_TOKEN ?? env.GH_TOKEN;
|
|
54
|
+
if (token === undefined || token === '')
|
|
55
|
+
throw new Error('GITHUB_TOKEN is not set');
|
|
56
|
+
return async (method, path, body) => {
|
|
57
|
+
const response = await fetch(`${base}${path}`, {
|
|
58
|
+
method,
|
|
59
|
+
headers: {
|
|
60
|
+
authorization: `Bearer ${token}`,
|
|
61
|
+
accept: 'application/vnd.github+json',
|
|
62
|
+
'x-github-api-version': '2022-11-28',
|
|
63
|
+
'user-agent': 'tslaws',
|
|
64
|
+
...(body === undefined ? {} : { 'content-type': 'application/json' }),
|
|
65
|
+
},
|
|
66
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
67
|
+
});
|
|
68
|
+
const text = await response.text();
|
|
69
|
+
if (!response.ok)
|
|
70
|
+
throw new Error(`GitHub ${method} ${path}: ${response.status} ${text.slice(0, 300)}`);
|
|
71
|
+
return text === '' ? undefined : JSON.parse(text);
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
async function all(api, path) {
|
|
75
|
+
const out = [];
|
|
76
|
+
for (let page = 1; page <= 30; page += 1) {
|
|
77
|
+
const batch = (await api('GET', `${path}${path.includes('?') ? '&' : '?'}per_page=100&page=${page}`));
|
|
78
|
+
out.push(...batch);
|
|
79
|
+
if (batch.length < 100)
|
|
80
|
+
break;
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
// ---- shared ---------------------------------------------------------------------------------------------------------
|
|
85
|
+
function repo(env) {
|
|
86
|
+
const name = env.GITHUB_REPOSITORY;
|
|
87
|
+
if (name === undefined || !/^[\w.-]+\/[\w.-]+$/.test(name))
|
|
88
|
+
throw new Error('GITHUB_REPOSITORY is not set');
|
|
89
|
+
return name;
|
|
90
|
+
}
|
|
91
|
+
function event(env) {
|
|
92
|
+
const path = env.GITHUB_EVENT_PATH;
|
|
93
|
+
return path !== undefined && existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {};
|
|
94
|
+
}
|
|
95
|
+
/** The `github` section of a tslaws.json text, with defaults. It must exist: it names the bot every check trusts. */
|
|
96
|
+
export function githubConfigOf(text) {
|
|
97
|
+
const raw = text === undefined ? undefined : JSON.parse(text).github;
|
|
98
|
+
if (raw === undefined)
|
|
99
|
+
throw new Error('tslaws github needs a "github" section in tslaws.json');
|
|
100
|
+
return parseGithubConfig(raw);
|
|
101
|
+
}
|
|
102
|
+
/** What the lock would record if everything were accepted now. Compiles the project; runs none of it. */
|
|
103
|
+
/** The id git gives a file's content: what the contents API reports as a file's `sha`. */
|
|
104
|
+
function gitBlobSha(bytes) {
|
|
105
|
+
return createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex');
|
|
106
|
+
}
|
|
107
|
+
export function projectState(options) {
|
|
108
|
+
const lock = readLock(options.lockFile);
|
|
109
|
+
const laws = readManifest(options.compiler, options.files, options.cwd);
|
|
110
|
+
const exempt = exemptionsOf(options);
|
|
111
|
+
const mode = readConfig(options.cwd).levels ?? 'names';
|
|
112
|
+
const levels = mode === 'imports'
|
|
113
|
+
? lockLevels(options.cwd, laws, 'imports')
|
|
114
|
+
: lock?.levels !== undefined
|
|
115
|
+
? Object.fromEntries([...new Set(laws.map((l) => l.file.replaceAll('\\', '/')))].map((f) => [
|
|
116
|
+
f,
|
|
117
|
+
classifyLawFile(options.cwd, f, 'names').kind,
|
|
118
|
+
]))
|
|
119
|
+
: undefined;
|
|
120
|
+
return { laws, exempt, levels, lock };
|
|
121
|
+
}
|
|
122
|
+
async function issueComments(api, name, pr) {
|
|
123
|
+
return all(api, `/repos/${name}/issues/${pr}/comments`);
|
|
124
|
+
}
|
|
125
|
+
async function upsertSticky(api, name, pr, bot, body, comments, project) {
|
|
126
|
+
const marker = stickyMarkerFor(project);
|
|
127
|
+
const mine = comments.find((c) => c.user.login === bot && c.body.startsWith(marker));
|
|
128
|
+
if (mine === undefined)
|
|
129
|
+
await api('POST', `/repos/${name}/issues/${pr}/comments`, { body });
|
|
130
|
+
else if (mine.body !== body)
|
|
131
|
+
await api('PATCH', `/repos/${name}/issues/comments/${mine.id}`, { body });
|
|
132
|
+
}
|
|
133
|
+
function linkFor(env, sha, ctx) {
|
|
134
|
+
const server = env.GITHUB_SERVER_URL ?? 'https://github.com';
|
|
135
|
+
const name = env.GITHUB_REPOSITORY ?? '';
|
|
136
|
+
// Raw text: renderSticky makes the whole cell inert. Brackets and backticks would break the link's markdown.
|
|
137
|
+
return (p) => {
|
|
138
|
+
const label = p.name.replace(/[`[\]]/g, "'");
|
|
139
|
+
if (p.line === 0 || name === '')
|
|
140
|
+
return `${label} (${p.file})`;
|
|
141
|
+
return `[${label}](${server}/${name}/blob/${sha}/${repoPath(ctx, p.file).split('/').map(encodeURIComponent).join('/')}#L${p.line})`;
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
/** A law name or path from the pull request, for a bot comment: inert, and quoted without a code span. */
|
|
145
|
+
function shown(text) {
|
|
146
|
+
return `“${inert(text)}”`;
|
|
147
|
+
}
|
|
148
|
+
function summary(env, text) {
|
|
149
|
+
if (env.GITHUB_STEP_SUMMARY !== undefined)
|
|
150
|
+
appendFileSync(env.GITHUB_STEP_SUMMARY, `${text}\n`);
|
|
151
|
+
}
|
|
152
|
+
function setOutput(env, key, value) {
|
|
153
|
+
if (env.GITHUB_OUTPUT !== undefined)
|
|
154
|
+
appendFileSync(env.GITHUB_OUTPUT, `${key}=${value}\n`);
|
|
155
|
+
}
|
|
156
|
+
// ---- report ---------------------------------------------------------------------------------------------------------
|
|
157
|
+
async function report(ctx) {
|
|
158
|
+
const config = githubConfigOf(readText(join(ctx.cwd, 'tslaws.json')));
|
|
159
|
+
const ev = event(ctx.env);
|
|
160
|
+
const pr = Number(ctx.flags.get('pr') ?? ev.pull_request?.number ?? NaN);
|
|
161
|
+
const sha = String(ev.pull_request?.head?.sha ?? ctx.env.GITHUB_SHA ?? '');
|
|
162
|
+
const checked = await check(ctx.options, true);
|
|
163
|
+
const state = projectState(ctx.options);
|
|
164
|
+
const proposals = proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), checked);
|
|
165
|
+
let api;
|
|
166
|
+
let comments = [];
|
|
167
|
+
try {
|
|
168
|
+
api = ctx.api ?? restApi(ctx.env);
|
|
169
|
+
if (Number.isInteger(pr))
|
|
170
|
+
comments = await issueComments(api, repo(ctx.env), pr);
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
ctx.err(`tslaws: cannot read the pull request's comments (${String(error)}); reporting without approvals\n`);
|
|
174
|
+
api = undefined;
|
|
175
|
+
}
|
|
176
|
+
const approvals = acceptedFingerprints(readApprovals(comments, config.bot));
|
|
177
|
+
const verdict = pullRequestVerdict(checked, proposals, config, approvals);
|
|
178
|
+
for (const p of proposals) {
|
|
179
|
+
const level = p.passes ? 'notice' : 'error';
|
|
180
|
+
const title = `tslaws proposal: ${p.name}`;
|
|
181
|
+
const message = p.outcome === undefined
|
|
182
|
+
? 'did not run'
|
|
183
|
+
: `${p.reason}; if accepted: ${p.outcome.status}${p.outcome.counterexample ? `; counterexample ${p.outcome.counterexample}` : ''}`;
|
|
184
|
+
ctx.out(`::${level} file=${escapeGithubProperty(repoPath(ctx, p.file))},line=${Math.max(1, p.line)},title=${escapeGithubProperty(title)}::${escapeGithubData(message)}\n`);
|
|
185
|
+
}
|
|
186
|
+
const project = repoPath(ctx, '');
|
|
187
|
+
const body = renderSticky(proposals, config, approvals, linkFor(ctx.env, sha, ctx), project);
|
|
188
|
+
summary(ctx.env, body.replace(stickyMarkerFor(project), ''));
|
|
189
|
+
if (api !== undefined && Number.isInteger(pr) && ctx.flags.has('comment')) {
|
|
190
|
+
try {
|
|
191
|
+
await upsertSticky(api, repo(ctx.env), pr, config.bot, body, comments, project);
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
// A pull request from a fork gets a read-only token: the step summary and annotations still carry the report.
|
|
195
|
+
ctx.err(`tslaws: cannot write the sticky comment (${String(error)})\n`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
const outFile = ctx.flags.get('out');
|
|
199
|
+
if (typeof outFile === 'string')
|
|
200
|
+
writeFileSync(outFile, `${JSON.stringify({ sha, proposals, verdict }, null, 2)}\n`);
|
|
201
|
+
setOutput(ctx.env, 'proposals', String(proposals.length));
|
|
202
|
+
for (const problem of verdict.problems)
|
|
203
|
+
ctx.out(`${problem}\n`);
|
|
204
|
+
ctx.out(verdict.ok ? `tslaws: ${proposals.length} proposal(s), all passing\n` : 'tslaws: the pull request is not ready\n');
|
|
205
|
+
return verdict.ok ? 0 : 1;
|
|
206
|
+
}
|
|
207
|
+
function readText(path) {
|
|
208
|
+
return existsSync(path) ? readFileSync(path, 'utf8') : undefined;
|
|
209
|
+
}
|
|
210
|
+
// ---- command --------------------------------------------------------------------------------------------------------
|
|
211
|
+
const rank = { none: 0, read: 1, triage: 2, write: 3, maintain: 4, admin: 5 };
|
|
212
|
+
/** Why `login` may not accept on this pull request, or undefined when they may. */
|
|
213
|
+
export async function refusal(api, name, pr, login, type, config) {
|
|
214
|
+
if (type === 'Bot' || login.endsWith('[bot]'))
|
|
215
|
+
return 'bots cannot accept laws';
|
|
216
|
+
const permission = (await api('GET', `/repos/${name}/collaborators/${encodeURIComponent(login)}/permission`));
|
|
217
|
+
const level = Math.max(rank[permission.permission] ?? 0, rank[permission.role_name ?? ''] ?? 0);
|
|
218
|
+
if (level < rank.write)
|
|
219
|
+
return `@${login} needs write access to the repository`;
|
|
220
|
+
for (const kind of config.approvers) {
|
|
221
|
+
if (kind === 'author' && pr.user.login === login && pr.user.type !== 'Bot')
|
|
222
|
+
return undefined;
|
|
223
|
+
if (kind === 'reviewers') {
|
|
224
|
+
if ((pr.requested_reviewers ?? []).some((r) => r.login === login))
|
|
225
|
+
return undefined;
|
|
226
|
+
const reviews = await all(api, `/repos/${name}/pulls/${pr.number}/reviews`);
|
|
227
|
+
if (reviews.some((r) => r.user?.login === login && login !== pr.user.login))
|
|
228
|
+
return undefined;
|
|
229
|
+
}
|
|
230
|
+
if ((kind === 'write' || kind === 'maintain' || kind === 'admin') && level >= rank[kind])
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
233
|
+
return `@${login} is not one of the approvers this project names (${config.approvers.join(', ')})`;
|
|
234
|
+
}
|
|
235
|
+
async function command(ctx) {
|
|
236
|
+
// The base branch's config: the workflow checks the default branch out at the root and the pull request beside it.
|
|
237
|
+
const config = githubConfigOf(readText(join(String(ctx.flags.get('config-from') ?? ctx.cwd), 'tslaws.json')));
|
|
238
|
+
const ev = event(ctx.env);
|
|
239
|
+
if (ev.action !== 'created' || ev.issue?.pull_request === undefined)
|
|
240
|
+
return 0;
|
|
241
|
+
const body = String(ev.comment?.body ?? '');
|
|
242
|
+
const commands = parseCommands(body);
|
|
243
|
+
if (commands.length === 0)
|
|
244
|
+
return 0;
|
|
245
|
+
const api = ctx.api ?? restApi(ctx.env);
|
|
246
|
+
const name = repo(ctx.env);
|
|
247
|
+
const number = Number(ev.issue.number);
|
|
248
|
+
const reply = (text) => api('POST', `/repos/${name}/issues/${number}/comments`, { body: text });
|
|
249
|
+
const login = String(ev.comment.user.login);
|
|
250
|
+
const pr = (await api('GET', `/repos/${name}/pulls/${number}`));
|
|
251
|
+
if (config.accept !== 'comment') {
|
|
252
|
+
await reply(`@${login} this project accepts passing proposals on merge into \`${config.branch}\`; there is nothing to accept by comment.`);
|
|
253
|
+
return 0;
|
|
254
|
+
}
|
|
255
|
+
const refused = await refusal(api, name, pr, login, String(ev.comment.user.type ?? 'User'), config);
|
|
256
|
+
if (refused !== undefined) {
|
|
257
|
+
await reply(`Not recorded: ${refused}.`);
|
|
258
|
+
return 0;
|
|
259
|
+
}
|
|
260
|
+
const checkedOut = String(ctx.flags.get('head-sha') ?? '');
|
|
261
|
+
if (checkedOut !== pr.head.sha) {
|
|
262
|
+
await reply(`Not recorded: the pull request moved to ${pr.head.sha.slice(0, 7)} while this ran; say it again.`);
|
|
263
|
+
return 0;
|
|
264
|
+
}
|
|
265
|
+
const pinned = /@([0-9a-f]{7,40})\b/i.exec(body)?.[1];
|
|
266
|
+
if (pinned !== undefined && !pr.head.sha.startsWith(pinned.toLowerCase())) {
|
|
267
|
+
await reply(`Not recorded: you named ${pinned}, but the pull request is at ${pr.head.sha.slice(0, 7)}.`);
|
|
268
|
+
return 0;
|
|
269
|
+
}
|
|
270
|
+
const state = projectState(ctx.options);
|
|
271
|
+
const proposals = proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), undefined);
|
|
272
|
+
const lines = [];
|
|
273
|
+
const records = [];
|
|
274
|
+
for (const cmd of commands) {
|
|
275
|
+
const { matched, unknown, ambiguous } = resolveNames(proposals, cmd);
|
|
276
|
+
if (unknown.length > 0)
|
|
277
|
+
lines.push(`- no proposal named ${unknown.map(shown).join(', ')}`);
|
|
278
|
+
if (ambiguous.length > 0)
|
|
279
|
+
lines.push(`- ${ambiguous.map(shown).join(', ')} names laws in several files; use \`file::name\``);
|
|
280
|
+
if (matched.length === 0)
|
|
281
|
+
continue;
|
|
282
|
+
records.push({
|
|
283
|
+
verb: cmd.verb,
|
|
284
|
+
by: login,
|
|
285
|
+
sha: pr.head.sha,
|
|
286
|
+
items: matched.map((p) => ({ key: p.key, fingerprint: p.fingerprint })),
|
|
287
|
+
});
|
|
288
|
+
lines.push(`- ${cmd.verb === 'accept' ? 'accepted' : 'withdrew'} ${matched.map((p) => `${shown(p.name)} (${shown(p.file)}, ${p.reason})`).join(', ')}`);
|
|
289
|
+
}
|
|
290
|
+
const text = `@${login} at ${pr.head.sha.slice(0, 7)}:\n${lines.join('\n') || '- nothing matched'}\n\n${records.length > 0 ? 'Recorded. The laws are written to `tsc-laws.lock` on merge, if they still pass and have not changed since.' : ''}`;
|
|
291
|
+
await reply(text);
|
|
292
|
+
// The records go in a comment of their own that holds nothing else, the only shape readApprovals counts.
|
|
293
|
+
if (records.length > 0)
|
|
294
|
+
await reply(recordComment(records));
|
|
295
|
+
try {
|
|
296
|
+
await api('POST', `/repos/${name}/issues/comments/${ev.comment.id}/reactions`, {
|
|
297
|
+
content: records.length > 0 ? '+1' : 'confused',
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
// a reaction is a courtesy
|
|
302
|
+
}
|
|
303
|
+
if (records.length > 0 && config.approvePullRequest) {
|
|
304
|
+
const comments = await issueComments(api, name, number);
|
|
305
|
+
const approvals = acceptedFingerprints(readApprovals(comments, config.bot));
|
|
306
|
+
if (proposals.length > 0 && proposals.every((p) => approvals.has(p.fingerprint)))
|
|
307
|
+
await api('POST', `/repos/${name}/pulls/${number}/reviews`, {
|
|
308
|
+
commit_id: pr.head.sha,
|
|
309
|
+
event: 'APPROVE',
|
|
310
|
+
body: 'tslaws: every proposal in this pull request has been accepted.',
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
// Re-run the pull request's report so its check sees the new approvals.
|
|
314
|
+
const workflow = ctx.flags.get('rerun-workflow');
|
|
315
|
+
if (typeof workflow === 'string' && records.length > 0) {
|
|
316
|
+
const runs = (await api('GET', `/repos/${name}/actions/workflows/${encodeURIComponent(workflow)}/runs?head_sha=${pr.head.sha}&event=pull_request&per_page=5`));
|
|
317
|
+
const latest = runs.workflow_runs[0];
|
|
318
|
+
if (latest !== undefined)
|
|
319
|
+
await api('POST', `/repos/${name}/actions/runs/${latest.id}/rerun`);
|
|
320
|
+
}
|
|
321
|
+
return 0;
|
|
322
|
+
}
|
|
323
|
+
// ---- merge ----------------------------------------------------------------------------------------------------------
|
|
324
|
+
async function merge(ctx) {
|
|
325
|
+
const lockPath = repoPath(ctx, 'tsc-laws.lock');
|
|
326
|
+
const configText = readText(join(ctx.cwd, 'tslaws.json'));
|
|
327
|
+
const config = githubConfigOf(configText);
|
|
328
|
+
if (isSharedBot(config))
|
|
329
|
+
ctx.out(`::warning title=tslaws::"bot" is ${config.bot}, which every workflow can act as; only a ruleset on ${config.branch} that restricts ${lockPath} keeps other workflows from writing it. A dedicated GitHub App closes this.
|
|
330
|
+
`);
|
|
331
|
+
const ev = event(ctx.env);
|
|
332
|
+
const ref = String(ev.ref ?? ctx.env.GITHUB_REF ?? '');
|
|
333
|
+
if (ref !== `refs/heads/${config.branch}`) {
|
|
334
|
+
ctx.err(`tslaws: ${ref} is not refs/heads/${config.branch}; the lock is written only there\n`);
|
|
335
|
+
return 1;
|
|
336
|
+
}
|
|
337
|
+
if (ctx.env.GITHUB_EVENT_NAME !== undefined && ctx.env.GITHUB_EVENT_NAME !== 'push') {
|
|
338
|
+
ctx.err('tslaws: merge runs on push only\n');
|
|
339
|
+
return 1;
|
|
340
|
+
}
|
|
341
|
+
const commits = (ev.commits ?? []);
|
|
342
|
+
const touches = (c) => [...(c.modified ?? []), ...(c.added ?? []), ...(c.removed ?? [])].includes(lockPath);
|
|
343
|
+
const api = ctx.api ?? restApi(ctx.env);
|
|
344
|
+
const name = repo(ctx.env);
|
|
345
|
+
const sha = String(ev.after ?? ctx.env.GITHUB_SHA ?? '');
|
|
346
|
+
// Made by the bot, as GitHub sees it: the account and a signature GitHub verified. The push payload's author name
|
|
347
|
+
// comes from the commit's e-mail address, which anyone can set, so it is not enough on its own.
|
|
348
|
+
const byBot = async (id) => {
|
|
349
|
+
const detail = (await api('GET', `/repos/${name}/commits/${id}`));
|
|
350
|
+
return detail.author?.login === config.bot && detail.commit.verification?.verified === true;
|
|
351
|
+
};
|
|
352
|
+
// The payload lists at most 20 commits; a longer push is never taken for the bot's.
|
|
353
|
+
if (commits.length > 0 && commits.length < 20 && commits.every(touches)) {
|
|
354
|
+
let all = true;
|
|
355
|
+
for (const c of commits)
|
|
356
|
+
if (!(await byBot(c.id)))
|
|
357
|
+
all = false;
|
|
358
|
+
if (all) {
|
|
359
|
+
ctx.out('tslaws: this push is the bot writing the lock; nothing to do\n');
|
|
360
|
+
return 0;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
for (const c of commits.filter(touches))
|
|
364
|
+
if (!(await byBot(c.id))) {
|
|
365
|
+
ctx.err(`tslaws: commit ${c.id.slice(0, 7)} changed ${lockPath} but was not made by ${config.bot} with a verified signature; nothing accepted. Revert it.\n`);
|
|
366
|
+
return 1;
|
|
367
|
+
}
|
|
368
|
+
// The push event lists at most 20 commits, and their file lists can be cut short, so compare the lock itself: this
|
|
369
|
+
// push is not the bot's alone (that case returned above), so it must leave the lock exactly as it was.
|
|
370
|
+
const before = String(ev.before ?? '');
|
|
371
|
+
if (/^[0-9a-f]{40}$/.test(before) && !/^0+$/.test(before)) {
|
|
372
|
+
const lockAt = async (ref) => {
|
|
373
|
+
try {
|
|
374
|
+
return (await api('GET', `/repos/${name}/contents/${lockPath}?ref=${ref}`)).sha;
|
|
375
|
+
}
|
|
376
|
+
catch {
|
|
377
|
+
return undefined;
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
if ((await lockAt(before)) !== (await lockAt(sha))) {
|
|
381
|
+
ctx.err(`tslaws: this push changed ${lockPath}, and not only through ${config.bot}; nothing accepted. Revert the change.
|
|
382
|
+
`);
|
|
383
|
+
return 1;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
// Runs queue behind one another (the concurrency group), so this checkout can predate a lock commit that an earlier
|
|
387
|
+
// run made. Start from the lock on the branch, so this run never undoes what an earlier one accepted, once every
|
|
388
|
+
// commit since this push that changed the lock is shown to be the bot's.
|
|
389
|
+
const branchRef = encodeURIComponent(config.branch);
|
|
390
|
+
const headLock = (await api('GET', `/repos/${name}/contents/${lockPath}?ref=${branchRef}`).catch(() => undefined));
|
|
391
|
+
const lockFile = ctx.options.lockFile;
|
|
392
|
+
const localBlob = existsSync(lockFile) ? gitBlobSha(readFileSync(lockFile)) : undefined;
|
|
393
|
+
if (headLock !== undefined && headLock.sha !== localBlob) {
|
|
394
|
+
const range = (await api('GET', `/repos/${name}/compare/${sha}...${branchRef}`));
|
|
395
|
+
const since = new Set(range.commits.map((c) => c.sha));
|
|
396
|
+
const touched = (await api('GET', `/repos/${name}/commits?sha=${branchRef}&path=${encodeURIComponent(lockPath)}&per_page=100`));
|
|
397
|
+
let trusted = range.status === 'ahead' && range.ahead_by === range.commits.length && touched.length < 100;
|
|
398
|
+
for (const c of touched)
|
|
399
|
+
if (trusted && since.has(c.sha) && !(await byBot(c.sha)))
|
|
400
|
+
trusted = false;
|
|
401
|
+
if (!trusted) {
|
|
402
|
+
ctx.err(`tslaws: ${lockPath} on ${config.branch} has moved on since this push, and not only through ${config.bot}; nothing accepted
|
|
403
|
+
`);
|
|
404
|
+
return 1;
|
|
405
|
+
}
|
|
406
|
+
writeFileSync(lockFile, Buffer.from(headLock.content, 'base64'));
|
|
407
|
+
}
|
|
408
|
+
const pulls = (await api('GET', `/repos/${name}/commits/${sha}/pulls`));
|
|
409
|
+
const checked = await check(ctx.options, true);
|
|
410
|
+
const state = projectState(ctx.options);
|
|
411
|
+
const proposals = proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), checked);
|
|
412
|
+
if (proposals.length === 0) {
|
|
413
|
+
ctx.out('tslaws: the lock already records every law\n');
|
|
414
|
+
return 0;
|
|
415
|
+
}
|
|
416
|
+
// Each record's author is checked again now: someone who lost write access, or a rule that changed since the
|
|
417
|
+
// comment, leaves their records out.
|
|
418
|
+
let records = [];
|
|
419
|
+
if (config.accept === 'comment')
|
|
420
|
+
for (const pr of pulls) {
|
|
421
|
+
const verdicts = new Map();
|
|
422
|
+
for (const record of readApprovals(await issueComments(api, name, pr.number), config.bot)) {
|
|
423
|
+
if (!verdicts.has(record.by))
|
|
424
|
+
verdicts.set(record.by, (await refusal(api, name, pr, record.by, 'User', config)) === undefined);
|
|
425
|
+
if (verdicts.get(record.by))
|
|
426
|
+
records.push(record);
|
|
427
|
+
else
|
|
428
|
+
ctx.err(`tslaws: ignoring the records of @${record.by} on #${pr.number}: no longer an approver\n`);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
const approvals = acceptedFingerprints(records);
|
|
432
|
+
const decision = decide(proposals, config, approvals);
|
|
433
|
+
const accepted = proposals.filter((p) => decision.accept.has(p.fingerprint));
|
|
434
|
+
if (accepted.length > 0) {
|
|
435
|
+
const next = acceptChanges(state.lock, state.laws, state.exempt, state.levels, decision.accept);
|
|
436
|
+
writeLockValue(ctx.options.lockFile, next);
|
|
437
|
+
const text = readFileSync(ctx.options.lockFile, 'utf8');
|
|
438
|
+
if (!ctx.flags.has('dry-run')) {
|
|
439
|
+
// Through the contents API, so GitHub signs the commit as the bot and `verify` can tell it from a forgery. The
|
|
440
|
+
// lock this run started from is the one it replaces: if anything wrote the lock since, GitHub refuses the write.
|
|
441
|
+
await api('PUT', `/repos/${name}/contents/${lockPath}`, {
|
|
442
|
+
message: `chore(tslaws): accept ${accepted.length} law change${accepted.length === 1 ? '' : 's'}${pulls[0] ? ` from #${pulls[0].number}` : ''}\n\n${accepted.map((p) => `- ${p.key} (${p.reason}${p.outcome ? `, ${p.outcome.status}` : ''}${approvals.has(p.fingerprint) ? `, accepted by @${approvals.get(p.fingerprint)}` : ''})`).join('\n')}`,
|
|
443
|
+
content: Buffer.from(text).toString('base64'),
|
|
444
|
+
branch: config.branch,
|
|
445
|
+
...(headLock === undefined ? {} : { sha: headLock.sha }),
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
const lines = [
|
|
450
|
+
...accepted.map((p) => `- ✅ ${shown(p.name)} (${shown(p.file)}, ${p.reason}) accepted${approvals.has(p.fingerprint) ? ` — @${approvals.get(p.fingerprint)}` : ''}`),
|
|
451
|
+
...decision.held.map(({ proposal, why }) => `- 🚫 ${shown(proposal.name)} (${shown(proposal.file)}, ${proposal.reason}) not accepted: ${why}`),
|
|
452
|
+
];
|
|
453
|
+
const where = repoPath(ctx, '');
|
|
454
|
+
const note = `### tslaws on \`${config.branch}\`${where === '' ? '' : ` (\`${where}\`)`}\n\n${lines.join('\n')}\n${decision.held.length > 0 ? `\n\`tslaws check\` fails on \`${config.branch}\` until the held proposals are fixed or removed.\n` : ''}`;
|
|
455
|
+
summary(ctx.env, note);
|
|
456
|
+
ctx.out(`${note}\n`);
|
|
457
|
+
for (const pr of pulls)
|
|
458
|
+
await api('POST', `/repos/${name}/issues/${pr.number}/comments`, { body: note }).catch(() => undefined);
|
|
459
|
+
setOutput(ctx.env, 'accepted', String(accepted.length));
|
|
460
|
+
return decision.held.length === 0 ? 0 : 1;
|
|
461
|
+
}
|
|
462
|
+
// ---- verify ---------------------------------------------------------------------------------------------------------
|
|
463
|
+
async function verify(ctx) {
|
|
464
|
+
const ev = event(ctx.env);
|
|
465
|
+
const pull = ev.pull_request;
|
|
466
|
+
if (pull === undefined) {
|
|
467
|
+
ctx.err('tslaws: verify runs on pull_request_target\n');
|
|
468
|
+
return 1;
|
|
469
|
+
}
|
|
470
|
+
const api = ctx.api ?? restApi(ctx.env);
|
|
471
|
+
const name = repo(ctx.env);
|
|
472
|
+
const contents = async (path, ref) => {
|
|
473
|
+
try {
|
|
474
|
+
const file = (await api('GET', `/repos/${name}/contents/${path}?ref=${ref}`));
|
|
475
|
+
return Buffer.from(file.content, 'base64').toString('utf8');
|
|
476
|
+
}
|
|
477
|
+
catch {
|
|
478
|
+
return undefined;
|
|
479
|
+
}
|
|
480
|
+
};
|
|
481
|
+
const lockPath = repoPath(ctx, 'tsc-laws.lock');
|
|
482
|
+
const configPath = repoPath(ctx, 'tslaws.json');
|
|
483
|
+
const baseText = await contents(configPath, pull.base.sha);
|
|
484
|
+
const config = githubConfigOf(baseText);
|
|
485
|
+
const problems = [];
|
|
486
|
+
const files = await all(api, `/repos/${name}/pulls/${pull.number}/files`);
|
|
487
|
+
const changed = new Set(files.flatMap((f) => [f.filename, ...(f.previous_filename ? [f.previous_filename] : [])]));
|
|
488
|
+
const protectedPaths = String(ctx.flags.get('protect') ?? '')
|
|
489
|
+
.split(',')
|
|
490
|
+
.map((p) => p.trim())
|
|
491
|
+
.filter(Boolean);
|
|
492
|
+
for (const path of protectedPaths)
|
|
493
|
+
if (changed.has(path))
|
|
494
|
+
problems.push(`${path} is protected: change it in a pull request of its own, merged by an administrator`);
|
|
495
|
+
if (changed.has(configPath)) {
|
|
496
|
+
const headText = await contents(configPath, pull.head.sha);
|
|
497
|
+
const section = (text) => JSON.stringify(text === undefined ? undefined : JSON.parse(text).github);
|
|
498
|
+
try {
|
|
499
|
+
if (section(baseText) !== section(headText))
|
|
500
|
+
problems.push(`the pull request changes the "github" section of ${configPath}, which decides who may accept laws`);
|
|
501
|
+
}
|
|
502
|
+
catch {
|
|
503
|
+
problems.push(`${configPath} does not parse`);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
// The bot never commits to a pull request's branch: it writes the lock on ${config.branch} after the merge. So any
|
|
507
|
+
// change to the lock in the pull request's diff (the full list, paginated above) is a forgery. Checking the diff, not
|
|
508
|
+
// each commit, also covers commits whose file list GitHub truncates (the commit API lists at most 300 files).
|
|
509
|
+
if (changed.has(lockPath))
|
|
510
|
+
problems.push(`the pull request changes ${lockPath}; only ${config.bot} writes the lock, on merge into ${config.branch}`);
|
|
511
|
+
for (const problem of problems)
|
|
512
|
+
ctx.out(`::error::${escapeGithubData(problem)}\n`);
|
|
513
|
+
if (problems.length === 0)
|
|
514
|
+
ctx.out('tslaws: the lock and its settings are untouched by this pull request\n');
|
|
515
|
+
return problems.length === 0 ? 0 : 1;
|
|
516
|
+
}
|
|
517
|
+
// ---- entry ----------------------------------------------------------------------------------------------------------
|
|
518
|
+
export async function githubCommand(action, ctx) {
|
|
519
|
+
try {
|
|
520
|
+
if (action === 'report')
|
|
521
|
+
return await report(ctx);
|
|
522
|
+
if (action === 'command')
|
|
523
|
+
return await command(ctx);
|
|
524
|
+
if (action === 'merge')
|
|
525
|
+
return await merge(ctx);
|
|
526
|
+
if (action === 'verify')
|
|
527
|
+
return await verify(ctx);
|
|
528
|
+
}
|
|
529
|
+
catch (error) {
|
|
530
|
+
ctx.err(`tslaws github ${action}: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
531
|
+
return 1;
|
|
532
|
+
}
|
|
533
|
+
ctx.err('usage: tslaws github report|command|merge|verify\n');
|
|
534
|
+
return 1;
|
|
535
|
+
}
|
package/dist/lock.d.ts
CHANGED
|
@@ -27,3 +27,26 @@ export declare function compareLock(lock: LockEntries | undefined, laws: Manifes
|
|
|
27
27
|
locked: Record<string, string> | undefined;
|
|
28
28
|
now: Record<string, string>;
|
|
29
29
|
}): LockViolation[];
|
|
30
|
+
/**
|
|
31
|
+
* One difference between the lock and the project: a law added, changed, removed or moved to another level, or a
|
|
32
|
+
* coverage exemption added or removed. `fingerprint` names the exact content a person accepts, so an approval given for
|
|
33
|
+
* one version of a law never accepts a later edit of it.
|
|
34
|
+
*/
|
|
35
|
+
export interface LockChange {
|
|
36
|
+
key: string;
|
|
37
|
+
kind: 'law' | 'exempt';
|
|
38
|
+
reason: 'added' | 'changed' | 'removed' | 'level';
|
|
39
|
+
fingerprint: string;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Every change a person would record by accepting the project as it is now. `levels` is the level of each laws file
|
|
43
|
+
* now, or undefined when the lock does not record levels.
|
|
44
|
+
*/
|
|
45
|
+
export declare function lockChanges(lock: Lock | undefined, laws: ManifestLaw[], exempt: string[], levels?: Record<string, string>): LockChange[];
|
|
46
|
+
/**
|
|
47
|
+
* The lock after accepting only the changes whose fingerprints are in `accepted`; every other entry keeps what the lock
|
|
48
|
+
* had. Levels are recorded per laws file, so a file's level is taken from now once every law change in it is accepted.
|
|
49
|
+
*/
|
|
50
|
+
export declare function acceptChanges(lock: Lock | undefined, laws: ManifestLaw[], exempt: string[], levels: Record<string, string> | undefined, accepted: ReadonlySet<string>): Lock;
|
|
51
|
+
/** Writes a lock value in the same canonical form as `writeLock`. */
|
|
52
|
+
export declare function writeLockValue(path: string, lock: Lock): void;
|
package/dist/lock.js
CHANGED
|
@@ -57,3 +57,87 @@ export function compareLock(lock, laws, levels) {
|
|
|
57
57
|
violations.push({ key, reason: 'removed' });
|
|
58
58
|
return violations;
|
|
59
59
|
}
|
|
60
|
+
const fingerprintOf = (...parts) => createHash('sha256').update(parts.join('\u0000')).digest('hex').slice(0, 16);
|
|
61
|
+
/**
|
|
62
|
+
* Every change a person would record by accepting the project as it is now. `levels` is the level of each laws file
|
|
63
|
+
* now, or undefined when the lock does not record levels.
|
|
64
|
+
*/
|
|
65
|
+
export function lockChanges(lock, laws, exempt, levels) {
|
|
66
|
+
const byKey = new Map(laws.map((law) => [lawKey(law.file, law.name), law]));
|
|
67
|
+
const compared = compareLock(lock?.laws, laws, levels === undefined ? undefined : { locked: lock?.levels, now: levels });
|
|
68
|
+
const changes = compared.map((violation) => {
|
|
69
|
+
const law = byKey.get(violation.key);
|
|
70
|
+
const hash = law === undefined ? 'removed' : lawHash(law);
|
|
71
|
+
const level = law === undefined ? '' : (levels?.[law.file.replaceAll('\\', '/')] ?? '');
|
|
72
|
+
return {
|
|
73
|
+
key: violation.key,
|
|
74
|
+
kind: 'law',
|
|
75
|
+
reason: violation.reason,
|
|
76
|
+
fingerprint: fingerprintOf('law', violation.key, hash, level),
|
|
77
|
+
};
|
|
78
|
+
});
|
|
79
|
+
const locked = new Set(lock?.exempt ?? []);
|
|
80
|
+
const now = new Set(exempt);
|
|
81
|
+
for (const key of [...now].filter((k) => !locked.has(k)).sort())
|
|
82
|
+
changes.push({ key, kind: 'exempt', reason: 'added', fingerprint: fingerprintOf('exempt', key, 'added') });
|
|
83
|
+
for (const key of [...locked].filter((k) => !now.has(k)).sort())
|
|
84
|
+
changes.push({ key, kind: 'exempt', reason: 'removed', fingerprint: fingerprintOf('exempt', key, 'removed') });
|
|
85
|
+
return changes;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The lock after accepting only the changes whose fingerprints are in `accepted`; every other entry keeps what the lock
|
|
89
|
+
* had. Levels are recorded per laws file, so a file's level is taken from now once every law change in it is accepted.
|
|
90
|
+
*/
|
|
91
|
+
export function acceptChanges(lock, laws, exempt, levels, accepted) {
|
|
92
|
+
const changes = lockChanges(lock, laws, exempt, levels);
|
|
93
|
+
const taken = changes.filter((c) => accepted.has(c.fingerprint));
|
|
94
|
+
const byKey = new Map(laws.map((law) => [lawKey(law.file, law.name), law]));
|
|
95
|
+
const entries = { ...lock?.laws };
|
|
96
|
+
const exemptions = new Set(lock?.exempt ?? []);
|
|
97
|
+
for (const change of taken) {
|
|
98
|
+
if (change.kind === 'exempt') {
|
|
99
|
+
if (change.reason === 'added')
|
|
100
|
+
exemptions.add(change.key);
|
|
101
|
+
else
|
|
102
|
+
exemptions.delete(change.key);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
const law = byKey.get(change.key);
|
|
106
|
+
if (law === undefined)
|
|
107
|
+
delete entries[change.key];
|
|
108
|
+
else
|
|
109
|
+
entries[change.key] = lawHash(law);
|
|
110
|
+
}
|
|
111
|
+
let recorded;
|
|
112
|
+
if (levels !== undefined) {
|
|
113
|
+
recorded = { ...lock?.levels };
|
|
114
|
+
const fileOf = (key) => key.slice(0, key.lastIndexOf('::'));
|
|
115
|
+
const open = new Set(changes.filter((c) => c.kind === 'law' && !accepted.has(c.fingerprint)).map((c) => fileOf(c.key)));
|
|
116
|
+
for (const [file, level] of Object.entries(levels))
|
|
117
|
+
if (!open.has(file))
|
|
118
|
+
recorded[file] = level;
|
|
119
|
+
for (const file of Object.keys(recorded))
|
|
120
|
+
if (!(file in levels) && !Object.keys(entries).some((key) => fileOf(key) === file))
|
|
121
|
+
delete recorded[file];
|
|
122
|
+
}
|
|
123
|
+
return { laws: entries, exempt: [...exemptions], ...(recorded === undefined ? {} : { levels: recorded }) };
|
|
124
|
+
}
|
|
125
|
+
/** Writes a lock value in the same canonical form as `writeLock`. */
|
|
126
|
+
export function writeLockValue(path, lock) {
|
|
127
|
+
const laws = {};
|
|
128
|
+
for (const key of Object.keys(lock.laws).sort((a, b) => a.localeCompare(b)))
|
|
129
|
+
laws[key] = lock.laws[key];
|
|
130
|
+
const body = {
|
|
131
|
+
version: 1,
|
|
132
|
+
laws,
|
|
133
|
+
exempt: [...lock.exempt].sort(),
|
|
134
|
+
...(lock.levels === undefined
|
|
135
|
+
? {}
|
|
136
|
+
: {
|
|
137
|
+
levels: Object.fromEntries(Object.keys(lock.levels)
|
|
138
|
+
.sort()
|
|
139
|
+
.map((f) => [f, lock.levels[f]])),
|
|
140
|
+
}),
|
|
141
|
+
};
|
|
142
|
+
writeFileSync(path, JSON.stringify(body, null, 2) + '\n');
|
|
143
|
+
}
|
package/dist/propertyRun.d.ts
CHANGED
|
@@ -22,3 +22,14 @@ export interface PropertyOutcome {
|
|
|
22
22
|
regression?: boolean;
|
|
23
23
|
}
|
|
24
24
|
export declare function summarise(details: fc.RunDetails<unknown[]>, options?: CheckOptions): PropertyOutcome;
|
|
25
|
+
/** Inputs a law has run on, at least, before a proof of it stands. */
|
|
26
|
+
export declare const crossCheckRuns = 50;
|
|
27
|
+
/**
|
|
28
|
+
* A `proved` verdict is checked against plain JavaScript: the law's property run (generators that stay inside what the
|
|
29
|
+
* proof assumes) already passed in this check, and counts when it ran `crossCheckRuns` inputs. A shorter one (a low
|
|
30
|
+
* `--runs`) is topped up with a run of `crossCheckRuns` from the same seed. Returns the outcome of the top-up when the
|
|
31
|
+
* law fails on it, `'timeout'` when it does not finish, and `undefined` when nothing disagrees with the proof.
|
|
32
|
+
*/
|
|
33
|
+
export declare function crossCheck(passed: Pick<PropertyOutcome, 'numRuns'>, parameters: number, rerun: (runs: number) => Promise<PropertyOutcome | 'timeout'>): Promise<PropertyOutcome | 'timeout' | undefined>;
|
|
34
|
+
/** Why a law counts as failed when the prover said `proved` and a JavaScript run disagrees. */
|
|
35
|
+
export declare function disagreement(outcome: Pick<PropertyOutcome, 'message'>): string;
|