Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

knip-check.ts

197 lines6.7 KB

1#!/usr/bin/env node
2// Runs CI's unused-code check as one cached Knip pass: files and dependencies
3// everywhere, unused exports in the workspaces that are kept clean of them.
4​
5import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
6import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import * as Digest from "effect/crypto/Digest";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import * as Schema from "effect/Schema";
14import * as Stream from "effect/Stream";
15import { Command, Flag } from "effect/cli";
16import { ChildProcess, ChildProcessSpawner } from "effect/process";
17​
18const encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
19​
20const EXPORT_WORKSPACES = [
21 "apps/server",
22 "apps/desktop",
23 "apps/web",
24 "packages/client-runtime",
25 "packages/contracts",
26 "packages/effect-acp",
27 "packages/effect-codex-app-server",
28 "packages/shared",
29 "packages/ssh",
30 "packages/tailscale",
31 "packages/provider-core",
32 "packages/provider-acp",
33 "packages/provider-acp-registry",
34 "packages/provider-testing",
35 "packages/provider-pi",
36 "packages/provider-muse",
37 "packages/provider-opencode",
38 "packages/provider-cursor",
39 "packages/provider-fx",
40 "packages/provider-grok",
41 "packages/provider-kiro",
42 "packages/secret-provider-core",
43 "packages/secret-provider-definitions",
44 "packages/secret-provider-onepassword",
45 "packages/source-control-core",
46 "packages/source-control-cursor-origin",
47 "packages/source-control-definitions",
48 "packages/source-control-azure-devops",
49 "packages/source-control-bitbucket",
50 "packages/source-control-forgejo",
51 "packages/source-control-gitcafe",
52 "packages/source-control-github",
53 "packages/source-control-gitlab",
54 "packages/source-control-tanstack-source",
55 "packages/source-control-testing",
56];
57​
58// Files that decide how an import resolves or what Knip reports, beyond the
59// source file that holds the import.
60const RESOLUTION_FILE =
61 /(^|\/)(package\.json|tsconfig[^/]*\.json|knip\.jsonc?|\.gitignore|pnpm-lock\.yaml|pnpm-workspace\.yaml)$|^patches\//;
62​
63// Knip's cache and the schema verdicts each trust the contents of the files
64// they read, so neither notices an unchanged import resolving elsewhere. Both
65// are kept only while this is unchanged: the file list, manifests, tsconfigs,
66// installed packages and these scripts. None (git failed) runs uncached.
67const fingerprint = Effect.fn("knipCheck.fingerprint")(function* (
68 cwd: string,
69 scripts: ReadonlyArray<string>,
70) {
71 const fs = yield* FileSystem.FileSystem;
72 const path = yield* Path.Path;
73 const digest = yield* Digest.Digest;
74 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
75 // Untracked files count and ignored ones do not, as for Knip. A tracked file
76 // deleted from disk is listed a second time by --deleted.
77 const [files, exitCode] = yield* Effect.scoped(
78 Effect.gen(function* () {
79 const handle = yield* spawner.spawn(
80 ChildProcess.make(
81 "git",
82 ["ls-files", "--cached", "--others", "--deleted", "--exclude-standard", "-z"],
83 { cwd },
84 ),
85 );
86 return yield* Effect.all(
87 [Stream.mkString(Stream.decodeText(handle.stdout)), handle.exitCode],
88 {
89 concurrency: 2,
90 },
91 );
92 }),
93 ).pipe(Effect.orElseSucceed(() => ["", 1] as const));
94 if (exitCode !== 0) return Option.none<string>();
95​
96 const contents = yield* Effect.forEach(
97 [
98 ...files
99 .split("\0")
100 .filter((file) => RESOLUTION_FILE.test(file))
101 .map((file) => path.join(cwd, file)),
102 path.join(cwd, "node_modules/.pnpm/lock.yaml"),
103 ...scripts,
104 ],
105 (file) =>
106 fs.readFile(file).pipe(
107 Effect.flatMap((bytes) => digest.digestHex(Digest.sha256, bytes)),
108 Effect.orElseSucceed(() => "missing"),
109 Effect.map((hash) => `${file}\0${hash}`),
110 ),
111 { concurrency: 32 },
112 );
113 return Option.some(
114 yield* digest.digestHex(
115 Digest.sha256,
116 new TextEncoder().encode(`${files}\n${contents.join("\n")}`),
117 ),
118 );
119});
120​
121export const knipCheck = Effect.fn("knipCheck")(function* (input: {
122 readonly cwd: Option.Option<string>;
123}) {
124 const fs = yield* FileSystem.FileSystem;
125 const path = yield* Path.Path;
126 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
127 const cwd = Option.isSome(input.cwd)
128 ? path.resolve(input.cwd.value)
129 : yield* path.fromFileUrl(new URL("..", import.meta.url));
130 const preprocessor = yield* path.fromFileUrl(new URL("knip-schemas.ts", import.meta.url));
131 const cli = path.join(
132 path.dirname(yield* path.fromFileUrl(new URL(import.meta.resolve("knip")))),
133 "cli.js",
134 );
135​
136 const cacheDir = path.join(cwd, "node_modules/.cache/knip-check");
137 const current = yield* fingerprint(cwd, [
138 preprocessor,
139 yield* path.fromFileUrl(new URL(import.meta.url)),
140 ]);
141 if (Option.isSome(current)) {
142 const stamp = path.join(cacheDir, "fingerprint");
143 const previous = yield* fs.readFileString(stamp).pipe(Effect.orElseSucceed(() => ""));
144 if (previous !== current.value) {
145 yield* fs.remove(cacheDir, { recursive: true, force: true });
146 yield* fs.makeDirectory(cacheDir, { recursive: true });
147 yield* fs.writeFileString(stamp, current.value);
148 }
149 }
150​
151 const preprocessorOptions = yield* encodeJson({
152 exportWorkspaces: EXPORT_WORKSPACES,
153 ...(Option.isSome(current) ? { verdicts: path.join(cacheDir, "schemas.json") } : {}),
154 });
155 const exitCode = yield* Effect.scoped(
156 Effect.gen(function* () {
157 const handle = yield* spawner.spawn(
158 ChildProcess.make(
159 "node",
160 [
161 cli,
162 "--include",
163 "files,dependencies",
164 "--exports",
165 "--no-config-hints",
166 "--preprocessor",
167 preprocessor,
168 "--preprocessor-options",
169 preprocessorOptions,
170 ...(Option.isSome(current) ? ["--cache", "--cache-location", cacheDir] : []),
171 ],
172 { cwd, stdin: "inherit", stdout: "inherit", stderr: "inherit" },
173 ),
174 );
175 return yield* handle.exitCode;
176 }),
177 );
178 yield* Effect.sync(() => (process.exitCode = exitCode));
179});
180​
181const command = Command.make(
182 "knip-check",
183 {
184 cwd: Flag.String("cwd").pipe(
185 Flag.withDescription("Project to check instead of this repository."),
186 Flag.optional,
187 ),
188 },
189 knipCheck,
190).pipe(Command.withDescription("Report unused files, dependencies and exports."));
191​
192if (import.meta.main) {
193 Command.run(command, { version: "0.0.0" }).pipe(
194 Effect.provide([NodeServices.layer, NodeCrypto.layer]),
195 NodeRuntime.runMain,
196 );