run-script.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. const { resolve } = require('path')
  2. const chalk = require('chalk')
  3. const runScript = require('@npmcli/run-script')
  4. const { isServerPackage } = runScript
  5. const rpj = require('read-package-json-fast')
  6. const log = require('npmlog')
  7. const didYouMean = require('./utils/did-you-mean.js')
  8. const isWindowsShell = require('./utils/is-windows-shell.js')
  9. const cmdList = [
  10. 'publish',
  11. 'install',
  12. 'uninstall',
  13. 'test',
  14. 'stop',
  15. 'start',
  16. 'restart',
  17. 'version',
  18. ].reduce((l, p) => l.concat(['pre' + p, p, 'post' + p]), [])
  19. const nocolor = {
  20. reset: s => s,
  21. bold: s => s,
  22. dim: s => s,
  23. blue: s => s,
  24. green: s => s,
  25. }
  26. const BaseCommand = require('./base-command.js')
  27. class RunScript extends BaseCommand {
  28. /* istanbul ignore next - see test/lib/load-all-commands.js */
  29. static get description () {
  30. return 'Run arbitrary package scripts'
  31. }
  32. /* istanbul ignore next - see test/lib/load-all-commands.js */
  33. static get params () {
  34. return [
  35. 'workspace',
  36. 'workspaces',
  37. 'include-workspace-root',
  38. 'if-present',
  39. 'ignore-scripts',
  40. 'script-shell',
  41. ]
  42. }
  43. /* istanbul ignore next - see test/lib/load-all-commands.js */
  44. static get name () {
  45. return 'run-script'
  46. }
  47. /* istanbul ignore next - see test/lib/load-all-commands.js */
  48. static get usage () {
  49. return ['<command> [-- <args>]']
  50. }
  51. async completion (opts) {
  52. const argv = opts.conf.argv.remain
  53. if (argv.length === 2) {
  54. // find the script name
  55. const json = resolve(this.npm.localPrefix, 'package.json')
  56. const { scripts = {} } = await rpj(json).catch(er => ({}))
  57. return Object.keys(scripts)
  58. }
  59. }
  60. exec (args, cb) {
  61. if (args.length)
  62. this.run(args).then(() => cb()).catch(cb)
  63. else
  64. this.list(args).then(() => cb()).catch(cb)
  65. }
  66. execWorkspaces (args, filters, cb) {
  67. if (args.length)
  68. this.runWorkspaces(args, filters).then(() => cb()).catch(cb)
  69. else
  70. this.listWorkspaces(args, filters).then(() => cb()).catch(cb)
  71. }
  72. async run ([event, ...args], { path = this.npm.localPrefix, pkg } = {}) {
  73. // this || undefined is because runScript will be unhappy with the default
  74. // null value
  75. const scriptShell = this.npm.config.get('script-shell') || undefined
  76. pkg = pkg || (await rpj(`${path}/package.json`))
  77. const { scripts = {} } = pkg
  78. if (event === 'restart' && !scripts.restart)
  79. scripts.restart = 'npm stop --if-present && npm start'
  80. else if (event === 'env' && !scripts.env)
  81. scripts.env = isWindowsShell ? 'SET' : 'env'
  82. pkg.scripts = scripts
  83. if (
  84. !Object.prototype.hasOwnProperty.call(scripts, event) &&
  85. !(event === 'start' && await isServerPackage(path))
  86. ) {
  87. if (this.npm.config.get('if-present'))
  88. return
  89. const suggestions = await didYouMean(this.npm, path, event)
  90. throw new Error(`Missing script: "${event}"${suggestions}\n\nTo see a list of scripts, run:\n npm run`)
  91. }
  92. // positional args only added to the main event, not pre/post
  93. const events = [[event, args]]
  94. if (!this.npm.config.get('ignore-scripts')) {
  95. if (scripts[`pre${event}`])
  96. events.unshift([`pre${event}`, []])
  97. if (scripts[`post${event}`])
  98. events.push([`post${event}`, []])
  99. }
  100. const opts = {
  101. path,
  102. args,
  103. scriptShell,
  104. stdio: 'inherit',
  105. stdioString: true,
  106. pkg,
  107. banner: log.level !== 'silent',
  108. }
  109. for (const [event, args] of events) {
  110. await runScript({
  111. ...opts,
  112. event,
  113. args,
  114. })
  115. }
  116. }
  117. async list (args, path) {
  118. path = path || this.npm.localPrefix
  119. const { scripts, name, _id } = await rpj(`${path}/package.json`)
  120. const pkgid = _id || name
  121. const color = this.npm.color
  122. if (!scripts)
  123. return []
  124. const allScripts = Object.keys(scripts)
  125. if (log.level === 'silent')
  126. return allScripts
  127. if (this.npm.config.get('json')) {
  128. this.npm.output(JSON.stringify(scripts, null, 2))
  129. return allScripts
  130. }
  131. if (this.npm.config.get('parseable')) {
  132. for (const [script, cmd] of Object.entries(scripts))
  133. this.npm.output(`${script}:${cmd}`)
  134. return allScripts
  135. }
  136. const indent = '\n '
  137. const prefix = ' '
  138. const cmds = []
  139. const runScripts = []
  140. for (const script of allScripts) {
  141. const list = cmdList.includes(script) ? cmds : runScripts
  142. list.push(script)
  143. }
  144. const colorize = color ? chalk : nocolor
  145. if (cmds.length) {
  146. this.npm.output(`${
  147. colorize.reset(colorize.bold('Lifecycle scripts'))} included in ${
  148. colorize.green(pkgid)}:`)
  149. }
  150. for (const script of cmds)
  151. this.npm.output(prefix + script + indent + colorize.dim(scripts[script]))
  152. if (!cmds.length && runScripts.length) {
  153. this.npm.output(`${
  154. colorize.bold('Scripts')
  155. } available in ${colorize.green(pkgid)} via \`${
  156. colorize.blue('npm run-script')}\`:`)
  157. } else if (runScripts.length)
  158. this.npm.output(`\navailable via \`${colorize.blue('npm run-script')}\`:`)
  159. for (const script of runScripts)
  160. this.npm.output(prefix + script + indent + colorize.dim(scripts[script]))
  161. this.npm.output('')
  162. return allScripts
  163. }
  164. async runWorkspaces (args, filters) {
  165. const res = []
  166. await this.setWorkspaces(filters)
  167. for (const workspacePath of this.workspacePaths) {
  168. const pkg = await rpj(`${workspacePath}/package.json`)
  169. const runResult = await this.run(args, {
  170. path: workspacePath,
  171. pkg,
  172. }).catch(err => {
  173. log.error(`Lifecycle script \`${args[0]}\` failed with error:`)
  174. log.error(err)
  175. log.error(` in workspace: ${pkg._id || pkg.name}`)
  176. log.error(` at location: ${workspacePath}`)
  177. const scriptMissing = err.message.startsWith('Missing script')
  178. // avoids exiting with error code in case there's scripts missing
  179. // in some workspaces since other scripts might have succeeded
  180. if (!scriptMissing)
  181. process.exitCode = 1
  182. return scriptMissing
  183. })
  184. res.push(runResult)
  185. }
  186. // in case **all** tests are missing, then it should exit with error code
  187. if (res.every(Boolean))
  188. throw new Error(`Missing script: ${args[0]}`)
  189. }
  190. async listWorkspaces (args, filters) {
  191. await this.setWorkspaces(filters)
  192. if (log.level === 'silent')
  193. return
  194. if (this.npm.config.get('json')) {
  195. const res = {}
  196. for (const workspacePath of this.workspacePaths) {
  197. const { scripts, name } = await rpj(`${workspacePath}/package.json`)
  198. res[name] = { ...scripts }
  199. }
  200. this.npm.output(JSON.stringify(res, null, 2))
  201. return
  202. }
  203. if (this.npm.config.get('parseable')) {
  204. for (const workspacePath of this.workspacePaths) {
  205. const { scripts, name } = await rpj(`${workspacePath}/package.json`)
  206. for (const [script, cmd] of Object.entries(scripts || {}))
  207. this.npm.output(`${name}:${script}:${cmd}`)
  208. }
  209. return
  210. }
  211. for (const workspacePath of this.workspacePaths)
  212. await this.list(args, workspacePath)
  213. }
  214. }
  215. module.exports = RunScript