-
Notifications
You must be signed in to change notification settings - Fork 899
/
init.ts
396 lines (342 loc) · 10.3 KB
/
init.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
import os from 'os';
import path from 'path';
import fs from 'fs-extra';
import {validateProjectName} from './validate';
import chalk from 'chalk';
import DirectoryAlreadyExistsError from './errors/DirectoryAlreadyExistsError';
import printRunInstructions from './printRunInstructions';
import {
CLIError,
logger,
getLoader,
Loader,
cacheManager,
prompt,
} from '@react-native-community/cli-tools';
import {installPods} from '@react-native-community/cli-platform-ios';
import {
installTemplatePackage,
getTemplateConfig,
copyTemplate,
executePostInitScript,
} from './template';
import {changePlaceholderInTemplate} from './editTemplate';
import * as PackageManager from '../../tools/packageManager';
import banner from './banner';
import TemplateAndVersionError from './errors/TemplateAndVersionError';
import {getBunVersionIfAvailable} from '../../tools/bun';
import {getNpmVersionIfAvailable} from '../../tools/npm';
import {getYarnVersionIfAvailable} from '../../tools/yarn';
import {createHash} from 'crypto';
import createGitRepository from './createGitRepository';
const DEFAULT_VERSION = 'latest';
type Options = {
template?: string;
npm?: boolean;
pm?: PackageManager.PackageManager;
directory?: string;
displayName?: string;
title?: string;
skipInstall?: boolean;
version?: string;
packageName?: string;
installPods?: string | boolean;
platformName?: string;
skipGitInit?: boolean;
};
interface TemplateOptions {
projectName: string;
templateUri: string;
npm?: boolean;
pm?: PackageManager.PackageManager;
directory: string;
projectTitle?: string;
skipInstall?: boolean;
packageName?: string;
installCocoaPods?: string | boolean;
version?: string;
}
interface TemplateReturnType {
didInstallPods?: boolean;
}
function doesDirectoryExist(dir: string) {
return fs.existsSync(dir);
}
async function setProjectDirectory(directory: string) {
if (doesDirectoryExist(directory)) {
throw new DirectoryAlreadyExistsError(directory);
}
try {
fs.mkdirSync(directory, {recursive: true});
process.chdir(directory);
} catch (error) {
throw new CLIError(
'Error occurred while trying to create project directory.',
error as Error,
);
}
return process.cwd();
}
function getTemplateName(cwd: string) {
// We use package manager to infer the name of the template module for us.
// That's why we get it from temporary package.json, where the name is the
// first and only dependency (hence 0).
const name = Object.keys(
JSON.parse(fs.readFileSync(path.join(cwd, './package.json'), 'utf8'))
.dependencies,
)[0];
return name;
}
//set cache to empty string to prevent installing cocoapods on freshly created project
function setEmptyHashForCachedDependencies(projectName: string) {
cacheManager.set(
projectName,
'dependencies',
createHash('md5').update('').digest('hex'),
);
}
async function createFromTemplate({
projectName,
templateUri,
npm,
pm,
directory,
projectTitle,
skipInstall,
packageName,
installCocoaPods,
}: TemplateOptions): Promise<TemplateReturnType> {
logger.debug('Initializing new project');
// Only print out the banner if we're not in a CI
if (!process.env.CI) {
logger.log(banner);
}
let didInstallPods = String(installCocoaPods) === 'true';
let packageManager = pm;
if (pm) {
packageManager = pm;
} else {
const userAgentPM = userAgentPackageManager();
// if possible, use the package manager from the user agent. Otherwise fallback to default (yarn)
packageManager = userAgentPM || 'yarn';
}
if (npm) {
logger.warn(
'Flag --npm is deprecated and will be removed soon. In the future, please use --pm npm instead.',
);
packageManager = 'npm';
}
// if the project with the name already has cache, remove the cache to avoid problems with pods installation
cacheManager.removeProjectCache(projectName);
const projectDirectory = await setProjectDirectory(directory);
const loader = getLoader({text: 'Downloading template'});
const templateSourceDir = fs.mkdtempSync(
path.join(os.tmpdir(), 'rncli-init-template-'),
);
try {
loader.start();
await installTemplatePackage(
templateUri,
templateSourceDir,
packageManager,
);
loader.succeed();
loader.start('Copying template');
const templateName = getTemplateName(templateSourceDir);
const templateConfig = getTemplateConfig(templateName, templateSourceDir);
await copyTemplate(
templateName,
templateConfig.templateDir,
templateSourceDir,
);
loader.succeed();
loader.start('Processing template');
await changePlaceholderInTemplate({
projectName,
projectTitle,
placeholderName: templateConfig.placeholderName,
placeholderTitle: templateConfig.titlePlaceholder,
packageName,
});
const {postInitScript} = templateConfig;
if (postInitScript) {
loader.info('Executing post init script ');
await executePostInitScript(
templateName,
postInitScript,
templateSourceDir,
);
}
if (!skipInstall) {
await installDependencies({
packageManager,
loader,
root: projectDirectory,
});
if (process.platform === 'darwin') {
const installPodsValue = String(installCocoaPods);
if (installPodsValue === 'true') {
didInstallPods = true;
await installPods(loader);
loader.succeed();
setEmptyHashForCachedDependencies(projectName);
} else if (installPodsValue === 'undefined') {
const {installCocoapods} = await prompt({
type: 'confirm',
name: 'installCocoapods',
message: `Do you want to install CocoaPods now? ${chalk.reset.dim(
'Only needed if you run your project in Xcode directly',
)}`,
});
didInstallPods = installCocoapods;
if (installCocoapods) {
await installPods(loader);
loader.succeed();
setEmptyHashForCachedDependencies(projectName);
}
}
}
} else {
didInstallPods = false;
loader.succeed('Dependencies installation skipped');
}
} catch (e) {
if (e instanceof Error) {
logger.error(
'Installing pods failed. This doesn\'t affect project initialization and you can safely proceed. \nHowever, you will need to install pods manually when running iOS, follow additional steps in "Run instructions for iOS" section.\n',
);
}
loader.fail();
didInstallPods = false;
} finally {
fs.removeSync(templateSourceDir);
}
if (process.platform === 'darwin') {
logger.log('\n');
logger.info(
`💡 To enable automatic CocoaPods installation when building for iOS you can create react-native.config.js with automaticPodsInstallation field. \n${chalk.reset.dim(
`For more details, see ${chalk.underline(
'https://github.com/react-native-community/cli/blob/main/docs/projects.md#projectiosautomaticpodsinstallation',
)}`,
)}
`,
);
}
return {didInstallPods};
}
async function installDependencies({
packageManager,
loader,
root,
}: {
packageManager: PackageManager.PackageManager;
loader: Loader;
root: string;
}) {
loader.start('Installing dependencies');
await PackageManager.installAll({
packageManager,
silent: true,
root,
});
loader.succeed();
}
function checkPackageManagerAvailability(
packageManager: PackageManager.PackageManager,
) {
if (packageManager === 'bun') {
return getBunVersionIfAvailable();
} else if (packageManager === 'npm') {
return getNpmVersionIfAvailable();
} else if (packageManager === 'yarn') {
return getYarnVersionIfAvailable();
}
return false;
}
function createTemplateUri(options: Options, version: string): string {
const isTypescriptTemplate =
options.template === 'react-native-template-typescript';
// This allows to correctly retrieve template uri for out of tree platforms.
const platform = options.platformName || 'react-native';
if (isTypescriptTemplate) {
logger.warn(
"Ignoring custom template: 'react-native-template-typescript'. Starting from React Native v0.71 TypeScript is used by default.",
);
return platform;
}
return options.template || `${platform}@${version}`;
}
async function createProject(
projectName: string,
directory: string,
version: string,
options: Options,
): Promise<TemplateReturnType> {
const templateUri = createTemplateUri(options, version);
return createFromTemplate({
projectName,
templateUri,
npm: options.npm,
pm: options.pm,
directory,
projectTitle: options.title,
skipInstall: options.skipInstall,
packageName: options.packageName,
installCocoaPods: options.installPods,
version,
});
}
function userAgentPackageManager() {
const userAgent = process.env.npm_config_user_agent;
if (userAgent) {
if (userAgent.startsWith('yarn')) {
return 'yarn';
}
if (userAgent.startsWith('npm')) {
return 'npm';
}
if (userAgent.startsWith('bun')) {
return 'bun';
}
}
return null;
}
export default (async function initialize(
[projectName]: Array<string>,
options: Options,
) {
if (!projectName) {
const {projName} = await prompt({
type: 'text',
name: 'projName',
message: 'How would you like to name the app?',
});
projectName = projName;
}
validateProjectName(projectName);
if (!!options.template && !!options.version) {
throw new TemplateAndVersionError(options.template);
}
const root = process.cwd();
const version = options.version || DEFAULT_VERSION;
const directoryName = path.relative(root, options.directory || projectName);
if (options.pm && !checkPackageManagerAvailability(options.pm)) {
logger.error(
'Seems like the package manager you want to use is not installed. Please install it or choose another package manager.',
);
return;
}
const {didInstallPods} = await createProject(
projectName,
directoryName,
version,
options,
);
const projectFolder = path.join(root, directoryName);
if (!options.skipGitInit) {
await createGitRepository(projectFolder);
}
printRunInstructions(projectFolder, projectName, {
showPodsInstructions: !didInstallPods,
});
});