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

mobile-native-static-check.ts

208 lines5.9 KB

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