-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
279 lines (245 loc) · 7.02 KB
/
index.js
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
#!/usr/bin/env node
'use strict';
const program = require('commander');
const fs = require('fs-extra');
const path = require('path');
const chalk = require('chalk');
const spawn = require('cross-spawn');
const execSync = require('child_process').execSync;
const tmp = require('tmp');
const packageJson = require('./package.json');
let projectName;
let projectTemplate;
program
.name('craft')
.version(packageJson.version)
.arguments('<project-directory> [template-url]')
.usage(
`${chalk.green('<project-directory>')} ${chalk.cyan(
'<template-url>'
)} [options]`
)
.action(function(name, template) {
projectName = name;
projectTemplate = template;
})
.parse(process.argv);
if (
typeof projectName === 'undefined' ||
typeof projectTemplate === 'undefined'
) {
console.error('Please specify the project directory and template url:');
console.log(
` ${chalk.cyan(program.name())} ${chalk.green(
'<project-directory>'
)} ${chalk.yellow('<template-url>')}`
);
console.log();
console.log('For example:');
console.log(
` ${chalk.cyan(program.name())} ${chalk.green(
'my-react-app'
)} ${chalk.yellow('https://github.com/cebroker/react-foundation')}`
);
console.log();
console.log(
`Run ${chalk.cyan(`${program.name()} --help`)} to see all options.`
);
process.exit(1);
}
if (!isCRAInstalled()) {
console.error('No create-react-app instalation has been detected.');
console.log('Please install create-react-app to continue.');
console.log();
console.log(
` ${chalk.cyan('npm')} install -g ${chalk.bold('create-react-app')}`
);
process.exit(1);
}
createApp(projectName)
.then(() => {
console.log();
console.log(chalk.magenta('Applying custom template...'));
console.log();
// Clone template to a temp directory
return getTemporaryDirectory().then(obj => {
return new Promise((resolve, reject) => {
const command = 'git';
const args = ['clone', projectTemplate, obj.tmpdir];
const child = spawn(command, args, { stdio: 'inherit' });
child.on('close', code => {
if (code !== 0) {
reject({
command: `${command} ${args.join(' ')}`
});
}
resolve(obj);
});
});
});
})
.then(obj => {
// Merge folders and files
console.log();
console.log('Copying files...');
const root = path.resolve(projectName);
const files = fs.readdirSync(obj.tmpdir);
const skips = ['node_modules', 'package.json', 'package-lock.json', '.git'];
let promises = [];
for (const file of files) {
if (skips.includes(file)) {
continue;
}
const src = path.join(obj.tmpdir, file);
const dest = path.join(root, file);
promises.push(
new Promise((resolve, reject) => {
fs.copy(src, dest, err => {
if (err) {
console.log(chalk.red(`- ${file}`));
} else {
console.log(`+ ${file}`);
}
resolve();
});
})
);
}
return Promise.all(promises).then(() => obj);
})
.then(obj => {
console.log();
console.log('Installing template packages...');
const root = path.resolve(projectName);
const originalDirectory = process.cwd();
process.chdir(root);
// Get dependencies to install
const templatePackageJsonPath = path.resolve(obj.tmpdir, 'package.json');
let templatePackageJson;
try {
templatePackageJson = require(templatePackageJsonPath);
} catch (error) {
return Promise.resolve(obj);
}
let templateDependencies = templatePackageJson.dependencies || {};
// Does not include already installed dependencies
// TODO: installed dependencies should be taken from package.json of just
// created app
const installedDependencies = ['react', 'react-dom', 'react-scripts'];
installedDependencies.forEach(key => {
delete templateDependencies[key];
});
// Install additional dependencies
return install(templateDependencies).then(() => {
const appPackageJson = require(path.join(root, 'package.json'));
// Dependencies are already available in app package.json so we can safely
// replace them. However we cannot replace template scripts with app
// scripts since the template could contains scripts customization
const scripts = Object.assign(
{},
appPackageJson.scripts,
templatePackageJson.scripts
);
const packageJson = Object.assign(
{},
templatePackageJson,
appPackageJson,
{ scripts }
);
fs.writeFileSync(
path.join(root, 'package.json'),
JSON.stringify(packageJson, null, 2)
);
return Object.assign({}, obj, { root });
});
})
.then(obj => {
// Perform cleanup
console.log();
console.log(chalk.green('Template applied successfullly!'));
obj.cleanup();
})
.catch(reason => {
console.log();
console.log('Aborting installation.');
if (reason.command) {
console.log(` ${chalk.cyan(reason.command)} has failed.`);
} else {
console.log(chalk.red('Unexpected error. Please report it as a bug:'));
console.log(reason);
}
console.log();
});
function createApp(name) {
return new Promise((resolve, reject) => {
const command = 'create-react-app';
const args = [name];
const child = spawn(command, args, { stdio: 'inherit' });
child.on('close', code => {
if (code !== 0) {
reject({
command: `${command} ${args.join(' ')}`
});
return;
}
resolve();
});
});
}
function isCRAInstalled() {
try {
execSync('create-react-app --version', { stdio: 'ignore' });
return true;
} catch (e) {
return false;
}
}
function getTemporaryDirectory() {
return new Promise((resolve, reject) => {
// Unsafe cleanup lets us recursively delete the directory if it contains
// contents; by default it only allows removal if it's empty
tmp.dir({ unsafeCleanup: true }, (err, tmpdir, callback) => {
if (err) {
reject(err);
} else {
resolve({
tmpdir: tmpdir,
cleanup: () => {
try {
callback();
} catch (ignored) {
// Callback might throw and fail, since it's a temp directory the
// OS will clean it up eventually...
}
}
});
}
});
});
}
function install(dependencies) {
return new Promise((resolve, reject) => {
let args = [
'install',
'--save',
//'--save-exact',
'--loglevel',
'error'
];
args = args.concat(
Object.keys(dependencies).map(key => {
return `${key}@${dependencies[key]}`;
})
);
const child = spawn('npm', args, { stdio: 'inherit' });
child.on('close', code => {
if (code !== 0) {
reject({
command: `${command} ${args.join(' ')}`
});
return;
}
resolve();
});
});
}