index.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. /**
  2. * @module index
  3. * @author Toru Nagashima
  4. * @copyright 2015 Toru Nagashima. All rights reserved.
  5. * See LICENSE file in root directory for full license.
  6. */
  7. "use strict"
  8. //------------------------------------------------------------------------------
  9. // Requirements
  10. //------------------------------------------------------------------------------
  11. const shellQuote = require("shell-quote")
  12. const matchTasks = require("./match-tasks")
  13. const readPackageJson = require("./read-package-json")
  14. const runTasks = require("./run-tasks")
  15. //------------------------------------------------------------------------------
  16. // Helpers
  17. //------------------------------------------------------------------------------
  18. const ARGS_PATTERN = /\{(!)?([*@]|\d+)([^}]+)?}/g
  19. /**
  20. * Converts a given value to an array.
  21. *
  22. * @param {string|string[]|null|undefined} x - A value to convert.
  23. * @returns {string[]} An array.
  24. */
  25. function toArray(x) {
  26. if (x == null) {
  27. return []
  28. }
  29. return Array.isArray(x) ? x : [x]
  30. }
  31. /**
  32. * Replaces argument placeholders (such as `{1}`) by arguments.
  33. *
  34. * @param {string[]} patterns - Patterns to replace.
  35. * @param {string[]} args - Arguments to replace.
  36. * @returns {string[]} replaced
  37. */
  38. function applyArguments(patterns, args) {
  39. const defaults = Object.create(null)
  40. return patterns.map(pattern => pattern.replace(ARGS_PATTERN, (whole, indirectionMark, id, options) => {
  41. if (indirectionMark != null) {
  42. throw Error(`Invalid Placeholder: ${whole}`)
  43. }
  44. if (id === "@") {
  45. return shellQuote.quote(args)
  46. }
  47. if (id === "*") {
  48. return shellQuote.quote([args.join(" ")])
  49. }
  50. const position = parseInt(id, 10)
  51. if (position >= 1 && position <= args.length) {
  52. return shellQuote.quote([args[position - 1]])
  53. }
  54. // Address default values
  55. if (options != null) {
  56. const prefix = options.slice(0, 2)
  57. if (prefix === ":=") {
  58. defaults[id] = shellQuote.quote([options.slice(2)])
  59. return defaults[id]
  60. }
  61. if (prefix === ":-") {
  62. return shellQuote.quote([options.slice(2)])
  63. }
  64. throw Error(`Invalid Placeholder: ${whole}`)
  65. }
  66. if (defaults[id] != null) {
  67. return defaults[id]
  68. }
  69. return ""
  70. }))
  71. }
  72. /**
  73. * Parse patterns.
  74. * In parsing process, it replaces argument placeholders (such as `{1}`) by arguments.
  75. *
  76. * @param {string|string[]} patternOrPatterns - Patterns to run.
  77. * A pattern is a npm-script name or a Glob-like pattern.
  78. * @param {string[]} args - Arguments to replace placeholders.
  79. * @returns {string[]} Parsed patterns.
  80. */
  81. function parsePatterns(patternOrPatterns, args) {
  82. const patterns = toArray(patternOrPatterns)
  83. const hasPlaceholder = patterns.some(pattern => ARGS_PATTERN.test(pattern))
  84. return hasPlaceholder ? applyArguments(patterns, args) : patterns
  85. }
  86. /**
  87. * Converts a given config object to an `--:=` style option array.
  88. *
  89. * @param {object|null} config -
  90. * A map-like object to overwrite package configs.
  91. * Keys are package names.
  92. * Every value is a map-like object (Pairs of variable name and value).
  93. * @returns {string[]} `--:=` style options.
  94. */
  95. function toOverwriteOptions(config) {
  96. const options = []
  97. for (const packageName of Object.keys(config)) {
  98. const packageConfig = config[packageName]
  99. for (const variableName of Object.keys(packageConfig)) {
  100. const value = packageConfig[variableName]
  101. options.push(`--${packageName}:${variableName}=${value}`)
  102. }
  103. }
  104. return options
  105. }
  106. /**
  107. * Converts a given config object to an `--a=b` style option array.
  108. *
  109. * @param {object|null} config -
  110. * A map-like object to set configs.
  111. * @returns {string[]} `--a=b` style options.
  112. */
  113. function toConfigOptions(config) {
  114. return Object.keys(config).map(key => `--${key}=${config[key]}`)
  115. }
  116. /**
  117. * Gets the maximum length.
  118. *
  119. * @param {number} length - The current maximum length.
  120. * @param {string} name - A name.
  121. * @returns {number} The maximum length.
  122. */
  123. function maxLength(length, name) {
  124. return Math.max(name.length, length)
  125. }
  126. //------------------------------------------------------------------------------
  127. // Public Interface
  128. //------------------------------------------------------------------------------
  129. /**
  130. * Runs npm-scripts which are matched with given patterns.
  131. *
  132. * @param {string|string[]} patternOrPatterns - Patterns to run.
  133. * A pattern is a npm-script name or a Glob-like pattern.
  134. * @param {object|undefined} [options] Optional.
  135. * @param {boolean} options.parallel -
  136. * If this is `true`, run scripts in parallel.
  137. * Otherwise, run scripts in sequencial.
  138. * Default is `false`.
  139. * @param {stream.Readable|null} options.stdin -
  140. * A readable stream to send messages to stdin of child process.
  141. * If this is `null`, ignores it.
  142. * If this is `process.stdin`, inherits it.
  143. * Otherwise, makes a pipe.
  144. * Default is `null`.
  145. * @param {stream.Writable|null} options.stdout -
  146. * A writable stream to receive messages from stdout of child process.
  147. * If this is `null`, cannot send.
  148. * If this is `process.stdout`, inherits it.
  149. * Otherwise, makes a pipe.
  150. * Default is `null`.
  151. * @param {stream.Writable|null} options.stderr -
  152. * A writable stream to receive messages from stderr of child process.
  153. * If this is `null`, cannot send.
  154. * If this is `process.stderr`, inherits it.
  155. * Otherwise, makes a pipe.
  156. * Default is `null`.
  157. * @param {string[]} options.taskList -
  158. * Actual name list of npm-scripts.
  159. * This function search npm-script names in this list.
  160. * If this is `null`, this function reads `package.json` of current directly.
  161. * @param {object|null} options.packageConfig -
  162. * A map-like object to overwrite package configs.
  163. * Keys are package names.
  164. * Every value is a map-like object (Pairs of variable name and value).
  165. * e.g. `{"npm-run-all": {"test": 777}}`
  166. * Default is `null`.
  167. * @param {boolean} options.silent -
  168. * The flag to set `silent` to the log level of npm.
  169. * Default is `false`.
  170. * @param {boolean} options.continueOnError -
  171. * The flag to ignore errors.
  172. * Default is `false`.
  173. * @param {boolean} options.printLabel -
  174. * The flag to print task names at the head of each line.
  175. * Default is `false`.
  176. * @param {boolean} options.printName -
  177. * The flag to print task names before running each task.
  178. * Default is `false`.
  179. * @param {number} options.maxParallel -
  180. * The maximum number of parallelism.
  181. * Default is unlimited.
  182. * @param {string} options.npmPath -
  183. * The path to npm.
  184. * Default is `process.env.npm_execpath`.
  185. * @returns {Promise}
  186. * A promise object which becomes fullfilled when all npm-scripts are completed.
  187. */
  188. module.exports = function npmRunAll(patternOrPatterns, options) { //eslint-disable-line complexity
  189. const stdin = (options && options.stdin) || null
  190. const stdout = (options && options.stdout) || null
  191. const stderr = (options && options.stderr) || null
  192. const taskList = (options && options.taskList) || null
  193. const config = (options && options.config) || null
  194. const packageConfig = (options && options.packageConfig) || null
  195. const args = (options && options.arguments) || []
  196. const parallel = Boolean(options && options.parallel)
  197. const silent = Boolean(options && options.silent)
  198. const continueOnError = Boolean(options && options.continueOnError)
  199. const printLabel = Boolean(options && options.printLabel)
  200. const printName = Boolean(options && options.printName)
  201. const race = Boolean(options && options.race)
  202. const maxParallel = parallel ? ((options && options.maxParallel) || 0) : 1
  203. const aggregateOutput = Boolean(options && options.aggregateOutput)
  204. const npmPath = options && options.npmPath
  205. try {
  206. const patterns = parsePatterns(patternOrPatterns, args)
  207. if (patterns.length === 0) {
  208. return Promise.resolve(null)
  209. }
  210. if (taskList != null && Array.isArray(taskList) === false) {
  211. throw new Error("Invalid options.taskList")
  212. }
  213. if (typeof maxParallel !== "number" || !(maxParallel >= 0)) {
  214. throw new Error("Invalid options.maxParallel")
  215. }
  216. if (!parallel && aggregateOutput) {
  217. throw new Error("Invalid options.aggregateOutput; It requires options.parallel")
  218. }
  219. if (!parallel && race) {
  220. throw new Error("Invalid options.race; It requires options.parallel")
  221. }
  222. const prefixOptions = [].concat(
  223. silent ? ["--silent"] : [],
  224. packageConfig ? toOverwriteOptions(packageConfig) : [],
  225. config ? toConfigOptions(config) : []
  226. )
  227. return Promise.resolve()
  228. .then(() => {
  229. if (taskList != null) {
  230. return { taskList, packageInfo: null }
  231. }
  232. return readPackageJson()
  233. })
  234. .then(x => {
  235. const tasks = matchTasks(x.taskList, patterns)
  236. const labelWidth = tasks.reduce(maxLength, 0)
  237. return runTasks(tasks, {
  238. stdin,
  239. stdout,
  240. stderr,
  241. prefixOptions,
  242. continueOnError,
  243. labelState: {
  244. enabled: printLabel,
  245. width: labelWidth,
  246. lastPrefix: null,
  247. lastIsLinebreak: true,
  248. },
  249. printName,
  250. packageInfo: x.packageInfo,
  251. race,
  252. maxParallel,
  253. npmPath,
  254. aggregateOutput,
  255. })
  256. })
  257. }
  258. catch (err) {
  259. return Promise.reject(new Error(err.message))
  260. }
  261. }