forked from microsoft/react-native-windows
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
496 lines (442 loc) · 14.4 KB
/
index.ts
File metadata and controls
496 lines (442 loc) · 14.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
494
495
496
/**
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT License.
* @format
*/
import chalk from 'chalk';
import path from 'path';
import username from 'username';
import childProcess from 'child_process';
import crypto from 'crypto';
import fs from '@react-native-windows/fs';
import semver from 'semver';
import _ from 'lodash';
import findUp from 'find-up';
import {
readProjectFile,
findPropertyValue,
} from '../commands/config/configUtils';
import * as nameHelpers from '../utils/nameHelpers';
import {
createDir,
copyAndReplaceAll,
copyAndReplaceWithChangedCallback,
} from '../generator-common';
import {GenerateOptions} from '..';
import {
CodedError,
getVersionOfNpmPackage,
} from '@react-native-windows/telemetry';
import {
findPackage,
WritableNpmPackage,
} from '@react-native-windows/package-utils';
const windowsDir = 'windows';
const bundleDir = 'Bundle';
/**
* This represents the data to insert nuget packages
*/
interface NugetPackage {
id: string;
version: string;
privateAssets: boolean;
}
function resolveRnwPath(subpath: string): string {
return require.resolve(path.join('react-native-windows', subpath), {
paths: [process.cwd()],
});
}
// Existing high cyclomatic complexity
// eslint-disable-next-line complexity
export async function copyProjectTemplateAndReplace(
srcRootPath: string,
destPath: string,
newProjectName: string,
namespace: string,
options: GenerateOptions,
) {
if (!srcRootPath) {
throw new CodedError(
'CopyProjectTemplateNoSourcePath',
'Need a path to copy from',
);
}
if (!destPath) {
throw new CodedError(
'CopyProjectTemplateNoDestPath',
'Need a path to copy to',
);
}
if (!newProjectName) {
throw new CodedError(
'CopyProjectTemplateNoProjectName',
'Need a project name',
);
}
const projectType = options.projectType;
const language = options.language;
// @react-native-community/cli init only allows alphanumerics in project names, but other
// new project tools (like expo and create-react-native-module) are less strict.
// The default (legacy) behavior of this flow is to clean the name rather than throw an error.
if (!nameHelpers.isValidProjectName(newProjectName)) {
newProjectName = nameHelpers.cleanName(newProjectName);
}
// Similar to the above, but we want to retain namespace separators
// The default (legacy) behavior of this flow is to clean the name rather than throw an error.
if (!nameHelpers.isValidProjectNamespace(namespace)) {
namespace = nameHelpers.cleanNamespace(namespace);
}
// Checking if we're overwriting an existing project and re-uses their projectGUID
const existingProjectPath = path.join(
destPath,
windowsDir,
newProjectName,
newProjectName + (language === 'cs' ? '.csproj' : '.vcxproj'),
);
let existingProjectGuid: string | undefined;
if (fs.existsSync(existingProjectPath)) {
console.log('Found existing project, extracting ProjectGuid.');
existingProjectGuid = findPropertyValue(
readProjectFile(existingProjectPath),
'ProjectGuid',
existingProjectPath,
).replace(/[{}]/g, '');
}
createDir(path.join(destPath, windowsDir));
createDir(path.join(destPath, windowsDir, newProjectName));
if (projectType === 'app') {
createDir(path.join(destPath, windowsDir, newProjectName, bundleDir));
createDir(path.join(destPath, windowsDir, newProjectName, 'BundleBuilder'));
}
const namespaceCpp = toCppNamespace(namespace);
if (options.experimentalNuGetDependency) {
console.log('Using experimental NuGet dependency.');
}
if (options.useWinUI3) {
throw new CodedError(
'IncompatibleOptions',
'Experimental WinUI 3 project has been deprecated.',
);
}
const projDir = 'proj';
const srcPath = path.join(srcRootPath, `${language}-${projectType}`);
const sharedPath = path.join(srcRootPath, `shared-${projectType}`);
const projectGuid = existingProjectGuid || crypto.randomUUID();
const rnwPath = path.dirname(resolveRnwPath('package.json'));
const rnwVersion = require(resolveRnwPath('package.json')).version;
const nugetVersion = options.nuGetTestVersion || rnwVersion;
const packageGuid = crypto.randomUUID();
const currentUser = username.sync()!; // Gets the current username depending on the platform.
let mainComponentName = newProjectName;
const appJsonPath = await findUp('app.json', {cwd: destPath});
if (appJsonPath) {
const appJson = await fs.readJsonFile<{name: string}>(appJsonPath);
mainComponentName = appJson.name;
}
// We should prefer putting new, necessary PackageReference dependencies into the appropriate
// external property sheets, but this is here if we "must" inject the dependency into the project file
const csNugetPackages: NugetPackage[] = [];
const cppNugetPackages: NugetPackage[] = [];
const templateVars: Record<string, any> = {
useMustache: true,
regExpPatternsToRemove: [],
name: newProjectName,
namespace: namespace,
namespaceCpp: namespaceCpp,
languageIsCpp: language === 'cpp',
rnwVersion: await getVersionOfNpmPackage('react-native-windows'),
rnwPathFromProjectRoot: path
.relative(destPath, rnwPath)
.replace(/\//g, '\\'),
mainComponentName: mainComponentName,
// Visual Studio is very picky about the casing of the guids for projects, project references and the solution
// https://www.bing.com/search?q=visual+studio+project+guid+casing&cvid=311a5ad7f9fc41089507b24600d23ee7&FORM=ANAB01&PC=U531
// we therefore have to precariously use the right casing in the right place or risk building in VS breaking.
projectGuidLower: `{${projectGuid.toLowerCase()}}`,
projectGuidUpper: `{${projectGuid.toUpperCase()}}`,
// packaging and signing variables:
packageGuid: packageGuid,
currentUser: currentUser,
devMode: options.useDevMode,
useExperimentalNuget: options.experimentalNuGetDependency,
nuGetTestFeed: options.nuGetTestFeed,
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
nuGetADOFeed: true || nugetVersion.startsWith('0.0.0-'), // Temporary true for all new projects until code-signing is restored, see issue #14030
// cpp template variables
useWinUI3: options.useWinUI3,
cppNugetPackages: cppNugetPackages,
// cs template variables
csNugetPackages: csNugetPackages,
// autolinking template variables
autolinkPropertiesForProps: '',
autolinkProjectReferencesForTargets: '',
autolinkCsUsingNamespaces: '',
autolinkCsReactPackageProviders: '',
autolinkCppIncludes: '',
autolinkCppPackageProviders:
'\n UNREFERENCED_PARAMETER(packageProviders);', // CODESYNC: @react-native-windows\cli\src\commands\autolinkWindows\autolinkWindows.ts
};
const commonMappings =
projectType === 'app'
? [
// app common mappings
{
from: path.join(srcRootPath, 'metro.config.js'),
to: 'metro.config.js',
},
{
from: path.join(srcRootPath, '_gitignore'),
to: path.join(windowsDir, '.gitignore'),
},
{
from: path.join(srcRootPath, 'b_gitignore'),
to: path.join(windowsDir, newProjectName, '.gitignore'),
},
{
from: path.join(srcRootPath, 'index.windows.bundle'),
to: path.join(
windowsDir,
newProjectName,
bundleDir,
'index.windows.bundle',
),
},
{
from: path.join(srcPath, projDir, 'MyApp.sln'),
to: path.join(windowsDir, newProjectName + '.sln'),
},
]
: [
// lib common mappings
{
from: path.join(srcRootPath, '_gitignore'),
to: path.join(windowsDir, '.gitignore'),
},
{
from: path.join(srcPath, projDir, 'MyLib.sln'),
to: path.join(windowsDir, newProjectName + '.sln'),
},
];
for (const mapping of commonMappings) {
await copyAndReplaceWithChangedCallback(
mapping.from,
destPath,
mapping.to,
templateVars,
options.overwrite,
);
}
if (language === 'cs') {
const csMappings =
projectType === 'app'
? [
// cs app mappings
{
from: path.join(srcPath, projDir, 'MyApp.csproj'),
to: path.join(
windowsDir,
newProjectName,
newProjectName + '.csproj',
),
},
]
: [
// cs lib mappings
{
from: path.join(srcPath, projDir, 'MyLib.csproj'),
to: path.join(
windowsDir,
newProjectName,
newProjectName + '.csproj',
),
},
];
for (const mapping of csMappings) {
await copyAndReplaceWithChangedCallback(
mapping.from,
destPath,
mapping.to,
templateVars,
options.overwrite,
);
}
} else {
const cppMappings =
projectType === 'app'
? [
// cpp app mappings
{
from: path.join(srcPath, projDir, 'MyApp.vcxproj'),
to: path.join(
windowsDir,
newProjectName,
newProjectName + '.vcxproj',
),
},
{
from: path.join(srcPath, projDir, 'MyApp.vcxproj.filters'),
to: path.join(
windowsDir,
newProjectName,
newProjectName + '.vcxproj.filters',
),
},
]
: [
// cpp lib mappings
{
from: path.join(srcPath, projDir, 'MyLib.vcxproj'),
to: path.join(
windowsDir,
newProjectName,
newProjectName + '.vcxproj',
),
},
{
from: path.join(srcPath, projDir, 'MyLib.vcxproj.filters'),
to: path.join(
windowsDir,
newProjectName,
newProjectName + '.vcxproj.filters',
),
},
{
from: path.join(srcPath, projDir, 'MyLib.def'),
to: path.join(
windowsDir,
newProjectName,
newProjectName + '.def',
),
},
];
for (const mapping of cppMappings) {
await copyAndReplaceWithChangedCallback(
mapping.from,
destPath,
mapping.to,
templateVars,
options.overwrite,
);
}
}
// shared proj
if (fs.existsSync(path.join(sharedPath, projDir))) {
const sharedProjMappings = [];
sharedProjMappings.push({
from: path.join(sharedPath, projDir, 'NuGet_Config'),
to: path.join(windowsDir, 'NuGet.Config'),
});
if (
fs.existsSync(
path.join(sharedPath, projDir, 'ExperimentalFeatures.props'),
)
) {
sharedProjMappings.push({
from: path.join(sharedPath, projDir, 'ExperimentalFeatures.props'),
to: path.join(windowsDir, 'ExperimentalFeatures.props'),
});
}
for (const mapping of sharedProjMappings) {
await copyAndReplaceWithChangedCallback(
mapping.from,
destPath,
mapping.to,
templateVars,
options.overwrite,
);
}
}
// shared assets
if (fs.existsSync(path.join(sharedPath, 'assets'))) {
await copyAndReplaceAll(
path.join(sharedPath, 'assets'),
destPath,
path.join(windowsDir, newProjectName, 'Assets'),
templateVars,
options.overwrite,
);
}
// shared src
if (fs.existsSync(path.join(sharedPath, 'src'))) {
await copyAndReplaceAll(
path.join(sharedPath, 'src'),
destPath,
path.join(windowsDir, newProjectName),
templateVars,
options.overwrite,
);
}
// src
if (fs.existsSync(path.join(srcPath, 'src'))) {
await copyAndReplaceAll(
path.join(srcPath, 'src'),
destPath,
path.join(windowsDir, newProjectName),
templateVars,
options.overwrite,
);
}
if (projectType === 'app') {
console.log(chalk.white.bold('To run your app on UWP:'));
console.log(chalk.white(' npx @react-native-community/cli run-windows'));
}
}
function toCppNamespace(namespace: string) {
return namespace.replace(/\./g, '::');
}
export async function installScriptsAndDependencies(options: {
verbose: boolean;
}) {
const projectPackage = await WritableNpmPackage.fromPath(process.cwd());
if (!projectPackage) {
throw new Error(
`The current directory '${process.cwd()}' is not the root of an npm package`,
);
}
await projectPackage.mergeProps({
scripts: {windows: 'npx @react-native-community/cli run-windows'},
});
const rnwPackage = await findPackage('react-native-windows');
if (!rnwPackage) {
throw new Error('Could not locate the package for react-native-windows');
}
const rnPackage = await findPackage('react-native');
if (!rnPackage) {
throw new Error('Could not locate the package for react-native');
}
// We add an exclusionList from metro config. This will be hoisted, but add
// an explicit dep because we require it directly.
const rnMetroConfigPacakge = await findPackage('@react-native/metro-config', {
searchPath: rnPackage.path,
});
const metroConfigPackage = await findPackage('metro-config', {
searchPath: rnMetroConfigPacakge?.path || rnPackage.path,
});
if (metroConfigPackage) {
await projectPackage.mergeProps({
devDependencies: {
'metro-config': `^${metroConfigPackage.json.version}`,
},
});
}
const rnPeerDependency = rnwPackage.json.peerDependencies['react-native'];
if (
!semver.satisfies(rnPackage.json.version, rnPeerDependency) &&
projectPackage.json.dependencies?.['react-native']
) {
console.log(
chalk.green('Installing a compatible version of react-native:'),
);
console.log(chalk.white(` ${rnPeerDependency}`));
// Patch package.json to have proper react-native version and install
await projectPackage.mergeProps({
dependencies: {'react-native': rnPeerDependency},
});
// Install dependencies using correct package manager
const isYarn = fs.existsSync(path.join(process.cwd(), 'yarn.lock'));
childProcess.execSync(
isYarn ? 'yarn' : 'npm i',
options.verbose ? {stdio: 'inherit'} : {},
);
}
}