1 var readline = require('readline')
2 var path = require('path')
3 var glob = require('glob')
4 var mm = require('minimatch')
5 var exec = require('child_process').exec
7 var helper = require('./helper')
8 var logger = require('./logger')
9 var constant = require('./constants')
11 var log = logger.create('init')
13 var StateMachine = require('./init/state_machine')
14 var COLOR_SCHEME = require('./init/color_schemes')
15 var formatters = require('./init/formatters')
17 // TODO(vojta): coverage
18 // TODO(vojta): html preprocessors
19 // TODO(vojta): SauceLabs
20 // TODO(vojta): BrowserStack
23 var printLogQueue = function () {
24 while (logQueue.length) {
29 var NODE_MODULES_DIR = path.resolve(__dirname, '../..')
31 // Karma is not in node_modules, probably a symlink,
32 // use current working dir.
33 if (!/node_modules$/.test(NODE_MODULES_DIR)) {
34 NODE_MODULES_DIR = path.resolve('node_modules')
37 var installPackage = function (pkgName) {
38 // Do not install if already installed.
40 require(NODE_MODULES_DIR + '/' + pkgName)
44 log.debug('Missing plugin "%s". Installing...', pkgName)
47 cwd: path.resolve(NODE_MODULES_DIR, '..')
50 exec('npm install ' + pkgName + ' --save-dev', options, function (err, stdout, stderr) {
51 // Put the logs into the queue and print them after answering current question.
52 // Otherwise the log would clobber the interactive terminal.
53 logQueue.push(function () {
55 log.debug('%s successfully installed.', pkgName)
56 } else if (/is not in the npm registry/.test(stderr)) {
57 log.warn('Failed to install "%s". It is not in the NPM registry!\n' +
58 ' Please install it manually.', pkgName)
59 } else if (/Error: EACCES/.test(stderr)) {
60 log.warn('Failed to install "%s". No permissions to write in %s!\n' +
61 ' Please install it manually.', pkgName, options.cwd)
63 log.warn('Failed to install "%s"\n Please install it manually.', pkgName)
69 var validatePattern = function (pattern) {
70 if (!glob.sync(pattern).length) {
71 log.warn('There is no file matching this pattern.\n')
75 var validateBrowser = function (name) {
76 // TODO(vojta): check if the path resolves to a binary
77 installPackage('karma-' + name.toLowerCase().replace('canary', '') + '-launcher')
80 var validateFramework = function (name) {
81 installPackage('karma-' + name)
84 var validateRequireJs = function (useRequire) {
86 validateFramework('requirejs')
92 question: 'Which testing framework do you want to use ?',
93 hint: 'Press tab to list possible options. Enter to move to the next question.',
94 options: ['jasmine', 'mocha', 'qunit', 'nodeunit', 'nunit', ''],
95 validate: validateFramework
98 question: 'Do you want to use Require.js ?',
99 hint: 'This will add Require.js plugin.\n' +
100 'Press tab to list possible options. Enter to move to the next question.',
101 options: ['no', 'yes'],
102 validate: validateRequireJs,
106 question: 'Do you want to capture any browsers automatically ?',
107 hint: 'Press tab to list possible options. Enter empty string to move to the next question.',
108 options: ['Chrome', 'ChromeCanary', 'Firefox', 'Safari', 'PhantomJS', 'Opera', 'IE', ''],
109 validate: validateBrowser,
113 question: 'What is the location of your source and test files ?',
114 hint: 'You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".\n' +
115 'Enter empty string to move to the next question.',
117 validate: validatePattern
120 question: 'Should any of the files included by the previous patterns be excluded ?',
121 hint: 'You can use glob patterns, eg. "**/*.swp".\n' +
122 'Enter empty string to move to the next question.',
124 validate: validatePattern
126 id: 'generateTestMain',
127 question: 'Do you wanna generate a bootstrap file for RequireJS?',
128 hint: 'This will generate test-main.js/coffee that configures RequireJS and starts the tests.',
129 options: ['no', 'yes'],
131 condition: function (answers) {
132 return answers.requirejs
136 question: 'Which files do you want to include with <script> tag ?',
137 hint: 'This should be a script that bootstraps your test by configuring Require.js and ' +
138 'kicking __karma__.start(), probably your test-main.js file.\n' +
139 'Enter empty string to move to the next question.',
141 validate: validatePattern,
142 condition: function (answers) {
143 return answers.requirejs && !answers.generateTestMain
147 question: 'Do you want Karma to watch all the files and run the tests on change ?',
148 hint: 'Press tab to list possible options.',
149 options: ['yes', 'no'],
153 var getBasePath = function (configFilePath, cwd) {
154 var configParts = path.dirname(configFilePath).split(path.sep)
155 var cwdParts = cwd.split(path.sep)
158 while (configParts.length && configParts[0] === cwdParts[0]) {
163 while (configParts.length) {
164 var part = configParts.shift()
166 base.unshift(cwdParts.pop())
167 } else if (part !== '.') {
172 return base.join(path.sep)
175 var processAnswers = function (answers, basePath, testMainFile) {
176 var processedAnswers = {
178 files: answers.files,
180 exclude: answers.exclude,
181 autoWatch: answers.autoWatch,
182 generateTestMain: answers.generateTestMain,
183 browsers: answers.browsers,
188 if (answers.framework) {
189 processedAnswers.frameworks.push(answers.framework)
192 if (answers.requirejs) {
193 processedAnswers.frameworks.push('requirejs')
194 processedAnswers.files = answers.includedFiles || []
195 processedAnswers.onlyServedFiles = answers.files
197 if (answers.generateTestMain) {
198 processedAnswers.files.push(testMainFile)
202 var allPatterns = answers.files.concat(answers.includedFiles || [])
203 if (allPatterns.some(function (pattern) {
204 return mm(pattern, '**/*.coffee')
206 installPackage('karma-coffee-preprocessor')
207 processedAnswers.preprocessors['**/*.coffee'] = ['coffee']
210 return processedAnswers
213 exports.init = function (config) {
215 var logLevel = constant.LOG_INFO
216 var colorScheme = COLOR_SCHEME.ON
218 if (helper.isDefined(config.colors)) {
219 colorScheme = config.colors ? COLOR_SCHEME.ON : COLOR_SCHEME.OFF
220 useColors = config.colors
223 if (helper.isDefined(config.logLevel)) {
224 logLevel = config.logLevel
227 logger.setup(logLevel, useColors)
229 // need to be registered before creating readlineInterface
230 process.stdin.on('keypress', function (s, key) {
234 var rli = readline.createInterface(process.stdin, process.stdout)
235 var sm = new StateMachine(rli, colorScheme)
237 rli.on('line', sm.onLine.bind(sm))
240 rli.on('SIGINT', function () {
245 sm.on('next_question', printLogQueue)
247 sm.process(questions, function (answers) {
248 var cwd = process.cwd()
249 var configFile = config.configFile || 'karma.conf.js'
250 var isCoffee = path.extname(configFile) === '.coffee'
251 var testMainFile = isCoffee ? 'test-main.coffee' : 'test-main.js'
252 var formatter = formatters.createForPath(configFile)
253 var processedAnswers = processAnswers(answers, getBasePath(configFile, cwd), testMainFile)
254 var configFilePath = path.resolve(cwd, configFile)
255 var testMainFilePath = path.resolve(cwd, testMainFile)
258 installPackage('coffee-script')
261 if (processedAnswers.generateTestMain) {
262 formatter.writeRequirejsConfigFile(testMainFilePath)
263 console.log(colorScheme.success(
264 'RequireJS bootstrap file generated at "' + testMainFilePath + '".\n'
268 formatter.writeConfigFile(configFilePath, processedAnswers)
269 console.log(colorScheme.success('Config file generated at "' + configFilePath + '".\n'))