forked from geddy/geddy
/
Jakefile
492 lines (410 loc) · 16 KB
/
Jakefile
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// Load the basic Geddy toolkit
require('../lib/geddy')
// Dependencies
var fs = require('fs')
, path = require('path')
, utils = require('../lib/utils')
, adapter = require('../lib/template/adapters').Adapter
, templato = new (require('../deps/templato'));
namespace('gen', function () {
var _writeTemplate = function (name, filename, dirname, options) {
options = options || {};
var names = utils.string.inflection(name)
, text = fs.readFileSync(path.join(__dirname, filename + '.ejs'), 'utf8').toString()
, bare = options.bare || false // Default to full controller
, templ
, filePath;
// Render with the right model name
templ = new adapter({data: {ext: '.ejs'}, text: text, templato: templato});
templ.process({names: names, bare: bare, properties: options.properties});
// Write file
filePath = path.join('app', dirname, names.filename[options.inflection] + '.js');
fs.writeFileSync(filePath, templ.markup, 'utf8');
console.log('[Added] ' + filePath);
};
var _formatModelProperties = function(properties) {
var obj = {'default': {name: 'id', type: 'string'}};
if(!properties) return obj;
var itemsArr = properties.split(' ')
, name
, type
, args
, i
, value;
i = -1;
while(++i < itemsArr.length) {
value = itemsArr[i];
name = value.replace(/:.*/g, '');
type = value.replace(/[a-zA-Z]*:?/, '');
args = type.replace(/[a-zA-Z]*:?/, '');
// Take off any args on the type
type = type.replace(/:.*/g, '');
// Defaults and alias's
if(!type) type = 'string';
if(type === 'integer') type = 'int';
if(type === 'bool') type = 'boolean';
if(args === 'def') args = 'default';
if(type === 'default' || type === 'def') {
// If the type is `default` assume they want `string`
// type and want this property to be default
type = 'string';
args = 'default';
}
// Set it as default if given the `default` argument
if(args === 'default') {
obj['default'] = {name: name, type: type};
// Add the original ID property
obj['id'] = obj['id'] || {name: 'id', type: 'string'};
} else {
// If ID property is given and it matches the default
// then rewrite the default with the new ID property
if(name === 'id' && obj['default'].name === 'id') {
obj['default'] = {name: name, type: type};
} else obj[name] = {name: name, type: type};
}
}
return obj;
};
// Creates a new Geddy app scaffold
task('app', [], function(name, engine) {
if(!name) throw new Error('No app name specified.');
if(!engine) engine = 'ejs';
var mkdirs = [
''
, 'config'
, 'app/models'
, 'app/controllers'
, 'lib'
, 'log'
, 'node_modules'
]
, cps = [
['views/' + engine, 'app/views']
, ['public', '']
, ['router.js', 'config']
, ['init.js', 'config']
, ['environment.js', 'config']
, ['development.js', 'config']
, ['production.js', 'config']
, ['main.js', 'app/controllers']
, ['application.js', 'app/controllers']
, ['favicon.ico', 'public']
];
mkdirs.forEach(function(dir) {
jake.mkdirP(path.join(name, dir));
});
cps.forEach(function(cp) {
jake.cpR(path.join(__dirname, 'base', cp[0]), path.join(name, cp[1]));
});
console.log('Created app ' + name + '.');
});
// Creates a resource with a model, controller and a resource route
task('resource', function(name, modelProperties) {
if(!name) throw new Error('No resource name specified.');
var names = utils.string.inflection(name);
jake.Task['gen:model'].invoke(name, modelProperties);
jake.Task['gen:controller'].invoke(name);
jake.Task['gen:route'].invoke(name);
// Create views folder but not actions
jake.mkdirP(path.join('app', 'views', names.filename.plural));
console.log('[Added] ' + names.filename.plural + ' view directory');
});
// Creates a full scaffold with views, a model, controller and a resource route
task('scaffold', function(name, engine, modelProperties) {
if(!modelProperties && engine) {
modelProperties = engine;
engine = '';
}
if(!name) throw new Error('No scaffold name specified.');
if(!engine) engine = 'ejs';
var names = utils.string.inflection(name)
, jsEnvironment = path.normalize('config/environment.js')
, coffeeEnvironment = path.normalize('config/environment.coffee')
, environmentPath
, environmentArr
, text
, splitText
, dbContent = '';
// Check if the environment file exists
utils.fileUtils.searchParentPath(jsEnvironment, function(err) {
if(err) {
var jsErr = err;
// If jsEnvironment wasn't found, try finding coffee variant
utils.fileUtils.searchParentPath(coffeeEnvironment, function(err) {
if(err) {
throw jsErr;
} else {
environmentPath = coffeeEnvironment;
}
});
} else {
environmentPath = jsEnvironment;
}
});
jake.Task['gen:modelScaffold'].invoke(name, modelProperties);
jake.Task['gen:controllerScaffold'].invoke(name, {properties: modelProperties});
jake.Task['gen:route'].invoke(name);
jake.Task['gen:viewsScaffold'].invoke(name, {engine: engine, properties: modelProperties});
// Add the following line to `config/environment.js/.coffee`
if(environmentPath) {
text = fs.readFileSync(environmentPath, 'utf8').toString();
// Create text to add to environment
if(environmentPath.match('.coffee')) {
dbContent = [
' db:'
, ' mongo:'
, ' db: \'' + names.property.plural + '\''
].join('\n');
splitText = 'config = ';
} else if(environmentPath.match('.js')) {
dbContent = [
' db: {'
, ' mongo: {'
, ' db: \'' + names.property.plural + '\''
, ' }'
, ' }'
].join('\n');
splitText = 'var config = {';
}
// Don't add the db config over and over
if(text.indexOf('db:') == -1) {
environmentArr = text.split(splitText);
environmentArr[0] += splitText + '\n' + dbContent + '\n';
text = environmentArr.join('');
fs.writeFileSync(environmentPath, text, 'utf8');
console.log('[Added] Database configuration to ' + environmentPath);
} else console.log('Database configuration already set in ' + environmentPath);
}
});
task('model', [], function(name, properties) {
if(!name) throw new Error('No model name specified.');
_writeTemplate(name, 'resource/model', 'models', {
inflection: 'singular'
, properties: _formatModelProperties(properties)
});
});
task('modelScaffold', [], function(name, properties) {
if(!name) throw new Error('No model name specified.');
_writeTemplate(name, 'scaffold/model', 'models', {
inflection: 'singular'
, properties: _formatModelProperties(properties)
});
});
task('controller', [], function(name) {
if(!name) throw new Error('No controller name specified.');
_writeTemplate(name, 'resource/controller', 'controllers', {inflection: 'plural', bare: false});
});
task('controllerScaffold', [], function(name, options) {
if(!name) throw new Error('No controller name specified.');
options = options || {};
_writeTemplate(name, 'scaffold/controller', 'controllers', {
inflection: 'plural'
, bare: false
, properties: _formatModelProperties(options.properties)
});
});
task('bareController', [], function(name, engine) {
if(!name) throw new Error('No controller name specified.');
if(!engine) engine = 'ejs';
_writeTemplate(name, 'resource/controller', 'controllers', {inflection: 'plural', bare: true});
jake.Task['gen:route'].invoke(name, {bare: true});
jake.Task['gen:views'].invoke(name, {bare: true, engine: engine});
});
task('route', [], function(name, options) {
if(!name) throw new Error('No route name specified.');
options = options || {};
var names = utils.string.inflection(name)
, routeType = options.bare ? 'Bare' : 'Resource'
, jsRouter = path.normalize('config/router.js')
, coffeeRouter = path.normalize('config/router.coffee')
, routerPath
, routerArr
, text
, splitText
, newRoute;
// Check if the router file exists
utils.fileUtils.searchParentPath(jsRouter, function(err) {
if(err) {
var jsErr = err;
// If jsEnvironment wasn't found, try finding coffee variant
utils.fileUtils.searchParentPath(coffeeRouter, function(err) {
if(err) {
throw jsErr;
} else {
routerPath = coffeeRouter;
}
});
} else {
routerPath = jsRouter;
}
});
if(routerPath) {
text = fs.readFileSync(routerPath, 'utf8');
if(routerPath.match('.coffee')) {
if(options.bare) {
newRoute = 'router.match(\'/' + names.filename.plural +
'\').to controller: \'' + names.constructor.plural +
'\', action: \'index\'';
} else {
newRoute = 'router.resource \'' + names.filename.plural + '\'';
}
} else if(routerPath.match('.js')) {
if(options.bare) {
newRoute = 'router.match(\'/' + names.filename.plural +
'\').to({controller: \'' + names.constructor.plural +
'\', action: \'index\'});';
} else {
newRoute = 'router.resource(\'' + names.filename.plural + '\');';
}
}
// Don't add the same route over and over
if(text.indexOf(newRoute) == -1) {
// Add the new resource route just above the export
routerArr = text.split('exports.router');
routerArr[0] += newRoute + '\n';
text = routerArr.join('exports.router');
fs.writeFileSync(routerPath, text, 'utf8');
console.log('[Added] ' + routeType + ' ' + names.filename.plural +
' route added to ' + routerPath);
}
else {
console.log(routeType + ' ' + names.filename.plural + ' route already defined in ' +
routerPath);
}
} else {
console.log('There is no router file to add routes too');
}
});
task('views', [], function(name, options) {
if(!name) throw new Error('No view name specified.');
options = options || {};
// Option defaults
options.engine = options.engine || 'ejs';
var names = utils.string.inflection(name)
, engine = options.engine
, appViewDir = path.join('app', 'views', names.filename.plural)
, templateViewDir = path.join(__dirname, 'views', engine)
, cmds = []
, ext = '.html'
, appLayoutPath
, actions
, addActionView;
// Set extension based on engine option
if(engine === 'ejs') ext += '.ejs';
if(engine === 'jade') ext += '.jade';
if(engine === 'handlebars') ext += '.hbs';
if(engine === 'mustache') ext += '.ms';
// Set application layout path
appLayoutPath = path.join('app', 'views', 'layouts', 'application');
// Copy template view to application path
addActionView = function(action) {
jake.cpR(path.join(templateViewDir, action + ext), appViewDir);
};
jake.mkdirP(appViewDir);
jake.mkdirP('app/views/layouts');
addActionView('index');
// Add views for the other CRUD actions when doing a full-on resource
if(!options.bare) {
['add', 'edit', 'show'].forEach(function (action) {
addActionView(action);
});
}
// Create default layout if one doesn't exist
// Hack: There should be a better way to detect if a application layout exists
if(!utils.compat.existsSync(appLayoutPath + '.html.ejs') && !utils.compat.existsSync(appLayoutPath + '.html.jade') &&
!utils.compat.existsSync(appLayoutPath + '.html.hbs') && !utils.compat.existsSync(appLayoutPath + '.html.ms')) {
// Copy template layout file to apps application layout file
jake.cpR(path.join(templateViewDir, 'layout' + ext), appLayoutPath + ext);
}
console.log('[Added] View templates');
});
task('viewsScaffold', function(name, options) {
if(!name) {
throw new Error('No view name specified.');
}
options = options || {};
// Option defaults
options.engine = options.engine || 'ejs';
var names = utils.string.inflection(name)
, engine = options.engine
, appViewDir = path.join('app', 'views', names.filename.plural)
, templateViewDir = path.join(__dirname, 'scaffold', 'views', engine)
, cmds = []
, ext = '.html'
, appLayoutPath
, actions
, addActionView
, text
, templ;
// Set extension based on engine option
if(engine === 'ejs') ext += '.ejs';
if(engine === 'jade') ext += '.jade';
if(engine === 'handlebars') ext += '.hbs';
if(engine === 'mustache') ext += '.ms';
// Set application layout path
appLayoutPath = path.join('app', 'views', 'layouts', 'application');
// Function to compile the template
addActionView = function(action) {
text = fs.readFileSync(path.join(templateViewDir, action + ext + '.ejs')).toString();
// Compile template text
templ = new adapter({data: {ext: '.ejs'}, text: text, templato: templato});
templ.process({names: names, properties: _formatModelProperties(options.properties)});
// Write file
fs.writeFileSync(path.join(appViewDir, action + ext),
templ.markup.replace(/<@/g, '<%').replace(/@>/g, '%>'), 'utf8');
};
jake.mkdirP(appViewDir);
jake.mkdirP('app/views/layouts');
// Add views for the other CRUD actions when doing a full-on resource
['index', 'add', 'show', 'edit'].forEach(function(action) {
addActionView(action);
});
// Create default layout if one doesn't exist
// Hack: There should be a better way to detect if a application layout exists
if(!utils.compat.existsSync(appLayoutPath + '.html.ejs') && !utils.compat.existsSync(appLayoutPath + '.html.jade') &&
!utils.compat.existsSync(appLayoutPath + '.html.hbs') && !utils.compat.existsSync(appLayoutPath + '.html.ms')) {
// Copy template layout file to apps application layout file
jake.cpR(path.join(templateViewDir, 'layout' + ext), appLayoutPath + ext);
}
console.log('[Added] View templates');
});
// Generate a new application secret in environment.js
task('secret', [], function() {
var jsEnvironment = path.normalize('config/environment.js')
, coffeeEnvironment = path.normalize('config/environment.coffee')
, secret = utils.string.uuid(128)
, environmentPath
, environmentArr
, text
, splitText;
// Check if the environment file exists
utils.fileUtils.searchParentPath(jsEnvironment, function(err) {
if(err) {
var jsErr = err;
// If jsEnvironment wasn't found, try finding coffee variant
utils.fileUtils.searchParentPath(coffeeEnvironment, function(err) {
if(err) {
throw jsErr;
} else {
environmentPath = coffeeEnvironment;
}
});
} else {
environmentPath = jsEnvironment;
}
});
if(environmentPath) {
text = fs.readFileSync(environmentPath, 'utf8').toString();
// Remove any old secret
text = text.replace(/\nconfig.secret.+\n/, '');
splitText = 'module.exports = config';
if(environmentPath.match('.js')) splitText += ';';
environmentArr = text.split(splitText);
environmentArr[0] += "config.secret = '" + secret + "'";
environmentArr[0] += environmentPath.match('.js') ? ';\n\n' : '\n\n';
text = environmentArr.join(splitText);
fs.writeFileSync(environmentPath, text, 'utf8');
console.log('[Added] Application secret to \'' + environmentPath + '\'');
} else console.log('There is no environment config to add the secret too');
});
});