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 * as Console from "effect/Console";
6import * as Data from "effect/Data";
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 PlatformError from "effect/PlatformError";
12import { Command } from "effect/unstable/cli";
13import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
14
15interface NativeStaticTool {
16 readonly command: string;
17 readonly installHint: string;
18}
19
20class NativeStaticCheckError extends Data.TaggedError("NativeStaticCheckError")<{
21 readonly message: string;
22}> {}
23
24const tools = [
25 {
26 command: "swiftlint",
27 installHint: "brew install swiftlint",
28 },
29 {
30 command: "ktlint",
31 installHint: "brew install ktlint",
32 },
33 {
34 command: "detekt",
35 installHint: "brew install detekt",
36 },
37] as const satisfies ReadonlyArray<NativeStaticTool>;
38
39const sourceExtensions = new Set([".swift", ".kt", ".kts"]);
40const excludedDirectories = new Set([
41 ".expo",
42 ".git",
43 "build",
44 "DerivedData",
45 "node_modules",
46 "Pods",
47 "Vendor",
48]);
49const generatedNativeProjectDirectories = new Set(["android", "ios"]);
50
51const appRoot = Effect.service(Path.Path).pipe(
52 Effect.flatMap((path) => path.fromFileUrl(new URL("../apps/mobile", import.meta.url))),
53);
54
55const commandOutputOptions = {
56 stdout: "inherit",
57 stderr: "inherit",
58} as const;
59
60const commandExists = Effect.fn("commandExists")(function* (command: string) {
61 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
62 const lookupCommand =
63 process.platform === "win32"
64 ? ChildProcess.make("where", [command], {
65 stdout: "ignore",
66 stderr: "ignore",
67 })
68 : ChildProcess.make("/bin/sh", ["-c", `command -v ${command}`], {
69 stdout: "ignore",
70 stderr: "ignore",
71 });
72
73 return yield* spawner.spawn(lookupCommand).pipe(
74 Effect.flatMap((child) => child.exitCode),
75 Effect.map((exitCode) => exitCode === 0),
76 Effect.orElseSucceed(() => false),
77 );
78});
79
80const warnMissingTool = (tool: NativeStaticTool, checkName: string) =>
81 Effect.logWarning(
82 `${tool.command} is not installed; skipping ${checkName}. Install it with '${tool.installHint}' or run 'brew bundle install --file apps/mobile/Brewfile'.`,
83 );
84
85const runCommand = Effect.fn("runCommand")(function* (
86 command: string,
87 args: ReadonlyArray<string>,
88 cwd: string,
89) {
90 yield* Console.log(`$ ${[command, ...args].join(" ")}`);
91 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
92 const child = yield* spawner.spawn(
93 ChildProcess.make(command, [...args], {
94 cwd,
95 ...commandOutputOptions,
96 shell: process.platform === "win32",
97 }),
98 );
99 const exitCode = Number(yield* child.exitCode);
100
101 if (exitCode !== 0) {
102 return yield* new NativeStaticCheckError({
103 message: `Command exited with non-zero exit code (${exitCode})`,
104 });
105 }
106});
107
108function collectSources(
109 directory: string,
110 root: string,
111): Effect.Effect<
112 ReadonlyArray<string>,
113 PlatformError.PlatformError,
114 FileSystem.FileSystem | Path.Path
115> {
116 return Effect.gen(function* () {
117 const fs = yield* FileSystem.FileSystem;
118 const path = yield* Path.Path;
119 const entries = yield* fs.readDirectory(directory);
120 const sources: Array<string> = [];
121
122 for (const entry of entries) {
123 const entryPath = path.join(directory, entry);
124 const stat = yield* fs.stat(entryPath);
125
126 if (stat.type === "Directory") {
127 const isGeneratedNativeProjectDirectory =
128 directory === root && generatedNativeProjectDirectories.has(entry);
129
130 if (excludedDirectories.has(entry) || isGeneratedNativeProjectDirectory) {
131 continue;
132 }
133
134 sources.push(...(yield* collectSources(entryPath, root)));
135 continue;
136 }
137
138 if (stat.type === "File" && sourceExtensions.has(path.extname(entry))) {
139 sources.push(entryPath);
140 }
141 }
142
143 return sources;
144 });
145}
146
147const runNativeStaticChecks = Effect.fn("runNativeStaticChecks")(function* () {
148 const path = yield* Path.Path;
149 const root = yield* appRoot;
150 const sources = yield* collectSources(root, root);
151 const swiftSources = sources.filter((source) => path.extname(source) === ".swift");
152 const kotlinSources = sources.filter((source) => {
153 const extension = path.extname(source);
154 return extension === ".kt" || extension === ".kts";
155 });
156 const availableTools = new Map<string, boolean>();
157
158 for (const tool of tools) {
159 availableTools.set(tool.command, yield* commandExists(tool.command));
160 }
161
162 yield* Console.log(
163 `Found ${swiftSources.length} Swift and ${kotlinSources.length} Kotlin native source files.`,
164 );
165
166 if (swiftSources.length > 0) {
167 if (availableTools.get("swiftlint")) {
168 yield* runCommand("swiftlint", ["lint", "--config", ".swiftlint.yml", "--strict"], root);
169 } else {
170 yield* warnMissingTool(tools[0], "SwiftLint");
171 }
172 }
173
174 if (kotlinSources.length > 0) {
175 const relativeKotlinSources = kotlinSources.map((source) => path.relative(root, source));
176
177 if (availableTools.get("ktlint")) {
178 yield* runCommand("ktlint", relativeKotlinSources, root);
179 } else {
180 yield* warnMissingTool(tools[1], "ktlint");
181 }
182
183 if (availableTools.get("detekt")) {
184 yield* runCommand(
185 "detekt",
186 [
187 "--config",
188 "detekt.yml",
189 "--input",
190 relativeKotlinSources.join(","),
191 "--build-upon-default-config",
192 ],
193 root,
194 );
195 } else {
196 yield* warnMissingTool(tools[2], "detekt");
197 }
198 }
199
200 yield* Console.log("Skipping generated native project folders: android/, ios/.");
201});
202
203export const mobileNativeStaticCheckCommand = Command.make("mobile-native-static-check", {}, () =>
204 runNativeStaticChecks(),
205).pipe(
206 Command.withDescription("Run mobile native static analysis when native tools are available."),
207);
208
209if (import.meta.main) {
210 Command.run(mobileNativeStaticCheckCommand, { version: "0.0.0" }).pipe(
211 Effect.scoped,
212 Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
213 NodeRuntime.runMain,
214 );
215}