/
init.js
executable file
·364 lines (294 loc) · 9.31 KB
/
init.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
var readline = require('readline');
var fs = require('fs');
var util = require('util');
var path = require('path');
var glob = require('glob');
var helper = require('./helper');
var logger = require('./logger');
var constant = require('./constants');
var log = logger.create('init');
var JS_TPL_PATH = __dirname + '/../config.tpl.js';
var COFFEE_TPL_PATH = __dirname + '/../config.tpl.coffee';
var COLORS_ON = {
END: '\x1B[39m',
NYAN: '\x1B[36m',
GREEN: '\x1B[32m',
BOLD: '\x1B[1m',
bold: function(str) {
return this.BOLD + str + '\x1B[22m';
},
green: function(str) {
return this.GREEN + str + this.END;
}
};
// nasty global
var colors = COLORS_ON;
var COLORS_OFF = {
END: '',
NYAN: '',
GREEN: '',
BOLD: '',
bold: function(str) {
return str;
},
green: function(str) {
return str;
}
};
var validatePattern = function(value) {
if (!glob.sync(value).length) {
log.warn('There is no file matching this pattern.\n' + colors.NYAN);
}
};
var validateBrowser = function(name) {
var moduleName = 'karma-' + name.toLowerCase().replace('canary', '') + '-launcher';
try {
require(moduleName);
} catch (e) {
log.warn('Missing "%s" plugin.\n npm install %s --save-dev' + colors.NYAN, moduleName, moduleName);
}
// TODO(vojta): check if the path resolves to a binary
};
var validateFramework = function(name) {
try {
require('karma-' + name);
} catch (e) {
log.warn('Missing "karma-%s" plugin.\n npm install karma-%s --save-dev' + colors.NYAN, name, name);
}
};
var validateRequireJs = function(useRequire) {
if (useRequire) {
validateFramework('requirejs');
}
};
var questions = [{
id: 'framework',
question: 'Which testing framework do you want to use ?',
hint: 'Press tab to list possible options. Enter to move to the next question.',
options: ['jasmine', 'mocha', 'qunit', ''],
validate: validateFramework
}, {
id: 'requirejs',
question: 'Do you want to use Require.js ?',
hint: 'This will add Require.js plugin.\n' +
'Press tab to list possible options. Enter to move to the next question.',
options: ['no', 'yes'],
validate: validateRequireJs,
boolean: true
}, {
id: 'browsers',
question: 'Do you want to capture a browser automatically ?',
hint: 'Press tab to list possible options. Enter empty string to move to the next question.',
options: ['Chrome', 'ChromeCanary', 'Firefox', 'Safari', 'PhantomJS', 'Opera', 'IE', ''],
validate: validateBrowser,
multiple: true
}, {
id: 'files',
question: 'What is the location of your source and test files ?',
hint: 'You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".\n' +
'Enter empty string to move to the next question.',
multiple: true,
validate: validatePattern
}, {
id: 'exclude',
question: 'Should any of the files included by the previous patterns be excluded ?',
hint: 'You can use glob patterns, eg. "**/*.swp".\n' +
'Enter empty string to move to the next question.',
multiple: true,
validate: validatePattern
}, {
id: 'includedFiles',
question: 'Which files do you want to include with <script> tag ?',
hint: 'This should be a script that bootstraps your test by configuring Require.js and ' +
'kicking __karma__.start(), probably your test-main.js file.\n' +
'Enter empty string to move to the next question.',
multiple: true,
validate: validatePattern,
condition: function(answers) {return answers.requirejs;}
}, {
id: 'autoWatch',
question: 'Do you want Karma to watch all the files and run the tests on change ?',
hint: 'Press tab to list possible options.',
options: ['yes', 'no'],
boolean: true
}];
var StateMachine = function(rli) {
var currentQuestion;
var answers;
var currentOptions;
var currentOptionsPointer;
var pendingQuestionId;
var done;
this.onKeypress = function(key) {
if (!currentOptions || !key) {
return;
}
if (key.name === 'tab' || key.name === 'right' || key.name === 'down') {
this.suggestNextOption();
} else if (key.name === 'left' || key.name === 'up') {
currentOptionsPointer = currentOptionsPointer + currentOptions.length - 2;
this.suggestNextOption();
}
if (!key.ctrl && !key.meta && key.name !== 'enter' && key.name !== 'return') {
key.name = 'escape';
}
};
this.suggestNextOption = function() {
if (!currentOptions) {
return;
}
currentOptionsPointer = (currentOptionsPointer + 1) % currentOptions.length;
rli._deleteLineLeft();
rli._deleteLineRight();
rli.write(currentOptions[currentOptionsPointer]);
};
this.onLine = function(line) {
if (pendingQuestionId) {
line = line.trim();
if (currentOptions) {
currentOptionsPointer = currentOptions.indexOf(line);
if (currentOptionsPointer === -1) {
return;
}
}
if (line === '') {
line = null;
}
if (currentQuestion.boolean) {
line = (line === 'yes' || line === 'true' || line === 'on');
}
if (line !== null && currentQuestion.validate) {
currentQuestion.validate(line);
}
if (currentQuestion.multiple) {
answers[pendingQuestionId] = answers[pendingQuestionId] || [];
if (line !== null) {
answers[pendingQuestionId].push(line);
rli.prompt();
if (currentOptions) {
currentOptions.splice(currentOptionsPointer, 1);
currentOptionsPointer = -1;
}
} else {
this.nextQuestion();
}
} else {
answers[pendingQuestionId] = line;
this.nextQuestion();
}
}
};
this.nextQuestion = function() {
rli.write(colors.END);
currentQuestion = questions.shift();
while (currentQuestion && currentQuestion.condition && !currentQuestion.condition(answers)) {
currentQuestion = questions.shift();
}
if (currentQuestion) {
pendingQuestionId = null;
rli.write('\n' + colors.bold(currentQuestion.question) + '\n');
rli.write(currentQuestion.hint + colors.NYAN + '\n');
currentOptions = currentQuestion.options || null;
currentOptionsPointer = -1;
pendingQuestionId = currentQuestion.id;
rli.prompt();
this.suggestNextOption();
} else {
pendingQuestionId = null;
currentOptions = null;
// end
done(answers);
}
};
this.process = function(_questions, _done) {
questions = _questions;
answers = {};
done = _done;
this.nextQuestion();
};
};
var quote = function(value) {
return '\'' + value + '\'';
};
var quoteNonIncludedPattern = function(value) {
return util.format('{pattern: %s, included: false}', quote(value));
};
var formatFiles = function(files) {
return files.join(',\n ');
};
var getBasePath = function(configFilePath, cwd) {
var configParts = path.dirname(configFilePath).split(path.sep);
var cwdParts = cwd.split(path.sep);
var base = [];
while (configParts.length && configParts[0] === cwdParts[0]) {
configParts.shift();
cwdParts.shift();
}
while (configParts.length) {
var part = configParts.shift();
if (part === '..') {
base.unshift(cwdParts.pop());
} else if (part !== '.') {
base.unshift('..');
}
}
return base.join(path.sep);
};
var getReplacementsFromAnswers = function(answers, basePath) {
var files = answers.files.map(answers.includedFiles ? quoteNonIncludedPattern : quote);
if (answers.includedFiles) {
files = answers.includedFiles.map(quote).concat(files);
}
var frameworks = [];
if (answers.framework) {
frameworks.push(answers.framework);
}
if (answers.requirejs) {
frameworks.push('requirejs');
}
return {
DATE: new Date(),
BASE_PATH: basePath,
FRAMEWORKS: frameworks.map(quote).join(', '),
FILES: formatFiles(files),
EXCLUDE: answers.exclude ? formatFiles(answers.exclude.map(quote)) : '',
AUTO_WATCH: answers.autoWatch ? 'true' : 'false',
BROWSERS: answers.browsers.map(quote).join(', ')
};
};
var COFFEE_REGEXP = /\.coffee$/;
var isCoffeeFile = function(filename) {
return COFFEE_REGEXP.test(filename);
};
exports.init = function(config) {
var useColors = true;
var logLevel = constant.LOG_INFO;
if (helper.isDefined(config.colors)) {
colors = config.colors ? COLORS_ON : COLORS_OFF;
useColors = config.colors;
}
if (helper.isDefined(config.logLevel)) {
logLevel = config.logLevel;
}
logger.setup(logLevel, useColors);
// need to be registered before creating readlineInterface
process.stdin.on('keypress', function(s, key) {
sm.onKeypress(key);
});
var rli = readline.createInterface(process.stdin, process.stdout);
var sm = new StateMachine(rli, colors);
rli.on('line', sm.onLine.bind(sm));
sm.process(questions, function(answers) {
var cwd = process.cwd();
var configFile = config.configFile;
var templateFile = isCoffeeFile(configFile) ? COFFEE_TPL_PATH : JS_TPL_PATH;
var replacements = getReplacementsFromAnswers(answers, getBasePath(configFile, process.cwd()));
var content = fs.readFileSync(templateFile).toString().replace(/%(.*)%/g, function(a, key) {
return replacements[key];
});
var configFilePath = path.resolve(cwd, configFile);
fs.writeFileSync(configFilePath, content);
rli.write(colors.green('\nConfig file generated at "' + configFilePath + '".\n\n'));
rli.close();
});
};