-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcli.ts
More file actions
304 lines (270 loc) · 8.92 KB
/
cli.ts
File metadata and controls
304 lines (270 loc) · 8.92 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
import assert from "node:assert/strict";
import path from "node:path";
import fs from "node:fs";
import { EventEmitter } from "node:events";
import { Command, Option } from "@commander-js/extra-typings";
import { spawn, SpawnFailure } from "bufout";
import { oraPromise } from "ora";
import chalk from "chalk";
import {
platforms,
allTargets,
findPlatformForTarget,
platformHasTarget,
} from "./platforms.js";
import { toDeclarationArguments } from "./cmake.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 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(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 }) => {
try {
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) {
// Skip redundant targets
if (platform.redundantTargets?.includes(target)) {
continue;
}
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,
);
}
} catch (error) {
if (error instanceof SpawnFailure) {
error.flushOutput("both");
}
throw error;
}
},
);
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) {
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");
// TODO: Add configuration (debug vs release) for platforms using single-config CMake generators
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 } = options;
await spawn(
"cmake",
[
"-S",
source,
"-B",
buildPath,
...platform.configureArgs(context, options),
...toDeclarationArguments({
CMAKE_LIBRARY_OUTPUT_DIRECTORY: outputPath,
}),
],
{
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 } = options;
await spawn(
"cmake",
["--build", buildPath, ...platform.buildArgs(context, options)],
{
outputMode: verbose ? "inherit" : "buffered",
outputPrefix: verbose ? chalk.dim(`[${target}] `) : undefined,
},
);
}
export { program };