-
Notifications
You must be signed in to change notification settings - Fork 676
Expand file tree
/
Copy pathrun-rn-cli-native-check.mjs
More file actions
493 lines (419 loc) · 13.4 KB
/
Copy pathrun-rn-cli-native-check.mjs
File metadata and controls
493 lines (419 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
import {
appendFileSync,
existsSync,
mkdirSync,
readFileSync,
writeFileSync
} from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import process from "node:process";
const repoRoot = process.cwd();
const defaultWorkDir = path.join(
process.env.TMPDIR ?? "/tmp",
"chartkit-rn-cli-native-check"
);
const defaultProjectName = "ChartKitRnCliNative";
const usage = `Usage:
node scripts/run-rn-cli-native-check.mjs --platform <ios|android|all> [options]
Options:
--dry-run Print commands without executing them.
--work-dir <path> Temporary generated RN CLI app path. Defaults to TMPDIR.
--project-name <name> Generated native project name. Defaults to ChartKitRnCliNative.
--rn-version <version> React Native template version. Defaults to installed RN.
--skip-init Use the existing work dir instead of regenerating it.
--skip-install Skip npm install in the generated app.
--skip-package-build Skip building local Chart Kit packages before install.
--ios-scheme <name> iOS scheme to build. Defaults to project name.
--log-file <path> Write command output to a local log file.
--help Show this help.
`;
let activeLogFile;
const writeLog = (value) => {
if (activeLogFile) appendFileSync(activeLogFile, value, "utf8");
};
const emit = (value) => {
process.stdout.write(value);
writeLog(value);
};
const emitError = (value) => {
process.stderr.write(value);
writeLog(value);
};
const parseArgs = (argv) => {
const options = {
dryRun: false,
iosScheme: undefined,
logFile: undefined,
platform: undefined,
projectName: defaultProjectName,
rnVersion: undefined,
skipInit: false,
skipInstall: false,
skipPackageBuild: false,
workDir: defaultWorkDir
};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
const readValue = () => {
const value = argv[index + 1];
if (!value || value.startsWith("--")) {
throw new Error(`${arg} requires a value`);
}
index += 1;
return value;
};
if (arg === "--dry-run") options.dryRun = true;
else if (arg === "--help" || arg === "-h") options.help = true;
else if (arg === "--ios-scheme") options.iosScheme = readValue();
else if (arg === "--log-file") options.logFile = readValue();
else if (arg === "--platform") options.platform = readValue();
else if (arg === "--project-name") options.projectName = readValue();
else if (arg === "--rn-version") options.rnVersion = readValue();
else if (arg === "--skip-init") options.skipInit = true;
else if (arg === "--skip-install") options.skipInstall = true;
else if (arg === "--skip-package-build") options.skipPackageBuild = true;
else if (arg === "--work-dir") options.workDir = readValue();
else throw new Error(`Unknown argument: ${arg}`);
}
if (options.help) return options;
if (!["ios", "android", "all"].includes(options.platform)) {
throw new Error("--platform must be one of ios, android, or all.");
}
return options;
};
const commandText = (command, args) =>
[command, ...args.map((arg) => (arg.includes(" ") ? `"${arg}"` : arg))].join(
" "
);
const writeCommandOutput = ({ result, summarizeOutput }) => {
const stdout = result.stdout ?? "";
const stderr = result.stderr ?? "";
const failed = result.status !== 0;
if (activeLogFile && summarizeOutput && !failed) {
emit(summarizeOutput({ stderr, stdout }));
return;
}
if (activeLogFile && stdout) emit(stdout);
if (activeLogFile && stderr) emitError(stderr);
};
const run = ({ args, command, cwd, dryRun, summarizeOutput }) => {
const relativeCwd = path.relative(repoRoot, cwd) || ".";
emit(`$ cd ${relativeCwd} && ${commandText(command, args)}\n`);
if (dryRun) return;
const result = spawnSync(command, args, {
cwd,
encoding: "utf8",
maxBuffer: activeLogFile ? 1024 * 1024 * 50 : undefined,
stdio: activeLogFile ? ["inherit", "pipe", "pipe"] : "inherit"
});
if (result.error) throw result.error;
writeCommandOutput({ result, summarizeOutput });
if (result.status !== 0) {
throw new Error(
`${commandText(command, args)} failed with exit code ${result.status ?? 1}`
);
}
};
const readJson = (filePath) => JSON.parse(readFileSync(filePath, "utf8"));
const writeJson = (filePath, value) => {
writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
};
const summarizeXcodebuildOutput = ({ stderr, stdout }) => {
const output = [stdout, stderr].filter(Boolean).join("\n");
const lines = output.split(/\r?\n/);
const keepers = lines.filter(
(line) =>
line.includes("Command line invocation:") ||
line.includes("/usr/bin/xcodebuild") ||
line.includes("Build settings from command line:") ||
line.includes("CODE_SIGNING_ALLOWED") ||
line.includes("Auto-linking React Native module") ||
line.includes("Found 1 module") ||
line.includes("Installing RNSVG") ||
line.includes("BUILD SUCCEEDED") ||
line.includes(
"warning: The value for NSLocationWhenInUseUsageDescription"
) ||
line.includes("warning: Run script build phase")
);
return [
`[xcodebuild output summarized: ${lines.length} lines, ${keepers.length} kept]`,
...keepers,
""
].join("\n");
};
const packageVersion = (packageName) =>
readJson(path.join(repoRoot, "node_modules", packageName, "package.json"))
.version;
const assertPath = (filePath, hint) => {
if (!existsSync(filePath)) throw new Error(`${hint}: ${filePath}`);
};
const candidateJavaHomes = [
process.env.JAVA_HOME,
"/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home",
"/usr/local/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home",
"/opt/homebrew/opt/openjdk/libexec/openjdk.jdk/Contents/Home",
"/usr/local/opt/openjdk/libexec/openjdk.jdk/Contents/Home"
].filter(Boolean);
const withPathPrefix = (directory) =>
[directory, process.env.PATH].filter(Boolean).join(path.delimiter);
const assertJavaAvailable = () => {
const pathResult = spawnSync("java", ["-version"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"]
});
if (pathResult.status === 0) return;
for (const javaHome of candidateJavaHomes) {
const javaCommand = path.join(javaHome, "bin", "java");
if (!existsSync(javaCommand)) continue;
const homeResult = spawnSync(javaCommand, ["-version"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"]
});
if (homeResult.status === 0) {
process.env.JAVA_HOME = javaHome;
process.env.PATH = withPathPrefix(path.dirname(javaCommand));
return;
}
}
const detail = (pathResult.stderr || pathResult.stdout || "").trim();
const suffix = detail ? `\n\n${detail}` : "";
throw new Error(
`Android RN CLI checks require a Java runtime. Install JDK 17 or set JAVA_HOME.${suffix}`
);
};
const candidateAndroidSdkPaths = [
process.env.ANDROID_HOME,
process.env.ANDROID_SDK_ROOT,
path.join(process.env.HOME ?? "", "Library", "Android", "sdk"),
"/opt/homebrew/share/android-commandlinetools",
"/usr/local/share/android-commandlinetools"
].filter(Boolean);
const assertAndroidSdkAvailable = () => {
const sdkPath = candidateAndroidSdkPaths.find((candidate) =>
existsSync(candidate)
);
if (sdkPath) {
process.env.ANDROID_HOME = process.env.ANDROID_HOME ?? sdkPath;
process.env.ANDROID_SDK_ROOT = process.env.ANDROID_SDK_ROOT ?? sdkPath;
return;
}
throw new Error(
"Android RN CLI checks require an Android SDK. Set ANDROID_HOME or ANDROID_SDK_ROOT."
);
};
const cliCommand = () => {
const binaryName = process.platform === "win32" ? "rnc-cli.cmd" : "rnc-cli";
return path.join(repoRoot, "node_modules", ".bin", binaryName);
};
const initializeProject = ({ dryRun, projectName, rnVersion, workDir }) => {
run({
args: [
"init",
projectName,
"--directory",
workDir,
"--version",
rnVersion,
"--pm",
"npm",
"--skip-install",
"--install-pods",
"false",
"--skip-git-init",
"--replace-directory",
"true",
"--package-name",
"io.chartkit.rnclibasic",
"--title",
"Chart Kit RN CLI Basic"
],
command: cliCommand(),
cwd: repoRoot,
dryRun
});
};
const writeMetroConfig = (workDir) => {
const source = `/* eslint-disable @typescript-eslint/no-require-imports */
const path = require("path");
const repoRoot = ${JSON.stringify(repoRoot)};
module.exports = {
projectRoot: __dirname,
watchFolders: [repoRoot],
resolver: {
disableHierarchicalLookup: true,
extraNodeModules: {
"@chart-kit/core": path.resolve(repoRoot, "packages/core/src/index.ts"),
"@chart-kit/svg-renderer": path.resolve(
repoRoot,
"packages/svg-renderer/src/index.ts"
),
"react-native-chart-kit/v2": path.resolve(
repoRoot,
"packages/react-native/src/index.ts"
)
},
nodeModulesPaths: [
path.resolve(__dirname, "node_modules"),
path.resolve(repoRoot, "node_modules")
]
},
transformer: {
babelTransformerPath: require.resolve("metro-babel-transformer")
}
};
`;
writeFileSync(path.join(workDir, "metro.config.js"), source, "utf8");
};
const overlayExampleSource = ({ dryRun, workDir }) => {
const exampleDir = path.join(repoRoot, "examples/rn-cli-basic");
for (const fileName of [
"App.tsx",
"index.js",
"babel.config.js",
"runtimePrelude.js"
]) {
const sourcePath = path.join(exampleDir, fileName);
const targetPath = path.join(workDir, fileName);
emit(
`copy ${path.relative(repoRoot, sourcePath)} -> ${path.relative(repoRoot, targetPath)}\n`
);
if (!dryRun) {
writeFileSync(targetPath, readFileSync(sourcePath, "utf8"), "utf8");
}
}
if (!dryRun) writeMetroConfig(workDir);
};
const updatePackageJson = ({ dryRun, projectName, workDir }) => {
emit(
`write ${path.relative(repoRoot, path.join(workDir, "package.json"))}\n`
);
if (dryRun) return;
const generatedPackage = readJson(path.join(workDir, "package.json"));
writeJson(path.join(workDir, "package.json"), {
...generatedPackage,
name: projectName,
private: true,
scripts: {
android: "react-native run-android",
ios: "react-native run-ios",
start: "react-native start"
},
dependencies: {
"react-native-chart-kit": `file:${repoRoot}`,
react: "^19.2.0",
"react-native": "^0.83.9",
"react-native-svg": "^15.15.4"
},
devDependencies: {
"@react-native-community/cli": "^20.1.3",
"@react-native/metro-config": "0.83.9",
typescript: "^5.9.3"
}
});
};
const prepareProject = (options) => {
const rnVersion = options.rnVersion ?? packageVersion("react-native");
assertPath(cliCommand(), "React Native community CLI binary is missing");
if (!options.skipPackageBuild) {
run({
args: ["run", "build"],
command: "npm",
cwd: repoRoot,
dryRun: options.dryRun
});
}
if (!options.skipInit) {
initializeProject({ ...options, rnVersion });
}
overlayExampleSource(options);
updatePackageJson(options);
if (!options.skipInstall) {
run({
args: ["install"],
command: "npm",
cwd: options.workDir,
dryRun: options.dryRun
});
}
};
const runAndroidReleaseBuild = ({ dryRun, workDir }) => {
const androidDir = path.join(workDir, "android");
const gradlew = process.platform === "win32" ? "gradlew.bat" : "./gradlew";
if (!dryRun) {
assertJavaAvailable();
assertAndroidSdkAvailable();
assertPath(androidDir, "Android native project is missing");
}
run({
args: ["assembleRelease"],
command: gradlew,
cwd: androidDir,
dryRun
});
if (!dryRun) emit("Android release build completed successfully.\n");
};
const runIosReleaseBuild = ({ dryRun, iosScheme, projectName, workDir }) => {
const iosDir = path.join(workDir, "ios");
if (!dryRun) assertPath(iosDir, "iOS native project is missing");
run({ args: ["install"], command: "pod", cwd: iosDir, dryRun });
run({
args: [
"-workspace",
`${projectName}.xcworkspace`,
"-scheme",
iosScheme ?? projectName,
"-configuration",
"Release",
"-destination",
"generic/platform=iOS",
"CODE_SIGNING_ALLOWED=NO",
"-quiet",
"build"
],
command: "xcodebuild",
cwd: iosDir,
dryRun,
summarizeOutput: summarizeXcodebuildOutput
});
if (!dryRun) emit("iOS release build completed successfully.\n");
};
const main = () => {
const options = parseArgs(process.argv.slice(2));
if (options.help) {
process.stdout.write(usage);
return;
}
options.workDir = path.resolve(repoRoot, options.workDir);
if (options.logFile) {
activeLogFile = path.resolve(repoRoot, options.logFile);
mkdirSync(path.dirname(activeLogFile), { recursive: true });
writeFileSync(
activeLogFile,
[
"# RN CLI Native Check Log",
`Date: ${new Date().toISOString()}`,
`Repo: ${repoRoot}`,
""
].join("\n"),
"utf8"
);
}
const platforms =
options.platform === "all" ? ["android", "ios"] : [options.platform];
prepareProject(options);
for (const platform of platforms) {
if (platform === "android") {
runAndroidReleaseBuild(options);
} else {
runIosReleaseBuild(options);
}
}
};
try {
main();
} catch (error) {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
}