tslaws 0.8.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/dist/cli.js CHANGED
@@ -78,6 +78,7 @@ function parse(args) {
78
78
  'head-sha',
79
79
  'rerun-workflow',
80
80
  'protect',
81
+ 'project-path',
81
82
  ]);
82
83
  for (let i = 0; i < args.length; i += 1) {
83
84
  const arg = args[i];
@@ -477,7 +478,7 @@ export async function main(args) {
477
478
  return 0;
478
479
  }
479
480
  if (command === 'github') {
480
- const { githubCommand } = await import("./githubCli.js");
481
+ const { githubCommand, projectPathOf } = await import("./githubCli.js");
481
482
  // The token stays with tslaws: laws run in worker threads and the compiler in a child process, and both get a copy of
482
483
  // process.env, so a law under test could otherwise read the token and act as the bot.
483
484
  const env = { ...process.env };
@@ -490,6 +491,7 @@ export async function main(args) {
490
491
  chosen.compiler = checkoutCompiler(resolve(cwd, trusted)) ?? 'tsc-laws';
491
492
  return githubCommand(files[0], {
492
493
  cwd,
494
+ projectPath: projectPathOf(cwd, flags.get('project-path')),
493
495
  options: chosen,
494
496
  env,
495
497
  flags,
package/dist/github.d.ts CHANGED
@@ -117,5 +117,7 @@ export declare function pullRequestVerdict(report: CheckReport, proposals: Propo
117
117
  problems: string[];
118
118
  };
119
119
  export declare const stickyMarker = "<!-- tslaws-proposals -->";
120
+ /** The sticky comment's marker for a project: the root's is unchanged; another project's names its path. */
121
+ export declare function stickyMarkerFor(project?: string): string;
120
122
  /** The sticky pull request comment: every proposal, what it did, and whether it will be accepted on merge. */
121
- export declare function renderSticky(proposals: Proposal[], config: GithubConfig, approvals: Map<string, string>, link: (p: Proposal) => string): string;
123
+ export declare function renderSticky(proposals: Proposal[], config: GithubConfig, approvals: Map<string, string>, link: (p: Proposal) => string, project?: string): string;
package/dist/github.js CHANGED
@@ -230,6 +230,15 @@ export function pullRequestVerdict(report, proposals, config, approvals) {
230
230
  }
231
231
  // ---- rendering ------------------------------------------------------------------------------------------------------
232
232
  export const stickyMarker = '<!-- tslaws-proposals -->';
233
+ /** The sticky comment's marker for a project: the root's is unchanged; another project's names its path. */
234
+ export function stickyMarkerFor(project = '') {
235
+ if (project === '')
236
+ return stickyMarker;
237
+ // Percent-encode every byte outside a small safe set (`-` and `%` included), so two paths never share a marker and
238
+ // no path can write `-->` to close the comment early.
239
+ const encoded = project.replace(/[^A-Za-z0-9/._@]/gu, (c) => [...new TextEncoder().encode(c)].map((b) => `%${b.toString(16).toUpperCase().padStart(2, '0')}`).join(''));
240
+ return `<!-- tslaws-proposals ${encoded} -->`;
241
+ }
233
242
  const cell = (text) => inert(text).replace(/\|/g, '\\|').replace(/\r?\n/g, ' ');
234
243
  function outcomeText(p) {
235
244
  if (p.outcome === undefined)
@@ -245,8 +254,9 @@ function outcomeText(p) {
245
254
  }
246
255
  const what = (p) => p.kind === 'exempt' ? `exemption ${p.reason}` : p.reason === 'level' ? 'level changed' : `law ${p.reason}`;
247
256
  /** The sticky pull request comment: every proposal, what it did, and whether it will be accepted on merge. */
248
- export function renderSticky(proposals, config, approvals, link) {
249
- const head = `${stickyMarker}\n### tslaws proposals\n\n`;
257
+ export function renderSticky(proposals, config, approvals, link, project = '') {
258
+ const title = project === '' ? '' : ` for \`${project.replace(/`/g, "'")}\``;
259
+ const head = `${stickyMarkerFor(project)}\n### tslaws proposals${title}\n\n`;
250
260
  if (proposals.length === 0)
251
261
  return `${head}No law, level or coverage exemption differs from \`tsc-laws.lock\`.\n`;
252
262
  const rows = proposals.map((p) => {
@@ -3,6 +3,11 @@ import { type Lock } from './lock.ts';
3
3
  import type { CheckOptions, ManifestLaw } from './types.ts';
4
4
  export interface GithubContext {
5
5
  cwd: string;
6
+ /**
7
+ * Where the project sits in the repository, repo-relative with '/' separators and no trailing slash ('' at the root).
8
+ * Every REST path and annotation names files from the repository root, so they carry it.
9
+ */
10
+ projectPath?: string;
6
11
  /** The check options for the whole project (every laws file, the lock at the root). */
7
12
  options: CheckOptions;
8
13
  env: NodeJS.ProcessEnv;
@@ -12,6 +17,8 @@ export interface GithubContext {
12
17
  /** For tests: a stand-in for the GitHub REST API. */
13
18
  api?: Api;
14
19
  }
20
+ /** `--project-path`, else where `cwd` sits inside its git repository (`git rev-parse --show-prefix`), else ''. */
21
+ export declare function projectPathOf(cwd: string, flag: string | true | undefined): string;
15
22
  export type Api = (method: string, path: string, body?: unknown) => Promise<unknown>;
16
23
  interface PullRequest {
17
24
  number: number;
package/dist/githubCli.js CHANGED
@@ -13,14 +13,41 @@
13
13
  // tslaws.json or a protected path. Reads the base branch's config, never the pull request's.
14
14
  import { readFileSync, writeFileSync, appendFileSync, existsSync } from 'node:fs';
15
15
  import { createHash } from 'node:crypto';
16
+ import { execFileSync } from 'node:child_process';
16
17
  import { join } from 'node:path';
17
18
  import { check, exemptionsOf } from "./check.js";
18
19
  import { readConfig } from "./coverage.js";
19
20
  import { readManifest } from "./compile.js";
20
- import { acceptedFingerprints, inert, recordComment, decide, parseCommands, isSharedBot, parseGithubConfig, proposalsOf, pullRequestVerdict, readApprovals, renderSticky, resolveNames, stickyMarker, } from "./github.js";
21
+ import { acceptedFingerprints, inert, recordComment, decide, parseCommands, isSharedBot, parseGithubConfig, proposalsOf, pullRequestVerdict, readApprovals, renderSticky, resolveNames, stickyMarkerFor, } from "./github.js";
21
22
  import { classifyLawFile, lockLevels } from "./lawKinds.js";
22
23
  import { acceptChanges, lockChanges, readLock, writeLockValue } from "./lock.js";
23
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
+ }
24
51
  function restApi(env) {
25
52
  const base = env.GITHUB_API_URL ?? 'https://api.github.com';
26
53
  const token = env.GITHUB_TOKEN ?? env.GH_TOKEN;
@@ -95,14 +122,15 @@ export function projectState(options) {
95
122
  async function issueComments(api, name, pr) {
96
123
  return all(api, `/repos/${name}/issues/${pr}/comments`);
97
124
  }
98
- async function upsertSticky(api, name, pr, bot, body, comments) {
99
- const mine = comments.find((c) => c.user.login === bot && c.body.startsWith(stickyMarker));
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));
100
128
  if (mine === undefined)
101
129
  await api('POST', `/repos/${name}/issues/${pr}/comments`, { body });
102
130
  else if (mine.body !== body)
103
131
  await api('PATCH', `/repos/${name}/issues/comments/${mine.id}`, { body });
104
132
  }
105
- function linkFor(env, sha) {
133
+ function linkFor(env, sha, ctx) {
106
134
  const server = env.GITHUB_SERVER_URL ?? 'https://github.com';
107
135
  const name = env.GITHUB_REPOSITORY ?? '';
108
136
  // Raw text: renderSticky makes the whole cell inert. Brackets and backticks would break the link's markdown.
@@ -110,7 +138,7 @@ function linkFor(env, sha) {
110
138
  const label = p.name.replace(/[`[\]]/g, "'");
111
139
  if (p.line === 0 || name === '')
112
140
  return `${label} (${p.file})`;
113
- return `[${label}](${server}/${name}/blob/${sha}/${p.file.split('/').map(encodeURIComponent).join('/')}#L${p.line})`;
141
+ return `[${label}](${server}/${name}/blob/${sha}/${repoPath(ctx, p.file).split('/').map(encodeURIComponent).join('/')}#L${p.line})`;
114
142
  };
115
143
  }
116
144
  /** A law name or path from the pull request, for a bot comment: inert, and quoted without a code span. */
@@ -153,13 +181,14 @@ async function report(ctx) {
153
181
  const message = p.outcome === undefined
154
182
  ? 'did not run'
155
183
  : `${p.reason}; if accepted: ${p.outcome.status}${p.outcome.counterexample ? `; counterexample ${p.outcome.counterexample}` : ''}`;
156
- ctx.out(`::${level} file=${escapeGithubProperty(p.file)},line=${Math.max(1, p.line)},title=${escapeGithubProperty(title)}::${escapeGithubData(message)}\n`);
184
+ ctx.out(`::${level} file=${escapeGithubProperty(repoPath(ctx, p.file))},line=${Math.max(1, p.line)},title=${escapeGithubProperty(title)}::${escapeGithubData(message)}\n`);
157
185
  }
158
- const body = renderSticky(proposals, config, approvals, linkFor(ctx.env, sha));
159
- summary(ctx.env, body.replace(stickyMarker, ''));
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), ''));
160
189
  if (api !== undefined && Number.isInteger(pr) && ctx.flags.has('comment')) {
161
190
  try {
162
- await upsertSticky(api, repo(ctx.env), pr, config.bot, body, comments);
191
+ await upsertSticky(api, repo(ctx.env), pr, config.bot, body, comments, project);
163
192
  }
164
193
  catch (error) {
165
194
  // A pull request from a fork gets a read-only token: the step summary and annotations still carry the report.
@@ -293,10 +322,11 @@ async function command(ctx) {
293
322
  }
294
323
  // ---- merge ----------------------------------------------------------------------------------------------------------
295
324
  async function merge(ctx) {
325
+ const lockPath = repoPath(ctx, 'tsc-laws.lock');
296
326
  const configText = readText(join(ctx.cwd, 'tslaws.json'));
297
327
  const config = githubConfigOf(configText);
298
328
  if (isSharedBot(config))
299
- ctx.out(`::warning title=tslaws::"bot" is ${config.bot}, which every workflow can act as; only a ruleset on ${config.branch} that restricts tsc-laws.lock keeps other workflows from writing it. A dedicated GitHub App closes this.
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.
300
330
  `);
301
331
  const ev = event(ctx.env);
302
332
  const ref = String(ev.ref ?? ctx.env.GITHUB_REF ?? '');
@@ -309,7 +339,7 @@ async function merge(ctx) {
309
339
  return 1;
310
340
  }
311
341
  const commits = (ev.commits ?? []);
312
- const touches = (c) => [...(c.modified ?? []), ...(c.added ?? []), ...(c.removed ?? [])].includes('tsc-laws.lock');
342
+ const touches = (c) => [...(c.modified ?? []), ...(c.added ?? []), ...(c.removed ?? [])].includes(lockPath);
313
343
  const api = ctx.api ?? restApi(ctx.env);
314
344
  const name = repo(ctx.env);
315
345
  const sha = String(ev.after ?? ctx.env.GITHUB_SHA ?? '');
@@ -332,7 +362,7 @@ async function merge(ctx) {
332
362
  }
333
363
  for (const c of commits.filter(touches))
334
364
  if (!(await byBot(c.id))) {
335
- ctx.err(`tslaws: commit ${c.id.slice(0, 7)} changed tsc-laws.lock but was not made by ${config.bot} with a verified signature; nothing accepted. Revert it.\n`);
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`);
336
366
  return 1;
337
367
  }
338
368
  // The push event lists at most 20 commits, and their file lists can be cut short, so compare the lock itself: this
@@ -341,14 +371,14 @@ async function merge(ctx) {
341
371
  if (/^[0-9a-f]{40}$/.test(before) && !/^0+$/.test(before)) {
342
372
  const lockAt = async (ref) => {
343
373
  try {
344
- return (await api('GET', `/repos/${name}/contents/tsc-laws.lock?ref=${ref}`)).sha;
374
+ return (await api('GET', `/repos/${name}/contents/${lockPath}?ref=${ref}`)).sha;
345
375
  }
346
376
  catch {
347
377
  return undefined;
348
378
  }
349
379
  };
350
380
  if ((await lockAt(before)) !== (await lockAt(sha))) {
351
- ctx.err(`tslaws: this push changed tsc-laws.lock, and not only through ${config.bot}; nothing accepted. Revert the change.
381
+ ctx.err(`tslaws: this push changed ${lockPath}, and not only through ${config.bot}; nothing accepted. Revert the change.
352
382
  `);
353
383
  return 1;
354
384
  }
@@ -357,19 +387,19 @@ async function merge(ctx) {
357
387
  // run made. Start from the lock on the branch, so this run never undoes what an earlier one accepted, once every
358
388
  // commit since this push that changed the lock is shown to be the bot's.
359
389
  const branchRef = encodeURIComponent(config.branch);
360
- const headLock = (await api('GET', `/repos/${name}/contents/tsc-laws.lock?ref=${branchRef}`).catch(() => undefined));
390
+ const headLock = (await api('GET', `/repos/${name}/contents/${lockPath}?ref=${branchRef}`).catch(() => undefined));
361
391
  const lockFile = ctx.options.lockFile;
362
392
  const localBlob = existsSync(lockFile) ? gitBlobSha(readFileSync(lockFile)) : undefined;
363
393
  if (headLock !== undefined && headLock.sha !== localBlob) {
364
394
  const range = (await api('GET', `/repos/${name}/compare/${sha}...${branchRef}`));
365
395
  const since = new Set(range.commits.map((c) => c.sha));
366
- const touched = (await api('GET', `/repos/${name}/commits?sha=${branchRef}&path=tsc-laws.lock&per_page=100`));
396
+ const touched = (await api('GET', `/repos/${name}/commits?sha=${branchRef}&path=${encodeURIComponent(lockPath)}&per_page=100`));
367
397
  let trusted = range.status === 'ahead' && range.ahead_by === range.commits.length && touched.length < 100;
368
398
  for (const c of touched)
369
399
  if (trusted && since.has(c.sha) && !(await byBot(c.sha)))
370
400
  trusted = false;
371
401
  if (!trusted) {
372
- ctx.err(`tslaws: tsc-laws.lock on ${config.branch} has moved on since this push, and not only through ${config.bot}; nothing accepted
402
+ ctx.err(`tslaws: ${lockPath} on ${config.branch} has moved on since this push, and not only through ${config.bot}; nothing accepted
373
403
  `);
374
404
  return 1;
375
405
  }
@@ -408,7 +438,7 @@ async function merge(ctx) {
408
438
  if (!ctx.flags.has('dry-run')) {
409
439
  // Through the contents API, so GitHub signs the commit as the bot and `verify` can tell it from a forgery. The
410
440
  // lock this run started from is the one it replaces: if anything wrote the lock since, GitHub refuses the write.
411
- await api('PUT', `/repos/${name}/contents/tsc-laws.lock`, {
441
+ await api('PUT', `/repos/${name}/contents/${lockPath}`, {
412
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')}`,
413
443
  content: Buffer.from(text).toString('base64'),
414
444
  branch: config.branch,
@@ -420,7 +450,8 @@ async function merge(ctx) {
420
450
  ...accepted.map((p) => `- ✅ ${shown(p.name)} (${shown(p.file)}, ${p.reason}) accepted${approvals.has(p.fingerprint) ? ` — @${approvals.get(p.fingerprint)}` : ''}`),
421
451
  ...decision.held.map(({ proposal, why }) => `- 🚫 ${shown(proposal.name)} (${shown(proposal.file)}, ${proposal.reason}) not accepted: ${why}`),
422
452
  ];
423
- const note = `### tslaws on \`${config.branch}\`\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` : ''}`;
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` : ''}`;
424
455
  summary(ctx.env, note);
425
456
  ctx.out(`${note}\n`);
426
457
  for (const pr of pulls)
@@ -447,7 +478,9 @@ async function verify(ctx) {
447
478
  return undefined;
448
479
  }
449
480
  };
450
- const baseText = await contents('tslaws.json', pull.base.sha);
481
+ const lockPath = repoPath(ctx, 'tsc-laws.lock');
482
+ const configPath = repoPath(ctx, 'tslaws.json');
483
+ const baseText = await contents(configPath, pull.base.sha);
451
484
  const config = githubConfigOf(baseText);
452
485
  const problems = [];
453
486
  const files = await all(api, `/repos/${name}/pulls/${pull.number}/files`);
@@ -459,22 +492,22 @@ async function verify(ctx) {
459
492
  for (const path of protectedPaths)
460
493
  if (changed.has(path))
461
494
  problems.push(`${path} is protected: change it in a pull request of its own, merged by an administrator`);
462
- if (changed.has('tslaws.json')) {
463
- const headText = await contents('tslaws.json', pull.head.sha);
495
+ if (changed.has(configPath)) {
496
+ const headText = await contents(configPath, pull.head.sha);
464
497
  const section = (text) => JSON.stringify(text === undefined ? undefined : JSON.parse(text).github);
465
498
  try {
466
499
  if (section(baseText) !== section(headText))
467
- problems.push('the pull request changes the "github" section of tslaws.json, which decides who may accept laws');
500
+ problems.push(`the pull request changes the "github" section of ${configPath}, which decides who may accept laws`);
468
501
  }
469
502
  catch {
470
- problems.push('tslaws.json does not parse');
503
+ problems.push(`${configPath} does not parse`);
471
504
  }
472
505
  }
473
506
  // The bot never commits to a pull request's branch: it writes the lock on ${config.branch} after the merge. So any
474
507
  // change to the lock in the pull request's diff (the full list, paginated above) is a forgery. Checking the diff, not
475
508
  // each commit, also covers commits whose file list GitHub truncates (the commit API lists at most 300 files).
476
- if (changed.has('tsc-laws.lock'))
477
- problems.push(`the pull request changes tsc-laws.lock; only ${config.bot} writes the lock, on merge into ${config.branch}`);
509
+ if (changed.has(lockPath))
510
+ problems.push(`the pull request changes ${lockPath}; only ${config.bot} writes the lock, on merge into ${config.branch}`);
478
511
  for (const problem of problems)
479
512
  ctx.out(`::error::${escapeGithubData(problem)}\n`);
480
513
  if (problems.length === 0)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tslaws",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Runs and checks `law` declarations compiled by tsc-laws: property tests, SMT proofs, tamper lock.",
5
5
  "bin": {
6
6
  "tslaws": "bin/tslaws.js"
@@ -73,11 +73,11 @@
73
73
  }
74
74
  },
75
75
  "optionalDependencies": {
76
- "tslaws-compiler-darwin-arm64": "0.8.0",
77
- "tslaws-compiler-darwin-x64": "0.8.0",
78
- "tslaws-compiler-linux-arm64-gnu": "0.8.0",
79
- "tslaws-compiler-linux-x64-gnu": "0.8.0",
80
- "tslaws-compiler-win32-x64-msvc": "0.8.0"
76
+ "tslaws-compiler-darwin-arm64": "0.9.0",
77
+ "tslaws-compiler-darwin-x64": "0.9.0",
78
+ "tslaws-compiler-linux-arm64-gnu": "0.9.0",
79
+ "tslaws-compiler-linux-x64-gnu": "0.9.0",
80
+ "tslaws-compiler-win32-x64-msvc": "0.9.0"
81
81
  },
82
82
  "publishConfig": {
83
83
  "access": "public"