Open History to see the last commit
1#!/usr/bin/env node
2
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
6import * as Console from "effect/Console";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Logger from "effect/Logger";
10import * as Path from "effect/Path";
11import * as Schema from "effect/Schema";
12import { Command } from "effect/cli";
13import { ChildProcess, ChildProcessSpawner } from "effect/process";
14
15interface NativeStaticTool {
16 readonly command: string;
17 readonly installHint: string;
18}
19
20const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
21
22export class NativeStaticCheckSourceDiscoveryError extends Schema.TaggedError<NativeStaticCheckSourceDiscoveryError>()(
23 "NativeStaticCheckSourceDiscoveryError",
24 {
25 operation: Schema.Literals(["resolve-root", "read-directory", "stat-entry"]),
26 path: Schema.String,
27 cause: Schema.Defect(),
28 },
29) {
30 override get message(): string {
31 return `Native source discovery operation '${this.operation}' failed.`;
32 }
33}
34
35export class NativeStaticCheckProcessError extends Schema.TaggedError<NativeStaticCheckProcessError>()(
36 "NativeStaticCheckProcessError",
37 {
38 operation: Schema.Literals(["spawn", "wait-for-exit"]),
39 command: Schema.String,
40 argumentCount: NonNegativeInt,
41 cwd: Schema.String,
42 shell: Schema.Boolean,
43 cause: Schema.Defect(),
44 },
45) {
46 override get message(): string {
47 return `Native static check process operation '${this.operation}' failed for command '${this.command}'.`;
48 }
49}
50
51export class NativeStaticCheckCommandError extends Schema.TaggedError<NativeStaticCheckCommandError>()(
52 "NativeStaticCheckCommandError",
53 {
54 command: Schema.String,
55 argumentCount: NonNegativeInt,
56 cwd: Schema.String,
57 shell: Schema.Boolean,
58 exitCode: Schema.Int,
59 },
60) {
61 override get message(): string {
62 return `Native static check command '${this.command}' exited with code ${this.exitCode}.`;
63 }
64}
65
66const kotlinToolCommands = ["ktlint", "detekt"] as const;
67
68export class NativeStaticCheckMissingToolError extends Schema.TaggedError<NativeStaticCheckMissingToolError>()(
69 "NativeStaticCheckMissingToolError",
70 {
71 commands: Schema.Array(Schema.Literals(kotlinToolCommands)),
72 },
73) {
74 override get message(): string {
75 const names = this.commands.join(" and ");
76 const verb = this.commands.length === 1 ? "is" : "are";
77 return `${names} ${verb} not installed; cannot run Kotlin static analysis. Install via \`brew bundle install --file apps/mobile/Brewfile\` or put the JVM tools on PATH.`;
78 }
79}
80
81const tools = [
82 {
83 command: "swiftlint",
84 installHint: "brew install swiftlint",
85 },
86 {
87 command: "ktlint",
88 installHint: "brew install ktlint",
89 },
90 {
91 command: "detekt",
92 installHint: "brew install detekt",
93 },
94] as const satisfies ReadonlyArray<NativeStaticTool>;
95
96const sourceExtensions = new Set([".swift", ".kt", ".kts"]);
97const excludedDirectories = new Set([
98 ".expo",
99 ".git",
100 "build",
101 "DerivedData",
102 "node_modules",
103 "Pods",
104 "Vendor",
105]);
106const generatedNativeProjectDirectories = new Set(["android", "ios"]);
107
108const mobileAppRootUrl = new URL("../apps/mobile", import.meta.url);
109const appRoot = Effect.service(Path.Path).pipe(
110 Effect.flatMap((path) => path.fromFileUrl(mobileAppRootUrl)),
111 Effect.mapError(
112 (cause) =>
113 new NativeStaticCheckSourceDiscoveryError({
114 operation: "resolve-root",
115 path: mobileAppRootUrl.pathname,
116 cause,
117 }),
118 ),
119);
120
121const commandOutputOptions = {
122 stdout: "inherit",
123 stderr: "inherit",
124} as const;
125
126const commandExists = Effect.fn("commandExists")(function* (command: string) {
127 return yield* isCommandAvailable(command);
128});
129
130const warnMissingTool = (tool: NativeStaticTool, checkName: string) =>
131 Effect.logWarning(
132 `${tool.command} is not installed; skipping ${checkName}. Install it with '${tool.installHint}' or run 'brew bundle install --file apps/mobile/Brewfile'.`,
133 );
134
135export const requireKotlinTools = Effect.fn("requireKotlinTools")(function* (available: {
136 readonly ktlint: boolean;
137 readonly detekt: boolean;
138}) {
139 const missing = kotlinToolCommands.filter((command) => !available[command]);
140 if (missing.length > 0) {
141 return yield* new NativeStaticCheckMissingToolError({ commands: missing });
142 }
143});
144
145export const runCommand = Effect.fn("runCommand")(function* (
146 command: string,
147 args: ReadonlyArray<string>,
148 cwd: string,
149) {
150 yield* Console.log(`$ ${[command, ...args].join(" ")}`);
151 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
152 const spawnCommand = yield* resolveSpawnCommand(command, args);
153 const processContext = {
154 command,
155 argumentCount: args.length,
156 cwd,
157 shell: spawnCommand.shell,
158 } as const;
159 const child = yield* spawner
160 .spawn(
161 ChildProcess.make(spawnCommand.command, spawnCommand.args, {
162 cwd,
163 ...commandOutputOptions,
164 shell: spawnCommand.shell,
165 }),
166 )
167 .pipe(
168 Effect.mapError(
169 (cause) =>
170 new NativeStaticCheckProcessError({
171 ...processContext,
172 operation: "spawn",
173 cause,
174 }),
175 ),
176 );
177 const exitCode = Number(
178 yield* child.exitCode.pipe(
179 Effect.mapError(
180 (cause) =>
181 new NativeStaticCheckProcessError({
182 ...processContext,
183 operation: "wait-for-exit",
184 cause,
185 }),
186 ),
187 ),
188 );
189
190 if (exitCode !== 0) {
191 return yield* new NativeStaticCheckCommandError({
192 ...processContext,
193 exitCode,
194 });
195 }
196});
197
198export const collectSources = Effect.fn("mobile-native-static-check.collectSources")(function* (
199 directory: string,
200 root: string,
201): Effect.fn.Return<
202 ReadonlyArray<string>,
203 NativeStaticCheckSourceDiscoveryError,
204 FileSystem.FileSystem | Path.Path
205> {
206 const fs = yield* FileSystem.FileSystem;
207 const path = yield* Path.Path;
208 const entries = yield* fs.readDirectory(directory).pipe(
209 Effect.mapError(
210 (cause) =>
211 new NativeStaticCheckSourceDiscoveryError({
212 operation: "read-directory",
213 path: directory,
214 cause,
215 }),
216 ),
217 );
218 const sources: Array<string> = [];
219
220 for (const entry of entries) {
221 const entryPath = path.join(directory, entry);
222 const stat = yield* fs.stat(entryPath).pipe(
223 Effect.mapError(
224 (cause) =>
225 new NativeStaticCheckSourceDiscoveryError({
226 operation: "stat-entry",
227 path: entryPath,
228 cause,
229 }),
230 ),
231 );
232
233 if (stat.type === "Directory") {
234 const isGeneratedNativeProjectDirectory =
235 directory === root && generatedNativeProjectDirectories.has(entry);
236
237 if (excludedDirectories.has(entry) || isGeneratedNativeProjectDirectory) {
238 continue;
239 }
240
241 sources.push(...(yield* collectSources(entryPath, root)));
242 continue;
243 }
244
245 if (stat.type === "File" && sourceExtensions.has(path.extname(entry))) {
246 sources.push(entryPath);
247 }
248 }
249
250 return sources;
251});
252
253const runNativeStaticChecks = Effect.fn("runNativeStaticChecks")(function* () {
254 const path = yield* Path.Path;
255 const root = yield* appRoot;
256 const sources = yield* collectSources(root, root);
257 const swiftSources = sources.filter((source) => path.extname(source) === ".swift");
258 const kotlinSources = sources.filter((source) => {
259 const extension = path.extname(source);
260 return extension === ".kt" || extension === ".kts";
261 });
262 const availableTools = new Map<string, boolean>();
263
264 for (const tool of tools) {
265 availableTools.set(tool.command, yield* commandExists(tool.command));
266 }
267
268 yield* Console.log(
269 `Found ${swiftSources.length} Swift and ${kotlinSources.length} Kotlin native source files.`,
270 );
271
272 if (swiftSources.length > 0) {
273 if (availableTools.get("swiftlint")) {
274 yield* runCommand("swiftlint", ["lint", "--config", ".swiftlint.yml", "--strict"], root);
275 } else {
276 yield* warnMissingTool(tools[0], "SwiftLint");
277 }
278 }
279
280 if (kotlinSources.length > 0) {
281 yield* requireKotlinTools({
282 ktlint: availableTools.get("ktlint") === true,
283 detekt: availableTools.get("detekt") === true,
284 });
285
286 const relativeKotlinSources = kotlinSources.map((source) => path.relative(root, source));
287 yield* runCommand("ktlint", relativeKotlinSources, root);
288 yield* runCommand(
289 "detekt",
290 [
291 "--config",
292 "detekt.yml",
293 "--input",
294 relativeKotlinSources.join(","),
295 "--build-upon-default-config",
296 ],
297 root,
298 );
299 }
300
301 yield* Console.log("Skipping generated native project folders: android/, ios/.");
302});
303
304export const mobileNativeStaticCheckCommand = Command.make("mobile-native-static-check", {}, () =>
305 runNativeStaticChecks(),
306).pipe(
307 Command.withDescription(
308 "Run mobile native static analysis. SwiftLint may be skipped when unavailable; ktlint and detekt are required when Kotlin sources exist.",
309 ),
310);
311
312if (import.meta.main) {
313 Command.run(mobileNativeStaticCheckCommand, { version: "0.0.0" }).pipe(
314 Effect.scoped,
315 Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
316 NodeRuntime.runMain,
317 );
318}