/
essentials.js
392 lines (318 loc) · 10.1 KB
/
essentials.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
const Fs = require('fs-extra');
const Handlebars = require('handlebars');
const Path = require('path');
const ReadlineSync = require('readline-sync');
const Tmp = require('tmp');
const Ascii = require('./ascii');
const Git = require('./git');
const LocalStorage = require('./local-storage');
const Paths = require('./paths');
const Rebase = require('./rebase');
const Step = require('./step');
const Submodule = require('./submodule');
const Utils = require('./utils');
/**
Contains some essential utilities that should usually run once to create a project or
initialize a project.
*/
const tmpDir = Tmp.dirSync({ unsafeCleanup: true });
const tmpPaths = Paths.resolveProject(tmpDir.name);
const exec = Utils.exec;
const defaultDumpFileName = 'tutorial.json';
const headEnd = '[//]: # (head-end)\n';
const footStart = '[//]: # (foot-start)\n';
(function () {
if (require.main !== module) {
return;
}
const argv = Minimist(process.argv.slice(2), {
string: ['_', 'message', 'm', 'output', 'o'],
boolean: ['override'],
});
const method = argv._[0];
const arg1 = argv._[1];
const output = argv.output || argv.o;
const override = argv.override;
const options = {
output,
override,
};
switch (method) {
case 'create': return createProject(arg1, options);
case 'ensure': return ensureTortilla(arg1);
}
}());
// Initialize tortilla project, it will use the skeleton as the template and it will fill
// it up with the provided details. Usually should only run once
function createProject(projectName, options) {
projectName = projectName || 'tortilla-project';
options = Utils.extend({
output: Path.resolve(projectName),
}, options);
// In case dir already exists verify the user's decision
if (Utils.exists(options.output)) {
options.override = options.override || ReadlineSync.keyInYN([
'Output path already exists.',
'Would you like to override it and continue?',
].join('\n'));
if (!options.override) {
return;
}
}
Fs.removeSync(tmpDir.name);
// Clone skeleton
Git.print(['clone', Paths.tortilla.skeleton, tmpDir.name], { cwd: '/tmp' });
// Checkout desired release
Git(['checkout', '0.0.1-alpha.4'], { cwd: tmpDir.name });
// Remove .git to remove unnecessary meta-data, git essentials should be
// initialized later on
Fs.removeSync(tmpPaths.git.resolve());
const packageName = Utils.kebabCase(projectName);
const title = Utils.startCase(projectName);
// Fill in template files
overwriteTemplateFile(tmpPaths.npm.package, {
name: packageName,
});
overwriteTemplateFile(tmpPaths.readme, {
title,
});
// Git chores
Git(['init'], { cwd: tmpDir.name });
Git(['add', '.'], { cwd: tmpDir.name });
Git(['commit', '-m', title], { cwd: tmpDir.name });
if (options.message) {
Git.print(['commit', '--amend', '-m', options.message], { cwd: tmpDir.name });
} else {
Git.print(['commit', '--amend'], { cwd: tmpDir.name });
}
// Initializing
ensureTortilla(tmpPaths);
// Copy from temp to output
Fs.removeSync(options.output);
Fs.copySync(tmpDir.name, options.output);
tmpDir.removeCallback();
}
// Make sure that tortilla essentials are initialized on an existing project.
// Used most commonly when cloning or creating a project
function ensureTortilla(projectDir) {
projectDir = projectDir || Utils.cwd();
const projectPaths = projectDir.resolve ? projectDir : Paths.resolveProject(projectDir);
const localStorage = LocalStorage.create(projectPaths);
const cwd = projectPaths.resolve();
// If tortilla is already initialized don't do anything
const isInitialized = localStorage.getItem('INIT');
if (isInitialized) {
return;
}
const hookFiles = Fs.readdirSync(projectPaths.tortilla.hooks);
// For each hook file in the hooks directory
hookFiles.forEach((hookFile) => {
const handlerPath = Path.resolve(projectPaths.tortilla.hooks, hookFile);
const hookName = Path.basename(hookFile, '.js');
const hookPath = Path.resolve(projectPaths.git.hooks, hookName);
// Place an executor in the project's git hooks
const hook = [
'',
'# Tortilla',
'cd .',
`node ${handlerPath} "$@"`,
].join('\n');
// If exists, append logic
if (Utils.exists(hookPath, 'file')) {
Fs.appendFileSync(hookPath, `\n${hook}`);
} else { // Else, create file
Fs.writeFileSync(hookPath, `#!/bin/sh${hook}`);
}
// Give read permissions to hooks so git can execute properly
Fs.chmodSync(hookPath, '755');
});
// Create root branch reference for continues integration testing
const activeBranchName = Git(['rev-parse', '--abbrev-ref', 'HEAD'], { cwd });
try {
Git(['rev-parse', `${activeBranchName}-root`], { cwd });
}
catch (e) {
Git(['branch', `${activeBranchName}-root`, activeBranchName], { cwd });
}
// Ensure submodules are initialized
Git.print(['submodule', 'init'], { cwd });
Git.print(['submodule', 'update'], { cwd });
// Mark tortilla flag as initialized
localStorage.setItem('INIT', true);
localStorage.setItem('USE_STRICT', true);
// The art should be printed only if the operation finished for all submodules
if (!Submodule.isOne()) {
Ascii.print('ready');
}
}
function naturalSort(as, bs) {
let a1, b1, i = 0, n, rx = /(\.\d+)|(\d+(\.\d+)?)|([^\d.]+)|(\.\D+)|(\.$)/g;
if (as === bs) {
return 0;
}
const a = as.toLowerCase().match(rx);
const b = bs.toLowerCase().match(rx);
const L = a.length;
while (i < L) {
if (!b[i]) {
return 1;
}
a1 = a[i];
b1 = b[i++];
if (a1 !== b1) {
n = a1 - b1;
if (!isNaN(n)) {
return n;
}
return a1 > b1 ? 1 : -1;
}
}
return b[i] ? -1 : 0;
}
// Dumps tutorial into a JSON file
// Output path defaults to cwd
function dumpProject(out = Utils.cwd(), options = {}) {
if (out instanceof Object && !(out instanceof String)) {
options = out;
out = Utils.cwd();
}
options = Object.assign({
filter: options.filter,
reject: options.reject,
}, options);
// Output path is relative to cwd
out = Path.resolve(Utils.cwd(), out);
// If provided output path is a dir assume the dump file should be created inside of it
if (Utils.exists(out, 'dir')) {
out = Path.join(out, defaultDumpFileName);
}
if (Utils.exists(out, 'file')) {
options.override = options.override || ReadlineSync.keyInYN([
'Output path already exists.',
'Would you like to override it and continue?',
].join('\n'));
if (!options.override) {
return;
}
}
console.log();
console.log(`Dumping into ${out}...`);
console.log();
// Will recursively ensure dirs as well
Fs.ensureFileSync(out);
// Run command once
const tagNames = Git(['tag', '-l'])
.split('\n')
.filter(Boolean);
let branchNames = tagNames
.filter((tagName) => {
return /^[^@]+?@\d+\.\d+\.\d+$/.test(tagName);
})
.map((tagName) => {
return tagName.split('@')[0];
})
.reduce((branchNames, branchName) => {
if (!branchNames.includes(branchName)) {
branchNames.push(branchName);
}
return branchNames;
}, []);
if (options.filter) {
branchNames = branchNames.filter((branchName) => {
return options.filter.includes(branchName);
});
}
if (options.reject) {
branchNames = branchNames.filter((branchName) => {
return !options.reject.includes(branchName);
});
}
const dump = branchNames.map((branchName) => {
const historyBranchName = `${branchName}-history`;
// Run command once
const releaseVersions = tagNames
.map((tagName) => {
return tagName.match(new RegExp(`${branchName}@(\\d+\\.\\d+\\.\\d+)`));
})
.filter(Boolean)
.map((match) => {
return match[1];
})
.reverse();
const releases = releaseVersions.map((releaseVersion) => {
const tagName = `${branchName}@${releaseVersion}`;
const tagRevision = Git(['rev-parse', tagName]);
const historyRevision = Git([
'log', historyBranchName, `--grep=^${tagName}:`, '--format=%H'
]).split('\n')
.filter(Boolean)
.pop();
const manuals = Fs.readdirSync(Paths.manuals.views).sort(naturalSort).map((manualName, stepIndex) => {
const format = '%H %s';
let stepLog, manualPath;
// Step
if (stepIndex) {
manualPath = Path.resolve(Paths.manuals.views, manualName);
stepLog = Git([
'log', branchName, `--grep=^Step ${stepIndex}:`, `--format=${format}`
]);
}
// Root
else {
manualPath = Paths.readme;
stepLog = Git([
'log', Git.rootHash(branchName), `--format=${format}`
]);
}
manualPath = Path.relative(Utils.cwd(), manualPath);
stepLog = stepLog.split(' ');
const stepRevision = stepLog.shift();
const manualTitle = stepLog.join(' ');
// Removing header and footer, since the view should be used externally on a
// different host which will make sure to show these two
let manualView = Git(['show', `${stepRevision}:${manualPath}`]);
if (manualView.includes(headEnd)) {
manualView = manualView
.split(headEnd)
.slice(1)
.join(headEnd);
}
if (manualView.includes(footStart)) {
manualView = manualView
.split(footStart)
.slice(0, -1)
.join(footStart);
}
manualView = manualView.trim();
return {
manualTitle,
stepRevision,
manualView,
};
});
return {
releaseVersion,
tagName,
tagRevision,
historyRevision,
manuals,
};
});
return {
branchName,
historyBranchName,
releases,
};
});
Fs.writeJsonSync(out, dump, { spaces: 2 });
}
function overwriteTemplateFile(path, scope) {
const templateContent = Fs.readFileSync(path, 'utf8');
const viewContent = Handlebars.compile(templateContent)(scope);
Fs.writeFileSync(path, viewContent);
}
module.exports = {
create: createProject,
ensure: ensureTortilla,
dump: dumpProject,
};