-
Notifications
You must be signed in to change notification settings - Fork 3
/
generator.ts
418 lines (361 loc) · 11.8 KB
/
generator.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
import template from 'mustache';
import username from 'username';
import chalk from 'chalk';
import { v4 as uuidv4 } from 'uuid';
import path from 'path';
import fs from 'fs-extra';
import os from 'os';
import { flatten, omit, merge } from 'lodash';
import { spawnSync } from 'child_process';
import { PackageManager } from './package-manager';
import { getVersion, sortKeys } from './utils';
import { Dictionary, Options } from './types';
type TemplateFolderName = 'javascript' | 'typescript';
interface GeneratorOptions extends Options {
projectName: string;
projectPath: string;
}
const TYPESCRIPT_FOLDER = 'typescript';
const JAVASCRIPT_FOLDER = 'javascript';
const WINDOWS_FOLDER = 'windows';
const COMMON_FOLDER = 'common';
const IOS_FOLDER = 'ios';
const TEMP_PACKAGE_JSON = '_package.json';
const NPM_INSTALL = 'npm i';
const NPM_RUN = 'npm run';
const YARN = 'yarn';
const TEMPLATE_PATH = path.resolve(__dirname, '..', 'template');
const COMMON_TEMPLATE_PATH = path.join(TEMPLATE_PATH, COMMON_FOLDER);
const WINDOWS_TEMPLATE_PATH = path.join(COMMON_TEMPLATE_PATH, WINDOWS_FOLDER);
const WINDOWS_TEMPORARY_KEY_PATH = path.join(
WINDOWS_TEMPLATE_PATH,
'ProjectName',
'ProjectName_TemporaryKey.pfx',
);
const JEST_TEMPLATE_PATH = path.join(COMMON_TEMPLATE_PATH, 'jest');
const { chdir } = process;
export class Generator {
private templateFolderName: TemplateFolderName;
private packageJson: Dictionary = {};
private runCommand: string;
private options: GeneratorOptions;
private params: Dictionary = {};
public constructor(options: GeneratorOptions) {
const { projectName, javascript, yarn } = options;
this.params = {
ProjectName: projectName,
displayName: projectName,
projectname: projectName.toLowerCase(),
};
this.templateFolderName = javascript
? JAVASCRIPT_FOLDER
: TYPESCRIPT_FOLDER;
this.runCommand = yarn ? YARN : NPM_RUN;
this.options = options;
}
public run(): void {
const { projectPath, skipInstall } = this.options;
console.log(
chalk.white.bold('Setting up new ReactXP app in %s'),
projectPath,
);
if (!fs.existsSync(projectPath)) {
fs.mkdirSync(projectPath);
}
this.setPackageJson();
this.generatePackageJson();
if (!skipInstall) {
this.installDependencies();
}
this.generateApp();
this.generateWindowsApp();
this.printInstructions();
}
private generateApp(): void {
const { skipJest, javascript } = this.options;
const templatePaths = [
COMMON_TEMPLATE_PATH,
path.join(TEMPLATE_PATH, this.templateFolderName),
];
const excludePaths = [WINDOWS_TEMPLATE_PATH, TEMP_PACKAGE_JSON];
if (skipJest) {
excludePaths.push(JEST_TEMPLATE_PATH);
excludePaths.push(`App.spec.${javascript ? 'js' : 'tsx'}`);
}
const pathParams = {
...this.params,
'_metro.config.js': 'metro.config.js',
'_babel.config.js': 'babel.config.js',
_eslintrc: '.eslintrc',
_gitignore: '.gitignore',
'_tsconfig.json': 'tsconfig.json',
'_tslint.json': 'tslint.json',
'_README.md': 'README.md',
};
const contnetParams = {
...this.params,
runCommand: this.runCommand,
version: getVersion(),
skipJest,
};
templatePaths.forEach((srcPath) =>
this.walk(srcPath, excludePaths).forEach((absolutePath) =>
this.copy(
absolutePath,
this.buildDestPath(absolutePath, srcPath, pathParams),
contnetParams,
),
),
);
}
private generateWindowsApp(): void {
const currentUser = username.sync();
const certificateThumbprint = this.buildSelfSignedCertificate(currentUser);
const contnetParams = {
...this.params,
...(certificateThumbprint && { certificateThumbprint }),
currentUser,
packageGuid: uuidv4(),
projectGuid: uuidv4(),
};
const pathParams = { ...this.params, _gitignore: '.gitignore' };
const excludePaths = certificateThumbprint
? [WINDOWS_TEMPORARY_KEY_PATH]
: [];
this.walk(WINDOWS_TEMPLATE_PATH, excludePaths).forEach((absolutePath) =>
this.copy(
absolutePath,
this.buildDestPath(absolutePath, COMMON_TEMPLATE_PATH, pathParams),
contnetParams,
),
);
}
private buildSelfSignedCertificate(currentUser: string | undefined): string {
const { projectPath, projectName } = this.options;
if (os.platform() !== 'win32') {
return '';
}
console.log(
'%s %s',
chalk.blue.bold('[windows]'),
chalk.white.bold('Generating self-signed certificate...'),
);
const certificateDestPath = path.join(
projectPath,
WINDOWS_FOLDER,
projectName,
);
const certificateFileDestPath = path.join(certificateDestPath, projectName);
const certificateArgs = [
[
'$cert = New-SelfSignedCertificate -KeyUsage DigitalSignature -KeyExportPolicy Exportable -Subject',
`"CN=${currentUser}" -TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.3", "2.5.29.19={text}Subject Type:End Entity")`,
`-CertStoreLocation "Cert:\\CurrentUser\\My"`,
].join(' '),
'$pwd = ConvertTo-SecureString -String password -Force -AsPlainText',
`New-Item -ErrorAction Ignore -ItemType directory -Path ${certificateDestPath}`,
[
`Export-PfxCertificate -Cert "cert:\\CurrentUser\\My\\$($cert.Thumbprint)"`,
`-FilePath ${certificateFileDestPath}_TemporaryKey.pfx -Password $pwd`,
].join(' '),
'$cert.Thumbprint',
].join(';');
if (!fs.existsSync(certificateDestPath)) {
fs.mkdirpSync(certificateDestPath);
}
const { status, stdout } = spawnSync('powershell', [
'-command',
certificateArgs,
]);
if (status === 0) {
console.log(
'%s %s',
chalk.blue.bold('[windows]'),
chalk.green.bold('Self-signed certificate generated successfully.'),
);
const output = stdout.toString().trim().split('\n');
return output[output.length - 1];
}
console.log(
'%s %s',
chalk.blue.bold('[windows]'),
chalk.red.bold('Failed to generate Self-signed certificate.'),
);
console.log(
'%s %s',
chalk.blue.bold('[windows]'),
chalk.yellow.bold(
'Using Default Certificate. Use Visual Studio to renew it.',
),
);
return '';
}
private generatePackageJson(): void {
const { projectPath, projectName, skipInstall } = this.options;
const packageJson = JSON.stringify(
{
name: projectName.toLowerCase(),
...omit(
this.packageJson,
skipInstall ? [] : ['devDependencies', 'dependencies'],
),
},
null,
2,
);
fs.writeFileSync(path.resolve(projectPath, 'package.json'), packageJson);
}
private printInstructions(): void {
const { projectName, projectPath, skipInstall, yarn } = this.options;
const xcodeProjectPath = `${path.resolve(
projectPath,
IOS_FOLDER,
projectName,
)}.xcodeproj`;
const windowsProjectPath = `${path.resolve(
projectPath,
WINDOWS_FOLDER,
projectName,
)}.sln`;
console.log(
chalk.green.bold('%s was successfully created. \n'),
projectName,
);
if (skipInstall) {
console.log(chalk.green.bold('To install dependencies:'));
console.log(' cd %s', projectPath);
console.log(chalk.white.bold(' %s \n'), yarn ? YARN : NPM_INSTALL);
}
console.log(chalk.yellow.bold('To run your app on Web:'));
console.log(' cd %s', projectPath);
console.log(chalk.white.bold(' %s start:web \n'), this.runCommand);
console.log(
chalk.yellow.bold('To build Web production version of your app:'),
);
console.log(' cd %s', projectPath);
console.log(chalk.white.bold(' %s build:web \n'), this.runCommand);
console.log(chalk.cyan.bold('To run your app on iOS:'));
console.log(' cd %s', projectPath);
console.log(chalk.white.bold(' %s start:ios'), this.runCommand);
console.log(' - or -');
console.log(
' open %s project in Xcode',
path.relative(projectPath, xcodeProjectPath),
);
console.log(' press the Run button \n');
console.log(chalk.green.bold('To run your app on Android:'));
console.log(' cd %s', projectPath);
console.log(
' Have an Android emulator running (quickest way to get started), or a device connected.',
);
console.log(chalk.white.bold(' %s start:android'), this.runCommand);
console.log(' - or -');
console.log(chalk.white.bold(' open android/ project in Android Studio'));
console.log(' press the Run button \n');
console.log(chalk.blue.bold('To run your app on Windows:'));
console.log(' cd %s', projectPath);
console.log(chalk.white.bold(' %s start:windows'), this.runCommand);
console.log(' - or -');
console.log(
chalk.white.bold(' open %s project in Visual Studio'),
windowsProjectPath,
);
console.log(' press the Run button \n');
}
private installDependencies(): void {
const { devDependencies, dependencies } = this.packageJson;
const { projectPath, yarn } = this.options;
const packageManager = new PackageManager(yarn);
chdir(projectPath);
packageManager.install(devDependencies, 'dev dependencies', true);
packageManager.install(dependencies, 'dependencies');
}
private setPackageJson(): void {
const packageJson = merge(
this.buildPackageJson(COMMON_FOLDER),
this.buildPackageJson(this.templateFolderName),
);
this.packageJson = {
...packageJson,
devDependencies: sortKeys(packageJson.devDependencies),
dependencies: sortKeys(packageJson.dependencies),
};
}
private buildPackageJson(srcFolder: string): Dictionary {
const { skipJest, yarn } = this.options;
const content = fs.readFileSync(
path.join(TEMPLATE_PATH, srcFolder, TEMP_PACKAGE_JSON),
{ encoding: 'utf8' },
);
const params = {
paramsPrefix: yarn ? ' ' : ' -- ',
runCommand: this.runCommand,
skipJest,
};
return JSON.parse(template.render(content, params, {}, ['<%', '%>']));
}
private buildDestPath(
absolutePath: string,
relativeTo: string,
params: Dictionary,
): string {
let destPath = path.resolve(
this.options.projectPath,
path.relative(relativeTo, absolutePath),
);
Object.keys(params).forEach(
(regexp) =>
(destPath = destPath.replace(
new RegExp(`\\b${regexp}`, 'g'),
params[regexp],
)),
);
return destPath;
}
private copy(srcPath: string, destPath: string, params: Dictionary): void {
if (fs.lstatSync(srcPath).isDirectory()) {
if (!fs.existsSync(destPath)) {
fs.mkdirSync(destPath);
}
return;
} else {
if (this.isBinary(srcPath)) {
fs.copyFileSync(srcPath, destPath);
} else {
const permissions = fs.statSync(srcPath).mode;
const content = template.render(
fs.readFileSync(srcPath, 'utf8'),
params,
{},
['<%', '%>'],
);
fs.writeFileSync(destPath, content, {
encoding: 'utf8',
mode: permissions,
});
}
}
}
private isBinary(srcPath: string): boolean {
return (
['.png', '.jpg', '.jar', '.ico', '.pfx', '.keystore'].indexOf(
path.extname(srcPath),
) >= 0
);
}
private walk(srcPath: string, excludePaths: string[] = []): string[] {
const isExcluded = (file: string) =>
excludePaths.some((p) => file.indexOf(p) >= 0);
if (!fs.lstatSync(srcPath).isDirectory()) {
return isExcluded(srcPath) ? [] : [srcPath];
}
return [
srcPath,
...flatten(
fs
.readdirSync(srcPath)
.map((child) => this.walk(path.join(srcPath, child))),
),
].filter((absolutePath) => !isExcluded(absolutePath));
}
}