-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathinitWindows.ts
More file actions
423 lines (372 loc) · 12.3 KB
/
Copy pathinitWindows.ts
File metadata and controls
423 lines (372 loc) · 12.3 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
/**
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
* @format
*/
import fs from '@react-native-windows/fs';
import path from 'path';
import chalk from 'chalk';
import {glob as globFunc} from 'glob';
import _ from 'lodash';
import {performance} from 'perf_hooks';
import {Ora} from 'ora';
import util from 'util';
const glob = util.promisify(globFunc);
import type {Command, Config} from '@react-native-community/cli-types';
import {CodedError, Telemetry} from '@react-native-windows/telemetry';
import {
newSpinner,
setExitProcessWithError,
} from '../../utils/commandWithProgress';
import * as pathHelpers from '../../utils/pathHelpers';
import {
getDefaultOptions,
startTelemetrySession,
endTelemetrySession,
} from '../../utils/telemetryHelpers';
import {copyAndReplaceWithChangedCallback} from '../../generator-common';
import * as nameHelpers from '../../utils/nameHelpers';
import {showOldArchitectureWarning} from '../../utils/oldArchWarning';
import type {InitOptions} from './initWindowsOptions';
import {initOptions} from './initWindowsOptions';
export interface TemplateFileMapping {
from: string;
to: string;
replacements?: Record<string, any>;
}
export interface InitWindowsTemplateConfig {
name: string;
description: string;
isDefault?: boolean;
preInstall?: (config: Config, options: InitOptions) => Promise<void>;
getFileMappings?: (
config: Config,
options: InitOptions,
) => Promise<TemplateFileMapping[]>;
postInstall?: (config: Config, options: InitOptions) => Promise<void>;
}
export class InitWindows {
protected readonly rnwPath: string;
protected readonly rnwConfig?: Record<string, any>;
protected readonly templates: Map<string, InitWindowsTemplateConfig> =
new Map();
constructor(readonly config: Config, readonly options: InitOptions) {
this.rnwPath = pathHelpers.resolveRnwRoot(this.config.root);
this.rnwConfig = this.config.project.windows?.rnwConfig;
}
protected verboseMessage(message: any) {
verboseMessage(message, !!this.options.logging);
}
protected async loadTemplates() {
const templatesRoot = path.join(this.rnwPath, 'templates');
for (const file of await glob('**/template.config.js', {
cwd: templatesRoot,
})) {
const templateName = path.dirname(file).replace(/[\\]/g, '/');
const templateConfig: InitWindowsTemplateConfig = require(path.join(
templatesRoot,
file,
));
this.templates.set(templateName, templateConfig);
}
if (this.templates.size === 0) {
throw new CodedError(
'NoTemplatesFound',
`No templates were found in ${templatesRoot}.`,
);
}
}
protected getDefaultTemplateName(): string {
for (const [name, config] of this.templates) {
if (config.isDefault) {
return name;
}
}
throw new CodedError(
'NoDefaultTemplate',
'No template specified and no default template found.',
);
}
protected getReactNativeProjectName(projectDir: string): string {
this.verboseMessage('Looking for project name in package.json...');
const pkgJsonPath = path.join(projectDir, 'package.json');
if (!fs.existsSync(pkgJsonPath)) {
throw new CodedError(
'NoPackageJson',
'Unable to find package.json. This should be run from within an existing react-native project.',
);
}
type PackageJson = {name: string};
let name = fs.readJsonFileSync<PackageJson>(pkgJsonPath).name;
if (!name) {
const appJsonPath = path.join(projectDir, 'app.json');
if (fs.existsSync(appJsonPath)) {
this.verboseMessage('Looking for project name in app.json...');
name = fs.readJsonFileSync<PackageJson>(pkgJsonPath).name;
}
}
if (!name) {
throw new CodedError(
'NoProjectName',
'Please specify name in package.json or app.json',
);
}
return name;
}
protected printTemplateList() {
if (this.templates.size === 0) {
console.log('\nNo templates found.\n');
return;
}
for (const [key, value] of this.templates.entries()) {
const defaultLabel = value.isDefault ? chalk.yellow('[Default] ') : '';
console.log(
`\n${key} - ${value.name}\n ${defaultLabel}${value.description}`,
);
}
console.log(`\n`);
}
// eslint-disable-next-line complexity
public async run(spinner: Ora) {
await this.loadTemplates();
spinner.info();
if (this.options.list) {
this.printTemplateList();
return;
}
this.options.template ??=
(this.rnwConfig?.['init-windows']?.template as string | undefined) ??
this.getDefaultTemplateName();
spinner.info(`Using template '${this.options.template}'...`);
if (!this.templates.has(this.options.template.replace(/[\\]/g, '/'))) {
throw new CodedError(
'InvalidTemplateName',
`Unable to find template '${this.options.template}'.`,
);
}
const isOldArchTemplate = this.options.template.startsWith('old');
if (isOldArchTemplate) {
showOldArchitectureWarning();
}
const templateConfig = this.templates.get(this.options.template)!;
// Check if there's a passed-in project name and if it's valid
if (
this.options.name &&
!nameHelpers.isValidProjectName(this.options.name)
) {
throw new CodedError(
'InvalidProjectName',
`The specified name '${this.options.name}' is not a valid identifier`,
);
}
// If no project name is provided, check previously used name or calculate a name and clean if necessary
if (!this.options.name) {
const projectName =
(this.rnwConfig?.['init-windows']?.name as string | undefined) ??
this.getReactNativeProjectName(this.config.root);
this.options.name = nameHelpers.isValidProjectName(projectName)
? projectName
: nameHelpers.cleanName(projectName);
}
// Final check that the project name is valid
if (!nameHelpers.isValidProjectName(this.options.name)) {
throw new CodedError(
'InvalidProjectName',
`The name '${this.options.name}' is not a valid identifier`,
);
}
// Check if there's a passed-in project namespace and if it's valid
if (
this.options.namespace &&
!nameHelpers.isValidProjectNamespace(this.options.namespace)
) {
throw new CodedError(
'InvalidProjectNamespace',
`The specified namespace '${this.options.namespace}' is not a valid identifier`,
);
}
// If no project namespace is provided, check previously used namespace or use the project name and clean if necessary
if (!this.options.namespace) {
const namespace =
(this.rnwConfig?.['init-windows']?.namespace as string | undefined) ??
this.options.name;
this.options.namespace = nameHelpers.isValidProjectNamespace(namespace)
? namespace
: nameHelpers.cleanNamespace(namespace);
}
// Final check that the project namespace is valid
if (!nameHelpers.isValidProjectNamespace(this.options.namespace)) {
throw new CodedError(
'InvalidProjectNamespace',
`The namespace '${this.options.namespace}' is not a valid identifier`,
);
}
if (templateConfig.preInstall) {
spinner.info(`Running ${this.options.template} preInstall()...`);
await templateConfig.preInstall(this.config, this.options);
}
// Get template files to copy and copy if available
if (templateConfig.getFileMappings) {
const fileMappings = await templateConfig.getFileMappings(
this.config,
this.options,
);
for (const fileMapping of fileMappings) {
const targetDir = path.join(
this.config.root,
path.dirname(fileMapping.to),
);
if (!(await fs.exists(targetDir))) {
await fs.mkdir(targetDir, {recursive: true});
}
await copyAndReplaceWithChangedCallback(
fileMapping.from,
this.config.root,
fileMapping.to,
fileMapping.replacements,
this.options.overwrite,
);
}
}
if (templateConfig.postInstall) {
spinner.info(`Running ${this.options.template} postInstall()...`);
await templateConfig.postInstall(this.config, this.options);
}
spinner.succeed();
}
}
/**
* Logs the given message if verbose is True.
* @param message The message to log.
* @param verbose Whether or not verbose logging is enabled.
*/
function verboseMessage(message: any, verbose?: boolean) {
if (verbose) {
console.log(message);
}
}
/**
* Sanitizes the given option for telemetry.
* @param key The key of the option.
* @param value The unsanitized value of the option.
* @returns The sanitized value of the option.
*/
function optionSanitizer(key: keyof InitOptions, value: any): any {
// Do not add a default case here.
// Strings risking PII should just return true if present, false otherwise.
// All others should return the value (or false if undefined).
switch (key) {
case 'name':
case 'namespace':
return value === undefined ? false : true; // Strip PII
case 'logging':
case 'template':
case 'overwrite':
case 'telemetry':
case 'list':
return value === undefined ? false : value; // Return value
}
}
/**
* Get the extra props to add to the `init-windows` telemetry event.
* @returns The extra props.
*/
async function getExtraProps(): Promise<Record<string, any>> {
const extraProps: Record<string, any> = {};
return extraProps;
}
function sanitizeOptions(
opts: Record<string, any>,
sanitizer: (key: keyof InitOptions, value: any) => any,
): Record<string, any> {
const sanitized: Record<string, any> = {};
for (const key in opts) {
if (Object.prototype.hasOwnProperty.call(opts, key)) {
sanitized[key] = sanitizer(key as keyof InitOptions, opts[key]);
}
}
return sanitized;
}
/**
* The function run when calling `npx @react-native-community/cli init-windows`.
* @param args Unprocessed args passed from react-native CLI.
* @param config Config passed from react-native CLI.
* @param options Options passed from react-native CLI.
*/
async function initWindows(
args: string[],
config: Config,
options: InitOptions,
) {
await startTelemetrySession(
'init-windows',
config,
options,
getDefaultOptions(config, initOptions),
optionSanitizer,
);
let initWindowsError: Error | undefined;
try {
await initWindowsInternal(args, config, options);
} catch (ex) {
initWindowsError =
ex instanceof Error ? (ex as Error) : new Error(String(ex));
Telemetry.trackException(initWindowsError);
}
// Now, instead of custom fields, just pass the final options object
await endTelemetrySession(initWindowsError, getExtraProps, options, opts =>
sanitizeOptions(opts, optionSanitizer),
);
setExitProcessWithError(options.logging, initWindowsError);
}
/**
* Initializes a new RNW project from a given template.
* @param args Unprocessed args passed from react-native CLI.
* @param config Config passed from react-native CLI.
* @param options Options passed from react-native CLI.
* @param existingSpinner Optional existing spinner to use instead of creating a new one.
*/
export async function initWindowsInternal(
args: string[],
config: Config,
options: InitOptions,
existingSpinner?: Ora,
) {
const startTime = performance.now();
const spinner = existingSpinner || newSpinner('Running init-windows...');
const shouldLog = !existingSpinner; // Only log completion messages if we created our own spinner
try {
const codegen = new InitWindows(config, options);
await codegen.run(spinner);
const endTime = performance.now();
if (shouldLog) {
console.log(
`${chalk.green('Success:')} init-windows completed. (${Math.round(
endTime - startTime,
)}ms)`,
);
}
} catch (e) {
if (!existingSpinner) {
spinner.fail();
}
const endTime = performance.now();
if (shouldLog) {
console.log(
`${chalk.red('Error:')} ${(e as any).toString()}. (${Math.round(
endTime - startTime,
)}ms)`,
);
}
throw e;
}
}
/**
* Initializes a new RNW project from a given template.
*/
export const initCommand: Command = {
name: 'init-windows',
description: 'Initializes a new RNW project from a given template',
func: initWindows,
options: initOptions,
};