paperlint 18.4.0 → 18.4.1

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.
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Which papers a path given to `paperlint lint` reaches (#582). One owner for the question, so the
3
+ * claimed scope, the papers' own settings and the record checks cannot disagree about it.
4
+ *
5
+ * The rule, every case of which is a row in `paper-dirs.test.ts`:
6
+ * - a paper is a folder with `paper.tex` or `PIPELINE-STATUS.md` at its top. `paperlint.json` alone
7
+ * is the project's settings, not a paper;
8
+ * - a path inside a paper (the paper itself, a review card, its `reviews/`) reaches the nearest
9
+ * paper at or above it, looking only up, so a snapshot kept beside the card never stands in for
10
+ * the paper the card belongs to;
11
+ * - any other folder (the project root, a papers directory, an archive) reaches the papers below
12
+ * it, at any depth; the walk stops at each paper, so a copy kept inside one is never a paper;
13
+ * - nothing under a folder named `extra/` is a paper, the same reach as lint's own ignore.
14
+ */
15
+ import { unique } from "remeda";
16
+ import { dirname, join, sep } from "node:path";
17
+ import { STATUS_FILE } from "./paper-folder.ts";
18
+ import { ESCAPE_HATCH } from "./paper-layout.ts";
19
+ import { MAIN_FILE } from "./paper-sources.ts";
20
+ import { absolutePath } from "./paths.ts";
21
+ import type { IsFile } from "./paper-folder.ts";
22
+
23
+ /** The two questions the rule asks of the disk. */
24
+ export interface PaperTree extends IsFile {
25
+ /** The folders a walk enters below `dir`: not hidden, not installed packages, not `extra/`. */
26
+ subfolders(dir: string): readonly string[];
27
+ }
28
+
29
+ /** The files that make a folder a paper. */
30
+ export const PAPER_MARKERS: readonly string[] = [MAIN_FILE, STATUS_FILE];
31
+
32
+ const underExtra = (dir: string): boolean =>
33
+ dir.split(sep).includes(ESCAPE_HATCH);
34
+
35
+ export const isPaper = (dir: string, tree: IsFile): boolean =>
36
+ !underExtra(dir) &&
37
+ PAPER_MARKERS.some((m) => tree.isFile(absolutePath(join(dir, m))));
38
+
39
+ /** The nearest paper at or above `dir`; null when there is none. */
40
+ export const paperOwning = (dir: string, tree: IsFile): string | null => {
41
+ if (isPaper(dir, tree)) return dir;
42
+ const parent = dirname(dir);
43
+ return parent === dir ? null : paperOwning(parent, tree);
44
+ };
45
+
46
+ /** The papers below `dir`, at any depth, not looking inside any paper it finds. */
47
+ export const papersBelow = (dir: string, tree: PaperTree): readonly string[] =>
48
+ tree
49
+ .subfolders(dir)
50
+ .flatMap((d) => (isPaper(d, tree) ? [d] : papersBelow(d, tree)));
51
+
52
+ /** The papers the absolute folders `dirs` reach, each once, in the order they were reached. */
53
+ export const papersReached = (
54
+ dirs: readonly string[],
55
+ tree: PaperTree,
56
+ ): readonly string[] =>
57
+ unique(
58
+ dirs.flatMap((d) => {
59
+ const owner = paperOwning(d, tree);
60
+ return owner === null ? papersBelow(d, tree) : [owner];
61
+ }),
62
+ );
@@ -842,7 +842,8 @@ describe("paperlint lint — a scaffolded paper has no layout finding", () => {
842
842
 
843
843
  describe("paperlint lint — extra/ is never read", () => {
844
844
  // An archived snapshot of an older paper carries every marker a paper does. Under extra/ it is
845
- // spillover the layout promises never to judge; anywhere else its folder reads as a paper root.
845
+ // spillover the layout promises never to judge; anywhere else inside the paper it is a copy, and
846
+ // lint claims only the paper's own files (#582).
846
847
  const SNAPSHOT = (dir: string) => ({
847
848
  [`${dir}/PIPELINE-STATUS.md`]: "# Pipeline status\n",
848
849
  [`${dir}/notes.txt`]: "x\n",
@@ -853,8 +854,13 @@ describe("paperlint lint — extra/ is never read", () => {
853
854
  expect(ids).toEqual(["pdf/measured", "paper/sources-fresh"]);
854
855
  });
855
856
 
856
- it("the same snapshot outside extra/ is reported, so the test above can fail", async () => {
857
+ it("the same snapshot elsewhere in the paper is a copy, not a paper: no rule reads it either (#582)", async () => {
857
858
  const { ids } = await lintScaffold(SNAPSHOT("research/old-2025"));
859
+ expect(ids).toEqual(["pdf/measured", "paper/sources-fresh"]);
860
+ });
861
+
862
+ it("a stray file at the paper's own top level is reported, so the two tests above can fail", async () => {
863
+ const { ids } = await lintScaffold({ "notes.txt": "x\n" });
858
864
  expect(ids).toContain("paper/allowed-files-only");
859
865
  });
860
866
  });
@@ -25,15 +25,103 @@ import {
25
25
  narrowToOwners,
26
26
  ownedPatterns,
27
27
  ownedScopes,
28
+ paperFiles,
29
+ papersScope,
30
+ rebaseGlob,
28
31
  ruleOwners,
29
32
  scopeToOwned,
30
33
  } from "./paper-files.ts";
34
+ import { FRAGMENT_FILES } from "./paper-includes.ts";
35
+
31
36
  import { lintReport } from "../test/lint-report.ts";
32
37
  import { z } from "zod";
33
38
 
34
39
  /** What `calculateConfigForFile` answers for a file inside the config's scope, read for its rules. */
35
40
  const Computed = z.object({ rules: z.record(z.string(), z.unknown()) });
36
41
 
42
+ describe("the papers the config claims (#582)", () => {
43
+ it("🔴 GUARD: with papers named, every file a block of paperlint's own claims is one of theirs", () => {
44
+ // A block written the old way, `**/paper.tex`, would claim a copy of a paper kept inside it (a
45
+ // review snapshot, a build copy) as a paper of its own. The fragment block is scoped per paper
46
+ // by name instead (includeBlocks), so its glob is not a paper's.
47
+ const claimed = ownedPatterns(
48
+ buildConfig(
49
+ {},
50
+ texLanguage,
51
+ papersScope(["/w/papers/p", "/w/papers/q"], "/w"),
52
+ ),
53
+ ).filter((g) => !FRAGMENT_FILES.includes(g));
54
+ expect(
55
+ claimed.filter(
56
+ (g) => !g.startsWith("papers/p/") && !g.startsWith("papers/q/"),
57
+ ),
58
+ ).toEqual([]);
59
+ expect(claimed).toContain("papers/q/paper.tex");
60
+ });
61
+
62
+ it("names each paper relative to ESLint's cwd, glob characters escaped, and puts its files under it", () => {
63
+ const scope = papersScope(
64
+ ["/w/papers/p", "/w/papers/[draft] x*", "/w"],
65
+ "/w",
66
+ );
67
+ expect(paperFiles(scope, "reviews/*.md")).toEqual([
68
+ "papers/p/reviews/*.md",
69
+ "papers/\\[draft\\] x\\*/reviews/*.md",
70
+ "reviews/*.md",
71
+ ]);
72
+ expect(paperFiles({ kind: "any" }, "paper.tex")).toEqual(["**/paper.tex"]);
73
+ });
74
+ });
75
+
76
+ describe("a paper's own settings read from its folder (#582)", () => {
77
+ it.each([
78
+ ["the same folder", "papers/a/paper.tex", "/w", ["papers/a/paper.tex"]],
79
+ [
80
+ "a paper's own folder",
81
+ "papers/a/paper.tex",
82
+ "/w/papers/a",
83
+ ["paper.tex"],
84
+ ],
85
+ ["another paper's folder", "papers/a/paper.tex", "/w/papers/b", []],
86
+ ["a folder above cwd", "papers/a/paper.tex", "/", ["w/papers/a/paper.tex"]],
87
+ [
88
+ "any folder",
89
+ "**/siblings/README.md",
90
+ "/w/papers/a",
91
+ ["**/siblings/README.md"],
92
+ ],
93
+ ])(
94
+ "rebases a cwd-relative glob onto a block's basePath: %s",
95
+ (_, glob, base, want) => {
96
+ expect(rebaseGlob(glob, "/w", base)).toEqual(want);
97
+ },
98
+ );
99
+
100
+ it("a paper's own block gets its paper's files, relative to its folder, and none of another paper's", () => {
101
+ const own = buildConfig(
102
+ {},
103
+ texLanguage,
104
+ papersScope(["/w/papers/a"], "/w"),
105
+ );
106
+ const scope = papersScope(["/w/papers/a"], "/w");
107
+ const block = (basePath: string) =>
108
+ narrowToOwners(
109
+ { basePath, rules: { "paper/stages": "warn" } },
110
+ ruleOwners(own),
111
+ scope,
112
+ );
113
+ expect(block("/w/papers/a")).toEqual([
114
+ {
115
+ basePath: "/w/papers/a",
116
+ files: ["PIPELINE-STATUS.md"],
117
+ rules: { "paper/stages": "warn" },
118
+ },
119
+ ]);
120
+ // ESLint refuses an empty `files`, so a block that can reach no claimed file is not emitted.
121
+ expect(block("/w/papers/b")).toEqual([]);
122
+ });
123
+ });
124
+
37
125
  const dirs: string[] = [];
38
126
  afterEach(() => {
39
127
  for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
@@ -40,8 +40,71 @@
40
40
  * - later global-ignore patterns win, across blocks, in config order;
41
41
  * - `files: [["a", "b"]]` matches a file only when BOTH patterns match.
42
42
  */
43
+ import { relative, sep } from "node:path";
43
44
  import type { ConfigBlock, RuleBlock, RuleEntry } from "./rules-config.ts";
44
45
 
46
+ /**
47
+ * Which papers' own files paperlint's blocks claim. `any` is the config's SHAPE, for the rule list and
48
+ * the docs: a file in any folder. `papers` is what `paperlint lint` runs on: the real papers, as glob
49
+ * prefixes relative to ESLint's `cwd` ("" for `cwd` itself), so a copy of a paper kept inside one (a
50
+ * review snapshot, a build copy) is claimed by no block (#582).
51
+ */
52
+ export type PaperScope =
53
+ | { readonly kind: "any" }
54
+ | {
55
+ readonly kind: "papers";
56
+ readonly cwd: string;
57
+ readonly prefixes: readonly string[];
58
+ };
59
+
60
+ export const ANY_PAPER: PaperScope = { kind: "any" };
61
+
62
+ /** The characters a glob reads as syntax, escaped so a folder's name matches only itself. Pure. */
63
+ const literalGlob = (path: string): string =>
64
+ path.replace(/[\\*?[\]{}()!+@]/gu, "\\$&");
65
+
66
+ /** `to` relative to `from`, `/`-separated. Pure. */
67
+ const posixRelative = (from: string, to: string): string =>
68
+ relative(from, to).split(sep).join("/");
69
+
70
+ /** The papers `dirs` under ESLint's `cwd`: the scope `paperlint lint` lints. Pure. */
71
+ export const papersScope = (
72
+ dirs: readonly string[],
73
+ cwd: string,
74
+ ): PaperScope => ({
75
+ kind: "papers",
76
+ cwd,
77
+ prefixes: dirs.map((d) => literalGlob(posixRelative(cwd, d))),
78
+ });
79
+
80
+ /** A glob of a paper's own file (`paper.tex`, `reviews/*.md`) in each paper of `scope`. Pure. */
81
+ export const paperFiles = (
82
+ scope: PaperScope,
83
+ glob: string,
84
+ ): readonly string[] =>
85
+ scope.kind === "any"
86
+ ? [`**/${glob}`]
87
+ : scope.prefixes.map((p) => (p === "" ? glob : `${p}/${glob}`));
88
+
89
+ /**
90
+ * A glob relative to `cwd`, as the block whose `basePath` is `base` must write it — ESLint reads a
91
+ * block's patterns from its `basePath`, and a paper's own settings carry the paper's folder. None
92
+ * when the glob names files outside `base`: that block can never reach them. A glob that starts with
93
+ * `**` matches at any depth and is kept as it is. Pure.
94
+ */
95
+ export const rebaseGlob = (
96
+ glob: string,
97
+ cwd: string,
98
+ base: string,
99
+ ): readonly string[] => {
100
+ if (glob.startsWith("**")) return [glob];
101
+ const up = posixRelative(base, cwd);
102
+ if (!up.startsWith(".."))
103
+ return [up === "" ? glob : `${literalGlob(up)}/${glob}`];
104
+ const down = `${literalGlob(posixRelative(cwd, base))}/`;
105
+ return glob.startsWith(down) ? [glob.slice(down.length)] : [];
106
+ };
107
+
45
108
  /**
46
109
  * A set of files paperlint lints: an own block's globs and the exceptions that block makes. A file is
47
110
  * in it when it matches one of `files` and none of `ignores`.
@@ -158,6 +221,7 @@ export function ruleOwners(
158
221
  export function narrowToOwners(
159
222
  block: RuleBlock,
160
223
  owners: ReadonlyMap<string, readonly OwnedScope[]>,
224
+ papers: PaperScope = ANY_PAPER,
161
225
  ): ScopedBlock[] {
162
226
  // Keyed by the owner's JSON, so rules with equal owners share one group of blocks.
163
227
  const groups = new Map<string, Record<string, RuleEntry>>();
@@ -170,24 +234,49 @@ export function narrowToOwners(
170
234
  ownerOf.set(key, owner);
171
235
  }
172
236
  return [...ownerOf].flatMap(([key, owner]) =>
173
- owner.map((scope) => within(block, scope, { ...groups.get(key) })),
237
+ owner.flatMap((scope) =>
238
+ within(block, rebased(scope, papers, block.basePath), {
239
+ ...groups.get(key),
240
+ }),
241
+ ),
174
242
  );
175
243
  }
176
244
 
177
- /** `block`'s rules over the files both it and `scope` claim, minus both sets of exceptions. */
245
+ /**
246
+ * `scope` as the block with `basePath` `base` must write it. The scope's globs are relative to ESLint's
247
+ * `cwd`; a paper's own settings are read from the paper's folder (#582).
248
+ */
249
+ function rebased(
250
+ scope: OwnedScope,
251
+ papers: PaperScope,
252
+ base: string,
253
+ ): OwnedScope {
254
+ if (papers.kind === "any") return scope;
255
+ const onto = (globs: readonly string[]): readonly string[] =>
256
+ globs.flatMap((g) => rebaseGlob(g, papers.cwd, base));
257
+ return { files: onto(scope.files), ignores: onto(scope.ignores) };
258
+ }
259
+
260
+ /**
261
+ * `block`'s rules over the files both it and `scope` claim, minus both sets of exceptions; none when
262
+ * the scope claims no file the block can reach (ESLint refuses an empty `files`).
263
+ */
178
264
  function within(
179
265
  block: RuleBlock,
180
266
  scope: OwnedScope,
181
267
  rules: Readonly<Record<string, RuleEntry>>,
182
- ): ScopedBlock {
268
+ ): readonly ScopedBlock[] {
269
+ if (scope.files.length === 0) return [];
183
270
  const files: readonly FilesEntry[] = block.files
184
271
  ? block.files.flatMap((f) => scope.files.map((o) => [f, o]))
185
272
  : scope.files;
186
273
  const ignores = [...(block.ignores ?? []), ...scope.ignores];
187
- return {
188
- basePath: block.basePath,
189
- files,
190
- ...(ignores.length ? { ignores } : {}),
191
- rules,
192
- };
274
+ return [
275
+ {
276
+ basePath: block.basePath,
277
+ files,
278
+ ...(ignores.length ? { ignores } : {}),
279
+ rules,
280
+ },
281
+ ];
193
282
  }
@@ -98,6 +98,24 @@ describe("🔴 an optional rule that reaches no paper — judged against the PRO
98
98
  });
99
99
  });
100
100
 
101
+ describe("paperlint lint — `rules` in a paper's paperlint.json as a list of blocks (#582)", () => {
102
+ it("turns a rule on for that paper alone, globs relative to the paper", async () => {
103
+ const root = project({
104
+ "papers/a/paperlint.json": JSON.stringify({
105
+ rules: [
106
+ {
107
+ files: ["paper.tex"],
108
+ rules: { "pdf/last-page-balance": "error" },
109
+ },
110
+ ],
111
+ }),
112
+ });
113
+ const r = await lint(root);
114
+ expect(rulesIn(r.out, "a")).toContain("pdf/last-page-balance");
115
+ expect(rulesIn(r.out, "b")).not.toContain("pdf/last-page-balance");
116
+ });
117
+ });
118
+
101
119
  describe("paperlint lint — `rules` in a paper's paperlint.json", () => {
102
120
  it("turns an optional rule on for that paper alone", async () => {
103
121
  const root = project({