-
Notifications
You must be signed in to change notification settings - Fork 0
/
commands.js
410 lines (324 loc) · 13.5 KB
/
commands.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
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
const WATERLINE_VERSION = "^0.11.8";
const MONGOOSE_VERSION = "^5.2.12";
let path = require('path');
let replHistory = require('repl.history');
let fs = require('fs');
let cpr = require('cpr');
let child = require('child_process');
let pluralize = require('pluralize');
let { yellow, red, green, orange, grey, chalk, log } = require('./lib/log');
let lodash = require('lodash');
let readline = require('readline');
const { Promise } = require('bluebird');
class Command {
constructor (commands, args) {
this.commands = commands;
this.args = args;
this.cliDir = __dirname;
this.path = process.cwd();
try {
this.gladCliConfig = require(path.join(this.cliDir, 'package.json'));
this.gladCliVersion = this.gladCliConfig.version;
this.config = require(path.join(process.cwd(), 'config'));
this.package = require(path.join(process.cwd(), 'package.json'));
this.gladConfig = require(path.join(process.cwd(), 'node_modules/glad/package.json'));
this.gladVersion = this.gladConfig.version;
} catch (err) {
this.package = this.package || false;
this.config = this.config || false;
this.gladCliConfig = this.gladCliConfig || false;
this.gladConfig = this.gladConfig || false;
this.gladCliVersion = this.gladCliVersion || false;
this.gladVersion = this.gladVersion || false;
}
Promise.each(this.commands, cmd => this[cmd].call(this))
.then(() => {})
.catch(err => log(err));
}
version () {
yellow(`Glad Version: ${this.gladConfig && this.gladConfig.version}`);
yellow(`Glad CLI Version: ${this.gladCliConfig && this.gladCliConfig.version}`);
yellow(`${this.package && this.package.name || 'Your Project'}: ${this.package && this.package.version}`);
return Promise.resolve();
}
help () {
green("Available Commands:")
yellow("glad api [name] # Creates a new API");
// yellow("glad stub [path] --model [model] # Creates a new API");
yellow("glad serve [-i] # Starts the server, pass in i for interactive mode");
yellow("glad run [-i] # Runs a job or script in the same process as a new application server (without binding to a port). Pass in i for interactive mode");
yellow("glad -v # Displays The Version of Glad");
// yellow("glad list [m|r] # Displays All of the controllers, models, routes in your application. Run glad list for controllers");
yellow("glad destroy [name] # Destroys an API, removes the model, route, controller, and test");
// yellow("glad p --editor [bin] # Sets your preferred editor, pass in the command that opens your editor from terminal");
yellow(" examples include subl, wstorm, atom, etc...");
green('\nALIASES:');
yellow("glad a [name] # glad api [name]");
yellow("glad s [i] # glad serve [i]");
yellow("glad r [i] # glad run [i]");
// yellow("glad l [m|r] # glad list [m|r]");
yellow("glad d [name] # glad destroy [name]");
process.exit(0);
}
empty () {
this.version();
log('\n');
this.help();
}
serve () {
require(path.join(this.path, 'index'));
return Promise.resolve();
}
interactive () {
return new Promise( (resolve, reject) => {
setTimeout(function () {
green(" Application will now run in interactive mode");
grey(' (ctrl + c) twice to exit interactive mode, then once more to quit the application\n');
replHistory(require('repl').start({
prompt: chalk.yellow("Glad > ")
}), path.join(process.cwd(), '.glad_history'));
resolve();
}, 1000);
});
}
console () {
process.env['CONSOLE_MODE'] = true;
return this.serve().then(() => this.interactive());
}
api () {
let withModel = this.args.model !== false;
let resource = this.args._.slice(1)[0];
let lower_name = lodash.toLower(resource);
let plural_lower_name = pluralize(lower_name);
let class_name = this.class_name = lodash.upperFirst(lower_name);
let config = require(path.join(this.path, 'config'));
let orm = config.orm || 'default';
let adapter = config.defaultAdapter || '';
let vars = [plural_lower_name, lower_name, class_name, orm, adapter, withModel];
let templateDir = 'blueprints/api';
this.modelPath = path.join(this.path, 'models', `${lower_name}.js`);
this.controllerPath = path.join(this.path, 'controllers', `${lower_name}.js`);
this.routePath = path.join(this.path, 'routes', `${lower_name}.js`);
this.model = fs.readFileSync(path.join(this.cliDir, templateDir, orm, 'model.js'), 'utf8');
this.controller = fs.readFileSync(path.join(this.cliDir, templateDir, (withModel ? orm : 'nomodel'), 'controller.js'), 'utf8');
this.route = fs.readFileSync(path.join(this.cliDir, templateDir, 'common/route.js'), 'utf8');
let modelExists = fs.existsSync(this.modelPath);
let routeExists = fs.existsSync(this.routePath);
let controllerExists = fs.existsSync(this.controllerPath);
if (!adapter && orm === 'waterline') {
orange('Your config does not have a defaultAdapter for waterline. You will need to specify the adapter in your model.');
}
return new Promise( (resolve, reject) => {
let rl;
let resources = [
withModel && modelExists && this.modelPath.replace(this.path + '/', ''),
routeExists && this.routePath.replace(this.path + '/', ''),
controllerExists && this.controllerPath.replace(this.path + '/', '')
].filter(x => x);
if (resources.length) {
red(`The following resources already exist.\n${resources.join('\n')}`);
rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("Overwrite existing resources? [y/n]\n", answer => {
if (answer === 'y') {
this.createApiResources(vars);
} else {
green('Ok, Glad has done nothing destructive and will exit now.');
}
rl.close();
resolve();
});
} else {
this.createApiResources(vars);
resolve();
}
});
}
createApiResources (vars) {
let withModel = vars.pop();
yellow(`Creating ${this.class_name} Controller`);
this.controller = this.replaceTemplateVariables(this.controller, vars);
if (withModel) {
yellow(`Creating ${this.class_name} Model`);
this.model = this.replaceTemplateVariables(this.model, vars);
}
yellow(`Creating ${this.class_name} Route`);
this.route = this.replaceTemplateVariables(this.route, vars);
if (withModel) {
fs.writeFileSync(this.modelPath, this.model, 'utf8');
}
fs.writeFileSync(this.controllerPath, this.controller, 'utf8');
fs.writeFileSync(this.routePath, this.route, 'utf8');
}
replaceTemplateVariables (tpl, vars) {
let [plural_lower_name, lower_name, class_name, orm, adapter] = vars;
tpl = tpl.replace(/{{plural_lower_name}}/g, plural_lower_name);
tpl = tpl.replace(/{{lower_name}}/g, lower_name);
tpl = tpl.replace(/{{class_name}}/g, class_name);
tpl = tpl.replace(/{{orm}}/g, orm);
tpl = tpl.replace(/{{adapter}}/g, adapter);
return tpl;
}
// Update this such that glad.js fires a ready event, and this listens to it.
// Using timeouts will definately cause headaches for folks with extensive initializers.
run () {
let resource = this.args._.slice(1)[0];
process.env['CONSOLE_MODE'] = true;
return this.serve().then( () => {
let resourcePath = path.join(this.path, resource);
setTimeout(() => {
yellow(`Getting ready to execute ${resourcePath}`);
}, 500);
setTimeout(() => {
let resourceModule = require(resourcePath);
resourceModule();
}, 3000);
});
}
destroy () {
let resource = this.args._.slice(1)[0];
if (!resource) {
return console.error("Please specify a resource that you would like to destroy");
}
resource = resource.toLowerCase();
this.modelPath = path.join(this.path, 'models', `${resource}.js`);
this.controllerPath = path.join(this.path, 'controllers', `${resource}.js`);
this.routePath = path.join(this.path, 'routes', `${resource}.js`);
this.viewsPath = path.join(this.path, 'views', `${resource}`);
let rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question(`Are you sure you want to remove the resources for ${resource}? [y/n]\n`, answer => {
if (answer === 'y') {
this.removeApiResources();
} else {
green('Ok, Glad has done nothing destructive and will exit now.');
}
rl.close();
});
}
removeApiResources () {
try {
yellow(`Removing ${this.modelPath}`);
fs.unlinkSync(this.modelPath);
} catch (e) {
if (e.code === 'ENOENT') {
grey(`Not Found > ${this.modelPath.split('/').slice(-2).join('/')}`);
} else {
red(e);
}
}
try {
yellow(`Removing ${this.controllerPath}`);
fs.unlinkSync(this.controllerPath);
} catch (e) {
if (e.code === 'ENOENT') {
grey(`Not Found > ${this.controllerPath.split('/').slice(-2).join('/')}`);
} else {
red(e);
}
}
try {
yellow(`Removing ${this.routePath}`);
fs.unlinkSync(this.routePath);
} catch (e) {
if (e.code === 'ENOENT') {
grey(`Not Found > ${this.routePath.split('/').slice(-2).join('/')}`);
} else {
red(e);
}
}
}
copyOverBlueprint (folder) {
return new Promise((resolve, reject) => {
cpr(path.join(this.cliDir, `blueprints/common`), process.cwd(), { overwrite: true }, function (err) {
cpr(folder, process.cwd(), { overwrite: true }, function(err) {
return err ? reject(err) : resolve();
});
});
});
}
initialize () {
try {
let pack = require(path.join(this.path, 'package.json'));
if (pack) {
red('Yikes! It seems like there is a package.json at this location. Refusing to overwrite existing node js project.');
process.exit();
}
} catch (err) {}
return new Promise( (resolve, reject) => {
let odm = this.args.odm || 'mongoose';
let adapter = this.args.adapter || "sails-disk";
let blueprint;
if (odm === 'none') {
odm = 'default';
}
blueprint = odm;
yellow(`creating a new ${odm || ''} project`);
this.copyOverBlueprint(path.join(this.cliDir, `blueprints/${blueprint}`)).then( () => {
let packageJson = require(path.join(this.path, 'package.json'));
let config = require(path.join(this.path, 'config.js'));
packageJson.dependencies.glad = `${this.gladCliVersion}`;
packageJson.author = process.env.USER;
packageJson.name = path.basename(this.path);
if (odm === 'waterline') {
packageJson.dependencies.waterline = WATERLINE_VERSION;
packageJson.dependencies[adapter] = "latest";
} else if (odm === 'mongoose') {
packageJson.dependencies.mongoose = MONGOOSE_VERSION;
}
fs.writeFileSync(path.join(this.path, 'package.json'), JSON.stringify(packageJson, null, 2), 'utf8');
fs.writeFileSync(path.join(this.path, '.gitignore'), 'node_modules\n.vagrant/\n.glad_history\n.DS_Store', 'utf8');
fs.writeFileSync(path.join(this.path, '.glad_history'),'', 'utf8');
if (odm === 'waterline' && adapter) {
config.defaultAdapter = adapter;
}
if ( (odm === 'waterline' && adapter === 'sails-mongo') || odm === 'mongoose') {
config.mongodb = {
host : 'localhost',
port : 27017,
database : 'app'
};
}
if (odm) {
config.orm = odm;
fs.writeFileSync(path.join(this.path, 'config.js'), 'module.exports = ' + JSON.stringify(config, null, 2), 'utf8');
}
this.npmInstall().then(resolve).catch(reject);
}).catch(err => reject(err));
});
}
npmInstall () {
return new Promise( (resolve, reject) => {
yellow("Installing Packages...");
// Install any Dependencies
let npm = child.spawn('npm', ['install'], {
cwd: this.path
});
npm.stdout.setEncoding('utf8');
npm.stdout.on('data', function (stdout) {
console.log(stdout);
});
npm.on('close', function(code) {
if (code === 0) {
green("All Done! ");
} else {
red("ERROR: NPM could not install required packages, You will have to do it manually");
}
resolve();
});
});
}
}
module.exports = Command;
// example commands
// glad api [name] # Creates a new API
//# glad serve [-i] # Starts the server, pass in i for interactive mode
// glad run [-i] # Runs a job or script in the same process as a new application server (without binding to a port). Pass in i for interactive mode
//# glad -v # Displays The Version of Glad
// glad destroy [name] # Destroys an API, removes the model, route, controller, and test
//# glad console # Creates an instance of the app in REPL & DEVELOPMENT MODE
// glad init --odm=[waterline|mongoose]# Creates a new Glad Project. Optionally, pass in the ODM you would like to use. (for the default stub only)