@mark1russell7/conventions 0.8.1 → 0.8.2

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.
@@ -1,7 +1,7 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { spawnSync } from "node:child_process";
3
- import { appendFileSync, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
4
- import { dirname, extname, join, posix, relative, resolve, sep } from "node:path";
3
+ import { appendFileSync, existsSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
4
+ import { basename, dirname, extname, join, posix, relative, resolve, sep } from "node:path";
5
5
  // src/config.ts
6
6
  /** The fields of the configuration of a rule that are not options. */
7
7
  const RULE_FIELDS = [
@@ -211,6 +211,13 @@ function packageFolders(root, globs = workspaceGlobs(root)) {
211
211
  /**
212
212
  * The shape of a rule, the facts that a rule reads (the context), and small helpers for the rules.
213
213
  */
214
+ /** This function gives `text` with the line `line` (from 1) replaced by `lines`, with the line ends of `text`. An empty `lines` removes the line. */
215
+ function replaceLine(text, line, lines) {
216
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
217
+ const all = text.split(/\r?\n/);
218
+ all.splice(line - 1, 1, ...lines);
219
+ return all.join(eol);
220
+ }
214
221
  /** The fields of `package.json` that hold dependencies. */
215
222
  const DEPENDENCY_FIELDS = [
216
223
  "dependencies",
@@ -1844,11 +1851,33 @@ function jobsOf(lines) {
1844
1851
  }
1845
1852
  const hasTopGroup = (lines) => lines.some((line) => indentOf(line) === 0 && line.startsWith("concurrency:"));
1846
1853
  /**
1854
+ * This function gives the edit that adds a concurrency group at the top of a workflow, before `jobs:`. A new run of a pull
1855
+ * request stops the old run. A run of another event waits for the old run, so that no release or scheduled run stops.
1856
+ */
1857
+ function groupEdits(file, text, lines) {
1858
+ const jobs = lines.findIndex((line) => indentOf(line) === 0 && line.startsWith("jobs:"));
1859
+ if (jobs < 0) return [];
1860
+ const pad = " ".repeat(childIndent(lines, jobs) ?? 2);
1861
+ const original = text.split(/\r?\n/)[jobs] ?? "jobs:";
1862
+ const group = [
1863
+ "concurrency:",
1864
+ pad + "group: ${{ github.workflow }}-${{ github.ref }}",
1865
+ pad + "cancel-in-progress: ${{ github.event_name == 'pull_request' }}",
1866
+ "",
1867
+ original
1868
+ ];
1869
+ return [{
1870
+ file,
1871
+ before: text,
1872
+ after: replaceLine(text, jobs + 1, group)
1873
+ }];
1874
+ }
1875
+ /**
1847
1876
  * This function gives the breaks of the concurrency groups. A workflow with no group at the top needs one in each job.
1848
1877
  * A job that calls a shared workflow of `grouped` gets its group from the jobs of that workflow. A shared workflow gets
1849
1878
  * its group from its caller, but a shared workflow of `grouped` has a group in each job.
1850
1879
  */
1851
- function concurrencyBreaks(file, lines, grouped) {
1880
+ function concurrencyBreaks(file, text, lines, grouped) {
1852
1881
  const name = file.slice(file.lastIndexOf("/") + 1);
1853
1882
  const jobs = jobsOf(lines);
1854
1883
  if (isShared(lines)) {
@@ -1860,32 +1889,55 @@ function concurrencyBreaks(file, lines, grouped) {
1860
1889
  }));
1861
1890
  }
1862
1891
  if (hasTopGroup(lines)) return [];
1863
- return jobs.filter((job) => !job.grouped && !(job.calls !== void 0 && grouped.includes(job.calls))).map((job) => ({
1892
+ const missing = jobs.filter((job) => !job.grouped && !(job.calls !== void 0 && grouped.includes(job.calls)));
1893
+ const edits = missing.length === 0 ? [] : groupEdits(file, text, lines);
1894
+ return missing.map((job) => ({
1864
1895
  file,
1865
1896
  line: job.line,
1866
- message: `${file}: the job ${job.name} has no concurrency group, and the workflow has none.`
1897
+ message: `${file}: the job ${job.name} has no concurrency group, and the workflow has none.`,
1898
+ edits
1867
1899
  }));
1868
1900
  }
1869
1901
  /** This function gives the breaks of the matrices: each `strategy` with a `matrix` has a `max-parallel` of `limit` or less. */
1870
- function matrixBreaks(file, lines, limit) {
1902
+ function matrixBreaks(file, text, lines, limit) {
1871
1903
  const breaks = [];
1904
+ const originals = text.split(/\r?\n/);
1872
1905
  lines.forEach((line, index) => {
1873
1906
  if (keyValue(line, "strategy") === void 0) return;
1874
1907
  const keyIndent = childIndent(lines, index);
1875
- const keys = lines.slice(index + 1, blockEnd(lines, index)).filter((text) => indentOf(text) === keyIndent);
1876
- if (!keys.some((text) => keyValue(text, "matrix") !== void 0)) return;
1877
- const raw = keys.map((text) => keyValue(text, "max-parallel")).find((value) => value !== void 0);
1908
+ if (keyIndent === void 0) return;
1909
+ const keys = [];
1910
+ for (let i = index + 1; i < blockEnd(lines, index); i++) if ((lines[i] ?? "").trim() !== "" && indentOf(lines[i] ?? "") === keyIndent) keys.push(i);
1911
+ if (!keys.some((i) => keyValue(lines[i] ?? "", "matrix") !== void 0)) return;
1912
+ const at = keys.find((i) => keyValue(lines[i] ?? "", "max-parallel") !== void 0);
1913
+ const raw = at === void 0 ? void 0 : keyValue(lines[at] ?? "", "max-parallel");
1878
1914
  const value = raw === void 0 ? NaN : Number(raw);
1879
- if (raw === void 0) breaks.push({
1880
- file,
1881
- line: index + 1,
1882
- message: `${file}: a matrix has no max-parallel.`
1883
- });
1884
- else if (!Number.isInteger(value) || value < 1 || value > limit) breaks.push({
1885
- file,
1886
- line: index + 1,
1887
- message: `${file}: a matrix has max-parallel ${raw}, and the most is ${String(limit)}.`
1888
- });
1915
+ const wanted = `${" ".repeat(keyIndent)}max-parallel: ${String(limit)}`;
1916
+ if (at === void 0 || raw === void 0) {
1917
+ const after = replaceLine(text, index + 1, [originals[index] ?? line, wanted]);
1918
+ breaks.push({
1919
+ file,
1920
+ line: index + 1,
1921
+ message: `${file}: a matrix has no max-parallel.`,
1922
+ edits: [{
1923
+ file,
1924
+ before: text,
1925
+ after
1926
+ }]
1927
+ });
1928
+ } else if (!Number.isInteger(value) || value < 1 || value > limit) {
1929
+ const after = replaceLine(text, at + 1, [wanted]);
1930
+ breaks.push({
1931
+ file,
1932
+ line: index + 1,
1933
+ message: `${file}: a matrix has max-parallel ${raw}, and the most is ${String(limit)}.`,
1934
+ edits: [{
1935
+ file,
1936
+ before: text,
1937
+ after
1938
+ }]
1939
+ });
1940
+ }
1889
1941
  });
1890
1942
  return breaks;
1891
1943
  }
@@ -1907,8 +1959,9 @@ function startsPerHour(field) {
1907
1959
  * This function gives the breaks of the schedules: the minute of each `cron` is the minute of the repository and the file. A
1908
1960
  * schedule that starts more than once in each hour starts at equal steps from that minute (`18,48` for each 30 minutes).
1909
1961
  */
1910
- function cronBreaks(file, lines, minute) {
1962
+ function cronBreaks(file, text, lines, minute) {
1911
1963
  const breaks = [];
1964
+ const originals = text.split(/\r?\n/);
1912
1965
  lines.forEach((line, index) => {
1913
1966
  const value = keyValue(line, "cron");
1914
1967
  if (value === void 0) return;
@@ -1916,11 +1969,18 @@ function cronBreaks(file, lines, minute) {
1916
1969
  const wanted = minuteField(minute, startsPerHour(fields[0] ?? ""));
1917
1970
  if (fields[0] === wanted) return;
1918
1971
  const expected = [wanted, ...fields.slice(1)].join(" ");
1972
+ const original = originals[index] ?? line;
1973
+ const edits = original.includes(value) ? [{
1974
+ file,
1975
+ before: text,
1976
+ after: replaceLine(text, index + 1, [original.replace(value, () => expected)])
1977
+ }] : [];
1919
1978
  breaks.push({
1920
1979
  file,
1921
1980
  line: index + 1,
1922
1981
  message: `${file}: the schedule "${value}" starts at minute ${fields[0] ?? "?"}, and the minute of this repository and file is ${String(minute)}.`,
1923
- fix: `cron: "${expected}"`
1982
+ fix: `cron: "${expected}"`,
1983
+ edits
1924
1984
  });
1925
1985
  });
1926
1986
  return breaks;
@@ -1974,13 +2034,13 @@ const runnerBudget = {
1974
2034
  continue;
1975
2035
  }
1976
2036
  const lines = text.split(/\r?\n/).map((line) => line.trimStart().startsWith("#") ? "" : line);
1977
- breaks.push(...matrixBreaks(file, lines, limit), ...concurrencyBreaks(file, lines, grouped));
2037
+ breaks.push(...matrixBreaks(file, text, lines, limit), ...concurrencyBreaks(file, text, lines, grouped));
1978
2038
  if (options["minute"] !== false) {
1979
2039
  if (lines.some((line) => keyValue(line, "cron") !== void 0) && repository === void 0) breaks.push({
1980
2040
  file,
1981
2041
  message: `${file} has a schedule, and the rule cannot find the repository (GITHUB_REPOSITORY, or a GitHub URL of the remote origin).`
1982
2042
  });
1983
- else if (repository !== void 0) breaks.push(...cronBreaks(file, lines, scheduleMinute(repository, file)));
2043
+ else if (repository !== void 0) breaks.push(...cronBreaks(file, text, lines, scheduleMinute(repository, file)));
1984
2044
  }
1985
2045
  }
1986
2046
  return breaks;
@@ -2121,46 +2181,6 @@ const sourceMain = {
2121
2181
  return breaks;
2122
2182
  }
2123
2183
  };
2124
- // src/rules/tests-required.ts
2125
- /**
2126
- * The rule `tests-required`: no test runner passes when it finds no test (`passWithNoTests`).
2127
- */
2128
- /** The files that set the options of a test runner: its configs, and package.json for the scripts. */
2129
- const RUNNER_FILE = /(?:^|\/)(?:(?:vitest|vite|jest|playwright)(?:\.[\w-]+)*\.config\.[cm]?[jt]s|vitest\.workspace\.[cm]?[jt]s|package\.json)$/;
2130
- /** The option in a config (`passWithNoTests: true`) or on a command line (`--passWithNoTests`, `--pass-with-no-tests`). */
2131
- const PASS_WITH_NO_TESTS = /passWithNoTests\s*:\s*true|--passWithNoTests(?!=false)|--pass-with-no-tests(?!=false)/;
2132
- const testsRequired = {
2133
- id: "tests-required",
2134
- title: "No test runner passes when it finds no test: no `passWithNoTests: true` in a config, and no `--passWithNoTests` in a script.",
2135
- reason: "With the option, a test step that finds 0 tests passes. A broken include pattern, a moved folder or a renamed file then turns the gate green with no test run. In the fleet audit of 2026-10-30, vex had the option in all 9 vitest configs and client in 2 packages that have tests.",
2136
- fix: "Remove the option. A package with no tests has no test script, so the shared CI skips it. A package whose tests a later change adds keeps no test script until then.",
2137
- sources: [{
2138
- repo: "fleet",
2139
- rule: "fail-closed",
2140
- doc: "docs/STRATEGY.md (2026-10-30, gates and probes fail closed)"
2141
- }],
2142
- options: {},
2143
- check(context) {
2144
- const files = context.gitFiles();
2145
- if (files === void 0) return { skipped: "the root is not in a git repository" };
2146
- const breaks = [];
2147
- for (const file of files.filter((path) => RUNNER_FILE.test(path)).sort(byCode)) {
2148
- let text;
2149
- try {
2150
- text = readFileSync(join(context.root, file), "utf8");
2151
- } catch {
2152
- continue;
2153
- }
2154
- const index = text.split(/\r?\n/).findIndex((line) => PASS_WITH_NO_TESTS.test(line));
2155
- if (index >= 0) breaks.push({
2156
- file,
2157
- line: index + 1,
2158
- message: `${file} lets the tests pass when they find no test (passWithNoTests).`
2159
- });
2160
- }
2161
- return breaks;
2162
- }
2163
- };
2164
2184
  // src/rules/tsconfig-test.ts
2165
2185
  /**
2166
2186
  * The rule `tsconfig-test`: each TypeScript package has a `tsconfig.test.json`, and its typecheck
@@ -2268,6 +2288,79 @@ const tsconfigTest = {
2268
2288
  return breaks;
2269
2289
  }
2270
2290
  };
2291
+ // src/rules/tests-required.ts
2292
+ /**
2293
+ * The rule `tests-required`: no test runner passes when it finds no test (`passWithNoTests`).
2294
+ */
2295
+ /** The files that set the options of a test runner: its configs, and package.json for the scripts. */
2296
+ const RUNNER_FILE = /(?:^|\/)(?:(?:vitest|vite|jest|playwright)(?:\.[\w-]+)*\.config\.[cm]?[jt]s|vitest\.workspace\.[cm]?[jt]s|package\.json)$/;
2297
+ /** The option in a config (`passWithNoTests: true`) or on a command line (`--passWithNoTests`, `--pass-with-no-tests`). */
2298
+ const PASS_WITH_NO_TESTS = /passWithNoTests\s*:\s*true|--passWithNoTests(?!=false)|--pass-with-no-tests(?!=false)/;
2299
+ /** A line that holds only the option in a config. `conventions fix` removes such a line. */
2300
+ const OPTION_LINE = /^\s*passWithNoTests\s*:\s*true\s*,?\s*$/;
2301
+ /** The option in a line of a config with more keys. The first form has the comma after it, and the second form has the comma before it. */
2302
+ const OPTION_IN_LINE = [/\bpassWithNoTests\s*:\s*true\s*,\s*/, /,?\s*\bpassWithNoTests\s*:\s*true\b/];
2303
+ /** The option on a command line, with the space before it. */
2304
+ const FLAG = / --(?:passWithNoTests|pass-with-no-tests)(?:=true)?(?=\s|"|$)/g;
2305
+ /** This function gives the folder of the package that holds `file`: the longest folder of a package that starts its path. */
2306
+ function packageOf(context, file) {
2307
+ let best = "";
2308
+ for (const info of context.packages) if (info.folder !== "" && file.startsWith(`${info.folder}/`) && info.folder.length > best.length) best = info.folder;
2309
+ return best;
2310
+ }
2311
+ /**
2312
+ * This function gives the edit that removes the option from one line, or no edit. The edit exists only when the package has
2313
+ * test files: then the test step still finds tests. A package with no tests needs a person, who removes its test script.
2314
+ */
2315
+ function removeOption(context, files, file, text, index) {
2316
+ if (!hasTests(files, packageOf(context, file))) return [];
2317
+ const line = text.split(/\r?\n/)[index] ?? "";
2318
+ if (OPTION_LINE.test(line)) return [{
2319
+ file,
2320
+ before: text,
2321
+ after: replaceLine(text, index + 1, [])
2322
+ }];
2323
+ const form = OPTION_IN_LINE.find((pattern) => pattern.test(line));
2324
+ const without = file.endsWith("package.json") ? line.replace(FLAG, "") : form === void 0 ? line : line.replace(form, "");
2325
+ return without === line ? [] : [{
2326
+ file,
2327
+ before: text,
2328
+ after: replaceLine(text, index + 1, [without])
2329
+ }];
2330
+ }
2331
+ const testsRequired = {
2332
+ id: "tests-required",
2333
+ title: "No test runner passes when it finds no test: no `passWithNoTests: true` in a config, and no `--passWithNoTests` in a script.",
2334
+ reason: "With the option, a test step that finds 0 tests passes. A broken include pattern, a moved folder or a renamed file then turns the gate green with no test run. In the fleet audit of 2026-10-30, vex had the option in all 9 vitest configs and client in 2 packages that have tests.",
2335
+ fix: "Remove the option. A package with no tests has no test script, so the shared CI skips it. A package whose tests a later change adds keeps no test script until then.",
2336
+ sources: [{
2337
+ repo: "fleet",
2338
+ rule: "fail-closed",
2339
+ doc: "docs/STRATEGY.md (2026-10-30, gates and probes fail closed)"
2340
+ }],
2341
+ options: {},
2342
+ check(context) {
2343
+ const files = context.gitFiles();
2344
+ if (files === void 0) return { skipped: "the root is not in a git repository" };
2345
+ const breaks = [];
2346
+ for (const file of files.filter((path) => RUNNER_FILE.test(path)).sort(byCode)) {
2347
+ let text;
2348
+ try {
2349
+ text = readFileSync(join(context.root, file), "utf8");
2350
+ } catch {
2351
+ continue;
2352
+ }
2353
+ const index = text.split(/\r?\n/).findIndex((line) => PASS_WITH_NO_TESTS.test(line));
2354
+ if (index >= 0) breaks.push({
2355
+ file,
2356
+ line: index + 1,
2357
+ message: `${file} lets the tests pass when they find no test (passWithNoTests).`,
2358
+ edits: removeOption(context, files, file, text, index)
2359
+ });
2360
+ }
2361
+ return breaks;
2362
+ }
2363
+ };
2271
2364
  // src/rules/typed-files.ts
2272
2365
  /**
2273
2366
  * The rule `typed-files`: each TypeScript file that git keeps is in a tsconfig that a `typecheck`
@@ -2391,6 +2484,65 @@ function referencesOf(config) {
2391
2484
  if (!Array.isArray(references)) return [];
2392
2485
  return references.flatMap((item) => typeof item === "object" && item !== null && typeof item.path === "string" ? [resolve(dirname(config), item.path)] : []);
2393
2486
  }
2487
+ /** A config file of a tool (`vitest.config.ts`), with its extension. */
2488
+ const CONFIG_FILE = /\.config(\.[cm]?ts)$/;
2489
+ /** A `rootDir` that is the folder of the tsconfig, so that the config files at the root are in it. */
2490
+ const ROOT_DIRS = /* @__PURE__ */ new Set([
2491
+ ".",
2492
+ "./",
2493
+ "${configDir}",
2494
+ "${configDir}/"
2495
+ ]);
2496
+ /**
2497
+ * This function gives the edit that adds the config files at the root of a package to its `tsconfig.test.json`. It adds
2498
+ * the include `*.config.ts`. When the `rootDir` is a subfolder, it sets `rootDir: "."`. The edit changes only these
2499
+ * values and keeps the format of the file. It gives no edit for a tsconfig with comments, so that no comment goes. It
2500
+ * also gives no edit when the changed text does not parse as the intended config.
2501
+ */
2502
+ function configEdit(root, tsconfig, extension) {
2503
+ const text = readFileSync(tsconfig, "utf8");
2504
+ let json;
2505
+ try {
2506
+ json = JSON.parse(text);
2507
+ } catch {
2508
+ return [];
2509
+ }
2510
+ const globs = json.include;
2511
+ if (!Array.isArray(globs)) return [];
2512
+ const glob = `${globs.length > 0 && globs.every((glob) => typeof glob === "string" && glob.startsWith("${configDir}/")) ? "${configDir}/" : ""}*.config${extension}`;
2513
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
2514
+ let after = text;
2515
+ if (!globs.includes(glob)) after = after.replace(/("include"\s*:\s*\[)([^\]]*)\]/, (_all, start, items) => {
2516
+ const kept = items.replace(/\s+$/, "");
2517
+ const end = items.slice(kept.length);
2518
+ if (kept.trim() === "") return `${start}${JSON.stringify(glob)}]`;
2519
+ const indent = kept.includes("\n") ? /\n([ \t]*)[^\n]*$/.exec(kept)?.[1] ?? "" : void 0;
2520
+ return `${start}${kept},${indent === void 0 ? " " : `${eol}${indent}`}${JSON.stringify(glob)}${end}]`;
2521
+ });
2522
+ const rootDir = json.compilerOptions?.["rootDir"];
2523
+ const moveRoot = typeof rootDir === "string" && !ROOT_DIRS.has(rootDir);
2524
+ if (moveRoot) after = after.replace(/("rootDir"\s*:\s*)"(?:[^"\\]|\\.)*"/, "$1\".\"");
2525
+ const intended = {
2526
+ ...json,
2527
+ ...moveRoot ? { compilerOptions: {
2528
+ ...json.compilerOptions,
2529
+ rootDir: "."
2530
+ } } : {},
2531
+ include: globs.includes(glob) ? globs : [...globs, glob]
2532
+ };
2533
+ let parsed;
2534
+ try {
2535
+ parsed = JSON.parse(after);
2536
+ } catch {
2537
+ return [];
2538
+ }
2539
+ if (JSON.stringify(parsed) !== JSON.stringify(intended)) return [];
2540
+ return after === text ? [] : [{
2541
+ file: fromRoot(root, tsconfig),
2542
+ before: text,
2543
+ after
2544
+ }];
2545
+ }
2394
2546
  /** The path of `file` relative to `root`, with `/`. */
2395
2547
  const fromRoot = (root, file) => relative(root, file).split("\\").join("/");
2396
2548
  const typedFiles = {
@@ -2421,6 +2573,7 @@ const typedFiles = {
2421
2573
  }];
2422
2574
  const breaks = [];
2423
2575
  const queue = [];
2576
+ const testConfigs = /* @__PURE__ */ new Map();
2424
2577
  const packages = [context.rootPackage, ...codePackages(context).filter((info) => info !== context.rootPackage)];
2425
2578
  for (const info of packages) {
2426
2579
  const scripts = info.manifest["scripts"];
@@ -2438,6 +2591,7 @@ const typedFiles = {
2438
2591
  continue;
2439
2592
  }
2440
2593
  queue.push(path);
2594
+ if (basename(path) === "tsconfig.test.json" && resolve(dirname(path)) === resolve(info.dir)) testConfigs.set(info.folder, path);
2441
2595
  }
2442
2596
  }
2443
2597
  const extra = Array.isArray(options["configs"]) ? options["configs"] : [];
@@ -2472,10 +2626,18 @@ const typedFiles = {
2472
2626
  message: "No typecheck script names a tsconfig, so no TypeScript file has a type check.",
2473
2627
  fix: "Add a script typecheck (`tsc -p tsconfig.json`) to each package."
2474
2628
  });
2475
- for (const file of files) if (!covered.has(file)) breaks.push({
2476
- file,
2477
- message: `${file} is in no tsconfig that a typecheck script examines.`
2478
- });
2629
+ for (const file of files) {
2630
+ if (covered.has(file)) continue;
2631
+ const folder = file.includes("/") ? file.slice(0, file.lastIndexOf("/")) : "";
2632
+ const extension = CONFIG_FILE.exec(file)?.[1];
2633
+ const tsconfig = testConfigs.get(folder);
2634
+ const edits = extension === void 0 || tsconfig === void 0 ? [] : configEdit(context.root, tsconfig, extension);
2635
+ breaks.push({
2636
+ file,
2637
+ message: `${file} is in no tsconfig that a typecheck script examines.`,
2638
+ edits
2639
+ });
2640
+ }
2479
2641
  return breaks;
2480
2642
  }
2481
2643
  };
@@ -2667,8 +2829,8 @@ const RULES = [
2667
2829
  ];
2668
2830
  // src/run.ts
2669
2831
  /**
2670
- * The commands `check` and `--list` of the bin `conventions`, as functions. `runChecks` starts the
2671
- * rules, and `runCli` reads the arguments and writes the result.
2832
+ * The commands `check`, `fix` and `--list` of the bin `conventions`, as functions. `runChecks` starts the
2833
+ * rules, `runFix` writes the edits of the breaks, and `runCli` reads the arguments and writes the result.
2672
2834
  */
2673
2835
  /** This function reads a `package.json` file. */
2674
2836
  function readPackage(root, dir) {
@@ -2784,6 +2946,51 @@ function runChecks(options) {
2784
2946
  failed: results.some((result) => result.status === "break" || result.status === "error")
2785
2947
  };
2786
2948
  }
2949
+ /** The most checks of `runFix`. Each check writes at most one edit of each file. */
2950
+ const MAX_PASSES = 20;
2951
+ /**
2952
+ * This function writes the edits of the breaks, and checks again, until no edit applies. In each pass it writes the first
2953
+ * edit of each file whose `before` is the current text of the file. The other edits of that file wait for the next check,
2954
+ * which gives them again from the new text. Thus a fix does not write over a change that it did not see.
2955
+ */
2956
+ function runFix(options) {
2957
+ const root = resolve(options.root);
2958
+ const changed = [];
2959
+ let result = runChecks(options);
2960
+ let passes = 1;
2961
+ while (passes < MAX_PASSES) {
2962
+ const written = /* @__PURE__ */ new Set();
2963
+ for (const rule of result.rules) for (const edit of rule.breaks.flatMap((item) => item.edits ?? [])) {
2964
+ if (written.has(edit.file)) continue;
2965
+ const path = join(root, edit.file);
2966
+ if (!existsSync(path) || readFileSync(path, "utf8") !== edit.before) continue;
2967
+ writeFileSync(path, edit.after);
2968
+ written.add(edit.file);
2969
+ if (!changed.includes(edit.file)) changed.push(edit.file);
2970
+ }
2971
+ if (written.size === 0) break;
2972
+ result = runChecks(options);
2973
+ passes += 1;
2974
+ }
2975
+ return {
2976
+ changed,
2977
+ passes,
2978
+ result
2979
+ };
2980
+ }
2981
+ /** This function gives a result for JSON: each break without the texts of its edits, and with `fixable`. */
2982
+ function withoutEdits(result) {
2983
+ return {
2984
+ ...result,
2985
+ rules: result.rules.map((rule) => ({
2986
+ ...rule,
2987
+ breaks: rule.breaks.map(({ edits, ...item }) => ({
2988
+ ...item,
2989
+ fixable: (edits ?? []).length > 0
2990
+ }))
2991
+ }))
2992
+ };
2993
+ }
2787
2994
  /** The most breaks of one rule in the text output. The JSON output has each break. */
2788
2995
  const MAX_SHOWN = 50;
2789
2996
  /** This function gives the place of a break as `file:line`. */
@@ -2804,7 +3011,7 @@ function formatResult(result) {
2804
3011
  const extra = rule.ignored > 0 ? ` (${rule.ignored} ignored: ${rule.note ?? ""})` : rule.note !== void 0 && rule.status !== "pass" ? ` (${rule.note})` : "";
2805
3012
  out.push(`${label[rule.status]} ${rule.id}${rule.breaks.length > 0 ? `: ${rule.breaks.length} break(s)` : ""}${extra}`);
2806
3013
  for (const item of rule.breaks.slice(0, MAX_SHOWN)) {
2807
- out.push(` ${placeOf(item)} ${item.message}`);
3014
+ out.push(` ${placeOf(item)} ${item.message}${(item.edits ?? []).length > 0 ? " (conventions fix writes the fix)" : ""}`);
2808
3015
  if (item.fix !== void 0) out.push(` fix: ${item.fix}`);
2809
3016
  }
2810
3017
  if (rule.breaks.length > MAX_SHOWN) out.push(` ... ${rule.breaks.length - MAX_SHOWN} more. Start \`conventions check --json\` for each break.`);
@@ -2868,9 +3075,11 @@ function listRules(config, rules = RULES) {
2868
3075
  }
2869
3076
  /** The help text of the bin. */
2870
3077
  const USAGE = `Usage: conventions check [options]
3078
+ conventions fix [options]
2871
3079
  conventions --list
2872
3080
 
2873
3081
  check Start each rule. Exit code 1 when a rule has a break.
3082
+ fix Write the fixes of the breaks that have one, and check again. Exit code 1 when a break stays.
2874
3083
  --list Show each rule: why, fix, options, state and the audit rows that it comes from.
2875
3084
 
2876
3085
  --root <folder> The root of the repository. The default is the current folder.
@@ -2891,6 +3100,7 @@ var UsageError = class extends Error {};
2891
3100
  /** This function starts the bin with the arguments `args`, and gives its exit code. */
2892
3101
  function runCli(args, io) {
2893
3102
  let check = false;
3103
+ let fix = false;
2894
3104
  let list = false;
2895
3105
  let json = false;
2896
3106
  let root = io.cwd;
@@ -2905,6 +3115,7 @@ function runCli(args, io) {
2905
3115
  return next;
2906
3116
  };
2907
3117
  if (arg === "check") check = true;
3118
+ else if (arg === "fix") fix = true;
2908
3119
  else if (arg === "--list" || arg === "list") list = true;
2909
3120
  else if (arg === "--json") json = true;
2910
3121
  else if (arg === "--root") root = resolve(io.cwd, value());
@@ -2915,7 +3126,7 @@ function runCli(args, io) {
2915
3126
  return 0;
2916
3127
  } else throw new UsageError(`An unknown argument: ${arg}`);
2917
3128
  }
2918
- if (!check && !list) throw new UsageError("Give the command check, or --list.");
3129
+ if (!check && !fix && !list) throw new UsageError("Give the command check or fix, or --list.");
2919
3130
  } catch (error) {
2920
3131
  if (!(error instanceof UsageError)) throw error;
2921
3132
  io.stderr(`conventions: ${error.message}\n\n${USAGE}`);
@@ -2933,18 +3144,32 @@ function runCli(args, io) {
2933
3144
  return 0;
2934
3145
  }
2935
3146
  let result;
3147
+ let fixed;
2936
3148
  try {
2937
- result = runChecks({
3149
+ const options = {
2938
3150
  root,
2939
3151
  only,
2940
3152
  env: io.env,
2941
3153
  ...base === void 0 ? {} : { base }
2942
- });
3154
+ };
3155
+ if (fix) {
3156
+ fixed = runFix(options);
3157
+ result = fixed.result;
3158
+ } else result = runChecks(options);
2943
3159
  } catch (error) {
2944
3160
  io.stderr(`conventions: ${error instanceof Error ? error.message : String(error)}\n`);
2945
3161
  return 1;
2946
3162
  }
2947
- if (json) io.stdout(`${JSON.stringify(result, null, 2)}\n`);
3163
+ if (fixed !== void 0 && !json) {
3164
+ const files = fixed.changed.map((file) => ` ${file}\n`).join("");
3165
+ io.stdout(fixed.changed.length === 0 ? "conventions fix: no break has a fix that applies.\n" : `conventions fix: changed ${fixed.changed.length} file(s) in ${fixed.passes} check(s):\n${files}\n`);
3166
+ }
3167
+ const shown = fixed === void 0 ? withoutEdits(result) : {
3168
+ changed: fixed.changed,
3169
+ passes: fixed.passes,
3170
+ ...withoutEdits(result)
3171
+ };
3172
+ if (json) io.stdout(`${JSON.stringify(shown, null, 2)}\n`);
2948
3173
  else {
2949
3174
  if (io.env["GITHUB_ACTIONS"] === "true") io.stdout(annotations(result));
2950
3175
  io.stdout(formatResult(result));
@@ -2953,6 +3178,6 @@ function runCli(args, io) {
2953
3178
  if (summary) appendFileSync(summary, summaryMarkdown(result));
2954
3179
  return result.failed ? 1 : 0;
2955
3180
  }
2956
- export { workspaceGlobs as $, isPinned as A, codePackages as B, runnerBudget as C, requiredScripts as D, roadmapParses as E, noBuildOutput as F, matchesAny as G, inFolder as H, STRICT_OPTIONS as I, runGit as J, parseJsonc as K, cuePreset as L, DEFAULT_ALLOWED as M, HOME_PATTERNS as N, releaseFiles as O, noLocalPaths as P, packageFolders as Q, DEPENDENCY_FIELDS as R, repositoryOfRemote as S, roadmapOfLine as T, keyLine as U, hasFile as V, lineOf as W, globFolders as X, specifiersOf as Y, globToRegExp as Z, tsconfigTest as _, listRules as a, pathsOf as b, runCli as c, workspaceProtocol as d, defaultOptions as et, typedScripts as f, hasTests as g, typedFiles as h, formatResult as i, pinnedGitDeps as j, isGitSpecifier as k, summaryMarkdown as l, scriptsOf as m, annotations as n, readConfig as o, configsOfScript as p, readJsonc as q, createContext as r, runChecks as s, USAGE as t, parseConfig as tt, RULES as u, testsRequired as v, scheduleMinute as w, sourceMain as x, isSourcePath as y, cleanPath as z };
3181
+ export { globToRegExp as $, isGitSpecifier as A, cleanPath as B, repositoryOfRemote as C, roadmapParses as D, roadmapOfLine as E, noLocalPaths as F, lineOf as G, hasFile as H, noBuildOutput as I, readJsonc as J, matchesAny as K, STRICT_OPTIONS as L, pinnedGitDeps as M, DEFAULT_ALLOWED as N, requiredScripts as O, HOME_PATTERNS as P, globFolders as Q, cuePreset as R, sourceMain as S, scheduleMinute as T, inFolder as U, codePackages as V, keyLine as W, runGit as X, replaceLine as Y, specifiersOf as Z, testsRequired as _, listRules as a, isSourcePath as b, runCli as c, RULES as d, packageFolders as et, workspaceProtocol as f, typedFiles as g, scriptsOf as h, formatResult as i, isPinned as j, releaseFiles as k, runFix as l, configsOfScript as m, annotations as n, defaultOptions as nt, readConfig as o, typedScripts as p, parseJsonc as q, createContext as r, parseConfig as rt, runChecks as s, USAGE as t, workspaceGlobs as tt, summaryMarkdown as u, hasTests as v, runnerBudget as w, pathsOf as x, tsconfigTest as y, DEPENDENCY_FIELDS as z };
2957
3182
 
2958
- //# sourceMappingURL=run-B7ftggFF.js.map
3183
+ //# sourceMappingURL=run-DD72yQn7.js.map