-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcli.ts
More file actions
356 lines (316 loc) · 10.4 KB
/
cli.ts
File metadata and controls
356 lines (316 loc) · 10.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
import assert from "node:assert/strict";
import path from "node:path";
import fs from "node:fs";
import { EventEmitter } from "node:events";
import {
chalk,
Command,
Option,
spawn,
oraPromise,
assertFixable,
} from "@react-native-node-api/cli-utils";
import { isSupportedTriplet } from "react-native-node-api";
import { getWeakNodeApiVariables } from "./weak-node-api.js";
import {
platforms,
allTargets,
findPlatformForTarget,
platformHasTarget,
} from "./platforms.js";
import { BaseOpts, TargetContext, Platform } from "./platforms/types.js";
// We're attaching a lot of listeners when spawning in parallel
EventEmitter.defaultMaxListeners = 100;
// TODO: Add automatic ccache support
const verboseOption = new Option(
"--verbose",
"Print more output during the build",
).default(process.env.CI === "true");
const sourcePathOption = new Option(
"--source <path>",
"Specify the source directory containing a CMakeLists.txt file",
).default(process.cwd());
// TODO: Add "MinSizeRel" and "RelWithDebInfo"
const configurationOption = new Option("--configuration <configuration>")
.choices(["Release", "Debug"] as const)
.default("Release");
// TODO: Derive default targets
// This is especially important when driving the build from within a React Native app package.
const { CMAKE_RN_TARGETS } = process.env;
const defaultTargets = CMAKE_RN_TARGETS ? CMAKE_RN_TARGETS.split(",") : [];
for (const target of defaultTargets) {
assert(
(allTargets as string[]).includes(target),
`Unexpected target in CMAKE_RN_TARGETS: ${target}`,
);
}
const targetOption = new Option("--target <target...>", "Targets to build for")
.choices(allTargets)
.default(
defaultTargets,
"CMAKE_RN_TARGETS environment variable split by ','",
);
const buildPathOption = new Option(
"--build <path>",
"Specify the build directory to store the configured CMake project",
);
const cleanOption = new Option(
"--clean",
"Delete the build directory before configuring the project",
);
const outPathOption = new Option(
"--out <path>",
"Specify the output directory to store the final build artifacts",
).default(false, "./{build}/{configuration}");
const defineOption = new Option(
"-D,--define <entry...>",
"Define cache variables passed when configuring projects",
).argParser<Record<string, string | CmakeTypedDefinition>>(
(input, previous = {}) => {
// TODO: Implement splitting of value using a regular expression (using named groups) for the format <var>[:<type>]=<value>
// and return an object keyed by variable name with the string value as value or alternatively an array of [value, type]
const match = input.match(
/^(?<name>[^:=]+)(:(?<type>[^=]+))?=(?<value>.+)$/,
);
if (!match || !match.groups) {
throw new Error(
`Invalid format for -D/--define argument: ${input}. Expected <var>[:<type>]=<value>`,
);
}
const { name, type, value } = match.groups;
return { ...previous, [name]: type ? { value, type } : value };
},
);
const noAutoLinkOption = new Option(
"--no-auto-link",
"Don't mark the output as auto-linkable by react-native-node-api",
);
const noWeakNodeApiLinkageOption = new Option(
"--no-weak-node-api-linkage",
"Don't pass the path of the weak-node-api library from react-native-node-api",
);
let program = new Command("cmake-rn")
.description("Build React Native Node API modules with CMake")
.addOption(targetOption)
.addOption(verboseOption)
.addOption(sourcePathOption)
.addOption(buildPathOption)
.addOption(outPathOption)
.addOption(configurationOption)
.addOption(defineOption)
.addOption(cleanOption)
.addOption(noAutoLinkOption)
.addOption(noWeakNodeApiLinkageOption);
for (const platform of platforms) {
const allOption = new Option(
`--${platform.id}`,
`Enable all ${platform.name} triplets`,
);
program = program.addOption(allOption);
program = platform.amendCommand(program);
}
program = program.action(
async ({ target: requestedTargets, ...baseOptions }) => {
assertFixable(
fs.existsSync(path.join(baseOptions.source, "CMakeLists.txt")),
`No CMakeLists.txt found in source directory: ${chalk.dim(baseOptions.source)}`,
{
instructions: `Change working directory into a directory with a CMakeLists.txt, create one or specify the correct source directory using --source`,
},
);
const buildPath = getBuildPath(baseOptions);
if (baseOptions.clean) {
await fs.promises.rm(buildPath, { recursive: true, force: true });
}
const targets = new Set<string>(requestedTargets);
for (const platform of Object.values(platforms)) {
// Forcing the types a bit here, since the platform id option is dynamically added
if ((baseOptions as Record<string, unknown>)[platform.id]) {
for (const target of platform.targets) {
targets.add(target);
}
}
}
if (targets.size === 0) {
for (const platform of Object.values(platforms)) {
if (platform.isSupportedByHost()) {
for (const target of await platform.defaultTargets()) {
targets.add(target);
}
}
}
if (targets.size === 0) {
throw new Error(
"Found no default targets: Install some platform specific build tools",
);
} else {
console.error(
chalk.yellowBright("ℹ"),
"Using default targets",
chalk.dim("(" + [...targets].join(", ") + ")"),
);
}
}
if (!baseOptions.out) {
baseOptions.out = path.join(buildPath, baseOptions.configuration);
}
const targetContexts = [...targets].map((target) => {
const platform = findPlatformForTarget(target);
const targetBuildPath = getTargetBuildPath(buildPath, target);
return {
target,
platform,
buildPath: targetBuildPath,
outputPath: path.join(targetBuildPath, "out"),
options: baseOptions,
};
});
// Configure every triplet project
const targetsSummary = chalk.dim(`(${getTargetsSummary(targetContexts)})`);
await oraPromise(
Promise.all(
targetContexts.map(({ platform, ...context }) =>
configureProject(platform, context, baseOptions),
),
),
{
text: `Configuring projects ${targetsSummary}`,
isSilent: baseOptions.verbose,
successText: `Configured projects ${targetsSummary}`,
failText: ({ message }) => `Failed to configure projects: ${message}`,
},
);
// Build every triplet project
await oraPromise(
Promise.all(
targetContexts.map(async ({ platform, ...context }) => {
// Delete any stale build artifacts before building
// This is important, since we might rename the output files
await fs.promises.rm(context.outputPath, {
recursive: true,
force: true,
});
await buildProject(platform, context, baseOptions);
}),
),
{
text: "Building projects",
isSilent: baseOptions.verbose,
successText: "Built projects",
failText: ({ message }) => `Failed to build projects: ${message}`,
},
);
// Perform post-build steps for each platform in sequence
for (const platform of platforms) {
const relevantTargets = targetContexts.filter(({ target }) =>
platformHasTarget(platform, target),
);
if (relevantTargets.length == 0) {
continue;
}
await platform.postBuild(
{
outputPath: baseOptions.out || baseOptions.source,
targets: relevantTargets,
},
baseOptions,
);
}
},
);
function getTargetsSummary(
targetContexts: { target: string; platform: Platform }[],
) {
const targetsPerPlatform: Record<string, string[]> = {};
for (const { target, platform } of targetContexts) {
if (!targetsPerPlatform[platform.id]) {
targetsPerPlatform[platform.id] = [];
}
targetsPerPlatform[platform.id].push(target);
}
return Object.entries(targetsPerPlatform)
.map(([platformId, targets]) => {
return `${platformId}: ${targets.join(", ")}`;
})
.join(" / ");
}
function getBuildPath({ build, source }: BaseOpts) {
// TODO: Add configuration (debug vs release)
return path.resolve(process.cwd(), build || path.join(source, "build"));
}
/**
* Namespaces the output path with a target name
*/
function getTargetBuildPath(buildPath: string, target: unknown) {
assert(typeof target === "string", "Expected target to be a string");
return path.join(buildPath, target.replace(/;/g, "_"));
}
async function configureProject<T extends string>(
platform: Platform<T[], Record<string, unknown>>,
context: TargetContext<T>,
options: BaseOpts,
) {
const { target, buildPath, outputPath } = context;
const { verbose, source, weakNodeApiLinkage } = options;
const nodeApiDefinitions =
weakNodeApiLinkage && isSupportedTriplet(target)
? getWeakNodeApiVariables(target)
: // TODO: Make this a part of the platform definition
{};
const definitions = {
...nodeApiDefinitions,
...options.define,
CMAKE_LIBRARY_OUTPUT_DIRECTORY: outputPath,
};
await spawn(
"cmake",
[
"-S",
source,
"-B",
buildPath,
...platform.configureArgs(context, options),
...toDefineArguments(definitions),
],
{
outputMode: verbose ? "inherit" : "buffered",
outputPrefix: verbose ? chalk.dim(`[${target}] `) : undefined,
},
);
}
async function buildProject<T extends string>(
platform: Platform<T[], Record<string, unknown>>,
context: TargetContext<T>,
options: BaseOpts,
) {
const { target, buildPath } = context;
const { verbose, configuration } = options;
await spawn(
"cmake",
[
"--build",
buildPath,
"--config",
configuration,
"--",
...platform.buildArgs(context, options),
],
{
outputMode: verbose ? "inherit" : "buffered",
outputPrefix: verbose ? chalk.dim(`[${target}] `) : undefined,
},
);
}
type CmakeTypedDefinition = { value: string; type: string };
function toDefineArguments(
declarations: Record<string, string | CmakeTypedDefinition>,
) {
return Object.entries(declarations).flatMap(([key, definition]) => {
if (typeof definition === "string") {
return ["-D", `${key}=${definition}`];
} else {
return ["-D", `${key}:${definition.type}=${definition.value}`];
}
});
}
export { program };