source: trip-planner-front/node_modules/karma/lib/init.js@ 76712b2

Last change on this file since 76712b2 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

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