cli.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. 'use strict'
  2. const path = require('path')
  3. const optimist = require('optimist')
  4. const fs = require('graceful-fs')
  5. const Server = require('./server')
  6. const helper = require('./helper')
  7. const constant = require('./constants')
  8. function processArgs (argv, options, fs, path) {
  9. if (argv.help) {
  10. console.log(optimist.help())
  11. process.exit(0)
  12. }
  13. if (argv.version) {
  14. console.log('Karma version: ' + constant.VERSION)
  15. process.exit(0)
  16. }
  17. // TODO(vojta): warn/throw when unknown argument (probably mispelled)
  18. Object.getOwnPropertyNames(argv).forEach(function (name) {
  19. let argumentValue = argv[name]
  20. if (name !== '_' && name !== '$0') {
  21. if (name.indexOf('_') !== -1) {
  22. throw new Error('Bad argument: ' + name + ' did you mean ' + name.replace('_', '-'))
  23. }
  24. if (Array.isArray(argumentValue)) {
  25. // If the same argument is defined multiple times, override.
  26. argumentValue = argumentValue.pop()
  27. }
  28. options[helper.dashToCamel(name)] = argumentValue
  29. }
  30. })
  31. if (helper.isString(options.autoWatch)) {
  32. options.autoWatch = options.autoWatch === 'true'
  33. }
  34. if (helper.isString(options.colors)) {
  35. options.colors = options.colors === 'true'
  36. }
  37. if (helper.isString(options.failOnEmptyTestSuite)) {
  38. options.failOnEmptyTestSuite = options.failOnEmptyTestSuite === 'true'
  39. }
  40. if (helper.isString(options.formatError)) {
  41. let required
  42. try {
  43. required = require(options.formatError)
  44. } catch (err) {
  45. console.error('Could not require formatError: ' + options.formatError, err)
  46. }
  47. // support exports.formatError and module.exports = function
  48. options.formatError = required.formatError || required
  49. if (!helper.isFunction(options.formatError)) {
  50. console.error('Format error must be a function, got: ' + typeof options.formatError)
  51. process.exit(1)
  52. }
  53. }
  54. if (helper.isString(options.logLevel)) {
  55. const logConstant = constant['LOG_' + options.logLevel.toUpperCase()]
  56. if (helper.isDefined(logConstant)) {
  57. options.logLevel = logConstant
  58. } else {
  59. console.error('Log level must be one of disable, error, warn, info, or debug.')
  60. process.exit(1)
  61. }
  62. } else if (helper.isDefined(options.logLevel)) {
  63. console.error('Log level must be one of disable, error, warn, info, or debug.')
  64. process.exit(1)
  65. }
  66. if (helper.isString(options.singleRun)) {
  67. options.singleRun = options.singleRun === 'true'
  68. }
  69. if (helper.isString(options.browsers)) {
  70. options.browsers = options.browsers.split(',')
  71. }
  72. if (options.reportSlowerThan === false) {
  73. options.reportSlowerThan = 0
  74. }
  75. if (helper.isString(options.reporters)) {
  76. options.reporters = options.reporters.split(',')
  77. }
  78. if (helper.isString(options.removedFiles)) {
  79. options.removedFiles = options.removedFiles.split(',')
  80. }
  81. if (helper.isString(options.addedFiles)) {
  82. options.addedFiles = options.addedFiles.split(',')
  83. }
  84. if (helper.isString(options.changedFiles)) {
  85. options.changedFiles = options.changedFiles.split(',')
  86. }
  87. if (helper.isString(options.refresh)) {
  88. options.refresh = options.refresh === 'true'
  89. }
  90. let configFile = argv._.shift()
  91. if (!configFile) {
  92. // default config file (if exists)
  93. if (fs.existsSync('./karma.conf.js')) {
  94. configFile = './karma.conf.js'
  95. } else if (fs.existsSync('./karma.conf.coffee')) {
  96. configFile = './karma.conf.coffee'
  97. } else if (fs.existsSync('./karma.conf.ts')) {
  98. configFile = './karma.conf.ts'
  99. } else if (fs.existsSync('./.config/karma.conf.js')) {
  100. configFile = './.config/karma.conf.js'
  101. } else if (fs.existsSync('./.config/karma.conf.coffee')) {
  102. configFile = './.config/karma.conf.coffee'
  103. } else if (fs.existsSync('./.config/karma.conf.ts')) {
  104. configFile = './.config/karma.conf.ts'
  105. }
  106. }
  107. options.configFile = configFile ? path.resolve(configFile) : null
  108. return options
  109. }
  110. function parseClientArgs (argv) {
  111. // extract any args after '--' as clientArgs
  112. let clientArgs = []
  113. argv = argv.slice(2)
  114. const idx = argv.indexOf('--')
  115. if (idx !== -1) {
  116. clientArgs = argv.slice(idx + 1)
  117. }
  118. return clientArgs
  119. }
  120. // return only args that occur before `--`
  121. function argsBeforeDoubleDash (argv) {
  122. const idx = argv.indexOf('--')
  123. return idx === -1 ? argv : argv.slice(0, idx)
  124. }
  125. function describeShared () {
  126. optimist
  127. .usage('Karma - Spectacular Test Runner for JavaScript.\n\n' +
  128. 'Usage:\n' +
  129. ' $0 <command>\n\n' +
  130. 'Commands:\n' +
  131. ' start [<configFile>] [<options>] Start the server / do single run.\n' +
  132. ' init [<configFile>] Initialize a config file.\n' +
  133. ' run [<options>] [ -- <clientArgs>] Trigger a test run.\n' +
  134. ' completion Shell completion for karma.\n\n' +
  135. 'Run --help with particular command to see its description and available options.')
  136. .describe('help', 'Print usage and options.')
  137. .describe('version', 'Print current version.')
  138. }
  139. function describeInit () {
  140. optimist
  141. .usage('Karma - Spectacular Test Runner for JavaScript.\n\n' +
  142. 'INIT - Initialize a config file.\n\n' +
  143. 'Usage:\n' +
  144. ' $0 init [<configFile>]')
  145. .describe('log-level', '<disable | error | warn | info | debug> Level of logging.')
  146. .describe('colors', 'Use colors when reporting and printing logs.')
  147. .describe('no-colors', 'Do not use colors when reporting or printing logs.')
  148. .describe('help', 'Print usage and options.')
  149. }
  150. function describeStart () {
  151. optimist
  152. .usage('Karma - Spectacular Test Runner for JavaScript.\n\n' +
  153. 'START - Start the server / do a single run.\n\n' +
  154. 'Usage:\n' +
  155. ' $0 start [<configFile>] [<options>]')
  156. .describe('port', '<integer> Port where the server is running.')
  157. .describe('auto-watch', 'Auto watch source files and run on change.')
  158. .describe('detached', 'Detach the server.')
  159. .describe('no-auto-watch', 'Do not watch source files.')
  160. .describe('log-level', '<disable | error | warn | info | debug> Level of logging.')
  161. .describe('colors', 'Use colors when reporting and printing logs.')
  162. .describe('no-colors', 'Do not use colors when reporting or printing logs.')
  163. .describe('reporters', 'List of reporters (available: dots, progress, junit, growl, coverage).')
  164. .describe('browsers', 'List of browsers to start (eg. --browsers Chrome,ChromeCanary,Firefox).')
  165. .describe('capture-timeout', '<integer> Kill browser if does not capture in given time [ms].')
  166. .describe('single-run', 'Run the test when browsers captured and exit.')
  167. .describe('no-single-run', 'Disable single-run.')
  168. .describe('report-slower-than', '<integer> Report tests that are slower than given time [ms].')
  169. .describe('fail-on-empty-test-suite', 'Fail on empty test suite.')
  170. .describe('no-fail-on-empty-test-suite', 'Do not fail on empty test suite.')
  171. .describe('help', 'Print usage and options.')
  172. }
  173. function describeRun () {
  174. optimist
  175. .usage('Karma - Spectacular Test Runner for JavaScript.\n\n' +
  176. 'RUN - Run the tests (requires running server).\n\n' +
  177. 'Usage:\n' +
  178. ' $0 run [<configFile>] [<options>] [ -- <clientArgs>]')
  179. .describe('port', '<integer> Port where the server is listening.')
  180. .describe('no-refresh', 'Do not re-glob all the patterns.')
  181. .describe('fail-on-empty-test-suite', 'Fail on empty test suite.')
  182. .describe('no-fail-on-empty-test-suite', 'Do not fail on empty test suite.')
  183. .describe('help', 'Print usage.')
  184. .describe('log-level', '<disable | error | warn | info | debug> Level of logging.')
  185. .describe('colors', 'Use colors when reporting and printing logs.')
  186. .describe('no-colors', 'Do not use colors when reporting or printing logs.')
  187. }
  188. function describeStop () {
  189. optimist
  190. .usage('Karma - Spectacular Test Runner for JavaScript.\n\n' +
  191. 'STOP - Stop the server (requires running server).\n\n' +
  192. 'Usage:\n' +
  193. ' $0 run [<configFile>] [<options>]')
  194. .describe('port', '<integer> Port where the server is listening.')
  195. .describe('log-level', '<disable | error | warn | info | debug> Level of logging.')
  196. .describe('help', 'Print usage.')
  197. }
  198. function describeCompletion () {
  199. optimist
  200. .usage('Karma - Spectacular Test Runner for JavaScript.\n\n' +
  201. 'COMPLETION - Bash/ZSH completion for karma.\n\n' +
  202. 'Installation:\n' +
  203. ' $0 completion >> ~/.bashrc\n')
  204. .describe('help', 'Print usage.')
  205. }
  206. exports.process = function () {
  207. const argv = optimist.parse(argsBeforeDoubleDash(process.argv.slice(2)))
  208. const options = {
  209. cmd: argv._.shift()
  210. }
  211. switch (options.cmd) {
  212. case 'start':
  213. describeStart()
  214. break
  215. case 'run':
  216. describeRun()
  217. options.clientArgs = parseClientArgs(process.argv)
  218. break
  219. case 'stop':
  220. describeStop()
  221. break
  222. case 'init':
  223. describeInit()
  224. break
  225. case 'completion':
  226. describeCompletion()
  227. break
  228. default:
  229. describeShared()
  230. if (!options.cmd) {
  231. processArgs(argv, options, fs, path)
  232. console.error('Command not specified.')
  233. } else {
  234. console.error('Unknown command "' + options.cmd + '".')
  235. }
  236. optimist.showHelp()
  237. process.exit(1)
  238. }
  239. return processArgs(argv, options, fs, path)
  240. }
  241. exports.run = function () {
  242. const config = exports.process()
  243. switch (config.cmd) {
  244. case 'start':
  245. new Server(config).start()
  246. break
  247. case 'run':
  248. require('./runner').run(config)
  249. break
  250. case 'stop':
  251. require('./stopper').stop(config)
  252. break
  253. case 'init':
  254. require('./init').init(config)
  255. break
  256. case 'completion':
  257. require('./completion').completion(config)
  258. break
  259. }
  260. }
  261. // just for testing
  262. exports.processArgs = processArgs
  263. exports.parseClientArgs = parseClientArgs
  264. exports.argsBeforeDoubleDash = argsBeforeDoubleDash