tslaws 0.10.0 → 1.1.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 +13 -2
- package/bin/tslaws.js +8 -2
- package/dist/badge.d.ts +64 -0
- package/dist/badge.js +121 -0
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +25 -5
- package/dist/bundled.js +2 -2
- package/dist/bundlerPlugins.d.ts +2 -0
- package/dist/bundlerPlugins.js +7 -0
- package/dist/certificates.d.ts +139 -0
- package/dist/certificates.js +433 -0
- package/dist/chc.d.ts +97 -0
- package/dist/chc.js +307 -0
- package/dist/check.d.ts +13 -1
- package/dist/check.js +218 -31
- package/dist/cli.d.ts +18 -0
- package/dist/cli.js +242 -34
- package/dist/compile.d.ts +15 -5
- package/dist/compile.js +203 -70
- package/dist/coverage.d.ts +38 -1
- package/dist/coverage.js +123 -19
- package/dist/e2eApi.js +3 -1
- package/dist/generators.js +12 -2
- package/dist/github.d.ts +49 -5
- package/dist/github.js +107 -24
- package/dist/githubCli.d.ts +28 -0
- package/dist/githubCli.js +1113 -212
- package/dist/hints.js +2 -1
- package/dist/init.js +42 -0
- package/dist/isolate.d.ts +33 -0
- package/dist/isolate.js +262 -0
- package/dist/isolatedCheck.d.ts +1 -0
- package/dist/isolatedCheck.js +16 -0
- package/dist/lawHost.d.ts +50 -0
- package/dist/lawHost.js +197 -0
- package/dist/lawRuntime.d.ts +45 -0
- package/dist/lawRuntime.js +321 -0
- package/dist/lock.d.ts +49 -9
- package/dist/lock.js +132 -21
- package/dist/mcp.js +28 -7
- package/dist/mutate.d.ts +4 -0
- package/dist/mutate.js +7 -1
- package/dist/plan.d.ts +1 -0
- package/dist/plan.js +4 -0
- package/dist/pluginHooks.d.ts +20 -0
- package/dist/pluginHooks.js +57 -0
- package/dist/pluginHost.d.ts +5 -0
- package/dist/pluginHost.js +43 -0
- package/dist/pluginWorker.d.ts +1 -0
- package/dist/pluginWorker.js +40 -0
- package/dist/plural.d.ts +2 -0
- package/dist/plural.js +4 -0
- package/dist/pool.d.ts +80 -7
- package/dist/pool.js +222 -11
- package/dist/projects.d.ts +43 -1
- package/dist/projects.js +283 -11
- package/dist/promote.d.ts +56 -2
- package/dist/promote.js +429 -13
- package/dist/property.js +5 -1
- package/dist/propertyWorker.js +9 -4
- package/dist/proposals.d.ts +52 -4
- package/dist/proposals.js +484 -21
- package/dist/reporters.js +5 -1
- package/dist/runtimeEnv.d.ts +13 -5
- package/dist/runtimeEnv.js +48 -10
- package/dist/sandbox.d.ts +98 -0
- package/dist/sandbox.js +673 -0
- package/dist/sandboxGuard.d.ts +56 -0
- package/dist/sandboxGuard.js +249 -0
- package/dist/seal.d.ts +9 -0
- package/dist/seal.js +426 -0
- package/dist/security/cli.d.ts +6 -0
- package/dist/security/cli.js +39 -0
- package/dist/security/cwe.d.ts +14 -0
- package/dist/security/cwe.js +40 -0
- package/dist/security/deps/cache.d.ts +28 -0
- package/dist/security/deps/cache.js +107 -0
- package/dist/security/deps/config.d.ts +16 -0
- package/dist/security/deps/config.js +43 -0
- package/dist/security/deps/imports.d.ts +4 -0
- package/dist/security/deps/imports.js +33 -0
- package/dist/security/deps/lockfiles.d.ts +23 -0
- package/dist/security/deps/lockfiles.js +153 -0
- package/dist/security/deps/osv.d.ts +66 -0
- package/dist/security/deps/osv.js +137 -0
- package/dist/security/deps/run.d.ts +54 -0
- package/dist/security/deps/run.js +135 -0
- package/dist/security/deps/severity.d.ts +26 -0
- package/dist/security/deps/severity.js +78 -0
- package/dist/security/generators.d.ts +9 -0
- package/dist/security/generators.js +36 -0
- package/dist/security/index.d.ts +27 -0
- package/dist/security/index.js +18 -0
- package/dist/security/integers.d.ts +31 -0
- package/dist/security/integers.js +105 -0
- package/dist/security/law.d.ts +54 -0
- package/dist/security/law.js +54 -0
- package/dist/security/pathTraversal.d.ts +29 -0
- package/dist/security/pathTraversal.js +146 -0
- package/dist/security/prototypePollution.d.ts +30 -0
- package/dist/security/prototypePollution.js +142 -0
- package/dist/security/redirect.d.ts +21 -0
- package/dist/security/redirect.js +154 -0
- package/dist/security/redos.d.ts +21 -0
- package/dist/security/redos.js +93 -0
- package/dist/security/validation.d.ts +25 -0
- package/dist/security/validation.js +89 -0
- package/dist/security/xss.d.ts +21 -0
- package/dist/security/xss.js +90 -0
- package/dist/settings.d.ts +20 -0
- package/dist/settings.js +32 -0
- package/dist/smt.d.ts +37 -1
- package/dist/smt.js +277 -111
- package/dist/smtWorker.d.ts +1 -0
- package/dist/smtWorker.js +26 -0
- package/dist/solvers.d.ts +9 -0
- package/dist/solvers.js +11 -5
- package/dist/symbolic.d.ts +54 -1
- package/dist/symbolic.js +239 -13
- package/dist/tsconfigResolve.d.ts +28 -0
- package/dist/tsconfigResolve.js +141 -0
- package/dist/types.d.ts +33 -0
- package/hooks/claude-hook.mjs +2 -0
- package/package.json +19 -7
package/dist/githubCli.js
CHANGED
|
@@ -5,28 +5,46 @@
|
|
|
5
5
|
// waits for an accept. Advisory: it runs the pull request's code, so it decides nothing about the lock.
|
|
6
6
|
// command issue_comment: reads `/tslaws accept|reject ...`, checks the commenter may accept, and records the
|
|
7
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
|
|
9
|
-
//
|
|
10
|
-
// The only place the
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
8
|
+
// merge push to the configured branch, or workflow_dispatch by someone with admin or maintain access: runs the
|
|
9
|
+
// laws on the branch's code, accepts what passes (and, in comment mode, what was accepted for that exact
|
|
10
|
+
// version) and commits tsc-laws.lock through the API as the bot. The only place the workflow writes the
|
|
11
|
+
// lock. While a project's "local" is true (the default) a person may also change its lock by hand, through
|
|
12
|
+
// `tslaws accept` or a merged pull request that a maintainer wrote and merged; merge accepts such a change
|
|
13
|
+
// as it stands and builds on it, and on demand it first checks where the branch's lock came from.
|
|
14
|
+
// verify pull_request_target: fails when the pull request changes a lock (unless the project's "local" is true
|
|
15
|
+
// and the pull request's author, and the author of each commit that changes the lock, has admin or maintain
|
|
16
|
+
// access), the "github" section of tslaws.json or a protected path. Reads the base branch's config, never
|
|
17
|
+
// the pull request's.
|
|
18
|
+
//
|
|
19
|
+
// From a monorepo root every mode covers all the projects in one process (`ctx.projects`): one sticky comment with a
|
|
20
|
+
// section per project, one commit for all the locks, approvals that count only for their own project, and a project
|
|
21
|
+
// list that verify and merge read from the base commit through the API, never from files the pull request controls.
|
|
14
22
|
import { readFileSync, writeFileSync, appendFileSync, existsSync } from 'node:fs';
|
|
15
23
|
import { createHash } from 'node:crypto';
|
|
16
24
|
import { execFileSync } from 'node:child_process';
|
|
17
25
|
import { join } from 'node:path';
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
26
|
+
import { exemptionsOf } from "./check.js";
|
|
27
|
+
import { checkIsolated, readReport } from "./isolate.js";
|
|
28
|
+
import { useSandbox } from "./sandbox.js";
|
|
29
|
+
import { extendsTarget, readConfig } from "./coverage.js";
|
|
30
|
+
import { discoverFromFiles, discoverySignature } from "./projects.js";
|
|
31
|
+
import { build, readManifest } from "./compile.js";
|
|
32
|
+
import { acceptedFingerprints, inert, recordComment, decide, parseCommands, isSharedBot, parseGithubConfig, proposalsOf, pullRequestVerdict, readApprovals, renderSticky, renderStickyAll, resolveNames, stickyMarkerFor, } from "./github.js";
|
|
33
|
+
import { lockLevels } from "./lawKinds.js";
|
|
34
|
+
import { acceptChanges, lawKey, lockChanges, readLock, writeLockValue } from "./lock.js";
|
|
24
35
|
import { escapeGithubData, escapeGithubProperty } from "./reporters.js";
|
|
36
|
+
import { plural } from "./plural.js";
|
|
25
37
|
/** A project-relative file as the repository names it: the project's prefix, then the path. */
|
|
26
38
|
function repoPath(ctx, file) {
|
|
27
39
|
const prefix = (ctx.projectPath ?? '').replace(/^\/+|\/+$/g, '');
|
|
28
|
-
|
|
29
|
-
|
|
40
|
+
return joinRepo(prefix, file);
|
|
41
|
+
}
|
|
42
|
+
/** Two repo-relative paths joined; either may be ''. */
|
|
43
|
+
export function joinRepo(prefix, file) {
|
|
44
|
+
const clean = file.replaceAll('\\', '/').replace(/^\/+/, '');
|
|
45
|
+
if (prefix === '')
|
|
46
|
+
return clean;
|
|
47
|
+
return clean === '' ? prefix : `${prefix}/${clean}`;
|
|
30
48
|
}
|
|
31
49
|
/** `--project-path`, else where `cwd` sits inside its git repository (`git rev-parse --show-prefix`), else ''. */
|
|
32
50
|
export function projectPathOf(cwd, flag) {
|
|
@@ -109,28 +127,21 @@ export function projectState(options) {
|
|
|
109
127
|
const laws = readManifest(options.compiler, options.files, options.cwd);
|
|
110
128
|
const exempt = exemptionsOf(options);
|
|
111
129
|
const mode = readConfig(options.cwd).levels ?? 'names';
|
|
112
|
-
|
|
113
|
-
|
|
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;
|
|
130
|
+
// Levels by name record nothing: a lock that still records them is a change until accepted again.
|
|
131
|
+
const levels = mode === 'imports' ? lockLevels(options.cwd, laws, 'imports') : undefined;
|
|
120
132
|
return { laws, exempt, levels, lock };
|
|
121
133
|
}
|
|
122
134
|
async function issueComments(api, name, pr) {
|
|
123
135
|
return all(api, `/repos/${name}/issues/${pr}/comments`);
|
|
124
136
|
}
|
|
125
|
-
async function upsertSticky(api, name, pr,
|
|
126
|
-
const
|
|
127
|
-
const mine = comments.find((c) => c.user.login === bot && c.body.startsWith(marker));
|
|
137
|
+
async function upsertSticky(api, name, pr, bots, body, comments, marker) {
|
|
138
|
+
const mine = comments.find((c) => bots.includes(c.user.login) && c.body.startsWith(marker));
|
|
128
139
|
if (mine === undefined)
|
|
129
140
|
await api('POST', `/repos/${name}/issues/${pr}/comments`, { body });
|
|
130
141
|
else if (mine.body !== body)
|
|
131
142
|
await api('PATCH', `/repos/${name}/issues/comments/${mine.id}`, { body });
|
|
132
143
|
}
|
|
133
|
-
function linkFor(env, sha,
|
|
144
|
+
function linkFor(env, sha, project) {
|
|
134
145
|
const server = env.GITHUB_SERVER_URL ?? 'https://github.com';
|
|
135
146
|
const name = env.GITHUB_REPOSITORY ?? '';
|
|
136
147
|
// Raw text: renderSticky makes the whole cell inert. Brackets and backticks would break the link's markdown.
|
|
@@ -138,7 +149,7 @@ function linkFor(env, sha, ctx) {
|
|
|
138
149
|
const label = p.name.replace(/[`[\]]/g, "'");
|
|
139
150
|
if (p.line === 0 || name === '')
|
|
140
151
|
return `${label} (${p.file})`;
|
|
141
|
-
return `[${label}](${server}/${name}/blob/${sha}/${
|
|
152
|
+
return `[${label}](${server}/${name}/blob/${sha}/${joinRepo(project, p.file).split('/').map(encodeURIComponent).join('/')}#L${p.line})`;
|
|
142
153
|
};
|
|
143
154
|
}
|
|
144
155
|
/** A law name or path from the pull request, for a bot comment: inert, and quoted without a code span. */
|
|
@@ -153,15 +164,203 @@ function setOutput(env, key, value) {
|
|
|
153
164
|
if (env.GITHUB_OUTPUT !== undefined)
|
|
154
165
|
appendFileSync(env.GITHUB_OUTPUT, `${key}=${value}\n`);
|
|
155
166
|
}
|
|
156
|
-
// ----
|
|
167
|
+
// ---- units ----------------------------------------------------------------------------------------------------------
|
|
168
|
+
/** The projects a run covers: one (the directory it runs in), or every selected project of a monorepo root. */
|
|
169
|
+
function unitsOf(ctx) {
|
|
170
|
+
return ctx.projects ?? [{ cwd: ctx.cwd, rel: '', path: repoPath(ctx, ''), options: ctx.options }];
|
|
171
|
+
}
|
|
172
|
+
const label = (unit) => (unit.path === '' ? '.' : unit.path);
|
|
173
|
+
/** The `github` settings in the tslaws.json of `dir`, `extends` followed (the project's own keys win); undefined if none. */
|
|
174
|
+
function configIn(dir) {
|
|
175
|
+
const raw = readConfig(dir).github;
|
|
176
|
+
return raw === undefined ? undefined : parseGithubConfig(raw);
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* The projects the shared flow covers, each with its own settings. A project with no `github` section is left out of a
|
|
180
|
+
* root run (and is an error in a single-project run, as it always was); so is one whose flow is `own`.
|
|
181
|
+
*/
|
|
182
|
+
function plan(ctx, units, dirOf) {
|
|
183
|
+
const monorepo = ctx.projects !== undefined;
|
|
184
|
+
const active = [];
|
|
185
|
+
const all = [];
|
|
186
|
+
for (const unit of units) {
|
|
187
|
+
const config = configIn(dirOf(unit));
|
|
188
|
+
if (config === undefined) {
|
|
189
|
+
if (!monorepo)
|
|
190
|
+
throw new Error('tslaws github needs a "github" section in tslaws.json');
|
|
191
|
+
ctx.out(`::notice title=tslaws::${escapeGithubData(label(unit))} has no "github" section; the shared flow leaves it out\n`);
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
all.push({ unit, config });
|
|
195
|
+
if (monorepo && config.flow === 'own') {
|
|
196
|
+
ctx.out(`::notice title=tslaws::${escapeGithubData(label(unit))} has "flow": "own"; its own workflow covers it\n`);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
active.push({ unit, config });
|
|
200
|
+
}
|
|
201
|
+
if (monorepo && all.length === 0)
|
|
202
|
+
throw new Error('no project here has a "github" section in tslaws.json');
|
|
203
|
+
if (monorepo && active.length === 0)
|
|
204
|
+
ctx.out('tslaws: every project with a "github" section runs its own flow; nothing to do here\n');
|
|
205
|
+
return { active, all };
|
|
206
|
+
}
|
|
207
|
+
/** The laws a project has, as this process sees them: a compile that runs none of the project. A report is held to it. */
|
|
208
|
+
function expectedOf(state) {
|
|
209
|
+
return {
|
|
210
|
+
laws: new Set(state.laws.map((law) => lawKey(law.file, law.name))),
|
|
211
|
+
lock: new Set(Object.keys(state.lock?.laws ?? {})),
|
|
212
|
+
exempt: new Set(state.exempt),
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
const lockShaOf = (unit) => existsSync(unit.options.lockFile) ? gitBlobSha(readFileSync(unit.options.lockFile)) : '';
|
|
216
|
+
const resultsRead = new WeakMap();
|
|
217
|
+
function resultsOf(ctx, file, mode, sha) {
|
|
218
|
+
const known = resultsRead.get(ctx.flags);
|
|
219
|
+
if (known !== undefined)
|
|
220
|
+
return known;
|
|
221
|
+
let value;
|
|
222
|
+
try {
|
|
223
|
+
value = JSON.parse(readFileSync(file, 'utf8'));
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
throw new Error(`cannot read the results in ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
227
|
+
}
|
|
228
|
+
if (typeof value !== 'object' || value === null || value.version !== 1 || typeof value.projects !== 'object')
|
|
229
|
+
throw new Error(`${file} is not a tslaws results file`);
|
|
230
|
+
if (value.mode !== mode)
|
|
231
|
+
throw new Error(`${file} holds results for ${String(value.mode)}, not ${mode}`);
|
|
232
|
+
if (value.sha !== sha)
|
|
233
|
+
throw new Error(`${file} was made for commit ${String(value.sha).slice(0, 7)}, but this run is for ${sha.slice(0, 7)}`);
|
|
234
|
+
resultsRead.set(ctx.flags, value);
|
|
235
|
+
return value;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* The report of one project's laws: from the results file when `--results` names one, else from a run in a child with no
|
|
239
|
+
* credentials. Either way it is validated as data before anything acts on it.
|
|
240
|
+
*/
|
|
241
|
+
async function runLaws(ctx, unit, mode, sha, state, only) {
|
|
242
|
+
const file = ctx.flags.get('results');
|
|
243
|
+
if (typeof file !== 'string')
|
|
244
|
+
return runIsolated(unit, state, only);
|
|
245
|
+
return readReport(resultEntry(ctx, file, unit, mode, sha).report, expectedFor(state, only));
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* The merge job's report for the laws it has to prove. With a results file, a project the laws job reported nothing for
|
|
249
|
+
* has no report (undefined), and a report may lack a law: the caller holds every law without a result, so a results file
|
|
250
|
+
* that falls short fails closed per law instead of failing the whole run. Anything else wrong with it still throws.
|
|
251
|
+
*/
|
|
252
|
+
async function mergeLaws(ctx, unit, sha, state, only) {
|
|
253
|
+
const file = ctx.flags.get('results');
|
|
254
|
+
if (typeof file !== 'string')
|
|
255
|
+
return runIsolated(unit, state, only);
|
|
256
|
+
const entry = resultEntry(ctx, file, unit, 'merge', sha);
|
|
257
|
+
if (entry.report === undefined)
|
|
258
|
+
return undefined;
|
|
259
|
+
return readReport(entry.report, { ...expectedFor(state), required: new Set() });
|
|
260
|
+
}
|
|
261
|
+
/** One project's entry of the results file, once it is known to come from this commit and this lock. */
|
|
262
|
+
function resultEntry(ctx, file, unit, mode, sha) {
|
|
263
|
+
const results = resultsOf(ctx, file, mode, sha);
|
|
264
|
+
const entry = Object.hasOwn(results.projects, unit.path) ? results.projects[unit.path] : undefined;
|
|
265
|
+
if (entry === undefined)
|
|
266
|
+
throw new Error(`${file} has no results for ${label(unit)}`);
|
|
267
|
+
if (typeof entry.error === 'string')
|
|
268
|
+
throw new Error(entry.error);
|
|
269
|
+
if (entry.lockSha !== lockShaOf(unit))
|
|
270
|
+
throw new Error(`${label(unit)}'s lock is not the one its laws were run against`);
|
|
271
|
+
return entry;
|
|
272
|
+
}
|
|
273
|
+
/** What a report must hold: every law, or just the ones a partial run was asked for. */
|
|
274
|
+
const expectedFor = (state, only) => ({
|
|
275
|
+
...expectedOf(state),
|
|
276
|
+
...(only === undefined ? {} : { required: new Set(only) }),
|
|
277
|
+
});
|
|
278
|
+
/** The laws of a project run in a child with no credentials: all of them, or only the laws with these keys. */
|
|
279
|
+
function runIsolated(unit, state, only) {
|
|
280
|
+
const options = only === undefined ? unit.options : { ...unit.options, onlyKeys: [...only] };
|
|
281
|
+
return checkIsolated(options, true, expectedFor(state, only));
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* What a run that proves nothing still has to find out, as the run of every law used to: that the project builds, and
|
|
285
|
+
* that the sandbox can be enforced here. A failure is thrown, so the run fails as it did when every law ran.
|
|
286
|
+
*/
|
|
287
|
+
function assertRunnable(unit, state) {
|
|
288
|
+
if (state.laws.length === 0)
|
|
289
|
+
return;
|
|
290
|
+
useSandbox(unit.options);
|
|
291
|
+
const built = build(unit.options.compiler, unit.options.files, unit.options.cwd);
|
|
292
|
+
if (!built.ok)
|
|
293
|
+
throw new Error(`the project does not compile:
|
|
294
|
+
${built.diagnostics}`);
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* The laws a merge has to run in a project: the ones the lock does not record as they are. A removal or an exemption runs
|
|
298
|
+
* nothing, and a law the lock records is neither proposed nor accepted by a merge, so proving it again would change nothing.
|
|
299
|
+
*/
|
|
300
|
+
function lawsToProve(changes) {
|
|
301
|
+
return changes.filter((c) => c.kind === 'law' && c.reason !== 'removed').map((c) => c.key);
|
|
302
|
+
}
|
|
303
|
+
/** `--results-out <file>`: run the laws of every project and write the reports, doing nothing else. Needs no token. */
|
|
304
|
+
async function collect(ctx, mode, file) {
|
|
305
|
+
const { active } = plan(ctx, unitsOf(ctx), (u) => u.cwd);
|
|
306
|
+
const ev = event(ctx.env);
|
|
307
|
+
const sha = String(mode === 'report' ? (ev.pull_request?.head?.sha ?? ctx.env.GITHUB_SHA) : (ev.after ?? ctx.env.GITHUB_SHA));
|
|
308
|
+
const projects = {};
|
|
309
|
+
for (const { unit } of active) {
|
|
310
|
+
const entry = { lockSha: lockShaOf(unit) };
|
|
311
|
+
try {
|
|
312
|
+
const state = projectState(unit.options);
|
|
313
|
+
if (mode === 'report')
|
|
314
|
+
entry.report = await runIsolated(unit, state);
|
|
315
|
+
else {
|
|
316
|
+
// A merge acts only on what the lock does not record, which it works out again from the same lock and files.
|
|
317
|
+
const only = lawsToProve(lockChanges(state.lock, state.laws, state.exempt, state.levels));
|
|
318
|
+
if (only.length > 0)
|
|
319
|
+
entry.report = await runIsolated(unit, state, only);
|
|
320
|
+
else
|
|
321
|
+
assertRunnable(unit, state);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
catch (error) {
|
|
325
|
+
entry.error = error instanceof Error ? error.message : String(error);
|
|
326
|
+
}
|
|
327
|
+
projects[unit.path] = entry;
|
|
328
|
+
}
|
|
329
|
+
writeFileSync(file, JSON.stringify({ version: 1, mode, sha, projects }));
|
|
330
|
+
ctx.out(`tslaws: ran the laws of ${active.length} project${active.length === 1 ? '' : 's'}; results are in ${file}\n`);
|
|
331
|
+
return 0;
|
|
332
|
+
}
|
|
157
333
|
async function report(ctx) {
|
|
158
|
-
const
|
|
334
|
+
const monorepo = ctx.projects !== undefined;
|
|
335
|
+
const { active } = plan(ctx, unitsOf(ctx), (u) => u.cwd);
|
|
336
|
+
if (active.length === 0)
|
|
337
|
+
return 0;
|
|
159
338
|
const ev = event(ctx.env);
|
|
160
339
|
const pr = Number(ctx.flags.get('pr') ?? ev.pull_request?.number ?? NaN);
|
|
161
340
|
const sha = String(ev.pull_request?.head?.sha ?? ctx.env.GITHUB_SHA ?? '');
|
|
162
|
-
const
|
|
163
|
-
const
|
|
164
|
-
|
|
341
|
+
const ran = [];
|
|
342
|
+
for (const a of active) {
|
|
343
|
+
try {
|
|
344
|
+
const state = projectState(a.unit.options);
|
|
345
|
+
const checked = await runLaws(ctx, a.unit, 'report', sha, state);
|
|
346
|
+
ran.push({
|
|
347
|
+
active: a,
|
|
348
|
+
checked,
|
|
349
|
+
proposals: proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), checked, a.unit.path),
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
catch (error) {
|
|
353
|
+
if (!monorepo)
|
|
354
|
+
throw error;
|
|
355
|
+
// One project that cannot run must not hide the others' reports.
|
|
356
|
+
ran.push({
|
|
357
|
+
active: a,
|
|
358
|
+
checked: undefined,
|
|
359
|
+
proposals: [],
|
|
360
|
+
failed: error instanceof Error ? error.message : String(error),
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
}
|
|
165
364
|
let api;
|
|
166
365
|
let comments = [];
|
|
167
366
|
try {
|
|
@@ -173,48 +372,108 @@ async function report(ctx) {
|
|
|
173
372
|
ctx.err(`tslaws: cannot read the pull request's comments (${String(error)}); reporting without approvals\n`);
|
|
174
373
|
api = undefined;
|
|
175
374
|
}
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
const
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
375
|
+
const reports = ran.map(({ active: a, checked, proposals, failed }) => {
|
|
376
|
+
// Only the records of this project count, and only those its own bot wrote.
|
|
377
|
+
const approvals = acceptedFingerprints(readApprovals(comments, a.config.bot), a.unit.path);
|
|
378
|
+
const verdict = checked === undefined
|
|
379
|
+
? { ok: false, problems: [`the project could not be checked: ${failed ?? 'unknown error'}`] }
|
|
380
|
+
: pullRequestVerdict(checked, proposals, a.config, approvals);
|
|
381
|
+
return { active: a, proposals, approvals, verdict };
|
|
382
|
+
});
|
|
383
|
+
for (const { active: a, proposals } of reports)
|
|
384
|
+
for (const p of proposals) {
|
|
385
|
+
const level = p.passes ? 'notice' : 'error';
|
|
386
|
+
const title = `tslaws proposal: ${p.name}`;
|
|
387
|
+
const message = p.outcome === undefined
|
|
388
|
+
? 'did not run'
|
|
389
|
+
: `${p.reason}; if accepted: ${p.outcome.status}${p.outcome.counterexample ? `; counterexample ${p.outcome.counterexample}` : ''}`;
|
|
390
|
+
ctx.out(`::${level} file=${escapeGithubProperty(joinRepo(a.unit.path, p.file))},line=${Math.max(1, p.line)},title=${escapeGithubProperty(title)}::${escapeGithubData(message)}\n`);
|
|
391
|
+
}
|
|
392
|
+
const rootPath = repoPath(ctx, '');
|
|
393
|
+
const marker = stickyMarkerFor(rootPath);
|
|
394
|
+
const body = monorepo
|
|
395
|
+
? renderStickyAll(reports.map((r) => ({
|
|
396
|
+
project: r.active.unit.path,
|
|
397
|
+
proposals: r.proposals,
|
|
398
|
+
config: r.active.config,
|
|
399
|
+
approvals: r.approvals,
|
|
400
|
+
link: linkFor(ctx.env, sha, r.active.unit.path),
|
|
401
|
+
})), marker)
|
|
402
|
+
: (() => {
|
|
403
|
+
const [only] = reports;
|
|
404
|
+
return renderSticky(only.proposals, only.active.config, only.approvals, linkFor(ctx.env, sha, rootPath), rootPath);
|
|
405
|
+
})();
|
|
406
|
+
summary(ctx.env, body.replace(marker, ''));
|
|
407
|
+
const bots = [...new Set(active.map((a) => a.config.bot))];
|
|
189
408
|
if (api !== undefined && Number.isInteger(pr) && ctx.flags.has('comment')) {
|
|
190
409
|
try {
|
|
191
|
-
await upsertSticky(api, repo(ctx.env), pr,
|
|
410
|
+
await upsertSticky(api, repo(ctx.env), pr, bots, body, comments, marker);
|
|
411
|
+
// A root run's one comment replaces the per-project comments an earlier, per-project workflow left.
|
|
412
|
+
if (monorepo)
|
|
413
|
+
for (const { unit } of active) {
|
|
414
|
+
if (unit.path === rootPath)
|
|
415
|
+
continue;
|
|
416
|
+
const old = stickyMarkerFor(unit.path);
|
|
417
|
+
for (const c of comments)
|
|
418
|
+
if (bots.includes(c.user.login) && c.body.startsWith(old))
|
|
419
|
+
await api('DELETE', `/repos/${repo(ctx.env)}/issues/comments/${c.id}`).catch(() => undefined);
|
|
420
|
+
}
|
|
192
421
|
}
|
|
193
422
|
catch (error) {
|
|
194
423
|
// A pull request from a fork gets a read-only token: the step summary and annotations still carry the report.
|
|
195
424
|
ctx.err(`tslaws: cannot write the sticky comment (${String(error)})\n`);
|
|
196
425
|
}
|
|
197
426
|
}
|
|
427
|
+
const proposals = reports.flatMap((r) => r.proposals);
|
|
428
|
+
const ok = reports.every((r) => r.verdict.ok);
|
|
198
429
|
const outFile = ctx.flags.get('out');
|
|
199
|
-
if (typeof outFile === 'string')
|
|
200
|
-
|
|
430
|
+
if (typeof outFile === 'string') {
|
|
431
|
+
const verdict = {
|
|
432
|
+
ok,
|
|
433
|
+
problems: reports.flatMap((r) => r.verdict.problems.map((p) => (monorepo ? `[${label(r.active.unit)}] ${p}` : p))),
|
|
434
|
+
};
|
|
435
|
+
const projects = monorepo
|
|
436
|
+
? {
|
|
437
|
+
projects: reports.map((r) => ({ project: r.active.unit.path, proposals: r.proposals, verdict: r.verdict })),
|
|
438
|
+
}
|
|
439
|
+
: {};
|
|
440
|
+
writeFileSync(outFile, `${JSON.stringify({ sha, proposals, verdict, ...projects }, null, 2)}\n`);
|
|
441
|
+
}
|
|
201
442
|
setOutput(ctx.env, 'proposals', String(proposals.length));
|
|
202
|
-
for (const
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
return
|
|
443
|
+
for (const r of reports)
|
|
444
|
+
for (const problem of r.verdict.problems)
|
|
445
|
+
ctx.out(`${monorepo ? `[${label(r.active.unit)}] ` : ''}${problem}\n`);
|
|
446
|
+
ctx.out(ok
|
|
447
|
+
? `tslaws: ${plural(proposals.length, 'proposal')}${monorepo ? ` in ${plural(reports.length, 'project')}` : ''}, all passing\n`
|
|
448
|
+
: 'tslaws: the pull request is not ready\n');
|
|
449
|
+
return ok ? 0 : 1;
|
|
209
450
|
}
|
|
210
451
|
// ---- command --------------------------------------------------------------------------------------------------------
|
|
211
452
|
const rank = { none: 0, read: 1, triage: 2, write: 3, maintain: 4, admin: 5 };
|
|
453
|
+
/** The repository permission `login` holds, as a rank (0 for a non-collaborator). Throws when GitHub cannot say. */
|
|
454
|
+
async function permissionRank(api, name, login) {
|
|
455
|
+
const permission = (await api('GET', `/repos/${name}/collaborators/${encodeURIComponent(login)}/permission`));
|
|
456
|
+
return Math.max(rank[permission?.permission ?? ''] ?? 0, rank[permission?.role_name ?? ''] ?? 0);
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Whether `login` has `admin` or `maintain` access: the people who may change tsc-laws.lock by hand or run the merge
|
|
460
|
+
* job on demand. A bot never counts, and neither does a login whose permission cannot be read.
|
|
461
|
+
*/
|
|
462
|
+
export async function maintains(api, name, login, type = 'User') {
|
|
463
|
+
if (type === 'Bot' || login.endsWith('[bot]'))
|
|
464
|
+
return false;
|
|
465
|
+
try {
|
|
466
|
+
return (await permissionRank(api, name, login)) >= rank.maintain;
|
|
467
|
+
}
|
|
468
|
+
catch {
|
|
469
|
+
return false;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
212
472
|
/** Why `login` may not accept on this pull request, or undefined when they may. */
|
|
213
473
|
export async function refusal(api, name, pr, login, type, config) {
|
|
214
474
|
if (type === 'Bot' || login.endsWith('[bot]'))
|
|
215
475
|
return 'bots cannot accept laws';
|
|
216
|
-
const
|
|
217
|
-
const level = Math.max(rank[permission.permission] ?? 0, rank[permission.role_name ?? ''] ?? 0);
|
|
476
|
+
const level = await permissionRank(api, name, login);
|
|
218
477
|
if (level < rank.write)
|
|
219
478
|
return `@${login} needs write access to the repository`;
|
|
220
479
|
for (const kind of config.approvers) {
|
|
@@ -232,9 +491,77 @@ export async function refusal(api, name, pr, login, type, config) {
|
|
|
232
491
|
}
|
|
233
492
|
return `@${login} is not one of the approvers this project names (${config.approvers.join(', ')})`;
|
|
234
493
|
}
|
|
494
|
+
/**
|
|
495
|
+
* Whether the bot may approve the pull request: every project with proposals, whatever its flow, has all of them
|
|
496
|
+
* accepted here and has opted in with `approvePullRequest`. A project that was declined, skipped, runs its own flow, or
|
|
497
|
+
* cannot be read counts against it, so one project's acceptance never approves another's pending proposals.
|
|
498
|
+
*/
|
|
499
|
+
async function everyProposalAccepted(all, eligible, byProject, comments) {
|
|
500
|
+
let any = false;
|
|
501
|
+
for (const a of all) {
|
|
502
|
+
const counted = eligible.some((e) => e.unit.path === a.unit.path);
|
|
503
|
+
let proposals;
|
|
504
|
+
try {
|
|
505
|
+
proposals =
|
|
506
|
+
byProject.get(a.unit.path) ??
|
|
507
|
+
(() => {
|
|
508
|
+
const state = projectState(a.unit.options);
|
|
509
|
+
return proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), undefined, a.unit.path);
|
|
510
|
+
})();
|
|
511
|
+
}
|
|
512
|
+
catch {
|
|
513
|
+
return false;
|
|
514
|
+
}
|
|
515
|
+
if (proposals.length === 0)
|
|
516
|
+
continue;
|
|
517
|
+
any = true;
|
|
518
|
+
if (!counted || !a.config.approvePullRequest)
|
|
519
|
+
return false;
|
|
520
|
+
const approvals = acceptedFingerprints(readApprovals(comments, a.config.bot), a.unit.path);
|
|
521
|
+
if (!proposals.every((p) => approvals.has(p.fingerprint)))
|
|
522
|
+
return false;
|
|
523
|
+
}
|
|
524
|
+
return any;
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* Whether the projects this run decided over are the projects the base commit has. The list in the pull request's own
|
|
528
|
+
* checkout can be steered by the pull request, so before approving, the base's list is read through the API and the
|
|
529
|
+
* pull request must not change how projects are found, nor any project's `github` (so `flow`), `standalone` or lock.
|
|
530
|
+
* It also must not add or remove a project. Anything unreadable counts as a change: no approval.
|
|
531
|
+
*/
|
|
532
|
+
async function discoveryHolds(ctx, api, name, pr, discovered) {
|
|
533
|
+
const problems = [];
|
|
534
|
+
try {
|
|
535
|
+
const read = readerOf(api, name);
|
|
536
|
+
const changed = await changedFiles(api, name, pr);
|
|
537
|
+
const { baseSide, headSide } = await inspectMonorepo(api, name, read, pr, changed, repoPath(ctx, ''), problems);
|
|
538
|
+
const head = new Set(headSide.paths);
|
|
539
|
+
const decided = new Set(discovered);
|
|
540
|
+
for (const rel of baseSide.paths) {
|
|
541
|
+
if (!head.has(rel))
|
|
542
|
+
problems.push(`${rel || '.'} is a project on the base and not on the pull request`);
|
|
543
|
+
if (!decided.has(rel))
|
|
544
|
+
problems.push(`${rel || '.'} is a project on the base that this run did not read`);
|
|
545
|
+
}
|
|
546
|
+
const base = new Set(baseSide.paths);
|
|
547
|
+
for (const rel of headSide.paths)
|
|
548
|
+
if (!base.has(rel))
|
|
549
|
+
problems.push(`${rel || '.'} is a new project`);
|
|
550
|
+
}
|
|
551
|
+
catch (error) {
|
|
552
|
+
problems.push(error instanceof Error ? error.message : String(error));
|
|
553
|
+
}
|
|
554
|
+
if (problems.length > 0)
|
|
555
|
+
ctx.out(`::notice title=tslaws::${escapeGithubData(`not approving the pull request: ${problems[0]}${problems.length > 1 ? ` (and ${problems.length - 1} more)` : ''}`)}\n`);
|
|
556
|
+
return problems.length === 0;
|
|
557
|
+
}
|
|
235
558
|
async function command(ctx) {
|
|
559
|
+
const monorepo = ctx.projects !== undefined;
|
|
236
560
|
// The base branch's config: the workflow checks the default branch out at the root and the pull request beside it.
|
|
237
|
-
const
|
|
561
|
+
const trusted = String(ctx.flags.get('config-from') ?? ctx.cwd);
|
|
562
|
+
const { active, all } = plan(ctx, unitsOf(ctx), (u) => join(trusted, u.rel));
|
|
563
|
+
if (active.length === 0)
|
|
564
|
+
return 0;
|
|
238
565
|
const ev = event(ctx.env);
|
|
239
566
|
if (ev.action !== 'created' || ev.issue?.pull_request === undefined)
|
|
240
567
|
return 0;
|
|
@@ -247,14 +574,41 @@ async function command(ctx) {
|
|
|
247
574
|
const number = Number(ev.issue.number);
|
|
248
575
|
const reply = (text) => api('POST', `/repos/${name}/issues/${number}/comments`, { body: text });
|
|
249
576
|
const login = String(ev.comment.user.login);
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
577
|
+
// A command that cannot be followed records nothing, even beside commands that can: a `--project` with no directory
|
|
578
|
+
// would otherwise read as "every project".
|
|
579
|
+
const unusable = commands.find((c) => c.error !== undefined);
|
|
580
|
+
if (unusable !== undefined) {
|
|
581
|
+
await reply(`@${login} Not recorded: ${unusable.error}.`);
|
|
253
582
|
return 0;
|
|
254
583
|
}
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
584
|
+
const pr = (await api('GET', `/repos/${name}/pulls/${number}`));
|
|
585
|
+
// Each project decides for itself: its own mode and its own approvers. The commenter accepts only where they may.
|
|
586
|
+
const eligible = [];
|
|
587
|
+
const declined = [];
|
|
588
|
+
for (const a of active) {
|
|
589
|
+
if (a.config.accept !== 'comment') {
|
|
590
|
+
const text = `this project accepts passing proposals on merge into \`${a.config.branch}\`; there is nothing to accept by comment`;
|
|
591
|
+
if (!monorepo) {
|
|
592
|
+
await reply(`@${login} ${text}.`);
|
|
593
|
+
return 0;
|
|
594
|
+
}
|
|
595
|
+
declined.push(`- ${shown(label(a.unit))}: ${text}`);
|
|
596
|
+
continue;
|
|
597
|
+
}
|
|
598
|
+
const refused = await refusal(api, name, pr, login, String(ev.comment.user.type ?? 'User'), a.config);
|
|
599
|
+
if (refused !== undefined) {
|
|
600
|
+
if (!monorepo) {
|
|
601
|
+
await reply(`Not recorded: ${refused}.`);
|
|
602
|
+
return 0;
|
|
603
|
+
}
|
|
604
|
+
declined.push(`- ${shown(label(a.unit))}: not recorded, ${refused}`);
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
eligible.push(a);
|
|
608
|
+
}
|
|
609
|
+
if (eligible.length === 0) {
|
|
610
|
+
if (declined.length > 0)
|
|
611
|
+
await reply(`@${login}\n${declined.join('\n')}`);
|
|
258
612
|
return 0;
|
|
259
613
|
}
|
|
260
614
|
const checkedOut = String(ctx.flags.get('head-sha') ?? '');
|
|
@@ -267,25 +621,38 @@ async function command(ctx) {
|
|
|
267
621
|
await reply(`Not recorded: you named ${pinned}, but the pull request is at ${pr.head.sha.slice(0, 7)}.`);
|
|
268
622
|
return 0;
|
|
269
623
|
}
|
|
270
|
-
const
|
|
271
|
-
|
|
272
|
-
|
|
624
|
+
const byProject = new Map();
|
|
625
|
+
for (const a of eligible) {
|
|
626
|
+
const state = projectState(a.unit.options);
|
|
627
|
+
byProject.set(a.unit.path, proposalsOf(lockChanges(state.lock, state.laws, state.exempt, state.levels), undefined, a.unit.path));
|
|
628
|
+
}
|
|
629
|
+
const proposals = [...byProject.values()].flat();
|
|
630
|
+
const lines = [...declined];
|
|
273
631
|
const records = [];
|
|
632
|
+
const where = (p) => (monorepo ? `${shown(p.project ?? '')}, ` : '');
|
|
274
633
|
for (const cmd of commands) {
|
|
275
634
|
const { matched, unknown, ambiguous } = resolveNames(proposals, cmd);
|
|
276
635
|
if (unknown.length > 0)
|
|
277
636
|
lines.push(`- no proposal named ${unknown.map(shown).join(', ')}`);
|
|
278
637
|
if (ambiguous.length > 0)
|
|
279
|
-
lines.push(
|
|
638
|
+
lines.push(monorepo
|
|
639
|
+
? `- ${ambiguous.map(shown).join(', ')} names laws in several files or projects; use the path from the repository root with \`::name\`, or add \`--project <dir>\``
|
|
640
|
+
: `- ${ambiguous.map(shown).join(', ')} names laws in several files; use \`file::name\``);
|
|
280
641
|
if (matched.length === 0)
|
|
281
642
|
continue;
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
643
|
+
// One record per project, each carrying its project: it counts for that project's lock and nowhere else.
|
|
644
|
+
for (const path of new Set(matched.map((p) => p.project ?? ''))) {
|
|
645
|
+
records.push({
|
|
646
|
+
verb: cmd.verb,
|
|
647
|
+
by: login,
|
|
648
|
+
sha: pr.head.sha,
|
|
649
|
+
project: path,
|
|
650
|
+
items: matched
|
|
651
|
+
.filter((p) => (p.project ?? '') === path)
|
|
652
|
+
.map((p) => ({ key: p.key, fingerprint: p.fingerprint })),
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
lines.push(`- ${cmd.verb === 'accept' ? 'accepted' : 'withdrew'} ${matched.map((p) => `${shown(p.name)} (${where(p)}${shown(p.file)}, ${p.reason})`).join(', ')}`);
|
|
289
656
|
}
|
|
290
657
|
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
658
|
await reply(text);
|
|
@@ -300,10 +667,10 @@ async function command(ctx) {
|
|
|
300
667
|
catch {
|
|
301
668
|
// a reaction is a courtesy
|
|
302
669
|
}
|
|
303
|
-
if (records.length > 0 && config.approvePullRequest) {
|
|
670
|
+
if (records.length > 0 && eligible.some((a) => a.config.approvePullRequest)) {
|
|
304
671
|
const comments = await issueComments(api, name, number);
|
|
305
|
-
|
|
306
|
-
|
|
672
|
+
if ((await everyProposalAccepted(all, eligible, byProject, comments)) &&
|
|
673
|
+
(!monorepo || (await discoveryHolds(ctx, api, name, pr, ctx.discovered ?? all.map((a) => a.unit.rel)))))
|
|
307
674
|
await api('POST', `/repos/${name}/pulls/${number}/reviews`, {
|
|
308
675
|
commit_id: pr.head.sha,
|
|
309
676
|
event: 'APPROVE',
|
|
@@ -320,147 +687,662 @@ async function command(ctx) {
|
|
|
320
687
|
}
|
|
321
688
|
return 0;
|
|
322
689
|
}
|
|
323
|
-
|
|
690
|
+
/**
|
|
691
|
+
* The contents API URL of a repository path. Every segment and the ref are encoded, so a `?`, `#`, `&` or `%` in a name
|
|
692
|
+
* a pull request controls cannot add to or override the query string (for example the `ref`).
|
|
693
|
+
*/
|
|
694
|
+
function contentsUrl(name, path, ref) {
|
|
695
|
+
const encoded = path.split('/').map(encodeURIComponent).join('/');
|
|
696
|
+
return `/repos/${name}/contents/${encoded}${ref === undefined ? '' : `?ref=${encodeURIComponent(ref)}`}`;
|
|
697
|
+
}
|
|
698
|
+
function readerOf(api, name) {
|
|
699
|
+
return async (path, ref) => {
|
|
700
|
+
let file;
|
|
701
|
+
try {
|
|
702
|
+
file = (await api('GET', contentsUrl(name, path, ref)));
|
|
703
|
+
}
|
|
704
|
+
catch {
|
|
705
|
+
return undefined;
|
|
706
|
+
}
|
|
707
|
+
// A symlink, a submodule or a directory is not a blob: refuse it rather than read it as missing.
|
|
708
|
+
if (Array.isArray(file) || (file.type !== undefined && file.type !== 'file') || typeof file.content !== 'string')
|
|
709
|
+
throw new Error(`${path} is not a regular file at ${ref.slice(0, 7)} (a symlink, a submodule or a directory)`);
|
|
710
|
+
return Buffer.from(file.content, 'base64').toString('utf8');
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
/** `tsc-laws.lock` by name, wherever it is. */
|
|
714
|
+
const isLock = (path) => path === 'tsc-laws.lock' || path.endsWith('/tsc-laws.lock');
|
|
715
|
+
/**
|
|
716
|
+
* The projects a commit has, from the repository's tree and the three files that decide it, read through the API:
|
|
717
|
+
* paths relative to the monorepo root (`prefix` is where that root sits in the repository). Never from a checkout, so
|
|
718
|
+
* a pull request cannot change what is read by changing its own files.
|
|
719
|
+
*/
|
|
720
|
+
async function projectsAt(api, name, read, sha, prefix) {
|
|
721
|
+
const tree = await treeAt(api, name, sha);
|
|
722
|
+
const lead = prefix === '' ? '' : `${prefix}/`;
|
|
723
|
+
const files = (tree.tree ?? [])
|
|
724
|
+
.filter((entry) => entry.type === 'blob' && entry.path.startsWith(lead))
|
|
725
|
+
.map((entry) => entry.path.slice(lead.length));
|
|
726
|
+
const inputs = {};
|
|
727
|
+
const [tslaws, packageJson, pnpmWorkspace] = await Promise.all(['tslaws.json', 'package.json', 'pnpm-workspace.yaml'].map((file) => read(joinRepo(prefix, file), sha)));
|
|
728
|
+
if (tslaws !== undefined)
|
|
729
|
+
inputs.tslaws = tslaws;
|
|
730
|
+
if (packageJson !== undefined)
|
|
731
|
+
inputs.packageJson = packageJson;
|
|
732
|
+
if (pnpmWorkspace !== undefined)
|
|
733
|
+
inputs.pnpmWorkspace = pnpmWorkspace;
|
|
734
|
+
return { paths: discoverFromFiles(files, inputs), inputs, truncated: tree.truncated === true, locks: tree.locks };
|
|
735
|
+
}
|
|
736
|
+
/** Every blob of a commit's tree, and the blob id of each `tsc-laws.lock`: a changed id is a changed lock. */
|
|
737
|
+
async function treeAt(api, name, sha) {
|
|
738
|
+
const got = (await api('GET', `/repos/${name}/git/trees/${encodeURIComponent(sha)}?recursive=1`));
|
|
739
|
+
const tree = got.tree ?? [];
|
|
740
|
+
const locks = new Map();
|
|
741
|
+
for (const entry of tree)
|
|
742
|
+
if (entry.type === 'blob' && isLock(entry.path))
|
|
743
|
+
locks.set(entry.path, entry.sha ?? '');
|
|
744
|
+
return { tree, truncated: got.truncated === true, locks };
|
|
745
|
+
}
|
|
746
|
+
/** The locks that differ between two commits: added, removed or changed, by repository path. */
|
|
747
|
+
function lockDifferences(base, head) {
|
|
748
|
+
const paths = new Set([...base.keys(), ...head.keys()]);
|
|
749
|
+
return [...paths].filter((path) => base.get(path) !== head.get(path)).sort();
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* A project's `github` section and `standalone` flag at a commit, with every file read to find them: its tslaws.json
|
|
753
|
+
* and the files it `extends`, the project's own keys winning, as `readConfig` does on disk.
|
|
754
|
+
*/
|
|
755
|
+
async function settingsAt(read, ref, dir) {
|
|
756
|
+
const files = [];
|
|
757
|
+
let standalone = false;
|
|
758
|
+
const load = async (path, first, trail) => {
|
|
759
|
+
if (trail.includes(path))
|
|
760
|
+
throw new Error(`${path}: "extends" forms a cycle (${[...trail, path].join(' -> ')})`);
|
|
761
|
+
if (!files.includes(path))
|
|
762
|
+
files.push(path);
|
|
763
|
+
const text = await read(path, ref);
|
|
764
|
+
if (text === undefined) {
|
|
765
|
+
// The project's own file may be absent (a project with no tslaws.json); an `extends` target that cannot be read is
|
|
766
|
+
// not, because the settings would then be a guess.
|
|
767
|
+
if (first)
|
|
768
|
+
return undefined;
|
|
769
|
+
throw new Error(`${path} is named by "extends" and cannot be read at ${ref.slice(0, 7)}`);
|
|
770
|
+
}
|
|
771
|
+
let json;
|
|
772
|
+
try {
|
|
773
|
+
json = JSON.parse(text);
|
|
774
|
+
}
|
|
775
|
+
catch {
|
|
776
|
+
// The parser's message quotes the file's text, which is not ours to echo into a log.
|
|
777
|
+
throw new Error(`${path} is not valid JSON`);
|
|
778
|
+
}
|
|
779
|
+
if (typeof json !== 'object' || json === null || Array.isArray(json))
|
|
780
|
+
throw new Error(`${path} is not an object`);
|
|
781
|
+
if (first)
|
|
782
|
+
standalone = json.standalone === true;
|
|
783
|
+
// The same rules loadMerged applies to the files on disk (coverage.ts), so both sides resolve one target.
|
|
784
|
+
const inherited = json.extends === undefined ? undefined : await load(extendsTarget(path, json.extends), false, [...trail, path]);
|
|
785
|
+
const own = json.github;
|
|
786
|
+
if (own === undefined)
|
|
787
|
+
return inherited;
|
|
788
|
+
const plain = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
789
|
+
return plain(inherited) && plain(own) ? { ...inherited, ...own } : own;
|
|
790
|
+
};
|
|
791
|
+
const github = await load(joinRepo(dir, 'tslaws.json'), true, []);
|
|
792
|
+
return { github, standalone, files };
|
|
793
|
+
}
|
|
324
794
|
async function merge(ctx) {
|
|
325
|
-
const
|
|
326
|
-
const
|
|
327
|
-
const
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
`);
|
|
795
|
+
const monorepo = ctx.projects !== undefined;
|
|
796
|
+
const rootPath = repoPath(ctx, '');
|
|
797
|
+
const failures = [];
|
|
798
|
+
const fail = (text) => {
|
|
799
|
+
failures.push(text);
|
|
800
|
+
ctx.err(`${text}\n`);
|
|
801
|
+
};
|
|
802
|
+
let units = unitsOf(ctx);
|
|
331
803
|
const ev = event(ctx.env);
|
|
332
804
|
const ref = String(ev.ref ?? ctx.env.GITHUB_REF ?? '');
|
|
333
|
-
|
|
334
|
-
|
|
805
|
+
const sha = String(ev.after ?? ctx.env.GITHUB_SHA ?? '');
|
|
806
|
+
const before = String(ev.before ?? '');
|
|
807
|
+
const known = /^[0-9a-f]{40}$/.test(before) && !/^0+$/.test(before);
|
|
808
|
+
const api = ctx.api ?? restApi(ctx.env);
|
|
809
|
+
const name = repo(ctx.env);
|
|
810
|
+
if (monorepo && known) {
|
|
811
|
+
// The projects the base of this push had count too, whatever the pushed files now say discovers.
|
|
812
|
+
try {
|
|
813
|
+
const base = await projectsAt(api, name, readerOf(api, name), before, rootPath);
|
|
814
|
+
if (base.truncated)
|
|
815
|
+
fail('tslaws: the repository is too large for the API to list its files; cannot check the projects');
|
|
816
|
+
const here = new Set(ctx.discovered ?? units.map((u) => u.rel));
|
|
817
|
+
for (const rel of base.paths) {
|
|
818
|
+
if (here.has(rel))
|
|
819
|
+
continue;
|
|
820
|
+
const options = ctx.optionsFor?.(rel);
|
|
821
|
+
if (options === undefined) {
|
|
822
|
+
ctx.out(`::notice title=tslaws::${escapeGithubData(rel || '.')} was a project before this push and is gone\n`);
|
|
823
|
+
continue;
|
|
824
|
+
}
|
|
825
|
+
fail(`tslaws: ${rel || '.'} was a project before this push and still exists, but is no longer discovered; its lock is checked here anyway`);
|
|
826
|
+
units = [...units, { cwd: join(ctx.cwd, rel), rel, path: joinRepo(rootPath, rel), options }];
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
catch (error) {
|
|
830
|
+
fail(`tslaws: cannot read the projects of ${before.slice(0, 7)} (${String(error)})`);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
const { active, all } = plan(ctx, units, (u) => u.cwd);
|
|
834
|
+
for (const a of active)
|
|
835
|
+
if (isSharedBot(a.config))
|
|
836
|
+
ctx.out(`::warning title=tslaws::"bot" is ${a.config.bot}, which every workflow can act as; only a ruleset on ${a.config.branch} that restricts ${joinRepo(a.unit.path, 'tsc-laws.lock')} keeps other workflows from writing it. A dedicated GitHub App closes this.
|
|
837
|
+
`);
|
|
838
|
+
const onBranch = active.filter((a) => ref === `refs/heads/${a.config.branch}`);
|
|
839
|
+
if (active.length === 0)
|
|
840
|
+
return 0;
|
|
841
|
+
if (onBranch.length === 0) {
|
|
842
|
+
const branches = [...new Set(active.map((a) => `refs/heads/${a.config.branch}`))];
|
|
843
|
+
ctx.err(`tslaws: ${ref} is not ${branches.join(' or ') || 'a branch any project writes'}; the lock is written only there\n`);
|
|
335
844
|
return 1;
|
|
336
845
|
}
|
|
337
|
-
|
|
338
|
-
|
|
846
|
+
const eventName = ctx.env.GITHUB_EVENT_NAME;
|
|
847
|
+
if (eventName !== undefined && eventName !== 'push' && eventName !== 'workflow_dispatch') {
|
|
848
|
+
ctx.err('tslaws: merge runs on push and workflow_dispatch only\n');
|
|
339
849
|
return 1;
|
|
340
850
|
}
|
|
851
|
+
// On demand there is no push and no pull request, so whoever started the run is the authority, and only someone
|
|
852
|
+
// with admin or maintain access may start it. A re-run keeps GITHUB_ACTOR (who first started the workflow) and names
|
|
853
|
+
// the person who re-ran it in GITHUB_TRIGGERING_ACTOR, so both must qualify.
|
|
854
|
+
const dispatched = eventName === 'workflow_dispatch';
|
|
855
|
+
const starter = String(ctx.env.GITHUB_ACTOR ?? ev.sender?.login ?? '');
|
|
856
|
+
const rerunner = String(ctx.env.GITHUB_TRIGGERING_ACTOR ?? '');
|
|
857
|
+
const actor = rerunner === '' ? starter : rerunner;
|
|
858
|
+
if (dispatched)
|
|
859
|
+
for (const login of new Set(rerunner === '' ? [starter] : [starter, rerunner])) {
|
|
860
|
+
if (login === '' || !(await maintains(api, name, login))) {
|
|
861
|
+
ctx.err(`tslaws: ${login === '' ? 'nobody' : `@${login}`} needs admin or maintain access to run this on demand\n`);
|
|
862
|
+
return 1;
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
const branch = ref.slice('refs/heads/'.length);
|
|
866
|
+
// A run can wait in the queue while the branch moves on. It would then test an older checkout and write its lock over
|
|
867
|
+
// the newer commits, so an on-demand run must be on the branch's current head, read from the API.
|
|
868
|
+
if (dispatched) {
|
|
869
|
+
const head = (await api('GET', `/repos/${name}/git/ref/heads/${encodeURIComponent(branch)}`).catch(() => undefined));
|
|
870
|
+
const current = head?.object?.sha;
|
|
871
|
+
const checkedOut = String(ctx.env.GITHUB_SHA ?? '');
|
|
872
|
+
if (current === undefined || checkedOut === '' || current !== checkedOut) {
|
|
873
|
+
ctx.err(`tslaws: ${current === undefined
|
|
874
|
+
? `the head of ${branch} could not be read`
|
|
875
|
+
: `${branch} is at ${current.slice(0, 7)} but this run checked out ${checkedOut === '' ? 'no commit' : checkedOut.slice(0, 7)}`}; nothing accepted. Run it again on the current head.
|
|
876
|
+
`);
|
|
877
|
+
return 1;
|
|
878
|
+
}
|
|
879
|
+
}
|
|
341
880
|
const commits = (ev.commits ?? []);
|
|
342
|
-
const
|
|
343
|
-
const
|
|
344
|
-
|
|
345
|
-
const
|
|
881
|
+
const pathsOf = (c) => [...(c.modified ?? []), ...(c.added ?? []), ...(c.removed ?? [])];
|
|
882
|
+
const lockOf = (unit) => joinRepo(unit.path, 'tsc-laws.lock');
|
|
883
|
+
// Every lock this repository has, with the bot that may write it where its settings are known.
|
|
884
|
+
const botsOf = new Map();
|
|
885
|
+
for (const a of all)
|
|
886
|
+
botsOf.set(lockOf(a.unit), [a.config.bot]);
|
|
887
|
+
const anyBot = [...new Set(all.map((a) => a.config.bot))];
|
|
888
|
+
for (const rel of ctx.discovered ?? []) {
|
|
889
|
+
const lock = joinRepo(joinRepo(rootPath, rel), 'tsc-laws.lock');
|
|
890
|
+
if (botsOf.has(lock))
|
|
891
|
+
continue;
|
|
892
|
+
let bot;
|
|
893
|
+
try {
|
|
894
|
+
bot = configIn(join(ctx.cwd, rel))?.bot;
|
|
895
|
+
}
|
|
896
|
+
catch {
|
|
897
|
+
bot = undefined;
|
|
898
|
+
}
|
|
899
|
+
botsOf.set(lock, bot === undefined ? anyBot : [bot]);
|
|
900
|
+
}
|
|
901
|
+
const watched = (path) => (monorepo ? isLock(path) : onBranch.some((a) => lockOf(a.unit) === path));
|
|
902
|
+
const touches = (c) => pathsOf(c).filter(watched);
|
|
346
903
|
// Made by the bot, as GitHub sees it: the account and a signature GitHub verified. The push payload's author name
|
|
347
904
|
// comes from the commit's e-mail address, which anyone can set, so it is not enough on its own.
|
|
348
|
-
const
|
|
349
|
-
|
|
350
|
-
|
|
905
|
+
const details = new Map();
|
|
906
|
+
const byBot = async (id, bots) => {
|
|
907
|
+
if (!details.has(id))
|
|
908
|
+
details.set(id, api('GET', `/repos/${name}/commits/${id}`));
|
|
909
|
+
const detail = await details.get(id);
|
|
910
|
+
return bots.includes(detail.author?.login ?? '') && detail.commit.verification?.verified === true;
|
|
351
911
|
};
|
|
912
|
+
const botsFor = (path) => botsOf.get(path) ?? anyBot;
|
|
913
|
+
// Or, while the project's "local" is true, one that reached its branch through a merged pull request where the pull
|
|
914
|
+
// request's author, the person who merged it, and the commit's own author (as GitHub sees them) all have admin
|
|
915
|
+
// or maintain access: that person changed the lock by hand and answers for it.
|
|
916
|
+
const people = new Map();
|
|
917
|
+
const maintainer = async (person) => {
|
|
918
|
+
if (person === undefined || person === null || person.login === '')
|
|
919
|
+
return false;
|
|
920
|
+
if (!people.has(person.login))
|
|
921
|
+
people.set(person.login, await maintains(api, name, person.login, person.type));
|
|
922
|
+
return people.get(person.login) === true;
|
|
923
|
+
};
|
|
924
|
+
const viaMaintainer = async (id, branchName) => {
|
|
925
|
+
const detail = (await api('GET', `/repos/${name}/commits/${id}`).catch(() => undefined));
|
|
926
|
+
if (!(await maintainer(detail?.author)))
|
|
927
|
+
return false;
|
|
928
|
+
const found = await api('GET', `/repos/${name}/commits/${id}/pulls`).catch(() => undefined);
|
|
929
|
+
for (const listed of Array.isArray(found) ? found : []) {
|
|
930
|
+
if ((listed.merged_at ?? null) === null && listed.merged !== true)
|
|
931
|
+
continue;
|
|
932
|
+
if (listed.base.ref !== branchName)
|
|
933
|
+
continue;
|
|
934
|
+
if (!(await maintainer(listed.user)))
|
|
935
|
+
continue;
|
|
936
|
+
// The list omits who merged it.
|
|
937
|
+
const full = (await api('GET', `/repos/${name}/pulls/${listed.number}`).catch(() => undefined));
|
|
938
|
+
if (await maintainer(full?.merged_by))
|
|
939
|
+
return true;
|
|
940
|
+
}
|
|
941
|
+
return false;
|
|
942
|
+
};
|
|
943
|
+
const trustedLock = async (id, config) => (await byBot(id, [config.bot])) || (config.local && (await viaMaintainer(id, config.branch)));
|
|
944
|
+
// Every commit from `from` to `to` that changed the lock is trusted, and the range is whole (no gap, no cut list).
|
|
945
|
+
const lockTrustedBetween = async (from, to, lockPath, config) => {
|
|
946
|
+
const range = (await api('GET', `/repos/${name}/compare/${from}...${to}`));
|
|
947
|
+
const since = new Set(range.commits.map((c) => c.sha));
|
|
948
|
+
const touched = (await api('GET', `/repos/${name}/commits?sha=${to}&path=${encodeURIComponent(lockPath)}&per_page=100`));
|
|
949
|
+
if (range.status !== 'ahead' || range.ahead_by !== range.commits.length || touched.length >= 100)
|
|
950
|
+
return false;
|
|
951
|
+
for (const c of touched)
|
|
952
|
+
if (since.has(c.sha) && !(await trustedLock(c.sha, config)))
|
|
953
|
+
return false;
|
|
954
|
+
return true;
|
|
955
|
+
};
|
|
956
|
+
const who = (config) => config.local
|
|
957
|
+
? `${config.bot} with a verified signature, nor merged through a pull request from someone with admin or maintain access`
|
|
958
|
+
: `${config.bot} with a verified signature`;
|
|
352
959
|
// 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
|
|
960
|
+
if (!dispatched && commits.length > 0 && commits.length < 20 && commits.every((c) => touches(c).length > 0)) {
|
|
961
|
+
let bots = true;
|
|
355
962
|
for (const c of commits)
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
963
|
+
for (const path of touches(c))
|
|
964
|
+
if (!(await byBot(c.id, botsFor(path))))
|
|
965
|
+
bots = false;
|
|
966
|
+
if (bots && failures.length === 0) {
|
|
359
967
|
ctx.out('tslaws: this push is the bot writing the lock; nothing to do\n');
|
|
360
968
|
return 0;
|
|
361
969
|
}
|
|
362
970
|
}
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
971
|
+
// A lock that belongs to no project here (one a pull request added, or a project it dropped from discovery) is
|
|
972
|
+
// outside every flow: nothing may change it but the bot.
|
|
973
|
+
if (monorepo) {
|
|
974
|
+
const owned = new Set(onBranch.map((a) => lockOf(a.unit)));
|
|
975
|
+
for (const c of commits)
|
|
976
|
+
for (const path of touches(c))
|
|
977
|
+
if (!owned.has(path) && !(await byBot(c.id, botsFor(path))))
|
|
978
|
+
fail(`tslaws: commit ${c.id.slice(0, 7)} changed ${path} but was not made by ${botsFor(path).join(' or ')} with a verified signature; revert it`);
|
|
979
|
+
}
|
|
980
|
+
const pulls = dispatched ? [] : (await api('GET', `/repos/${name}/commits/${sha}/pulls`));
|
|
981
|
+
const commentsOf = new Map();
|
|
982
|
+
const commentsFor = (pr) => {
|
|
983
|
+
if (!commentsOf.has(pr.number))
|
|
984
|
+
commentsOf.set(pr.number, issueComments(api, name, pr.number));
|
|
985
|
+
return commentsOf.get(pr.number);
|
|
986
|
+
};
|
|
987
|
+
const verdicts = new Map();
|
|
988
|
+
const writes = [];
|
|
989
|
+
const sections = [];
|
|
990
|
+
let held = 0;
|
|
991
|
+
let accepted = 0;
|
|
992
|
+
for (const { unit, config } of onBranch) {
|
|
993
|
+
const lockPath = lockOf(unit);
|
|
994
|
+
const lockFile = unit.options.lockFile;
|
|
995
|
+
// Per project: one project's failure leaves the others' locks to be written.
|
|
996
|
+
const stop = (text) => {
|
|
997
|
+
fail(text);
|
|
998
|
+
sections.push(`- 🚫 ${shown(label(unit))}: not accepted: ${text.replace(/^tslaws: /, '')}`);
|
|
999
|
+
};
|
|
1000
|
+
// On demand, the run builds on the lock as the branch holds it, so where that lock came from matters: the latest
|
|
1001
|
+
// commit that changed it must be trusted. (The bot refuses to build on an untrusted lock, and a maintainer answers
|
|
1002
|
+
// for the lock they merge, so an older change under a trusted commit was vouched for by whoever made that commit.)
|
|
1003
|
+
if (dispatched) {
|
|
1004
|
+
// No pull request means no author or reviewers to match, so the project's access levels decide: whoever starts
|
|
1005
|
+
// or re-runs the job must reach the lowest level its "approvers" names (admin when it names only admin), and
|
|
1006
|
+
// never less than maintain.
|
|
1007
|
+
const levels = config.approvers.flatMap((kind) => (kind in rank ? [rank[kind]] : []));
|
|
1008
|
+
const needed = Math.max(rank.maintain, ...(levels.length > 0 ? [Math.min(...levels)] : []));
|
|
1009
|
+
let short;
|
|
1010
|
+
for (const login of new Set(rerunner === '' ? [starter] : [starter, rerunner]))
|
|
1011
|
+
if (short === undefined && (await permissionRank(api, name, login).catch(() => 0)) < needed)
|
|
1012
|
+
short = login;
|
|
1013
|
+
if (short !== undefined) {
|
|
1014
|
+
stop(`tslaws: @${short} needs ${needed >= rank.admin ? 'admin' : 'admin or maintain'} access to accept in this project on demand (its approvers are ${config.approvers.join(', ')}); nothing accepted.`);
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
1017
|
+
const latest = await api('GET', `/repos/${name}/commits?sha=${encodeURIComponent(config.branch)}&path=${encodeURIComponent(lockPath)}&per_page=1`).catch(() => undefined);
|
|
1018
|
+
const newest = Array.isArray(latest) ? latest[0] : undefined;
|
|
1019
|
+
if (!Array.isArray(latest) ||
|
|
1020
|
+
(newest !== undefined && !(await trustedLock(newest.sha, config).catch(() => false)))) {
|
|
1021
|
+
stop(`tslaws: ${newest === undefined ? `the history of ${lockPath} on ${config.branch} could not be read` : `the latest commit that changed ${lockPath} on ${config.branch} (${newest.sha.slice(0, 7)}) was not made by ${who(config)}`}; nothing accepted. Merge the lock through a pull request from a maintainer, or revert that commit.`);
|
|
1022
|
+
continue;
|
|
1023
|
+
}
|
|
367
1024
|
}
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
1025
|
+
const mine = commits.filter((c) => pathsOf(c).includes(lockPath));
|
|
1026
|
+
let refused = false;
|
|
1027
|
+
for (const c of mine)
|
|
1028
|
+
if (!refused && !(await trustedLock(c.id, config))) {
|
|
1029
|
+
stop(`tslaws: commit ${c.id.slice(0, 7)} changed ${lockPath} but was not made by ${who(config)}; nothing accepted. Revert it.`);
|
|
1030
|
+
refused = true;
|
|
1031
|
+
}
|
|
1032
|
+
if (refused)
|
|
1033
|
+
continue;
|
|
1034
|
+
// The push event lists at most 20 commits, and their file lists can be cut short, so compare the lock itself: this
|
|
1035
|
+
// push is not the bot's alone (that case returned above), so it must leave the lock exactly as it was, or change it
|
|
1036
|
+
// only through commits shown to be trusted.
|
|
1037
|
+
const lockAt = async (at) => {
|
|
373
1038
|
try {
|
|
374
|
-
return (await api('GET',
|
|
1039
|
+
return (await api('GET', contentsUrl(name, lockPath, at))).sha;
|
|
375
1040
|
}
|
|
376
1041
|
catch {
|
|
377
1042
|
return undefined;
|
|
378
1043
|
}
|
|
379
1044
|
};
|
|
380
|
-
if (
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
1045
|
+
if (known &&
|
|
1046
|
+
(await lockAt(before)) !== (await lockAt(sha)) &&
|
|
1047
|
+
!(config.local && (await lockTrustedBetween(before, sha, lockPath, config).catch(() => false)))) {
|
|
1048
|
+
stop(`tslaws: this push changed ${lockPath}, and not only through ${config.bot}; nothing accepted. Revert the change.`);
|
|
1049
|
+
continue;
|
|
384
1050
|
}
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
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;
|
|
1051
|
+
// Runs queue behind one another (the concurrency group), so this checkout can predate a lock commit that an earlier
|
|
1052
|
+
// run made. Start from the lock on the branch, so this run never undoes what an earlier one accepted, once every
|
|
1053
|
+
// commit since this push that changed the lock is shown to be the bot's.
|
|
1054
|
+
const branchRef = encodeURIComponent(config.branch);
|
|
1055
|
+
const headLock = (await api('GET', contentsUrl(name, lockPath, config.branch)).catch(() => undefined));
|
|
1056
|
+
const localBlob = existsSync(lockFile) ? gitBlobSha(readFileSync(lockFile)) : undefined;
|
|
1057
|
+
// With results from another job, the lock they were made against must be the branch's lock now: a lock that is gone (or
|
|
1058
|
+
// cannot be read) counts as movement when the checkout has one, so a stale lock is never written back.
|
|
1059
|
+
if (typeof ctx.flags.get('results') === 'string' && headLock?.sha !== localBlob) {
|
|
1060
|
+
stop(`tslaws: ${lockPath} on ${config.branch} has moved on since the laws ran on this checkout; nothing accepted. Run the workflow again.`);
|
|
1061
|
+
continue;
|
|
405
1062
|
}
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
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`);
|
|
1063
|
+
if (headLock !== undefined && headLock.sha !== localBlob) {
|
|
1064
|
+
if (!(await lockTrustedBetween(sha, branchRef, lockPath, config))) {
|
|
1065
|
+
stop(`tslaws: ${lockPath} on ${config.branch} has moved on since this push, and not only through ${config.bot}${config.local ? ' or a maintainer' : ''}; nothing accepted`);
|
|
1066
|
+
continue;
|
|
429
1067
|
}
|
|
1068
|
+
writeFileSync(lockFile, Buffer.from(headLock.content, 'base64'));
|
|
1069
|
+
}
|
|
1070
|
+
// What the lock does not record yet is all a merge acts on, and the files alone tell what that is. A project the
|
|
1071
|
+
// lock already records runs nothing, and otherwise only the laws that changed run: a law the lock records is
|
|
1072
|
+
// neither proposed nor accepted here, so proving it again would change nothing.
|
|
1073
|
+
let checked;
|
|
1074
|
+
let state;
|
|
1075
|
+
let changes;
|
|
1076
|
+
try {
|
|
1077
|
+
state = projectState(unit.options);
|
|
1078
|
+
changes = lockChanges(state.lock, state.laws, state.exempt, state.levels);
|
|
1079
|
+
const toRun = lawsToProve(changes);
|
|
1080
|
+
if (toRun.length > 0)
|
|
1081
|
+
checked = await mergeLaws(ctx, unit, sha, state, toRun);
|
|
1082
|
+
else
|
|
1083
|
+
assertRunnable(unit, state);
|
|
1084
|
+
}
|
|
1085
|
+
catch (error) {
|
|
1086
|
+
if (!monorepo)
|
|
1087
|
+
throw error;
|
|
1088
|
+
stop(`tslaws: ${label(unit)} could not be checked: ${error instanceof Error ? error.message : String(error)}`);
|
|
1089
|
+
continue;
|
|
430
1090
|
}
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
1091
|
+
const proposals = proposalsOf(changes, checked, unit.path);
|
|
1092
|
+
if (proposals.length === 0) {
|
|
1093
|
+
ctx.out(`tslaws: ${monorepo ? `${label(unit)}: ` : ''}the lock already records every law; no law ran\n`);
|
|
1094
|
+
continue;
|
|
1095
|
+
}
|
|
1096
|
+
// Each record's author is checked again now, against this project's own approvers: someone who lost write access,
|
|
1097
|
+
// or a rule that changed since the comment, leaves their records out.
|
|
1098
|
+
const records = [];
|
|
1099
|
+
if (config.accept === 'comment')
|
|
1100
|
+
for (const pr of pulls)
|
|
1101
|
+
for (const record of readApprovals(await commentsFor(pr), config.bot)) {
|
|
1102
|
+
if ((record.project ?? '') !== unit.path)
|
|
1103
|
+
continue;
|
|
1104
|
+
const key = `${unit.path}\0${pr.number}\0${record.by}`;
|
|
1105
|
+
if (!verdicts.has(key))
|
|
1106
|
+
verdicts.set(key, (await refusal(api, name, pr, record.by, 'User', config)) === undefined);
|
|
1107
|
+
if (verdicts.get(key))
|
|
1108
|
+
records.push(record);
|
|
1109
|
+
else
|
|
1110
|
+
ctx.err(`tslaws: ignoring the records of @${record.by} on #${pr.number}: no longer an approver\n`);
|
|
1111
|
+
}
|
|
1112
|
+
// The maintainer who started a run on demand accepts everything that passes, as an approver would on a pull request.
|
|
1113
|
+
const approvals = dispatched
|
|
1114
|
+
? new Map(proposals.map((p) => [p.fingerprint, actor]))
|
|
1115
|
+
: acceptedFingerprints(records, unit.path);
|
|
1116
|
+
// A law that had to run and has no result (the laws job reported nothing for it) is held whatever `requirePassing` says.
|
|
1117
|
+
const unproven = (p) => p.outcome === undefined && p.kind === 'law' && p.reason !== 'removed';
|
|
1118
|
+
const decision = decide(proposals.filter((p) => !unproven(p)), config, approvals);
|
|
1119
|
+
for (const proposal of proposals.filter(unproven))
|
|
1120
|
+
decision.held.push({
|
|
1121
|
+
proposal,
|
|
1122
|
+
why: 'changed after the laws job ran, or has no result there; run the workflow again',
|
|
1123
|
+
});
|
|
1124
|
+
const wins = proposals.filter((p) => decision.accept.has(p.fingerprint));
|
|
1125
|
+
if (wins.length > 0) {
|
|
1126
|
+
const next = acceptChanges(state.lock, state.laws, state.exempt, state.levels, decision.accept);
|
|
1127
|
+
// A certificate would come from the run of the laws, which is not trusted with the lock: readReport drops them, and a
|
|
1128
|
+
// lock written here records none (a record the lock already holds stays only while its law and problem match).
|
|
1129
|
+
writeLockValue(lockFile, next);
|
|
1130
|
+
writes.push({
|
|
1131
|
+
path: lockPath,
|
|
1132
|
+
text: readFileSync(lockFile, 'utf8'),
|
|
1133
|
+
was: headLock?.sha,
|
|
1134
|
+
unit,
|
|
1135
|
+
accepted: wins,
|
|
1136
|
+
approvals,
|
|
1137
|
+
});
|
|
1138
|
+
}
|
|
1139
|
+
accepted += wins.length;
|
|
1140
|
+
held += decision.held.length;
|
|
1141
|
+
sections.push([
|
|
1142
|
+
...(monorepo ? [`#### \`${label(unit).replace(/`/g, "'")}\`\n`] : []),
|
|
1143
|
+
...wins.map((p) => `- ✅ ${shown(p.name)} (${shown(p.file)}, ${p.reason}) accepted${approvals.has(p.fingerprint) ? ` — @${approvals.get(p.fingerprint)}` : ''}`),
|
|
1144
|
+
...decision.held.map(({ proposal, why }) => `- 🚫 ${shown(proposal.name)} (${shown(proposal.file)}, ${proposal.reason}) not accepted: ${why}`),
|
|
1145
|
+
].join('\n'));
|
|
1146
|
+
}
|
|
1147
|
+
if (writes.length > 0 && !ctx.flags.has('dry-run')) {
|
|
1148
|
+
const detail = (w) => w.accepted
|
|
1149
|
+
.map((p) => `- ${monorepo ? `${joinRepo(w.unit.path, '')}`.replace(/\/$/, '') + (w.unit.path === '' ? '' : ': ') : ''}${p.key} (${p.reason}${p.outcome ? `, ${p.outcome.status}` : ''}${w.approvals.has(p.fingerprint) ? `, accepted by @${w.approvals.get(p.fingerprint)}` : ''})`)
|
|
1150
|
+
.join('\n');
|
|
1151
|
+
const count = writes.reduce((n, w) => n + w.accepted.length, 0);
|
|
1152
|
+
const message = `chore(tslaws): accept ${count} law change${count === 1 ? '' : 's'}${writes.length > 1 ? ` in ${writes.length} projects` : ''}${pulls[0] ? ` from #${pulls[0].number}` : dispatched ? ` on request of @${actor}` : ''}\n\n${writes.map(detail).join('\n')}`;
|
|
1153
|
+
if (writes.length === 1) {
|
|
1154
|
+
const [only] = writes;
|
|
439
1155
|
// Through the contents API, so GitHub signs the commit as the bot and `verify` can tell it from a forgery. The
|
|
440
1156
|
// lock this run started from is the one it replaces: if anything wrote the lock since, GitHub refuses the write.
|
|
441
|
-
await api('PUT',
|
|
442
|
-
message
|
|
443
|
-
content: Buffer.from(text).toString('base64'),
|
|
444
|
-
branch
|
|
445
|
-
...(
|
|
1157
|
+
await api('PUT', contentsUrl(name, only.path), {
|
|
1158
|
+
message,
|
|
1159
|
+
content: Buffer.from(only.text).toString('base64'),
|
|
1160
|
+
branch,
|
|
1161
|
+
...(only.was === undefined ? {} : { sha: only.was }),
|
|
446
1162
|
});
|
|
447
1163
|
}
|
|
1164
|
+
else {
|
|
1165
|
+
await commitTogether(api, name, branch, writes, message);
|
|
1166
|
+
}
|
|
448
1167
|
}
|
|
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
1168
|
const where = repoPath(ctx, '');
|
|
454
|
-
const note = `### tslaws on \`${
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
1169
|
+
const note = `### tslaws on \`${branch}\`${monorepo || where === '' ? '' : ` (\`${where}\`)`}\n\n${sections.join('\n')}\n${held > 0 ? `\n\`tslaws check\` fails on \`${branch}\` until the held proposals are fixed or removed.\n` : ''}`;
|
|
1170
|
+
if (sections.length > 0) {
|
|
1171
|
+
summary(ctx.env, note);
|
|
1172
|
+
ctx.out(`${note}\n`);
|
|
1173
|
+
for (const pr of pulls)
|
|
1174
|
+
await api('POST', `/repos/${name}/issues/${pr.number}/comments`, { body: note }).catch(() => undefined);
|
|
1175
|
+
}
|
|
1176
|
+
setOutput(ctx.env, 'accepted', String(accepted));
|
|
1177
|
+
if (failures.length > 0 && writes.length > 0)
|
|
1178
|
+
ctx.out(`tslaws: wrote ${plural(writes.length, 'lock')}; ${plural(failures.length, 'problem')} above ${failures.length === 1 ? 'leaves' : 'leave'} the job failed\n`);
|
|
1179
|
+
return held === 0 && failures.length === 0 ? 0 : 1;
|
|
1180
|
+
}
|
|
1181
|
+
/**
|
|
1182
|
+
* Several locks in one commit, through the git data API: the parent is the branch's head now, each lock must still be
|
|
1183
|
+
* the one this run built on, and the branch moves by a plain (never forced) update, so GitHub refuses it if anything
|
|
1184
|
+
* landed in between.
|
|
1185
|
+
*/
|
|
1186
|
+
async function commitTogether(api, name, branch, writes, message) {
|
|
1187
|
+
const ref = encodeURIComponent(branch);
|
|
1188
|
+
const head = (await api('GET', `/repos/${name}/git/ref/heads/${ref}`)).object.sha;
|
|
1189
|
+
for (const w of writes) {
|
|
1190
|
+
let now;
|
|
1191
|
+
try {
|
|
1192
|
+
now = (await api('GET', contentsUrl(name, w.path, head))).sha;
|
|
1193
|
+
}
|
|
1194
|
+
catch {
|
|
1195
|
+
now = undefined;
|
|
1196
|
+
}
|
|
1197
|
+
if (now !== w.was)
|
|
1198
|
+
throw new Error(`${w.path} changed on ${branch} while this ran; nothing written`);
|
|
1199
|
+
}
|
|
1200
|
+
const parent = (await api('GET', `/repos/${name}/git/commits/${head}`));
|
|
1201
|
+
const tree = (await api('POST', `/repos/${name}/git/trees`, {
|
|
1202
|
+
base_tree: parent.tree.sha,
|
|
1203
|
+
tree: writes.map((w) => ({ path: w.path, mode: '100644', type: 'blob', content: w.text })),
|
|
1204
|
+
}));
|
|
1205
|
+
const made = (await api('POST', `/repos/${name}/git/commits`, { message, tree: tree.sha, parents: [head] }));
|
|
1206
|
+
await api('PATCH', `/repos/${name}/git/refs/heads/${ref}`, { sha: made.sha, force: false });
|
|
1207
|
+
}
|
|
1208
|
+
/**
|
|
1209
|
+
* What a project's settings were and are. Always read at both commits and compared: the list of changed files is capped
|
|
1210
|
+
* by the API, so it cannot be what decides whether to look.
|
|
1211
|
+
*/
|
|
1212
|
+
async function checkProjectAt(read, pull, problems, dir) {
|
|
1213
|
+
const configPath = joinRepo(dir, 'tslaws.json');
|
|
1214
|
+
const base = await settingsAt(read, pull.base.sha, dir);
|
|
1215
|
+
let head;
|
|
1216
|
+
try {
|
|
1217
|
+
head = await settingsAt(read, pull.head.sha, dir);
|
|
1218
|
+
}
|
|
1219
|
+
catch (error) {
|
|
1220
|
+
problems.push(`${configPath} does not read on the pull request: ${error instanceof Error ? error.message : String(error)}`);
|
|
1221
|
+
}
|
|
1222
|
+
if (head !== undefined) {
|
|
1223
|
+
if (JSON.stringify(base.github) !== JSON.stringify(head.github))
|
|
1224
|
+
problems.push(`the pull request changes the "github" section of ${configPath}, which decides who may accept laws`);
|
|
1225
|
+
else if (base.standalone !== head.standalone)
|
|
1226
|
+
problems.push(`the pull request changes "standalone" in ${configPath}, which decides whether root runs cover it`);
|
|
1227
|
+
}
|
|
1228
|
+
return base.github === undefined ? undefined : parseGithubConfig(base.github);
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* Why a pull request may not change `lockPath`, for a project whose base settings are `config`. With "local" on, a
|
|
1232
|
+
* maintainer's pull request may: its author needs admin or maintain access, and so does the author of each commit that
|
|
1233
|
+
* changes the lock, so a maintainer cannot carry someone else's lock through. Without it, only the bot writes the lock.
|
|
1234
|
+
*/
|
|
1235
|
+
async function lockChangeProblems(api, name, pull, lockPath, config, evidence) {
|
|
1236
|
+
if (!config.local)
|
|
1237
|
+
return [`the pull request changes ${lockPath}; only ${config.bot} writes the lock, on merge into ${config.branch}`];
|
|
1238
|
+
evidence.author ??= maintains(api, name, pull.user.login, pull.user.type);
|
|
1239
|
+
if (!(await evidence.author))
|
|
1240
|
+
return [
|
|
1241
|
+
`the pull request changes ${lockPath}; only ${config.bot} writes the lock, on merge into ${config.branch}, unless its author has admin or maintain access to the repository`,
|
|
1242
|
+
];
|
|
1243
|
+
// GitHub lists at most 300 files for a commit; a full list may hide the lock, so it counts as touching it. It lists at
|
|
1244
|
+
// most 250 commits for a pull request; a full list may hide a commit, so the pull request cannot be checked. The
|
|
1245
|
+
// author is the one GitHub matches from the commit's e-mail, which anyone with push access to the branch can set: the
|
|
1246
|
+
// pull request's author, a maintainer, answers for what is pushed to it, and the ruleset is the hard control.
|
|
1247
|
+
evidence.commits ??= (async () => {
|
|
1248
|
+
const listed = await all(api, `/repos/${name}/pulls/${pull.number}/commits`);
|
|
1249
|
+
const list = [];
|
|
1250
|
+
// At the limit the pull request fails whatever its commits say, so they are not read.
|
|
1251
|
+
for (const c of listed.length >= 250 ? [] : listed) {
|
|
1252
|
+
const detail = (await api('GET', `/repos/${name}/commits/${c.sha}`));
|
|
1253
|
+
list.push({ sha: c.sha, author: detail.author, files: detail.files ?? [] });
|
|
1254
|
+
}
|
|
1255
|
+
return { full: listed.length >= 250, list };
|
|
1256
|
+
})();
|
|
1257
|
+
const { full, list } = await evidence.commits;
|
|
1258
|
+
const problems = [];
|
|
1259
|
+
if (full)
|
|
1260
|
+
problems.push(`the pull request changes ${lockPath} and has 250 or more commits, more than GitHub lists; split it so each commit can be checked`);
|
|
1261
|
+
for (const c of list) {
|
|
1262
|
+
const touchesLock = c.files.length >= 300 || c.files.some((f) => f.filename === lockPath || f.previous_filename === lockPath);
|
|
1263
|
+
if (touchesLock && !(await maintains(api, name, c.author?.login ?? '', c.author?.type)))
|
|
1264
|
+
problems.push(`commit ${c.sha.slice(0, 7)} in the pull request changes ${lockPath}, but ${c.author?.login ? `@${c.author.login} does not` : 'its author does not'} have admin or maintain access to the repository`);
|
|
1265
|
+
}
|
|
1266
|
+
return problems;
|
|
1267
|
+
}
|
|
1268
|
+
/** The most files the pull request files API lists (30 pages of 100); a pull request with more is cut short. */
|
|
1269
|
+
const filesListLimit = 3000;
|
|
1270
|
+
/**
|
|
1271
|
+
* The files a pull request changes, with the old name of each file it renames. Fails when the list cannot be the whole
|
|
1272
|
+
* of it: at the API's cap, or not the number GitHub says the pull request changes. The security checks do not decide
|
|
1273
|
+
* from this list alone, but a list that may be short is never used.
|
|
1274
|
+
*/
|
|
1275
|
+
async function changedFiles(api, name, pull) {
|
|
1276
|
+
const files = await all(api, `/repos/${name}/pulls/${pull.number}/files`);
|
|
1277
|
+
if (files.length >= filesListLimit)
|
|
1278
|
+
throw new Error(`the pull request changes ${filesListLimit} files or more, which the API cannot list in full; nothing can be checked`);
|
|
1279
|
+
if (files.length !== pull.changed_files)
|
|
1280
|
+
throw new Error(`GitHub lists ${plural(files.length, 'changed file')} for the pull request but reports ${pull.changed_files === undefined ? 'no count of files' : plural(pull.changed_files, 'file')} changed; nothing can be checked`);
|
|
1281
|
+
return new Set(files.flatMap((f) => [f.filename, ...(f.previous_filename ? [f.previous_filename] : [])]));
|
|
1282
|
+
}
|
|
1283
|
+
/**
|
|
1284
|
+
* Everything a pull request must not change from under a monorepo's checks, read through the API at the base and at the
|
|
1285
|
+
* head: the project list (and how it is found), each project's `github` and `standalone` settings, and any lock. Adds a
|
|
1286
|
+
* line to `problems` for each. Returns what it read, for a caller that decides more from it. A lock change is a problem
|
|
1287
|
+
* unless `maintainersMayChangeLocks` and its project's base settings have "local" on and a maintainer wrote it.
|
|
1288
|
+
*/
|
|
1289
|
+
async function inspectMonorepo(api, name, read, pull, changed, rootPath, problems, maintainersMayChangeLocks = false) {
|
|
1290
|
+
const checkProject = (dir) => checkProjectAt(read, pull, problems, dir);
|
|
1291
|
+
// Every project of the base and every project of the head, read through the API: a pull request that edits the
|
|
1292
|
+
// files that discover projects cannot hide a project from this check.
|
|
1293
|
+
const baseSide = await projectsAt(api, name, read, pull.base.sha, rootPath);
|
|
1294
|
+
const headSide = await projectsAt(api, name, read, pull.head.sha, rootPath);
|
|
1295
|
+
if (baseSide.truncated || headSide.truncated)
|
|
1296
|
+
problems.push('the repository is too large for the API to list its files; the projects cannot be checked');
|
|
1297
|
+
const label = (rel) => joinRepo(rootPath, rel) || '.';
|
|
1298
|
+
const headSet = new Set(headSide.paths);
|
|
1299
|
+
for (const rel of baseSide.paths)
|
|
1300
|
+
if (!headSet.has(rel))
|
|
1301
|
+
problems.push(`${label(rel)} is a project on ${pull.base.ref} but the pull request no longer discovers it, so its lock would go unwatched: restore it, or merge this in a pull request of its own by an administrator`);
|
|
1302
|
+
const inputs = [
|
|
1303
|
+
['tslaws.json', 'tslaws'],
|
|
1304
|
+
['package.json', 'packageJson'],
|
|
1305
|
+
['pnpm-workspace.yaml', 'pnpmWorkspace'],
|
|
1306
|
+
];
|
|
1307
|
+
for (const [file, key] of inputs) {
|
|
1308
|
+
const path = joinRepo(rootPath, file);
|
|
1309
|
+
const was = baseSide.inputs[key];
|
|
1310
|
+
const now = headSide.inputs[key];
|
|
1311
|
+
const sig = (text) => (text === undefined ? 'absent' : discoverySignature({ [key]: text }));
|
|
1312
|
+
if (sig(was) !== sig(now))
|
|
1313
|
+
problems.push(`the pull request changes how projects are discovered (${path}), which decides what this check watches`);
|
|
1314
|
+
}
|
|
1315
|
+
const union = [...new Set([...baseSide.paths, ...headSide.paths])];
|
|
1316
|
+
const configs = new Map();
|
|
1317
|
+
const evidence = {};
|
|
1318
|
+
// Every project, whatever the pull request changed: a settings file need not end in .json (an `extends` base in a
|
|
1319
|
+
// .jsonc file, say), so no extension decides whether to look. checkProject compares only the files a project reads.
|
|
1320
|
+
for (const rel of union)
|
|
1321
|
+
try {
|
|
1322
|
+
configs.set(rel, await checkProject(joinRepo(rootPath, rel)));
|
|
1323
|
+
}
|
|
1324
|
+
catch (error) {
|
|
1325
|
+
problems.push(`${label(rel)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1326
|
+
}
|
|
1327
|
+
// Any lock the pull request touches, in a project or not: the bot writes locks, after the merge. Found by comparing the
|
|
1328
|
+
// two trees' blob ids (not only the files list, which can be cut short).
|
|
1329
|
+
for (const file of new Set([...lockDifferences(baseSide.locks, headSide.locks), ...[...changed].filter(isLock)])) {
|
|
1330
|
+
const owner = union.find((rel) => joinRepo(rootPath, joinRepo(rel, 'tsc-laws.lock')) === file);
|
|
1331
|
+
const config = owner === undefined ? undefined : configs.get(owner);
|
|
1332
|
+
if (config !== undefined && maintainersMayChangeLocks) {
|
|
1333
|
+
// The project's own settings, as the base has them: a maintainer may change its lock while its "local" is true.
|
|
1334
|
+
problems.push(...(await lockChangeProblems(api, name, pull, file, config, evidence)));
|
|
1335
|
+
continue;
|
|
1336
|
+
}
|
|
1337
|
+
problems.push(config === undefined
|
|
1338
|
+
? `the pull request changes ${file}; a lock changes only when the bot writes it on merge, and this one is ${owner === undefined ? 'outside every project' : 'in a project with no "github" settings'}`
|
|
1339
|
+
: `the pull request changes ${file}; only ${config.bot} writes the lock, on merge into ${config.branch}`);
|
|
1340
|
+
}
|
|
1341
|
+
return { baseSide, headSide, union };
|
|
461
1342
|
}
|
|
462
1343
|
// ---- verify ---------------------------------------------------------------------------------------------------------
|
|
463
1344
|
async function verify(ctx) {
|
|
1345
|
+
const monorepo = ctx.projects !== undefined;
|
|
464
1346
|
const ev = event(ctx.env);
|
|
465
1347
|
const pull = ev.pull_request;
|
|
466
1348
|
if (pull === undefined) {
|
|
@@ -469,22 +1351,10 @@ async function verify(ctx) {
|
|
|
469
1351
|
}
|
|
470
1352
|
const api = ctx.api ?? restApi(ctx.env);
|
|
471
1353
|
const name = repo(ctx.env);
|
|
472
|
-
const
|
|
473
|
-
|
|
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);
|
|
1354
|
+
const read = readerOf(api, name);
|
|
1355
|
+
const rootPath = repoPath(ctx, '');
|
|
485
1356
|
const problems = [];
|
|
486
|
-
const
|
|
487
|
-
const changed = new Set(files.flatMap((f) => [f.filename, ...(f.previous_filename ? [f.previous_filename] : [])]));
|
|
1357
|
+
const changed = await changedFiles(api, name, pull);
|
|
488
1358
|
const protectedPaths = String(ctx.flags.get('protect') ?? '')
|
|
489
1359
|
.split(',')
|
|
490
1360
|
.map((p) => p.trim())
|
|
@@ -492,22 +1362,31 @@ async function verify(ctx) {
|
|
|
492
1362
|
for (const path of protectedPaths)
|
|
493
1363
|
if (changed.has(path))
|
|
494
1364
|
problems.push(`${path} is protected: change it in a pull request of its own, merged by an administrator`);
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
1365
|
+
const checkProject = (dir) => checkProjectAt(read, pull, problems, dir);
|
|
1366
|
+
if (!monorepo) {
|
|
1367
|
+
// One project, as a package's own workflow runs it: its lock and its settings only.
|
|
1368
|
+
const configPath = joinRepo(rootPath, 'tslaws.json');
|
|
1369
|
+
const lockPath = joinRepo(rootPath, 'tsc-laws.lock');
|
|
1370
|
+
const config = await checkProject(rootPath);
|
|
1371
|
+
if (config === undefined)
|
|
1372
|
+
throw new Error('tslaws github needs a "github" section in tslaws.json');
|
|
1373
|
+
// The bot never commits to a pull request's branch: it writes the lock on ${config.branch} after the merge. So any
|
|
1374
|
+
// change to the lock in the pull request's diff (the full list, paginated above) is a forgery. Checking the diff, not
|
|
1375
|
+
// each commit, also covers commits whose file list GitHub truncates (the commit API lists at most 300 files). With
|
|
1376
|
+
// "local" on, a pull request from someone with admin or maintain access may change it: see lockChangeProblems.
|
|
1377
|
+
const [baseTree, headTree] = await Promise.all([
|
|
1378
|
+
treeAt(api, name, pull.base.sha),
|
|
1379
|
+
treeAt(api, name, pull.head.sha),
|
|
1380
|
+
]);
|
|
1381
|
+
if (baseTree.truncated || headTree.truncated)
|
|
1382
|
+
problems.push('the repository is too large for the API to list its files; the lock cannot be checked');
|
|
1383
|
+
if (changed.has(lockPath) || lockDifferences(baseTree.locks, headTree.locks).includes(lockPath))
|
|
1384
|
+
problems.push(...(await lockChangeProblems(api, name, pull, lockPath, config, {})));
|
|
1385
|
+
void configPath;
|
|
1386
|
+
}
|
|
1387
|
+
else {
|
|
1388
|
+
await inspectMonorepo(api, name, read, pull, changed, rootPath, problems, true);
|
|
505
1389
|
}
|
|
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
1390
|
for (const problem of problems)
|
|
512
1391
|
ctx.out(`::error::${escapeGithubData(problem)}\n`);
|
|
513
1392
|
if (problems.length === 0)
|
|
@@ -517,6 +1396,28 @@ async function verify(ctx) {
|
|
|
517
1396
|
// ---- entry ----------------------------------------------------------------------------------------------------------
|
|
518
1397
|
export async function githubCommand(action, ctx) {
|
|
519
1398
|
try {
|
|
1399
|
+
const out = ctx.flags.get('results-out');
|
|
1400
|
+
if (out !== undefined || ctx.flags.has('results')) {
|
|
1401
|
+
if (action !== 'report' && action !== 'merge') {
|
|
1402
|
+
ctx.err('tslaws github: --results and --results-out are for report and merge\n');
|
|
1403
|
+
return 1;
|
|
1404
|
+
}
|
|
1405
|
+
if (out !== undefined && ctx.flags.has('results')) {
|
|
1406
|
+
ctx.err('tslaws github: use --results-out to run the laws or --results to act on them, not both\n');
|
|
1407
|
+
return 1;
|
|
1408
|
+
}
|
|
1409
|
+
if (out !== undefined) {
|
|
1410
|
+
if (typeof out !== 'string') {
|
|
1411
|
+
ctx.err('tslaws github: --results-out needs a file\n');
|
|
1412
|
+
return 1;
|
|
1413
|
+
}
|
|
1414
|
+
return await collect(ctx, action, out);
|
|
1415
|
+
}
|
|
1416
|
+
if (typeof ctx.flags.get('results') !== 'string') {
|
|
1417
|
+
ctx.err('tslaws github: --results needs a file\n');
|
|
1418
|
+
return 1;
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
520
1421
|
if (action === 'report')
|
|
521
1422
|
return await report(ctx);
|
|
522
1423
|
if (action === 'command')
|