tslaws 0.8.0 → 0.10.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/coverage.js CHANGED
@@ -6,11 +6,12 @@
6
6
  // but only once the exemption is in tsc-laws.lock, so an agent cannot exempt its own code.
7
7
  import { parseGithubConfig } from "./github.js";
8
8
  import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
9
- import { dirname, join, relative, resolve } from 'node:path';
9
+ import { dirname, isAbsolute, join, posix, relative, resolve } from 'node:path';
10
10
  import ts from 'typescript';
11
11
  import { parseE2eConfig } from "./e2e.js";
12
12
  import { globMatcher } from "./globs.js";
13
13
  import { customLawFile } from "./lawFiles.js";
14
+ import { importMetaEnvOf, parseEnvConfig } from "./runtimeEnv.js";
14
15
  import { solversProblem } from "./solvers.js";
15
16
  const settingKeys = ['runs', 'propertyTimeoutMs', 'proofTimeoutMs', 'bound'];
16
17
  const configKeys = [
@@ -21,21 +22,36 @@ const configKeys = [
21
22
  'compilerOptions',
22
23
  'e2e',
23
24
  'bundlerPlugins',
25
+ 'env',
24
26
  'github',
25
27
  ...settingKeys,
26
28
  ];
27
- /** Validates the top level of tslaws.json: known keys only, and the run settings are integers of at least 1. */
28
- export function parseConfig(raw) {
29
+ /** Keys that steer inheritance and discovery rather than a run; `readConfig` acts on them and drops them. */
30
+ const structuralKeys = ['extends', 'projects'];
31
+ /** Why `value` is not a usable `projects` list (directory globs relative to the file), or undefined. */
32
+ export function projectsProblem(value) {
33
+ if (!Array.isArray(value) ||
34
+ value.some((entry) => typeof entry !== 'string' || entry.replace(/^!/, '') === '' || entry.startsWith('/')))
35
+ return `"projects" must be an array of directory globs relative to tslaws.json, got ${JSON.stringify(value)}`;
36
+ return undefined;
37
+ }
38
+ /** The top-level checks that hold for one file on its own; `source` names that file in every message. */
39
+ function checkFile(raw, source) {
29
40
  const fail = (message) => {
30
- throw new Error(`tslaws.json: ${message}`);
41
+ throw new Error(`${source}: ${message}`);
31
42
  };
32
43
  if (typeof raw !== 'object' || raw === null || Array.isArray(raw))
33
44
  return fail('must be a JSON object');
34
45
  const object = raw;
35
46
  for (const key of Object.keys(object)) {
36
- if (key !== '$schema' && !configKeys.includes(key))
37
- fail(`unknown option "${key}"; supported options are ${configKeys.join(', ')}`);
47
+ if (key !== '$schema' && !configKeys.includes(key) && !structuralKeys.includes(key))
48
+ fail(`unknown option "${key}"; supported options are ${[...configKeys, ...structuralKeys].join(', ')}`);
38
49
  }
50
+ if (object.extends !== undefined && (typeof object.extends !== 'string' || object.extends === ''))
51
+ fail(`"extends" must be a path to another tslaws.json, got ${JSON.stringify(object.extends)}`);
52
+ const projects = object.projects === undefined ? undefined : projectsProblem(object.projects);
53
+ if (projects !== undefined)
54
+ fail(projects);
39
55
  for (const key of settingKeys) {
40
56
  const value = object[key];
41
57
  if (value !== undefined && (typeof value !== 'number' || !Number.isInteger(value) || value < 1))
@@ -45,6 +61,8 @@ export function parseConfig(raw) {
45
61
  if (plugins !== undefined &&
46
62
  (!Array.isArray(plugins) || plugins.some((entry) => typeof entry !== 'string' || entry === '')))
47
63
  fail(`"bundlerPlugins" must be an array of module paths, got ${JSON.stringify(plugins)}`);
64
+ if (object.env !== undefined)
65
+ parseEnvConfig(object.env);
48
66
  const levels = object.levels;
49
67
  if (levels !== undefined && levels !== 'names' && levels !== 'imports')
50
68
  fail(`"levels" must be "names" or "imports", got ${JSON.stringify(levels)}`);
@@ -56,19 +74,138 @@ export function parseConfig(raw) {
56
74
  (!Array.isArray(laws) ||
57
75
  laws.some((entry) => typeof entry !== 'string' || entry.replace(/^!/, '') === '' || entry.startsWith('/'))))
58
76
  fail(`"laws" must be an array of project-relative globs, got ${JSON.stringify(laws)}`);
77
+ return object;
78
+ }
79
+ /**
80
+ * Validates the top level of tslaws.json: known keys only, and the run settings are integers of at least 1. `extends`
81
+ * and `projects` are accepted (a string, and a list of globs) but are not part of the result: `readConfig` has
82
+ * already acted on `extends`, and discovery reads `projects` from the file itself.
83
+ */
84
+ export function parseConfig(raw, source = 'tslaws.json') {
85
+ const object = checkFile(raw, source);
59
86
  if (object.github !== undefined)
60
87
  parseGithubConfig(object.github);
61
- return object;
88
+ const config = { ...object };
89
+ for (const key of structuralKeys)
90
+ delete config[key];
91
+ return config;
92
+ }
93
+ /**
94
+ * The settings that name a file or directory by path, rebased when inherited through `extends`: a value is written
95
+ * relative to the file that declares it (as in tsconfig), so it is rebased to the extending file. `bundlerPlugins` are
96
+ * module paths and `e2e.server.cwd` is the directory the dev server runs in. A trailing `[]` means every element of an
97
+ * array. `cover` and `laws` are not here on purpose: they are globs relative to the project that uses the config, so a
98
+ * shared base saying `"cover": ["src/**"]` means each package's own src/. `compilerOptions` and `github` hold no
99
+ * paths. Add a new file-reference option here when it is added to `configKeys`.
100
+ */
101
+ const pathFields = ['bundlerPlugins[]', 'e2e.server.cwd'];
102
+ /** `entry`, written relative to the directory `from`, as a path relative to `to`. A leading `!` and absolute paths stay. */
103
+ function rebase(entry, from, to) {
104
+ const negated = entry.startsWith('!');
105
+ const body = negated ? entry.slice(1) : entry;
106
+ const prefix = relative(to, from).replaceAll('\\', '/');
107
+ if (prefix === '' || isAbsolute(body))
108
+ return entry;
109
+ return `${negated ? '!' : ''}${posix.join(prefix, body)}`;
110
+ }
111
+ function rebaseFields(config, from, to) {
112
+ const out = { ...config };
113
+ for (const field of pathFields) {
114
+ const parts = field.split('.');
115
+ let node = out;
116
+ for (const [index, part] of parts.entries()) {
117
+ const list = part.endsWith('[]');
118
+ const key = list ? part.slice(0, -2) : part;
119
+ const value = node[key];
120
+ if (index === parts.length - 1) {
121
+ if (list && Array.isArray(value))
122
+ node[key] = value.map((entry) => (typeof entry === 'string' ? rebase(entry, from, to) : entry));
123
+ else if (!list && typeof value === 'string')
124
+ node[key] = rebase(value, from, to);
125
+ }
126
+ else if (isPlain(value)) {
127
+ node[key] = { ...value };
128
+ node = node[key];
129
+ }
130
+ else
131
+ break;
132
+ }
133
+ }
134
+ return out;
135
+ }
136
+ function isPlain(value) {
137
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
62
138
  }
139
+ /** Objects merge key by key; anything else, arrays included, is replaced. The child wins. */
140
+ function deepMerge(base, child) {
141
+ const out = { ...base };
142
+ for (const [key, value] of Object.entries(child)) {
143
+ if (key === '__proto__')
144
+ continue;
145
+ const inherited = out[key];
146
+ out[key] = isPlain(value) && isPlain(inherited) ? deepMerge(inherited, value) : value;
147
+ }
148
+ return out;
149
+ }
150
+ /**
151
+ * Loads `file` and the files it `extends`, merged, with paths relative to the directory of `file`. `chain` holds the
152
+ * files being loaded, outermost first, so a cycle or a missing file is reported with the way it was reached; every
153
+ * file read is added to `loaded`.
154
+ */
155
+ function loadMerged(file, cwd, chain, loaded) {
156
+ const shown = (path) => relative(cwd, path).replaceAll('\\', '/') || path;
157
+ const trail = [...chain, file];
158
+ let text;
159
+ try {
160
+ text = readFileSync(file, 'utf8');
161
+ }
162
+ catch {
163
+ throw new Error(`${shown(file)}: no such file (reached by extends: ${trail.map(shown).join(' -> ')})`);
164
+ }
165
+ loaded.push(file);
166
+ let json;
167
+ try {
168
+ json = JSON.parse(text);
169
+ }
170
+ catch (error) {
171
+ throw new Error(`${shown(file)}: ${error.message}`);
172
+ }
173
+ const { extends: parent, ...own } = checkFile(json, shown(file));
174
+ if (parent === undefined)
175
+ return own;
176
+ const baseFile = resolve(dirname(file), parent);
177
+ if (trail.includes(baseFile))
178
+ throw new Error(`${shown(file)}: "extends" forms a cycle (${[...trail, baseFile].map(shown).join(' -> ')})`);
179
+ const base = rebaseFields(loadMerged(baseFile, cwd, trail, loaded), dirname(baseFile), dirname(file));
180
+ // `projects` lists directories under the file that wrote it, so it is never inherited.
181
+ delete base.projects;
182
+ return deepMerge(base, own);
183
+ }
184
+ /** The settings of tslaws.json in `cwd`, with every `extends` followed; `{}` when there is no file. */
63
185
  export function readConfig(cwd) {
64
186
  const path = join(cwd, 'tslaws.json');
65
187
  if (!existsSync(path))
66
188
  return {};
67
- const config = parseConfig(JSON.parse(readFileSync(path, 'utf8')));
68
- if (config.e2e !== undefined)
69
- config.e2e = parseE2eConfig(config.e2e);
189
+ const loaded = [];
190
+ const merged = loadMerged(path, cwd, [], loaded);
191
+ let config;
192
+ try {
193
+ config = parseConfig(merged);
194
+ if (config.e2e !== undefined)
195
+ config.e2e = parseE2eConfig(config.e2e);
196
+ }
197
+ catch (error) {
198
+ if (loaded.length === 1)
199
+ throw error;
200
+ const files = loaded.map((file) => relative(cwd, file).replaceAll('\\', '/')).join(', ');
201
+ throw new Error(`${error.message} (merged from ${files})`);
202
+ }
70
203
  return config;
71
204
  }
205
+ /** The `import.meta.env` of the project's laws: `process.env`, the defaults and the `env` of tslaws.json. */
206
+ export function lawEnv(cwd, surface) {
207
+ return importMetaEnvOf(readConfig(cwd).env, surface);
208
+ }
72
209
  /** Source files matching the `cover` globs (a leading `!` excludes), minus laws files and declarations. */
73
210
  export function coverFiles(cwd, globs) {
74
211
  // Plain JavaScript sources are covered only when the project compiles them (`allowJs`).
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)
@@ -0,0 +1,28 @@
1
+ export interface Project {
2
+ /** Absolute directory of the project. */
3
+ dir: string;
4
+ /** Directory relative to the repository root, with `/` separators; '' for the root itself. */
5
+ path: string;
6
+ }
7
+ export interface DiscoverOptions {
8
+ /** Keep projects whose `path` matches one of these globs (a leading `!` excludes). */
9
+ filter?: string[];
10
+ /** Keep only projects whose `path` is exactly one of these. */
11
+ only?: string[];
12
+ }
13
+ /**
14
+ * The `packages:` list of pnpm-workspace.yaml. Only the plain shapes pnpm documents are read: a block list of
15
+ * (optionally quoted) globs, or a one-line `[a, b]`. That keeps this free of a YAML dependency.
16
+ */
17
+ export declare function pnpmPackages(text: string): string[];
18
+ /**
19
+ * Every project under `root`, sorted by path. The root itself is one only when it has a tslaws.json and either that
20
+ * file has no `projects` key (a plain single project that happens to hold others) or the root carries laws of its
21
+ * own (see `rootHasLaws`); a root whose tslaws.json only lists projects is just the list.
22
+ */
23
+ export declare function discoverProjects(root: string, opts?: DiscoverOptions): Project[];
24
+ /**
25
+ * Whether `cwd` is the root of a monorepo run: it has no tslaws.json but discovery finds projects below it, or its
26
+ * tslaws.json has a `projects` list.
27
+ */
28
+ export declare function isMonorepoRoot(cwd: string): boolean;