run-task.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. /**
  2. * @module run-task
  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 path = require("path")
  12. const chalk = require("chalk")
  13. const parseArgs = require("shell-quote").parse
  14. const padEnd = require("string.prototype.padend")
  15. const createHeader = require("./create-header")
  16. const createPrefixTransform = require("./create-prefix-transform-stream")
  17. const spawn = require("./spawn")
  18. //------------------------------------------------------------------------------
  19. // Helpers
  20. //------------------------------------------------------------------------------
  21. const colors = [chalk.cyan, chalk.green, chalk.magenta, chalk.yellow, chalk.red]
  22. let colorIndex = 0
  23. const taskNamesToColors = new Map()
  24. /**
  25. * Select a color from given task name.
  26. *
  27. * @param {string} taskName - The task name.
  28. * @returns {function} A colorize function that provided by `chalk`
  29. */
  30. function selectColor(taskName) {
  31. let color = taskNamesToColors.get(taskName)
  32. if (!color) {
  33. color = colors[colorIndex]
  34. colorIndex = (colorIndex + 1) % colors.length
  35. taskNamesToColors.set(taskName, color)
  36. }
  37. return color
  38. }
  39. /**
  40. * Wraps stdout/stderr with a transform stream to add the task name as prefix.
  41. *
  42. * @param {string} taskName - The task name.
  43. * @param {stream.Writable} source - An output stream to be wrapped.
  44. * @param {object} labelState - An label state for the transform stream.
  45. * @returns {stream.Writable} `source` or the created wrapped stream.
  46. */
  47. function wrapLabeling(taskName, source, labelState) {
  48. if (source == null || !labelState.enabled) {
  49. return source
  50. }
  51. const label = padEnd(taskName, labelState.width)
  52. const color = source.isTTY ? selectColor(taskName) : (x) => x
  53. const prefix = color(`[${label}] `)
  54. const stream = createPrefixTransform(prefix, labelState)
  55. stream.pipe(source)
  56. return stream
  57. }
  58. /**
  59. * Converts a given stream to an option for `child_process.spawn`.
  60. *
  61. * @param {stream.Readable|stream.Writable|null} stream - An original stream to convert.
  62. * @param {process.stdin|process.stdout|process.stderr} std - A standard stream for this option.
  63. * @returns {string|stream.Readable|stream.Writable} An option for `child_process.spawn`.
  64. */
  65. function detectStreamKind(stream, std) {
  66. return (
  67. stream == null ? "ignore" :
  68. // `|| !std.isTTY` is needed for the workaround of https://github.com/nodejs/node/issues/5620
  69. stream !== std || !std.isTTY ? "pipe" :
  70. /* else */ stream
  71. )
  72. }
  73. /**
  74. * Ensure the output of shell-quote's `parse()` is acceptable input to npm-cli.
  75. *
  76. * The `parse()` method of shell-quote sometimes returns special objects in its
  77. * output array, e.g. if it thinks some elements should be globbed. But npm-cli
  78. * only accepts strings and will throw an error otherwise.
  79. *
  80. * See https://github.com/substack/node-shell-quote#parsecmd-env
  81. *
  82. * @param {object|string} arg - Item in the output of shell-quote's `parse()`.
  83. * @returns {string} A valid argument for npm-cli.
  84. */
  85. function cleanTaskArg(arg) {
  86. return arg.pattern || arg.op || arg
  87. }
  88. //------------------------------------------------------------------------------
  89. // Interface
  90. //------------------------------------------------------------------------------
  91. /**
  92. * Run a npm-script of a given name.
  93. * The return value is a promise which has an extra method: `abort()`.
  94. * The `abort()` kills the child process to run the npm-script.
  95. *
  96. * @param {string} task - A npm-script name to run.
  97. * @param {object} options - An option object.
  98. * @param {stream.Readable|null} options.stdin -
  99. * A readable stream to send messages to stdin of child process.
  100. * If this is `null`, ignores it.
  101. * If this is `process.stdin`, inherits it.
  102. * Otherwise, makes a pipe.
  103. * @param {stream.Writable|null} options.stdout -
  104. * A writable stream to receive messages from stdout of child process.
  105. * If this is `null`, cannot send.
  106. * If this is `process.stdout`, inherits it.
  107. * Otherwise, makes a pipe.
  108. * @param {stream.Writable|null} options.stderr -
  109. * A writable stream to receive messages from stderr of child process.
  110. * If this is `null`, cannot send.
  111. * If this is `process.stderr`, inherits it.
  112. * Otherwise, makes a pipe.
  113. * @param {string[]} options.prefixOptions -
  114. * An array of options which are inserted before the task name.
  115. * @param {object} options.labelState - A state object for printing labels.
  116. * @param {boolean} options.printName - The flag to print task names before running each task.
  117. * @returns {Promise}
  118. * A promise object which becomes fullfilled when the npm-script is completed.
  119. * This promise object has an extra method: `abort()`.
  120. * @private
  121. */
  122. module.exports = function runTask(task, options) {
  123. let cp = null
  124. const promise = new Promise((resolve, reject) => {
  125. const stdin = options.stdin
  126. const stdout = wrapLabeling(task, options.stdout, options.labelState)
  127. const stderr = wrapLabeling(task, options.stderr, options.labelState)
  128. const stdinKind = detectStreamKind(stdin, process.stdin)
  129. const stdoutKind = detectStreamKind(stdout, process.stdout)
  130. const stderrKind = detectStreamKind(stderr, process.stderr)
  131. const spawnOptions = { stdio: [stdinKind, stdoutKind, stderrKind] }
  132. // Print task name.
  133. if (options.printName && stdout != null) {
  134. stdout.write(createHeader(
  135. task,
  136. options.packageInfo,
  137. options.stdout.isTTY
  138. ))
  139. }
  140. // Execute.
  141. const npmPath = options.npmPath || process.env.npm_execpath //eslint-disable-line no-process-env
  142. const npmPathIsJs = typeof npmPath === "string" && /\.m?js/.test(path.extname(npmPath))
  143. const execPath = (npmPathIsJs ? process.execPath : npmPath || "npm")
  144. const isYarn = path.basename(npmPath || "npm").startsWith("yarn")
  145. const spawnArgs = ["run"]
  146. if (npmPathIsJs) {
  147. spawnArgs.unshift(npmPath)
  148. }
  149. if (!isYarn) {
  150. Array.prototype.push.apply(spawnArgs, options.prefixOptions)
  151. }
  152. else if (options.prefixOptions.indexOf("--silent") !== -1) {
  153. spawnArgs.push("--silent")
  154. }
  155. Array.prototype.push.apply(spawnArgs, parseArgs(task).map(cleanTaskArg))
  156. cp = spawn(execPath, spawnArgs, spawnOptions)
  157. // Piping stdio.
  158. if (stdinKind === "pipe") {
  159. stdin.pipe(cp.stdin)
  160. }
  161. if (stdoutKind === "pipe") {
  162. cp.stdout.pipe(stdout, { end: false })
  163. }
  164. if (stderrKind === "pipe") {
  165. cp.stderr.pipe(stderr, { end: false })
  166. }
  167. // Register
  168. cp.on("error", (err) => {
  169. cp = null
  170. reject(err)
  171. })
  172. cp.on("close", (code) => {
  173. cp = null
  174. resolve({ task, code })
  175. })
  176. })
  177. promise.abort = function abort() {
  178. if (cp != null) {
  179. cp.kill()
  180. cp = null
  181. }
  182. }
  183. return promise
  184. }