@avi2dg/checks 0.11.0 → 0.12.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.
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env bun
2
+ import { Console, Effect, FileSystem, Path, Schema } from "effect";
3
+ import { changedPaths, collect, git, pathsAt, rangeEnds, type Change } from "./git.ts";
4
+ import { runMain, Usage } from "./main.ts";
5
+ import { readQuality, renderJson, type Quality } from "./quality-file.ts";
6
+
7
+ type Size = NonNullable<Quality["size"]>;
8
+
9
+ type Overrun = {
10
+ readonly file: string;
11
+ readonly line: number | undefined;
12
+ readonly message: string;
13
+ };
14
+
15
+ type Measured = {
16
+ readonly scope: string;
17
+ readonly held: readonly string[];
18
+ readonly overruns: readonly Overrun[];
19
+ readonly advisory: readonly Overrun[];
20
+ };
21
+
22
+ class OxlintUnreadable extends Schema.TaggedError<OxlintUnreadable>()("OxlintUnreadable", {
23
+ message: Schema.String,
24
+ }) {}
25
+
26
+ const NAME = "size-budget";
27
+ const USAGE = "usage: size-budget.ts <ref> | <base-ref> <head-ref>";
28
+ const DECLARATIONS = ":(exclude,glob)**/*.d.ts";
29
+ const TYPESCRIPT = [":(glob)**/*.ts", ":(glob)**/*.tsx", DECLARATIONS];
30
+ const FILE_RULE = "eslint(max-lines)";
31
+ const FUNCTION_RULE = "eslint(max-lines-per-function)";
32
+ const OXLINT_FOUND_NOTHING = 0;
33
+ const OXLINT_FOUND_ERRORS = 1;
34
+
35
+ const decodeReport = Schema.decodeUnknownEffect(
36
+ Schema.fromJsonString(
37
+ Schema.Struct({
38
+ diagnostics: Schema.Array(
39
+ Schema.Struct({
40
+ code: Schema.String,
41
+ message: Schema.String,
42
+ filename: Schema.String,
43
+ labels: Schema.Array(Schema.Struct({ span: Schema.Struct({ line: Schema.Int }) })),
44
+ }),
45
+ ),
46
+ }),
47
+ ),
48
+ );
49
+
50
+ function sizeConfig({ fileLines, functionLines }: Size): unknown {
51
+ const counted = { skipBlankLines: false, skipComments: false };
52
+ return {
53
+ plugins: [],
54
+ categories: { correctness: "off" },
55
+ rules: {
56
+ "max-lines": ["error", { max: fileLines, ...counted }],
57
+ "max-lines-per-function": ["error", { max: functionLines, ...counted }],
58
+ },
59
+ };
60
+ }
61
+
62
+ function heldByChange(changes: readonly Change[]): readonly string[] {
63
+ return changes.flatMap((change) => {
64
+ if (change.kind === "written" || (change.kind === "renamed" && change.edited)) return [change.path];
65
+ return [];
66
+ });
67
+ }
68
+
69
+ const materialize = Effect.fn("materialize")(function* (root: string, head: string, files: readonly string[], scratch: string) {
70
+ const path = yield* Path.Path;
71
+ const env = { GIT_INDEX_FILE: path.join(scratch, "index") };
72
+ yield* git(["read-tree", head], root, { env });
73
+ const tree = `${path.join(scratch, "tree")}${path.sep}`;
74
+ yield* git(["checkout-index", "-z", "--stdin", `--prefix=${tree}`], root, { env, input: files.map((file) => `${file}\0`).join("") });
75
+ return tree;
76
+ });
77
+
78
+ // oxlint reads files from disk, and the working tree need not hold the head: a merge checkout or an uncommitted edit.
79
+ const measure = Effect.fn("measure")(
80
+ function* (root: string, head: string, size: Size, files: readonly string[]) {
81
+ if (files.length === 0) return [];
82
+ const fs = yield* FileSystem.FileSystem;
83
+ const path = yield* Path.Path;
84
+ const scratch = yield* fs.makeTempDirectoryScoped({ prefix: "checks-size-budget-" });
85
+ const config = path.join(scratch, "size.oxlintrc.json");
86
+ yield* fs.writeFileString(config, renderJson(sizeConfig(size)));
87
+ const tree = yield* materialize(root, head, files, scratch);
88
+
89
+ const { stdout, stderr, exitCode } = yield* collect("oxlint", ["-c", config, "-f", "json", "."], tree).pipe(
90
+ Effect.mapError((cause) => new OxlintUnreadable({ message: `cannot run oxlint: ${cause.message}` })),
91
+ );
92
+ if (exitCode !== OXLINT_FOUND_NOTHING && exitCode !== OXLINT_FOUND_ERRORS) {
93
+ return yield* new OxlintUnreadable({ message: `oxlint exited ${exitCode}: ${stderr.trim() || stdout.trim()}` });
94
+ }
95
+ const { diagnostics } = yield* decodeReport(stdout).pipe(
96
+ Effect.mapError((cause) => new OxlintUnreadable({ message: `cannot read oxlint's report: ${cause.message}` })),
97
+ );
98
+ return diagnostics.flatMap(({ code, message, filename, labels }): Overrun[] => {
99
+ if (code === FILE_RULE) return [{ file: filename, line: undefined, message }];
100
+ if (code === FUNCTION_RULE) return [{ file: filename, line: labels[0]?.span.line, message }];
101
+ return [];
102
+ });
103
+ },
104
+ Effect.scoped,
105
+ );
106
+
107
+ const runBudget = Effect.fn("runBudget")(function* (root: string, size: Size, production: readonly string[], base: string, head: string) {
108
+ const pathspecs = [...production.map((glob) => `:(glob)${glob}`), DECLARATIONS];
109
+ const held =
110
+ size.applies === "all" ? yield* pathsAt(head, pathspecs, root) : heldByChange(yield* changedPaths(base, head, pathspecs, root));
111
+ const holds = new Set(held);
112
+ const others = (yield* pathsAt(head, TYPESCRIPT, root)).filter((file) => !holds.has(file));
113
+ const overruns = (yield* measure(root, head, size, [...held, ...others])).toSorted(
114
+ (a, b) => a.file.localeCompare(b.file) || (a.line ?? 0) - (b.line ?? 0),
115
+ );
116
+ return {
117
+ scope: size.applies === "all" ? "every production file" : "the production files the range adds or changes",
118
+ held,
119
+ overruns: overruns.filter((overrun) => holds.has(overrun.file)),
120
+ advisory: overruns.filter((overrun) => !holds.has(overrun.file)),
121
+ } satisfies Measured;
122
+ });
123
+
124
+ function describe({ file, line, message }: Overrun): string {
125
+ return ` ${file}${line === undefined ? "" : `:${line}`}: ${message}`;
126
+ }
127
+
128
+ function report({ scope, held, overruns, advisory }: Measured, { fileLines, functionLines }: Size): string {
129
+ const budget = `${fileLines} lines per file and ${functionLines} per function`;
130
+ const verdict =
131
+ overruns.length === 0
132
+ ? [`${NAME}: ${held.length} file(s), ${scope}, keep within ${budget}`]
133
+ : [`${NAME}: ${overruns.length} overrun(s) of ${budget} in ${scope}:`, ...overruns.map(describe)];
134
+ const notice =
135
+ advisory.length === 0
136
+ ? []
137
+ : [`${NAME}: advisory, ${advisory.length} overrun(s) where the budget does not hold yet:`, ...advisory.map(describe)];
138
+ return [...verdict, ...notice].join("\n");
139
+ }
140
+
141
+ const budget = Effect.gen(function* () {
142
+ const [first, second, ...extra] = process.argv.slice(2);
143
+ if (first === undefined || extra.length > 0) return yield* new Usage({ message: USAGE });
144
+
145
+ const root = (yield* git(["rev-parse", "--show-toplevel"])).trim();
146
+ const { source, quality } = yield* readQuality(root);
147
+ if (quality.size === undefined) {
148
+ yield* Console.log(`${NAME}: ${source} declares no size budget`);
149
+ return true;
150
+ }
151
+ const { base, head } = yield* rangeEnds(first, second, root);
152
+ const measured = yield* runBudget(root, quality.size, quality.sources?.production ?? [], base, head);
153
+
154
+ yield* Console.log(report(measured, quality.size));
155
+ return measured.overruns.length === 0;
156
+ });
157
+
158
+ if (import.meta.main) runMain(NAME, budget);