-
Notifications
You must be signed in to change notification settings - Fork 105
/
nodebootstrap
executable file
·360 lines (302 loc) · 12.9 KB
/
nodebootstrap
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
#!/usr/bin/env node
const os = require('os')
, path = require('path')
, fs = require('fs')
, fse = require('fs-extra')
, extract = require('extract-zip')
, ncp = require('ncp').ncp
, cli = require('child_process')
, chalk = require('chalk')
, Promise = require('bluebird')
, getPort = require('get-port')
, request = require('request');
const error = chalk.bold.red
, warning = chalk.keyword('orange');
const defaultDynPort = 5507;
let projectURL = 'https://github.com/inadarei/nodebootstrap-webapp/archive/main.zip';
const projectURLMicroservice = 'https://github.com/inadarei/nodebootstrap-microservice/archive/main.zip';
const projectURLCLI = 'https://github.com/inadarei/nodebootstrap-cli/archive/main.zip';
const argv = require('minimist')(process.argv.slice(2));
if (argv.v || argv.V || argv.version) {
version_info();
process.exit(0);
}
if ( argv.h || argv.help) {
help();
process.exit(0);
}
if (argv._.length === 0 || typeof argv._[0] === 'undefined' || argv._[0].length <2) {
console.log('');
console.log(error('ERROR: Mandatory argument <project_name> is missing!'));
console.log(' Please run `nodebootstrap -h` to see help.');
process.exit(1);
}
const _name = argv._[0];
let mode = 'microservice'
, _path = _name;
if (argv.m || argv.mode) {
mode = argv.m || argv.mode;
}
if (['webapp', 'api', 'microservice', 'cli'].indexOf(mode) === -1) {
console.log(error('ERROR: invalid value provided for the \'mode\' parameter.'));
console.log(' Please run `nodebootstrap -h` to see allowed values.');
process.exit(1);
}
if (argv.p || argv.path) {
_path = (argv.p) ? argv.p : argv.path;
}
if (_path !== '.' && fs.existsSync(_path)) {
console.log(error('Error: folder \'%s\' already exists. Aborting.', _path));
process.exit(1);
}
const pkgPath = _path + '/package.json';
if (_path === '.' && fs.existsSync(pkgPath)) {
console.log(error('Error: folder \'%s\' already contains a node project. Aborting.', _path));
process.exit(1);
}
let banner = 'Building \'' + _name + '\'';
if (_path && _path !== _name) {
banner += ' at \'' + _path + '\'';
}
if (mode) {
banner += ' in ' + mode + ' mode.';
} else {
banner += '.';
}
console.log(banner);
const rlSync = require('readline-sync');
if (mode === 'microservice') {
console.log(warning(' ATTENTION: microservice mode requires properly set-up Docker environment.'));
let dockerSetUp = rlSync.question(' Do you have proper Docker setup (y/n)? ');
dockerSetUp = dockerSetUp.toLowerCase();
if ( dockerSetUp !== 'y' ) {
console.log('Aborting. Please install Docker on your system and try again');
process.exit(0);
}
console.log("\tStarting installation…")
}
if (_path === '.') {
const readline = require('readline');
console.log('');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
const prompt1 = chalk.red('You indicated current folder as the build path. Are you certain ' + '(y/N)? ');
rl.question(prompt1, function(answer) {
rl.close();
answer = answer.toLowerCase();
if ( answer !== 'y' ) {
process.exit(0);
}
build_bootstrapped_project(_path, mode);
});
} else {
build_bootstrapped_project(_path, mode);
}
function version_info() {
console.log(require('./package.json').version);
}
function help() {
console.log('');
console.log(require('./package.json').description);
console.log('');
console.log(chalk.bold('Usage:'));
console.log(' ' + chalk.gray('nodebootstrap') + chalk.yellow(' <project_name>') + chalk.gray(' [options]'));
console.log('');
console.log(chalk.bold('Options:'));
console.log(' -m, [--mode] build mode to use.');
console.log(' Possible values: "webapp", "api", "cli" or "microservice" (default).');
console.log(' -p, [--path=PATH] output to the specified folder. Default is: <project_name>.');
console.log(' You can also indicate "." to build directly inside the current folder.');
console.log(' -h, [--help] output usage information');
console.log(' -v, [-V], [--version] output the version number');
console.log('');
console.log(chalk.bold('Description:'));
console.log(' The \'nodebootstrap \' command creates a new application with a default');
console.log(' structure and configuration at the path you specify.');
console.log('');
console.log(chalk.bold('Examples:'));
console.log(' # create a skeleton of a containerized microservice:');
console.log(' > nodebootstrap ms-first');
console.log(' # create a skeleton of an express MVC webapp:');
console.log(' > nodebootstrap -m webapp nodeapp-first');
console.log(' # create a skeleton of a console or client Node application');
console.log(' > nodebootstrap -m cli client-first');
console.log('');
console.log('See more information at: ' + chalk.underline('http://www.nodebootstrap.io'));
console.log('');
}
/* eslint-disable no-unused-vars */
function logToFile(data) {
const d = new Date();
const timestamp = d.toLocaleString(); // -> "2/1/2013 7:37:08 AM"
const options = {'flag' : 'a+'};
const msg = '\n ' + timestamp + ': ' + data;
fs.writeFileSync('/tmp/ika.log', msg, options);
}
/* eslint-enable no-unused-vars */
function build_bootstrapped_project(projectPath, mode) {
let tmp = os.tmpdir();
// Mac adds "/" to tmpdir(), Linux Debian doesn't. Life's beautiful.
if (tmp.substr(-1) !== path.sep) { tmp = tmp + path.sep; }
const zipFilepath = tmp + Date.now() + '-nodebootstrap.zip';
console.log("\tDownloading zip archive to " + zipFilepath);
const writer = fs.createWriteStream(zipFilepath);
if (mode === 'microservice') {
projectURL = projectURLMicroservice;
}
if (mode === 'cli') {
projectURL = projectURLCLI;
}
request(projectURL).pipe(writer);
writer.on('finish', async function () {
console.log("\tZip archive downloaded");
try {
await extract(zipFilepath, {dir: tmp})
console.log('\tExtraction complete')
let srcPath;
if (mode === 'microservice') {
srcPath = tmp + 'nodebootstrap-microservice';
} else if (mode == 'cli') {
srcPath = tmp + 'nodebootstrap-cli';
} else {
srcPath = tmp + 'nodebootstrap-webapp';
}
srcPath += "-main"
const ncp_opts = {stopOnErr: true, clobber: true};
ncp.limit = 16;
fse.ensureDirSync(projectPath); //create destination directory structure, if necessary.
ncp(srcPath, projectPath, ncp_opts, async function (err) {
fse.removeSync(srcPath); //clean-up
checkErrorFatal(err);
dynamicPort = await findDynPort();
console.log("Will launch on port: " + dynamicPort);
const setupScript = setupScriptContent(mode, _name, dynamicPort);
fs.writeFile(projectPath + '/setup.sh', setupScript, function(err) {
checkErrorFatal(err);
console.log("Setup.sh created");
cli.exec ('chmod u+x ' + projectPath + '/setup.sh', function(err) {
checkErrorFatal(err);
console.log('Project Created.');
console.log('Executing installation of dependencies. This may take several minutes…');
const cliSetupCmd = './setup.sh';
const setupcli = cli.execFile(cliSetupCmd, [], {'cwd' : projectPath}, function(err) {
checkErrorFatal(err);
fs.unlinkSync(projectPath + '/setup.sh');
showCompletionMessage(mode, projectPath, dynamicPort);
});
setupcli.stderr.pipe(process.stderr);
setupcli.stdout.pipe(process.stdout);
});
});
});
} catch (err) {
checkErrorFatal(err);
} finally {
fs.unlinkSync(zipFilepath);
}
});
}
function checkErrorFatal(err) {
if (err) {
console.log(error(err));
process.exit(1);
}
}
function showCompletionMessage(mode, projectPath, dynamicPort) {
console.log('');
console.log('======================= Installation Completed! ===================');
console.log('You can now run your newly minted Node app by executing:');
if (mode === 'webapp' || mode === 'api') {
console.log(' > cd ' + projectPath);
console.log(' > npm run dev');
} else { // works for microservice and cli
console.log(' > cd ' + projectPath);
console.log(' > make');
}
if (mode !== 'cli') {
console.log('');
console.log('Once the app is up and running you can access it from your browser at: ');
if (mode !== 'microservice') {
console.log('http://localhost:3000/');
} else {
console.log('http://localhost:' + dynamicPort + '/');
}
}
console.log('===================================================================');
console.log('');
}
function findDynPort() {
return new Promise( (resolve, reject) => {
let startPort;
const batchSize = 20;
const stepSize = 100;
const portPromises = [];
let increment = 0;
let opts = {};
while (increment < batchSize) {
startPort = defaultDynPort + batchSize * stepSize;
opts = {port: startPort, host: '0.0.0.0'};
portPromises.push(getPort(opts));
increment++;
}
Promise.any(portPromises).then( port => {
resolve(port);
});
});
}
function setupScriptContent(mode, project_name, dynamicPort) {
let setupScript = '#!/usr/bin/env sh\n';
let sedCmd;
if (os.platform === 'darwin') {
sedCmd = 'sed -i \'\' ';
} else {
sedCmd = 'sed -i ';
}
if (mode === 'webapp' || mode === 'api') {
setupScript += 'npm -q install nodemon -g\n';
if (mode === 'webapp') {
setupScript += 'npm -q install bower -g\n';
setupScript += 'bower install\n';
} else if (mode === 'api') {
setupScript += 'rm -rf ./lib/hello && rm -rf views && rm -rf public\n';
setupScript += 'rm -f .bowerrc bower.json \n';
setupScript += sedCmd + ' -E \'/.*nodebootstrap-htmlapp.*/d\' package.json \n';
setupScript += sedCmd + ' -E \'/.*nodebootstrap-htmlapp.*/d\' server.js \n';
setupScript += sedCmd + ' -E \'/.*runningApp\.use.+require\(.+hello.+\).*/d\' appConfig.js \n';
} // default: microservice
setupScript += 'rm -rf README.md LICENSE\n';
setupScript += 'npm -q install\n';
setupScript += 'chmod u+x ./bin/start.sh\n';
setupScript += 'chmod u+x ./bin/stop.sh\n';
setupScript += 'chmod u+x ./bin/dev_start.sh\n';
} else if (mode === 'cli') {
const cli_name = project_name.replace(/[^a-z0-9\-]/gi,'');
setupScript += sedCmd + ' \'s/nodebootstrap-cli-example/' + cli_name + '/g\' docker-compose.yml \n';
setupScript += sedCmd + ' \'s/nodebootstrap-cli-example/' + cli_name + '/g\' package.json \n';
setupScript += sedCmd + ' \'s/nodebootstrap-cli-example/' + cli_name + '/g\' Makefile \n';
setupScript += 'rm -rf node_modules\n'; // just in case
setupScript += 'make build\n';
} else { // microservice is much easier :)
// make name safe
let ms_name = project_name.replace(/[^a-z0-9\-]/gi,'');
if (!ms_name.startsWith('ms-')) {
ms_name = 'ms-' + ms_name;
}
// @todo: safe port using https://github.com/indexzero/node-portfinder
setupScript += sedCmd + ' \'s/ms-nodebootstrap-example/' + ms_name + '/g\' docker-compose.yml \n';
setupScript += sedCmd + ' \'s/ms-nodebootstrap-example/' + ms_name + '/g\' package.json \n';
setupScript += sedCmd + ' \'s/ms-nodebootstrap-example/' + ms_name + '/g\' Makefile \n';
setupScript += sedCmd + ' \'s/ms-nodebootstrap-example-db/' + ms_name + '-db/g\' database.env \n';
setupScript += sedCmd + ' \'s/ms-nodebootstrap-example-db/' + ms_name + '-db/g\' docker-compose.yml \n';
setupScript += sedCmd + ' \'s/5501:5501/' + dynamicPort + ':5501/g\' docker-compose.yml \n';
setupScript += 'rm -rf node_modules\n'; // just in case
setupScript += 'make build\n';
//setupScript += 'npm run build\n';
//setupScript += 'npm start\n';
//setupScript += 'npm stop\n';
}
return setupScript;
}