Bug:Fix file validation issue
[vnfsdk/refrepo.git] / vnfmarket / src / main / webapp / vnfmarket / node_modules / karma / lib / init.js
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
6
7 var helper = require('./helper')
8 var logger = require('./logger')
9 var constant = require('./constants')
10
11 var log = logger.create('init')
12
13 var StateMachine = require('./init/state_machine')
14 var COLOR_SCHEME = require('./init/color_schemes')
15 var formatters = require('./init/formatters')
16
17 // TODO(vojta): coverage
18 // TODO(vojta): html preprocessors
19 // TODO(vojta): SauceLabs
20 // TODO(vojta): BrowserStack
21
22 var logQueue = []
23 var printLogQueue = function () {
24   while (logQueue.length) {
25     logQueue.shift()()
26   }
27 }
28
29 var NODE_MODULES_DIR = path.resolve(__dirname, '../..')
30
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')
35 }
36
37 var installPackage = function (pkgName) {
38   // Do not install if already installed.
39   try {
40     require(NODE_MODULES_DIR + '/' + pkgName)
41     return
42   } catch (e) {}
43
44   log.debug('Missing plugin "%s". Installing...', pkgName)
45
46   var options = {
47     cwd: path.resolve(NODE_MODULES_DIR, '..')
48   }
49
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 () {
54       if (!err) {
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)
62       } else {
63         log.warn('Failed to install "%s"\n  Please install it manually.', pkgName)
64       }
65     })
66   })
67 }
68
69 var validatePattern = function (pattern) {
70   if (!glob.sync(pattern).length) {
71     log.warn('There is no file matching this pattern.\n')
72   }
73 }
74
75 var validateBrowser = function (name) {
76   // TODO(vojta): check if the path resolves to a binary
77   installPackage('karma-' + name.toLowerCase().replace('canary', '') + '-launcher')
78 }
79
80 var validateFramework = function (name) {
81   installPackage('karma-' + name)
82 }
83
84 var validateRequireJs = function (useRequire) {
85   if (useRequire) {
86     validateFramework('requirejs')
87   }
88 }
89
90 var questions = [{
91   id: 'framework',
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
96 }, {
97   id: 'requirejs',
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,
103   boolean: true
104 }, {
105   id: 'browsers',
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,
110   multiple: true
111 }, {
112   id: 'files',
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.',
116   multiple: true,
117   validate: validatePattern
118 }, {
119   id: 'exclude',
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.',
123   multiple: true,
124   validate: validatePattern
125 }, {
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'],
130   boolean: true,
131   condition: function (answers) {
132     return answers.requirejs
133   }
134 }, {
135   id: 'includedFiles',
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.',
140   multiple: true,
141   validate: validatePattern,
142   condition: function (answers) {
143     return answers.requirejs && !answers.generateTestMain
144   }
145 }, {
146   id: 'autoWatch',
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'],
150   boolean: true
151 }]
152
153 var getBasePath = function (configFilePath, cwd) {
154   var configParts = path.dirname(configFilePath).split(path.sep)
155   var cwdParts = cwd.split(path.sep)
156   var base = []
157
158   while (configParts.length && configParts[0] === cwdParts[0]) {
159     configParts.shift()
160     cwdParts.shift()
161   }
162
163   while (configParts.length) {
164     var part = configParts.shift()
165     if (part === '..') {
166       base.unshift(cwdParts.pop())
167     } else if (part !== '.') {
168       base.unshift('..')
169     }
170   }
171
172   return base.join(path.sep)
173 }
174
175 var processAnswers = function (answers, basePath, testMainFile) {
176   var processedAnswers = {
177     basePath: basePath,
178     files: answers.files,
179     onlyServedFiles: [],
180     exclude: answers.exclude,
181     autoWatch: answers.autoWatch,
182     generateTestMain: answers.generateTestMain,
183     browsers: answers.browsers,
184     frameworks: [],
185     preprocessors: {}
186   }
187
188   if (answers.framework) {
189     processedAnswers.frameworks.push(answers.framework)
190   }
191
192   if (answers.requirejs) {
193     processedAnswers.frameworks.push('requirejs')
194     processedAnswers.files = answers.includedFiles || []
195     processedAnswers.onlyServedFiles = answers.files
196
197     if (answers.generateTestMain) {
198       processedAnswers.files.push(testMainFile)
199     }
200   }
201
202   var allPatterns = answers.files.concat(answers.includedFiles || [])
203   if (allPatterns.some(function (pattern) {
204       return mm(pattern, '**/*.coffee')
205     })) {
206     installPackage('karma-coffee-preprocessor')
207     processedAnswers.preprocessors['**/*.coffee'] = ['coffee']
208   }
209
210   return processedAnswers
211 }
212
213 exports.init = function (config) {
214   var useColors = true
215   var logLevel = constant.LOG_INFO
216   var colorScheme = COLOR_SCHEME.ON
217
218   if (helper.isDefined(config.colors)) {
219     colorScheme = config.colors ? COLOR_SCHEME.ON : COLOR_SCHEME.OFF
220     useColors = config.colors
221   }
222
223   if (helper.isDefined(config.logLevel)) {
224     logLevel = config.logLevel
225   }
226
227   logger.setup(logLevel, useColors)
228
229   // need to be registered before creating readlineInterface
230   process.stdin.on('keypress', function (s, key) {
231     sm.onKeypress(key)
232   })
233
234   var rli = readline.createInterface(process.stdin, process.stdout)
235   var sm = new StateMachine(rli, colorScheme)
236
237   rli.on('line', sm.onLine.bind(sm))
238
239   // clean colors
240   rli.on('SIGINT', function () {
241     sm.kill()
242     process.exit(0)
243   })
244
245   sm.on('next_question', printLogQueue)
246
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)
256
257     if (isCoffee) {
258       installPackage('coffee-script')
259     }
260
261     if (processedAnswers.generateTestMain) {
262       formatter.writeRequirejsConfigFile(testMainFilePath)
263       console.log(colorScheme.success(
264         'RequireJS bootstrap file generated at "' + testMainFilePath + '".\n'
265       ))
266     }
267
268     formatter.writeConfigFile(configFilePath, processedAnswers)
269     console.log(colorScheme.success('Config file generated at "' + configFilePath + '".\n'))
270   })
271 }