@avi2dg/checks 0.10.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,180 @@
1
+ #!/usr/bin/env bun
2
+ import { Console, Effect, FileSystem, Path, Schema } from "effect";
3
+ import kitOxlint from "../oxlintrc.json" with { type: "json" };
4
+ import effectLanguageService from "../presets/effect.language-service.json" with { type: "json" };
5
+ import effectOxlint from "../presets/effect.oxlint.json" with { type: "json" };
6
+ import { git } from "./git.ts";
7
+ import { runMain, Usage } from "./main.ts";
8
+ import { readQuality, renderJson, type Quality } from "./quality-file.ts";
9
+
10
+ // oxlint resolves an override's files, and the language service an override's include, against the
11
+ // directory of the config that holds it, so a fragment anywhere but the root matches nothing there.
12
+ export const OXLINT_FRAGMENT = "oxlintrc.quality.json";
13
+ export const TSCONFIG_FRAGMENT = "tsconfig.quality.json";
14
+
15
+ const NAME = "checks-quality";
16
+ const USAGE = `usage: ${NAME} --check | generate`;
17
+ const GENERATE = `${NAME} generate`;
18
+
19
+ type EffectSources = NonNullable<NonNullable<Quality["sources"]>["effect"]>;
20
+
21
+ export type Fragment = {
22
+ readonly file: typeof OXLINT_FRAGMENT | typeof TSCONFIG_FRAGMENT;
23
+ readonly extendedBy: string;
24
+ readonly reader: string;
25
+ readonly content: unknown;
26
+ };
27
+
28
+ class NativeConfigUnreadable extends Schema.TaggedError<NativeConfigUnreadable>()("NativeConfigUnreadable", {
29
+ message: Schema.String,
30
+ }) {}
31
+
32
+ function oxlintFragment({ paths, exempt = [] }: EffectSources): unknown {
33
+ const override = {
34
+ files: paths,
35
+ ...(exempt.length === 0 ? {} : { excludeFiles: exempt }),
36
+ // An override that leaves out any of the kit's plugins turns on the category rules of the ones it adds.
37
+ plugins: [...kitOxlint.plugins, ...effectOxlint.plugins.filter((plugin) => !kitOxlint.plugins.includes(plugin))],
38
+ rules: effectOxlint.rules,
39
+ };
40
+ return {
41
+ $schema: "./node_modules/oxlint/configuration_schema.json",
42
+ // A config without plugins brings oxlint's default plugins into the one extending it.
43
+ plugins: kitOxlint.plugins,
44
+ overrides: [override],
45
+ };
46
+ }
47
+
48
+ function tsconfigFragment({ paths, exempt = [] }: EffectSources): unknown {
49
+ const override = { include: paths, ...(exempt.length === 0 ? {} : { exclude: exempt }), options: effectLanguageService };
50
+ return { compilerOptions: { plugins: [{ name: "@effect/language-service", overrides: [override] }] } };
51
+ }
52
+
53
+ const FRAGMENTS = [
54
+ { file: OXLINT_FRAGMENT, extendedBy: ".oxlintrc.json", reader: "oxlint", build: oxlintFragment },
55
+ { file: TSCONFIG_FRAGMENT, extendedBy: "tsconfig.json", reader: "the language service", build: tsconfigFragment },
56
+ ] as const;
57
+
58
+ export function fragmentsFor(quality: Quality): readonly Fragment[] {
59
+ const effect = quality.sources?.effect;
60
+ if (effect === undefined) return [];
61
+ return FRAGMENTS.map(({ build, ...fragment }) => ({ ...fragment, content: build(effect) }));
62
+ }
63
+
64
+ const NativeConfig = Schema.Struct({
65
+ extends: Schema.optionalKey(Schema.Union([Schema.String, Schema.Array(Schema.String)])),
66
+ });
67
+ const decodeNativeConfig = Schema.decodeUnknownEffect(NativeConfig);
68
+
69
+ const parseJsonc = (text: string, file: string) =>
70
+ Effect.try({
71
+ try: (): unknown => Bun.JSONC.parse(text),
72
+ catch: (error) => new NativeConfigUnreadable({ message: `cannot parse ${file}: ${String(error)}` }),
73
+ });
74
+
75
+ const extendsOf = Effect.fn("extendsOf")(function* (root: string, file: string) {
76
+ const fs = yield* FileSystem.FileSystem;
77
+ const path = yield* Path.Path;
78
+ const target = path.join(root, file);
79
+ if (!(yield* fs.exists(target))) return [];
80
+ const config = yield* fs.readFileString(target).pipe(
81
+ Effect.flatMap((text) => parseJsonc(text, file)),
82
+ Effect.flatMap(decodeNativeConfig),
83
+ Effect.mapError((cause) => new NativeConfigUnreadable({ message: `cannot read extends from ${file}: ${cause.message}` })),
84
+ );
85
+ const listed = config.extends ?? [];
86
+ return (typeof listed === "string" ? [listed] : listed).map((entry) => path.normalize(entry));
87
+ });
88
+
89
+ const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
90
+
91
+ const sameJson = (text: string, content: unknown): Effect.Effect<boolean> =>
92
+ decodeJson(text).pipe(
93
+ Effect.map((parsed) => Bun.deepEquals(parsed, content, true)),
94
+ Effect.orElseSucceed(() => false),
95
+ );
96
+
97
+ const fragmentProblems = Effect.fn("fragmentProblems")(function* (root: string, source: string, expected: readonly Fragment[]) {
98
+ const fs = yield* FileSystem.FileSystem;
99
+ const path = yield* Path.Path;
100
+ const problems: string[] = [];
101
+ for (const { file } of FRAGMENTS) {
102
+ const target = path.join(root, file);
103
+ const fragment = expected.find((candidate) => candidate.file === file);
104
+ const present = yield* fs.exists(target);
105
+ if (fragment === undefined) {
106
+ if (present) problems.push(`${file} is left over, since no sources.effect is declared; run ${GENERATE}`);
107
+ continue;
108
+ }
109
+ if (!present) {
110
+ problems.push(`${file} is missing; run ${GENERATE}`);
111
+ } else if (!(yield* sameJson(yield* fs.readFileString(target), fragment.content))) {
112
+ problems.push(`${file} is stale against ${source} and the kit's presets; run ${GENERATE}`);
113
+ }
114
+ if (!(yield* extendsOf(root, fragment.extendedBy)).includes(file)) {
115
+ problems.push(`${fragment.extendedBy} does not extend ./${file}, so ${fragment.reader} never reads it`);
116
+ }
117
+ }
118
+ return problems;
119
+ });
120
+
121
+ const unmatchedPaths = Effect.fn("unmatchedPaths")(function* (root: string, quality: Quality) {
122
+ const declared = [
123
+ ...(quality.size === undefined ? [] : (quality.sources?.production ?? [])).map((glob) => ({
124
+ glob,
125
+ key: "sources.production",
126
+ holds: "no source to the size budget",
127
+ })),
128
+ ...(quality.sources?.effect?.paths ?? []).map((glob) => ({ glob, key: "sources.effect.paths", holds: "nothing to the Effect rules" })),
129
+ ];
130
+ const problems: string[] = [];
131
+ for (const { glob, key, holds } of declared) {
132
+ const matched = yield* git(["ls-files", "--cached", "--others", "--exclude-standard", "--", `:(glob)${glob}`], root);
133
+ if (matched.trim() === "") problems.push(`${key} ${glob} matches no file, so it holds ${holds}`);
134
+ }
135
+ return problems;
136
+ });
137
+
138
+ const check = Effect.fn("check")(function* (root: string) {
139
+ const { source, quality } = yield* readQuality(root);
140
+ const expected = fragmentsFor(quality);
141
+ const problems = [...(yield* fragmentProblems(root, source, expected)), ...(yield* unmatchedPaths(root, quality))];
142
+ if (problems.length > 0) {
143
+ yield* Console.error([`${NAME}: ${problems.length} problem(s) with what ${source} declares:`, ...problems.map((line) => ` ${line}`)].join("\n"));
144
+ return false;
145
+ }
146
+ yield* Console.log(
147
+ expected.length === 0
148
+ ? `${NAME}: no sources.effect is declared, so nothing is generated`
149
+ : `${NAME}: ${expected.map((fragment) => fragment.file).join(" and ")} hold what ${source} declares`,
150
+ );
151
+ return true;
152
+ });
153
+
154
+ const generate = Effect.fn("generate")(function* (root: string) {
155
+ const fs = yield* FileSystem.FileSystem;
156
+ const path = yield* Path.Path;
157
+ const { quality } = yield* readQuality(root);
158
+ const expected = fragmentsFor(quality);
159
+ for (const { file } of FRAGMENTS) {
160
+ const target = path.join(root, file);
161
+ const fragment = expected.find((candidate) => candidate.file === file);
162
+ if (fragment !== undefined) {
163
+ yield* fs.writeFileString(target, renderJson(fragment.content));
164
+ yield* Console.log(`${NAME}: wrote ${file}`);
165
+ } else if (yield* fs.exists(target)) {
166
+ yield* fs.remove(target);
167
+ yield* Console.log(`${NAME}: removed ${file}`);
168
+ }
169
+ }
170
+ return yield* check(root);
171
+ });
172
+
173
+ const main = Effect.gen(function* () {
174
+ const [mode, ...extra] = process.argv.slice(2);
175
+ if (extra.length > 0 || (mode !== "--check" && mode !== "generate")) return yield* new Usage({ message: USAGE });
176
+ const root = (yield* git(["rev-parse", "--show-toplevel"])).trim();
177
+ return mode === "generate" ? yield* generate(root) : yield* check(root);
178
+ });
179
+
180
+ if (import.meta.main) runMain(NAME, main);
@@ -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);