This repository has been archived by the owner on Jun 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
418 lines (368 loc) · 13 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
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
'use strict';
var each = require('async-each');
var fs = require('fs');
var Handlebars = require('handlebars');
var inflection = require('inflection');
var mkdirp = require('mkdirp');
var sysPath = require('path');
var logger = require('loggy');
var clone = function(object) {
if (typeof object !== 'object') return object;
if (Array.isArray(object)) return object.slice().map(clone);
var cloned = {};
Object.keys(object).forEach(function(key) {
cloned[key] = clone(object[key]);
});
return cloned;
}
// Async filter.
var filter = function(list, predicate, callback) {
each(list, function(item, next) {
predicate(item, function(value) {
next(undefined, value);
});
}, function(error, filtered) {
if (error) throw new Error(error);
callback(list.filter(function(_, index) {
return filtered[index];
}));
});
};
exports.formatTemplate = function(template, templateData) {
if (!template) return '';
var key = '__TEMPLATE_FORMATTER';
var compiled = Handlebars.compile(template.replace(/\\\{/, key));
return compiled(templateData).toString().replace(key, '\\');
};
Handlebars.registerHelper('camelize', (function() {
var camelize = function(string) {
var regexp = /[-_]([a-z])/g;
var rest = string.replace(regexp, function(match, char) {
return char.toUpperCase();
});
return rest[0].toUpperCase() + rest.slice(1);
};
return function(options) {
return new Handlebars.SafeString(camelize(options.fn(this)));
};
})());
Handlebars.registerHelper('through', (function() {
return function(options) {
return new Handlebars.SafeString("{{" + options.hash["value"] + "}}")
};
})());
exports.loadHelpers = function(helpersPath) {
var path = sysPath.resolve(helpersPath);
var helpers = require(path);
helpers(Handlebars);
}
exports.generateFile = function(path, data, method, callback) {
fs.exists(path, function(exists) {
if (exists && method !== 'overwrite' && method !== 'append') {
logger.info("skipping " + path + " (already exists)");
if (callback != null) return callback();
} else {
var parentDir = sysPath.dirname(path);
var write = function() {
if (method === 'create' || method === 'overwrite') {
logger.info("create " + path);
fs.writeFile(path, data, callback);
} else if (method === 'append') {
logger.info("appending to " + path);
fs.appendFile(path, data, callback);
}
};
fs.exists(parentDir, function(exists) {
if (exists) return write();
logger.info("init " + parentDir);
// chmod 755.
mkdirp(parentDir, 0x1ed, function(error) {
if (error != null) return logger.error(error);
write();
});
});
}
});
};
exports.destroyFile = function(path, callback) {
fs.unlink(path, function(error) {
if (error != null) {
callback(error);
return logger.error("" + error);
}
logger.info("destroy " + path);
callback();
});
};
exports.amendFile = function(path, contents, callback) {
fs.readFile(path, 'utf8', function(error, existingContents) {
fs.writeFile(path, existingContents.replace(contents, ''), function(error) {
if (error != null) {
callback(error);
return logger.error("" + error);
}
logger.info("editing contents of " + path);
callback();
});
});
};
exports.scaffoldFile = function(revert, from, base, method, templateData, parentPath, name, callback) {
// inject directly
templateData.pluralName = name ? inflection.pluralize(name) : templateData.pluralName
templateData.parentPath = parentPath
var to = exports.formatTemplate(parentPath + '/' + base, templateData);
if (revert && method !== 'append') {
exports.destroyFile(to, callback);
} else {
fs.readFile(from, 'utf8', function(error, contents) {
var formatted = (function() {
try {
return exports.formatTemplate(contents, templateData);
} catch (error) {
console.log(error);
return contents;
}
})();
if (revert && method === 'append') {
exports.amendFile(to, formatted, callback);
} else {
exports.generateFile(to, formatted, method, callback);
}
});
}
};
exports.scaffoldFiles = function(revert, templateData) {
return function(generator, callback) {
if (generator.helpers) exports.loadHelpers(generator.helpers);
each(generator.files, function(args, next) {
exports.scaffoldFile(
revert, args.from, args.base, args.method, templateData,
args.parentPath, args.name, next
);
}, callback);
};
};
exports.isDirectory = function(generatorsPath) {
return function(path, callback) {
fs.stat(sysPath.join(generatorsPath, path), function(error, stats) {
if (error != null) logger.error(error);
callback(stats.isDirectory());
});
};
};
exports.readGeneratorConfig = function(generatorsPath) {
return function(type, callback) {
var path = sysPath.resolve(sysPath.join(generatorsPath, type, 'generator.json'));
var json = require(path);
json.type = type;
var helpersPath = sysPath.join(generatorsPath, type, 'helpers.js');
fs.stat(sysPath.resolve(helpersPath), function(error, stats) {
if (error == null && stats.isFile()) {
json.helpers = helpersPath;
}
callback(null, json);
});
};
};
exports.formatGeneratorConfig = function(path, json, templateData) {
var join = function(file) {
return sysPath.join(path, file);
};
if (json.dependencies == null) json.dependencies = [];
var defaultMethod = 'create';
json.files = json.files.map(function(object) {
return {
method: object.method || defaultMethod,
base: sysPath.basename(object.to),
from: join(object.from),
parentPath: templateData.parentPath || sysPath.dirname(object.to)
};
});
if (templateData.parentPath)
json.parentPath = templateData.parentPath;
json.dependencies = json.dependencies.map(function(object) {
if (!object.type) {
object.type = object.name;
object.name = undefined;
}
var dependencyTemplateData = clone(templateData);
dependencyTemplateData.parentPath = json.parentPath;
if (object.parentPath && !json.parentPath) {
logger.warn('generator "' + json.type + '" needs parentPath to function correctly with dependencies');
}
return {
method: object.method || defaultMethod,
type: exports.formatTemplate(object.type, dependencyTemplateData),
name: exports.formatTemplate(object.name || dependencyTemplateData.name, dependencyTemplateData),
parentPath: exports.formatTemplate(object.parentPath || templateData.parentPath, dependencyTemplateData)
};
});
return Object.freeze(json);
};
exports.getDependencyTree = function(generators, type, memo, dep) {
if (memo == null) memo = [];
var generator = clone(generators.filter(function(gen) {
return gen.type === type;
})[0]);
if (generator == null) {
throw new Error("Invalid generator " + type);
}
if (dep && dep.parentPath) {
generator.files.forEach(function(file) {
if (dep.parentPath) file.parentPath = dep.parentPath;
if (dep.name) file.name = dep.name;
});
}
(generator.dependencies || []).forEach(function(dependency) {
exports.getDependencyTree(generators, dependency.type, memo, dependency);
});
memo.push(Object.freeze(generator));
return memo;
};
exports.generateFiles = function(revert, generatorsPath, type, templateData, callback) {
fs.readdir(generatorsPath, function(error, files) {
if (error != null) throw new Error(error);
// Get directories from generators directory.
filter(files, exports.isDirectory(generatorsPath), function(directories) {
// Read all generator configs.
each(directories, exports.readGeneratorConfig(generatorsPath), function(error, configs) {
if (error != null) throw new Error(error);
var generators = directories.map(function(directory, index) {
var path = sysPath.join(generatorsPath, directory);
return exports.formatGeneratorConfig(path, configs[index], templateData);
});
// Calculate dependency trees, do the scaffolding.
var tree = exports.getDependencyTree(generators, type);
// console.log(JSON.stringify(tree, null, 2));
each(tree, exports.scaffoldFiles(revert, templateData), callback);
});
});
});
};
exports.listGenerators = function(generatorsPath, callback) {
fs.readdir(generatorsPath, function(error, files) {
if (error != null) throw new Error(error);
// Get directories from generators directory.
filter(files, exports.isDirectory(generatorsPath), function(directories) {
console.log("List of available generators in ./" + generatorsPath + ":");
each(directories, exports.readGeneratorConfig(generatorsPath), function(error, configs) {
configs.map(function(generator) {
var doc = " * ";
doc += (generator.name) ? generator.name : generator.type;
if (generator.description) doc += " ("+ generator.description + ")";
console.log(doc);
});
});
});
});
};
exports.helpGenerator = function(generatorsPath, type, templateData) {
fs.readdir(generatorsPath, function(error, files) {
if (error != null) throw new Error(error);
// Get directories from generators directory.
filter(files, exports.isDirectory(generatorsPath), function(directories) {
// Read all generator configs.
each(directories, exports.readGeneratorConfig(generatorsPath), function(error, configs) {
if (error != null) throw new Error(error);
var generators = directories.map(function(directory, index) {
var path = sysPath.join(generatorsPath, directory);
return exports.formatGeneratorConfig(path, configs[index], templateData);
});
var tree = exports.getDependencyTree(generators, type);
tree.reverse();
tree.map(function(generator, index) {
if (index == 0) {
console.log("Documentation for '" + type + "' generator:");
if (generator.description) {
console.log(generator.description+"\n");
}
console.log("'scaffolt " + type + " name'");
} else {
var doc = " * " + generator.type;
if (generator.description) {
doc += " (" + generator.description + ")";
}
console.log(doc);
}
each(generator.files, function(args) {
console.log("\twill " + args.method + " " + args.to);
});
if (index == 0 && tree.length > 1) {
console.log("");
console.log("Dependencies:");
}
});
});
});
});
};
var checkIfExists = function(generatorsPath, callback) {
fs.exists(generatorsPath, function(exists) {
if (!exists) {
var msg = 'Generators directory "' + generatorsPath + '" does not exist';
logger.error(msg);
return callback(new Error(msg));
}
callback();
});
};
var scaffolt = module.exports = function(type, name, options, callback) {
// Set some default params.
if (options == null) options = {};
if (callback == null) callback = function() {};
var pluralName = options.pluralName;
var generatorsPath = options.generatorsPath;
var revert = options.revert;
var parentPath = options.parentPath;
if (pluralName == null) pluralName = inflection.pluralize(name);
if (generatorsPath == null) generatorsPath = 'generators';
if (revert == null) revert = false;
var templateData = {name: name, pluralName: pluralName, parentPath: parentPath, type:type};
for(var key in options){
switch(key[0]) {
case '$':
templateData[key] = options[key];
break;
case '@':
templateData[key.substring(1)] = options[key];
break;
default:
break;
}
}
checkIfExists(generatorsPath, function(exists) {
exports.generateFiles(revert, generatorsPath, type, templateData, function(error) {
if (error != null) {
logger.error(error);
return callback(error);
}
callback();
});
});
};
scaffolt.list = function(options, callback) {
// Set some default params
if (options == null) options = {};
if (callback == null) callback = function() {};
var generatorsPath = options.generatorsPath;
if (generatorsPath == null) generatorsPath = 'generators';
checkIfExists(generatorsPath, function() {
exports.listGenerators(generatorsPath, function(error) {
if (error != null) {
logger.error(error);
return callback(error);
}
callback();
});
});
};
scaffolt.help = function(type, options) {
// Set some default params
if (options == null) options = {};
var generatorsPath = options.generatorsPath;
if (generatorsPath == null) generatorsPath = 'generators';
var templateData = {name: "name", pluralName: "names"};
checkIfExists(generatorsPath, function() {
exports.helpGenerator(generatorsPath, type, templateData);
});
};