-
Notifications
You must be signed in to change notification settings - Fork 98
/
copy-assets.ts
565 lines (511 loc) · 15.3 KB
/
copy-assets.ts
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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
import type { Config as CLIConfig } from "@react-native-community/cli-types";
import { error, info, warn } from "@rnx-kit/console";
import { isNonEmptyArray } from "@rnx-kit/tools-language/array";
import type { PackageManifest } from "@rnx-kit/tools-node/package";
import {
findPackageDependencyDir,
findPackageDir,
readPackage,
} from "@rnx-kit/tools-node/package";
import type { AllPlatforms } from "@rnx-kit/tools-react-native";
import { parsePlatform } from "@rnx-kit/tools-react-native";
import type { SpawnSyncOptions } from "child_process";
import { spawnSync } from "child_process";
import * as fs from "fs-extra";
import * as os from "os";
import * as path from "path";
export type AndroidArchive = {
targetName?: string;
version?: string;
output?: string;
android?: {
androidPluginVersion?: string;
compileSdkVersion?: number;
defaultConfig?: {
minSdkVersion?: number;
targetSdkVersion?: number;
};
};
};
export type NativeAssets = {
assets?: string[];
strings?: string[];
aar?: AndroidArchive & {
env?: Record<string, string | number>;
dependencies?: Record<string, AndroidArchive>;
};
xcassets?: string[];
};
export type Options = {
platform: AllPlatforms;
assetsDest: string;
bundleAar: boolean;
xcassetsDest?: string;
[key: string]: unknown;
};
export type Context = {
projectRoot: string;
manifest: PackageManifest;
options: Options;
};
export type AssetsConfig = {
getAssets?: (context: Context) => Promise<NativeAssets>;
};
const defaultAndroidConfig: Required<Required<AndroidArchive>["android"]> = {
androidPluginVersion: "7.1.3",
compileSdkVersion: 31,
defaultConfig: {
minSdkVersion: 23,
targetSdkVersion: 29,
},
};
function ensureOption(options: Options, opt: string, flag = opt) {
if (options[opt] == null) {
error(`Missing required option: --${flag}`);
process.exit(1);
}
}
function findGradleProject(projectRoot: string): string | undefined {
if (fs.existsSync(path.join(projectRoot, "android", "build.gradle"))) {
return path.join(projectRoot, "android");
}
if (fs.existsSync(path.join(projectRoot, "build.gradle"))) {
return projectRoot;
}
return undefined;
}
function gradleTargetName(packageName: string): string {
return (
packageName.startsWith("@") ? packageName.slice(1) : packageName
).replace(/[^\w\-.]+/g, "_");
}
function isAssetsConfig(config: unknown): config is AssetsConfig {
return typeof config === "object" && config !== null && "getAssets" in config;
}
function keysOf(record: Record<string, unknown> | undefined): string[] {
return record ? Object.keys(record) : [];
}
export function versionOf(pkgName: string): string {
const packageDir = findPackageDependencyDir(pkgName);
if (!packageDir) {
throw new Error(`Could not find module '${pkgName}'`);
}
const { version } = readPackage(packageDir);
return version;
}
function getAndroidPaths(
context: Context,
packageName: string,
{ targetName, version, output }: AndroidArchive
) {
const projectRoot = findPackageDependencyDir(packageName);
if (!projectRoot) {
throw new Error(`Could not find module '${packageName}'`);
}
const gradleFriendlyName = targetName || gradleTargetName(packageName);
const aarVersion = version || versionOf(packageName);
switch (packageName) {
case "hermes-engine":
return {
targetName: gradleFriendlyName,
version: aarVersion,
projectRoot,
output: path.join(projectRoot, "android", "hermes-release.aar"),
destination: path.join(
context.options.assetsDest,
"aar",
`hermes-release-${versionOf(packageName)}.aar`
),
};
case "react-native":
return {
targetName: gradleFriendlyName,
version: aarVersion,
projectRoot,
output: path.join(projectRoot, "android"),
destination: path.join(
context.options.assetsDest,
"aar",
"react-native"
),
};
default: {
const androidProject = findGradleProject(projectRoot);
return {
targetName: gradleFriendlyName,
version: aarVersion,
projectRoot,
androidProject,
output:
output ||
(androidProject &&
path.join(
androidProject,
"build",
"outputs",
"aar",
`${gradleFriendlyName}-release.aar`
)),
destination: path.join(
context.options.assetsDest,
"aar",
`${gradleFriendlyName}-${aarVersion}.aar`
),
};
}
}
}
function run(command: string, args: string[], options: SpawnSyncOptions) {
const { status } = spawnSync(command, args, options);
if (status !== 0) {
process.exit(status || 1);
}
}
export async function assembleAarBundle(
context: Context,
packageName: string,
{ aar }: NativeAssets
): Promise<void> {
if (!aar) {
return;
}
const findUp = require("find-up");
const gradlew = await findUp(
os.platform() === "win32" ? "gradlew.bat" : "gradlew"
);
if (!gradlew) {
warn(`Skipped \`${packageName}\`: cannot find \`gradlew\``);
return;
}
const { targetName, version, androidProject, output } = getAndroidPaths(
context,
packageName,
aar
);
if (!androidProject || !output) {
warn(`Skipped \`${packageName}\`: cannot find \`build.gradle\``);
return;
}
const { env: customEnv, dependencies, android } = aar;
const env = {
NODE_MODULES_PATH: path.join(process.cwd(), "node_modules"),
REACT_NATIVE_VERSION: versionOf("react-native"),
...process.env,
...customEnv,
};
const outputDir = path.join(context.options.assetsDest, "aar");
await fs.ensureDir(outputDir);
const dest = path.join(outputDir, `${targetName}-${version}.aar`);
const targets = [`:${targetName}:assembleRelease`];
const targetsToCopy: [string, string][] = [[output, dest]];
const settings = path.join(androidProject, "settings.gradle");
if (fs.existsSync(settings)) {
if (dependencies) {
for (const [dependencyName, aar] of Object.entries(dependencies)) {
const { targetName, output, destination } = getAndroidPaths(
context,
dependencyName,
aar
);
if (output) {
if (!fs.existsSync(output)) {
targets.push(`:${targetName}:assembleRelease`);
targetsToCopy.push([output, destination]);
} else if (!fs.existsSync(destination)) {
targetsToCopy.push([output, destination]);
}
}
}
}
// Run only one Gradle task at a time
run(gradlew, targets, { cwd: androidProject, stdio: "inherit", env });
} else {
const reactNativePath = findPackageDependencyDir("react-native");
if (!reactNativePath) {
throw new Error("Could not find 'react-native'");
}
const buildDir = path.join(
process.cwd(),
"node_modules",
".rnx-gradle-build",
targetName
);
const compileSdkVersion =
android?.compileSdkVersion ?? defaultAndroidConfig.compileSdkVersion;
const minSdkVersion =
android?.defaultConfig?.minSdkVersion ??
defaultAndroidConfig.defaultConfig.minSdkVersion;
const targetSdkVersion =
android?.defaultConfig?.targetSdkVersion ??
defaultAndroidConfig.defaultConfig.targetSdkVersion;
const androidPluginVersion =
android?.androidPluginVersion ??
defaultAndroidConfig.androidPluginVersion;
const buildRelativeReactNativePath = path.relative(
buildDir,
reactNativePath
);
const buildGradle = [
"buildscript {",
" ext {",
` compileSdkVersion = ${compileSdkVersion}`,
` minSdkVersion = ${minSdkVersion}`,
` targetSdkVersion = ${targetSdkVersion}`,
` androidPluginVersion = "${androidPluginVersion}"`,
" }",
"",
" repositories {",
" mavenCentral()",
" google()",
" }",
"",
" dependencies {",
' classpath("com.android.tools.build:gradle:${project.ext.androidPluginVersion}")',
" }",
"}",
"",
"allprojects {",
" repositories {",
" maven {",
" // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm",
` url("\${rootDir}/${buildRelativeReactNativePath}/android")`,
" }",
" mavenCentral()",
" google()",
" }",
"}",
"",
].join("\n");
const gradleProperties = "android.useAndroidX=true\n";
const settingsGradle = [
`include(":${targetName}")`,
`project(":${targetName}").projectDir = file("${androidProject}")`,
"",
].join("\n");
await fs.ensureDir(buildDir);
await fs.writeFile(path.join(buildDir, "build.gradle"), buildGradle);
await fs.writeFile(
path.join(buildDir, "gradle.properties"),
gradleProperties
);
await fs.writeFile(path.join(buildDir, "settings.gradle"), settingsGradle);
// Run only one Gradle task at a time
run(gradlew, targets, { cwd: buildDir, stdio: "inherit", env });
}
await Promise.all(targetsToCopy.map(([src, dest]) => fs.copy(src, dest)));
}
async function copyFiles(files: unknown, destination: string): Promise<void> {
if (!isNonEmptyArray<string>(files)) {
return;
}
await fs.ensureDir(destination);
await Promise.all(
files.map((file) => {
const basename = path.basename(file);
return fs.copy(file, `${destination}/${basename}`);
})
);
}
async function copyXcodeAssets(
xcassets: unknown,
destination: string
): Promise<void> {
if (!isNonEmptyArray<string>(xcassets)) {
return;
}
await fs.ensureDir(destination);
await Promise.all(
xcassets.map((catalog) => {
const dest = `${destination}/${path.basename(catalog)}`;
return fs.copy(catalog, dest);
})
);
}
export async function copyAssets(
{ options: { assetsDest, xcassetsDest } }: Context,
packageName: string,
{ assets, strings, xcassets }: NativeAssets
): Promise<void> {
const tasks = [
copyFiles(assets, `${assetsDest}/assets/${packageName}`),
copyFiles(strings, `${assetsDest}/strings/${packageName}`),
];
if (typeof xcassetsDest === "string") {
tasks.push(copyXcodeAssets(xcassets, xcassetsDest));
}
await Promise.all(tasks);
}
export async function gatherConfigs({
projectRoot,
manifest,
}: Context): Promise<Record<string, AssetsConfig | null> | undefined> {
const { dependencies, devDependencies } = manifest;
const packages = [...keysOf(dependencies), ...keysOf(devDependencies)];
if (packages.length === 0) {
return;
}
const resolveOptions = { paths: [projectRoot] };
const assetsConfigs: Record<string, AssetsConfig | null> = {};
for (const pkg of packages) {
try {
const pkgPath = path.dirname(
require.resolve(`${pkg}/package.json`, resolveOptions)
);
const reactNativeConfig = `${pkgPath}/react-native.config.js`;
if (fs.existsSync(reactNativeConfig)) {
const { nativeAssets } = require(reactNativeConfig);
if (nativeAssets) {
assetsConfigs[pkg] = nativeAssets;
}
}
} catch (err) {
warn(err);
}
}
// Overrides from project config
const reactNativeConfig = `${projectRoot}/react-native.config.js`;
if (fs.existsSync(reactNativeConfig)) {
const { nativeAssets } = require(reactNativeConfig);
const overrides = Object.entries(nativeAssets);
for (const [pkgName, config] of overrides) {
if (config === null || isAssetsConfig(config)) {
assetsConfigs[pkgName] = config;
}
}
}
return assetsConfigs;
}
/**
* Copies additional assets not picked by bundlers into desired directory.
*
* The way this works is by scanning all direct dependencies of the current
* project for a file, `react-native.config.js`, whose contents include a
* field, `nativeAssets`, and a function that returns assets to copy:
*
* ```js
* // react-native.config.js
* module.exports = {
* nativeAssets: {
* getAssets: (context) => {
* return {
* assets: [],
* strings: [],
* xcassets: [],
* };
* }
* }
* };
* ```
*
* We also allow the project itself to override this where applicable. The
* format is similar and looks like this:
*
* ```js
* // react-native.config.js
* module.exports = {
* nativeAssets: {
* "some-library": {
* getAssets: (context) => {
* return {
* assets: [],
* strings: [],
* xcassets: [],
* };
* }
* },
* "another-library": {
* getAssets: (context) => {
* return {
* assets: [],
* strings: [],
* xcassets: [],
* };
* }
* }
* }
* };
* ```
*
* @param options Options dictate what gets copied where
*/
export async function copyProjectAssets(options: Options): Promise<void> {
const projectRoot = findPackageDir() || process.cwd();
const content = await fs.readFile(`${projectRoot}/package.json`, {
encoding: "utf-8",
});
const manifest: PackageManifest = JSON.parse(content);
const context = { projectRoot, manifest, options };
const assetConfigs = await gatherConfigs(context);
if (!assetConfigs) {
return;
}
const dependencies = Object.entries(assetConfigs);
for (const [packageName, config] of dependencies) {
if (!isAssetsConfig(config)) {
continue;
}
const { getAssets } = config;
if (typeof getAssets !== "function") {
warn(`Skipped \`${packageName}\`: getAssets is not a function`);
continue;
}
const assets = await getAssets(context);
if (options.bundleAar && assets.aar) {
info(`Assembling "${packageName}"`);
await assembleAarBundle(context, packageName, assets);
} else {
info(`Copying assets for "${packageName}"`);
await copyAssets(context, packageName, assets);
}
}
if (options.bundleAar) {
const dummyAar = { targetName: "dummy" };
const copyTasks = [];
for (const dependencyName of ["hermes-engine", "react-native"]) {
const { output, destination } = getAndroidPaths(
context,
dependencyName,
dummyAar
);
if (
output &&
(!fs.existsSync(destination) || fs.statSync(destination).isDirectory())
) {
info(`Copying Android Archive of "${dependencyName}"`);
copyTasks.push(fs.copy(output, destination));
}
}
await Promise.all(copyTasks);
}
}
export const rnxCopyAssetsCommand = {
name: "rnx-copy-assets",
description:
"Copies additional assets not picked by bundlers into desired directory.",
func: (_argv: string[], _config: CLIConfig, options: Options) => {
ensureOption(options, "platform");
ensureOption(options, "assetsDest", "assets-dest");
return copyProjectAssets(options);
},
options: [
{
name: "--platform <string>",
description: "platform to target",
parse: parsePlatform,
},
{
name: "--assets-dest <string>",
description: "path of the directory to copy assets into",
},
{
name: "--bundle-aar <boolean>",
description: "whether to bundle AARs of dependencies",
default: false,
},
{
name: "--xcassets-dest <string>",
description:
"path of the directory to copy Xcode asset catalogs into. Asset catalogs will only be copied if a destination path is specified.",
},
],
};