UNPKG

8.1 kBJavaScriptView Raw
1var readline = require('readline')
2var path = require('path')
3var glob = require('glob')
4var mm = require('minimatch')
5var exec = require('child_process').exec
6
7var helper = require('./helper')
8var logger = require('./logger')
9
10var log = logger.create('init')
11
12var StateMachine = require('./init/state_machine')
13var COLOR_SCHEME = require('./init/color_schemes')
14var formatters = require('./init/formatters')
15
16// TODO(vojta): coverage
17// TODO(vojta): html preprocessors
18// TODO(vojta): SauceLabs
19// TODO(vojta): BrowserStack
20
21var logQueue = []
22var printLogQueue = function () {
23 while (logQueue.length) {
24 logQueue.shift()()
25 }
26}
27
28var NODE_MODULES_DIR = path.resolve(__dirname, '../..')
29
30// Karma is not in node_modules, probably a symlink,
31// use current working dir.
32if (!/node_modules$/.test(NODE_MODULES_DIR)) {
33 NODE_MODULES_DIR = path.resolve('node_modules')
34}
35
36var installPackage = function (pkgName) {
37 // Do not install if already installed.
38 try {
39 require(NODE_MODULES_DIR + '/' + pkgName)
40 return
41 } catch (e) {}
42
43 log.debug('Missing plugin "%s". Installing...', pkgName)
44
45 var options = {
46 cwd: path.resolve(NODE_MODULES_DIR, '..')
47 }
48
49 exec('npm install ' + pkgName + ' --save-dev', options, function (err, stdout, stderr) {
50 // Put the logs into the queue and print them after answering current question.
51 // Otherwise the log would clobber the interactive terminal.
52 logQueue.push(function () {
53 if (!err) {
54 log.debug('%s successfully installed.', pkgName)
55 } else if (/is not in the npm registry/.test(stderr)) {
56 log.warn('Failed to install "%s". It is not in the NPM registry!\n' +
57 ' Please install it manually.', pkgName)
58 } else if (/Error: EACCES/.test(stderr)) {
59 log.warn('Failed to install "%s". No permissions to write in %s!\n' +
60 ' Please install it manually.', pkgName, options.cwd)
61 } else {
62 log.warn('Failed to install "%s"\n Please install it manually.', pkgName)
63 }
64 })
65 })
66}
67
68var validatePattern = function (pattern) {
69 if (!glob.sync(pattern).length) {
70 log.warn('There is no file matching this pattern.\n')
71 }
72}
73
74var validateBrowser = function (name) {
75 // TODO(vojta): check if the path resolves to a binary
76 installPackage('karma-' + name.toLowerCase().replace('canary', '') + '-launcher')
77}
78
79var validateFramework = function (name) {
80 installPackage('karma-' + name)
81}
82
83var validateRequireJs = function (useRequire) {
84 if (useRequire) {
85 validateFramework('requirejs')
86 }
87}
88
89var questions = [{
90 id: 'framework',
91 question: 'Which testing framework do you want to use ?',
92 hint: 'Press tab to list possible options. Enter to move to the next question.',
93 options: ['jasmine', 'mocha', 'qunit', 'nodeunit', 'nunit', ''],
94 validate: validateFramework
95}, {
96 id: 'requirejs',
97 question: 'Do you want to use Require.js ?',
98 hint: 'This will add Require.js plugin.\n' +
99 'Press tab to list possible options. Enter to move to the next question.',
100 options: ['no', 'yes'],
101 validate: validateRequireJs,
102 boolean: true
103}, {
104 id: 'browsers',
105 question: 'Do you want to capture any browsers automatically ?',
106 hint: 'Press tab to list possible options. Enter empty string to move to the next question.',
107 options: ['Chrome', 'ChromeCanary', 'Firefox', 'Safari', 'PhantomJS', 'Opera', 'IE', ''],
108 validate: validateBrowser,
109 multiple: true
110}, {
111 id: 'files',
112 question: 'What is the location of your source and test files ?',
113 hint: 'You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".\n' +
114 'Enter empty string to move to the next question.',
115 multiple: true,
116 validate: validatePattern
117}, {
118 id: 'exclude',
119 question: 'Should any of the files included by the previous patterns be excluded ?',
120 hint: 'You can use glob patterns, eg. "**/*.swp".\n' +
121 'Enter empty string to move to the next question.',
122 multiple: true,
123 validate: validatePattern
124}, {
125 id: 'generateTestMain',
126 question: 'Do you wanna generate a bootstrap file for RequireJS?',
127 hint: 'This will generate test-main.js/coffee that configures RequireJS and starts the tests.',
128 options: ['no', 'yes'],
129 boolean: true,
130 condition: function (answers) {
131 return answers.requirejs
132 }
133}, {
134 id: 'includedFiles',
135 question: 'Which files do you want to include with <script> tag ?',
136 hint: 'This should be a script that bootstraps your test by configuring Require.js and ' +
137 'kicking __karma__.start(), probably your test-main.js file.\n' +
138 'Enter empty string to move to the next question.',
139 multiple: true,
140 validate: validatePattern,
141 condition: function (answers) {
142 return answers.requirejs && !answers.generateTestMain
143 }
144}, {
145 id: 'autoWatch',
146 question: 'Do you want Karma to watch all the files and run the tests on change ?',
147 hint: 'Press tab to list possible options.',
148 options: ['yes', 'no'],
149 boolean: true
150}]
151
152var getBasePath = function (configFilePath, cwd) {
153 var configParts = path.dirname(configFilePath).split(path.sep)
154 var cwdParts = cwd.split(path.sep)
155 var base = []
156
157 while (configParts.length && configParts[0] === cwdParts[0]) {
158 configParts.shift()
159 cwdParts.shift()
160 }
161
162 while (configParts.length) {
163 var part = configParts.shift()
164 if (part === '..') {
165 base.unshift(cwdParts.pop())
166 } else if (part !== '.') {
167 base.unshift('..')
168 }
169 }
170
171 return base.join(path.sep)
172}
173
174var processAnswers = function (answers, basePath, testMainFile) {
175 var processedAnswers = {
176 basePath: basePath,
177 files: answers.files,
178 onlyServedFiles: [],
179 exclude: answers.exclude,
180 autoWatch: answers.autoWatch,
181 generateTestMain: answers.generateTestMain,
182 browsers: answers.browsers,
183 frameworks: [],
184 preprocessors: {}
185 }
186
187 if (answers.framework) {
188 processedAnswers.frameworks.push(answers.framework)
189 }
190
191 if (answers.requirejs) {
192 processedAnswers.frameworks.push('requirejs')
193 processedAnswers.files = answers.includedFiles || []
194 processedAnswers.onlyServedFiles = answers.files
195
196 if (answers.generateTestMain) {
197 processedAnswers.files.push(testMainFile)
198 }
199 }
200
201 var allPatterns = answers.files.concat(answers.includedFiles || [])
202 if (allPatterns.some(function (pattern) {
203 return mm(pattern, '**/*.coffee')
204 })) {
205 installPackage('karma-coffee-preprocessor')
206 processedAnswers.preprocessors['**/*.coffee'] = ['coffee']
207 }
208
209 return processedAnswers
210}
211
212exports.init = function (config) {
213 logger.setupFromConfig(config)
214
215 var colorScheme = COLOR_SCHEME.ON
216
217 if (helper.isDefined(config.colors)) {
218 colorScheme = config.colors ? COLOR_SCHEME.ON : COLOR_SCHEME.OFF
219 }
220 // need to be registered before creating readlineInterface
221 process.stdin.on('keypress', function (s, key) {
222 sm.onKeypress(key)
223 })
224
225 var rli = readline.createInterface(process.stdin, process.stdout)
226 var sm = new StateMachine(rli, colorScheme)
227
228 rli.on('line', sm.onLine.bind(sm))
229
230 // clean colors
231 rli.on('SIGINT', function () {
232 sm.kill()
233 process.exit(0)
234 })
235
236 sm.on('next_question', printLogQueue)
237
238 sm.process(questions, function (answers) {
239 var cwd = process.cwd()
240 var configFile = config.configFile || 'karma.conf.js'
241 var isCoffee = path.extname(configFile) === '.coffee'
242 var testMainFile = isCoffee ? 'test-main.coffee' : 'test-main.js'
243 var formatter = formatters.createForPath(configFile)
244 var processedAnswers = processAnswers(answers, getBasePath(configFile, cwd), testMainFile)
245 var configFilePath = path.resolve(cwd, configFile)
246 var testMainFilePath = path.resolve(cwd, testMainFile)
247
248 if (isCoffee) {
249 installPackage('coffee-script')
250 }
251
252 if (processedAnswers.generateTestMain) {
253 formatter.writeRequirejsConfigFile(testMainFilePath)
254 console.log(colorScheme.success(
255 'RequireJS bootstrap file generated at "' + testMainFilePath + '".\n'
256 ))
257 }
258
259 formatter.writeConfigFile(configFilePath, processedAnswers)
260 console.log(colorScheme.success('Config file generated at "' + configFilePath + '".\n'))
261 })
262}