@avi2dg/checks 0.10.0 → 0.11.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,172 @@
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 problems: string[] = [];
123
+ for (const glob of quality.sources?.effect?.paths ?? []) {
124
+ const matched = yield* git(["ls-files", "--cached", "--others", "--exclude-standard", "--", `:(glob)${glob}`], root);
125
+ if (matched.trim() === "") problems.push(`sources.effect.paths ${glob} matches no file, so it holds nothing to the Effect rules`);
126
+ }
127
+ return problems;
128
+ });
129
+
130
+ const check = Effect.fn("check")(function* (root: string) {
131
+ const { source, quality } = yield* readQuality(root);
132
+ const expected = fragmentsFor(quality);
133
+ const problems = [...(yield* fragmentProblems(root, source, expected)), ...(yield* unmatchedPaths(root, quality))];
134
+ if (problems.length > 0) {
135
+ yield* Console.error([`${NAME}: ${problems.length} problem(s) with what ${source} declares:`, ...problems.map((line) => ` ${line}`)].join("\n"));
136
+ return false;
137
+ }
138
+ yield* Console.log(
139
+ expected.length === 0
140
+ ? `${NAME}: no sources.effect is declared, so nothing is generated`
141
+ : `${NAME}: ${expected.map((fragment) => fragment.file).join(" and ")} hold what ${source} declares`,
142
+ );
143
+ return true;
144
+ });
145
+
146
+ const generate = Effect.fn("generate")(function* (root: string) {
147
+ const fs = yield* FileSystem.FileSystem;
148
+ const path = yield* Path.Path;
149
+ const { quality } = yield* readQuality(root);
150
+ const expected = fragmentsFor(quality);
151
+ for (const { file } of FRAGMENTS) {
152
+ const target = path.join(root, file);
153
+ const fragment = expected.find((candidate) => candidate.file === file);
154
+ if (fragment !== undefined) {
155
+ yield* fs.writeFileString(target, renderJson(fragment.content));
156
+ yield* Console.log(`${NAME}: wrote ${file}`);
157
+ } else if (yield* fs.exists(target)) {
158
+ yield* fs.remove(target);
159
+ yield* Console.log(`${NAME}: removed ${file}`);
160
+ }
161
+ }
162
+ return yield* check(root);
163
+ });
164
+
165
+ const main = Effect.gen(function* () {
166
+ const [mode, ...extra] = process.argv.slice(2);
167
+ if (extra.length > 0 || (mode !== "--check" && mode !== "generate")) return yield* new Usage({ message: USAGE });
168
+ const root = (yield* git(["rev-parse", "--show-toplevel"])).trim();
169
+ return mode === "generate" ? yield* generate(root) : yield* check(root);
170
+ });
171
+
172
+ if (import.meta.main) runMain(NAME, main);