routie dev init since i didn't adhere to any proper guidance up until now
This commit is contained in:
+42
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* @module create-header
|
||||
* @author Toru Nagashima
|
||||
* @copyright 2016 Toru Nagashima. All rights reserved.
|
||||
* See LICENSE file in root directory for full license.
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Creates the header text for a given task.
|
||||
*
|
||||
* @param {string} nameAndArgs - A task name and arguments.
|
||||
* @param {object} packageInfo - A package.json's information.
|
||||
* @param {object} packageInfo.body - A package.json's JSON object.
|
||||
* @param {string} packageInfo.path - A package.json's file path.
|
||||
* @param {boolean} isTTY - The flag to color the header.
|
||||
* @returns {string} The header of a given task.
|
||||
*/
|
||||
module.exports = function createHeader (nameAndArgs, packageInfo, isTTY, ansiStyles) {
|
||||
if (!packageInfo) {
|
||||
return `\n> ${nameAndArgs}\n\n`
|
||||
}
|
||||
|
||||
const index = nameAndArgs.indexOf(' ')
|
||||
const name = (index === -1) ? nameAndArgs : nameAndArgs.slice(0, index)
|
||||
const args = (index === -1) ? '' : nameAndArgs.slice(index + 1)
|
||||
const packageName = packageInfo.body.name
|
||||
const packageVersion = packageInfo.body.version
|
||||
const scriptBody = packageInfo.body.scripts[name]
|
||||
const packagePath = packageInfo.path
|
||||
const color = isTTY ? ansiStyles.gray : { open: '', close: '' }
|
||||
|
||||
return `
|
||||
${color.open}> ${packageName}@${packageVersion} ${name} ${packagePath}${color.close}
|
||||
${color.open}> ${scriptBody} ${args}${color.close}
|
||||
|
||||
`
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* @module create-prefix-transform-stream
|
||||
* @author Toru Nagashima
|
||||
* @copyright 2016 Toru Nagashima. All rights reserved.
|
||||
* See LICENSE file in root directory for full license.
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
const stream = require('stream')
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
const ALL_BR = /\n/g
|
||||
|
||||
/**
|
||||
* The transform stream to insert a specific prefix.
|
||||
*
|
||||
* Several streams can exist for the same output stream.
|
||||
* This stream will insert the prefix if the last output came from other instance.
|
||||
* To do that, this stream is using a shared state object.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
class PrefixTransform extends stream.Transform {
|
||||
/**
|
||||
* @param {string} prefix - A prefix text to be inserted.
|
||||
* @param {object} state - A state object.
|
||||
* @param {string} state.lastPrefix - The last prefix which is printed.
|
||||
* @param {boolean} state.lastIsLinebreak -The flag to check whether the last output is a line break or not.
|
||||
*/
|
||||
constructor (prefix, state) {
|
||||
super()
|
||||
|
||||
this.prefix = prefix
|
||||
this.state = state
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms the output chunk.
|
||||
*
|
||||
* @param {string|Buffer} chunk - A chunk to be transformed.
|
||||
* @param {string} _encoding - The encoding of the chunk.
|
||||
* @param {function} callback - A callback function that is called when done.
|
||||
* @returns {void}
|
||||
*/
|
||||
_transform (chunk, _encoding, callback) {
|
||||
const prefix = this.prefix
|
||||
const nPrefix = `\n${prefix}`
|
||||
const state = this.state
|
||||
const firstPrefix =
|
||||
state.lastIsLinebreak
|
||||
? prefix
|
||||
: (state.lastPrefix !== prefix)
|
||||
? '\n'
|
||||
: ''
|
||||
const prefixed = `${firstPrefix}${chunk}`.replace(ALL_BR, nPrefix)
|
||||
const index = prefixed.indexOf(prefix, Math.max(0, prefixed.length - prefix.length))
|
||||
|
||||
state.lastPrefix = prefix
|
||||
state.lastIsLinebreak = (index !== -1)
|
||||
|
||||
callback(null, (index !== -1) ? prefixed.slice(0, index) : prefixed)
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Public API
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Create a transform stream to insert the specific prefix.
|
||||
*
|
||||
* Several streams can exist for the same output stream.
|
||||
* This stream will insert the prefix if the last output came from other instance.
|
||||
* To do that, this stream is using a shared state object.
|
||||
*
|
||||
* @param {string} prefix - A prefix text to be inserted.
|
||||
* @param {object} state - A state object.
|
||||
* @param {string} state.lastPrefix - The last prefix which is printed.
|
||||
* @param {boolean} state.lastIsLinebreak -The flag to check whether the last output is a line break or not.
|
||||
* @returns {stream.Transform} The created transform stream.
|
||||
*/
|
||||
module.exports = function createPrefixTransform (prefix, state) {
|
||||
return new PrefixTransform(prefix, state)
|
||||
}
|
||||
+306
@@ -0,0 +1,306 @@
|
||||
/**
|
||||
* @module index
|
||||
* @author Toru Nagashima
|
||||
* @copyright 2015 Toru Nagashima. All rights reserved.
|
||||
* See LICENSE file in root directory for full license.
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
const shellQuote = require('shell-quote')
|
||||
const matchTasks = require('./match-tasks')
|
||||
const readPackageJson = require('./read-package-json')
|
||||
const runTasks = require('./run-tasks')
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
const ARGS_PATTERN = /\{(!)?([*@%]|\d+)([^}]+)?}/g
|
||||
const ARGS_UNPACK_PATTERN = /\{(!)?([%])([^}]+)?}/g
|
||||
|
||||
/**
|
||||
* Converts a given value to an array.
|
||||
*
|
||||
* @param {string|string[]|null|undefined} x - A value to convert.
|
||||
* @returns {string[]} An array.
|
||||
*/
|
||||
function toArray (x) {
|
||||
if (x == null) {
|
||||
return []
|
||||
}
|
||||
return Array.isArray(x) ? x : [x]
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces argument placeholders (such as `{1}`) by arguments.
|
||||
*
|
||||
* @param {string[]} patterns - Patterns to replace.
|
||||
* @param {string[]} args - Arguments to replace.
|
||||
* @returns {string[]} replaced
|
||||
*/
|
||||
function applyArguments (patterns, args) {
|
||||
const defaults = Object.create(null)
|
||||
|
||||
const unfoldedPatterns = patterns
|
||||
.flatMap(pattern => {
|
||||
const match = ARGS_UNPACK_PATTERN.exec(pattern)
|
||||
if (match && match[2] === '%') {
|
||||
const result = []
|
||||
for (let i = 0, length = args.length; i < length; i++) {
|
||||
const argPosition = i + 1
|
||||
result.push(pattern.replace(ARGS_UNPACK_PATTERN, (whole, indirectionMark, id, options) => {
|
||||
if (indirectionMark != null || options != null || id !== '%') {
|
||||
throw Error(`Invalid Placeholder: ${whole}`)
|
||||
}
|
||||
return `{${argPosition}}`
|
||||
}))
|
||||
}
|
||||
return result
|
||||
}
|
||||
return pattern
|
||||
})
|
||||
|
||||
return unfoldedPatterns.map(pattern => pattern.replace(ARGS_PATTERN, (whole, indirectionMark, id, options) => {
|
||||
if (indirectionMark != null) {
|
||||
throw Error(`Invalid Placeholder: ${whole}`)
|
||||
}
|
||||
if (id === '@') {
|
||||
return shellQuote.quote(args)
|
||||
}
|
||||
if (id === '*') {
|
||||
return shellQuote.quote([args.join(' ')])
|
||||
}
|
||||
|
||||
const position = parseInt(id, 10)
|
||||
if (position >= 1 && position <= args.length) {
|
||||
return shellQuote.quote([args[position - 1]])
|
||||
}
|
||||
|
||||
// Address default values
|
||||
if (options != null) {
|
||||
const prefix = options.slice(0, 2)
|
||||
|
||||
if (prefix === ':=') {
|
||||
defaults[id] = shellQuote.quote([options.slice(2)])
|
||||
return defaults[id]
|
||||
}
|
||||
if (prefix === ':-') {
|
||||
return shellQuote.quote([options.slice(2)])
|
||||
}
|
||||
|
||||
throw Error(`Invalid Placeholder: ${whole}`)
|
||||
}
|
||||
if (defaults[id] != null) {
|
||||
return defaults[id]
|
||||
}
|
||||
|
||||
return ''
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse patterns.
|
||||
* In parsing process, it replaces argument placeholders (such as `{1}`) by arguments.
|
||||
*
|
||||
* @param {string|string[]} patternOrPatterns - Patterns to run.
|
||||
* A pattern is a npm-script name or a Glob-like pattern.
|
||||
* @param {string[]} args - Arguments to replace placeholders.
|
||||
* @returns {string[]} Parsed patterns.
|
||||
*/
|
||||
function parsePatterns (patternOrPatterns, args) {
|
||||
const patterns = toArray(patternOrPatterns)
|
||||
const hasPlaceholder = patterns.some(pattern => ARGS_PATTERN.test(pattern))
|
||||
|
||||
return hasPlaceholder ? applyArguments(patterns, args) : patterns
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a given config object to an `--:=` style option array.
|
||||
*
|
||||
* @param {object|null} config -
|
||||
* A map-like object to overwrite package configs.
|
||||
* Keys are package names.
|
||||
* Every value is a map-like object (Pairs of variable name and value).
|
||||
* @returns {string[]} `--:=` style options.
|
||||
*/
|
||||
function toOverwriteOptions (config) {
|
||||
const options = []
|
||||
|
||||
for (const packageName of Object.keys(config)) {
|
||||
const packageConfig = config[packageName]
|
||||
|
||||
for (const variableName of Object.keys(packageConfig)) {
|
||||
const value = packageConfig[variableName]
|
||||
|
||||
options.push(`--${packageName}:${variableName}=${value}`)
|
||||
}
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a given config object to an `--a=b` style option array.
|
||||
*
|
||||
* @param {object|null} config -
|
||||
* A map-like object to set configs.
|
||||
* @returns {string[]} `--a=b` style options.
|
||||
*/
|
||||
function toConfigOptions (config) {
|
||||
return Object.keys(config).map(key => `--${key}=${config[key]}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the maximum length.
|
||||
*
|
||||
* @param {number} length - The current maximum length.
|
||||
* @param {string} name - A name.
|
||||
* @returns {number} The maximum length.
|
||||
*/
|
||||
function maxLength (length, name) {
|
||||
return Math.max(name.length, length)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Runs npm-scripts which are matched with given patterns.
|
||||
*
|
||||
* @param {string|string[]} patternOrPatterns - Patterns to run.
|
||||
* A pattern is a npm-script name or a Glob-like pattern.
|
||||
* @param {object|undefined} [options] Optional.
|
||||
* @param {boolean} options.parallel -
|
||||
* If this is `true`, run scripts in parallel.
|
||||
* Otherwise, run scripts in sequencial.
|
||||
* Default is `false`.
|
||||
* @param {stream.Readable|null} options.stdin -
|
||||
* A readable stream to send messages to stdin of child process.
|
||||
* If this is `null`, ignores it.
|
||||
* If this is `process.stdin`, inherits it.
|
||||
* Otherwise, makes a pipe.
|
||||
* Default is `null`.
|
||||
* @param {stream.Writable|null} options.stdout -
|
||||
* A writable stream to receive messages from stdout of child process.
|
||||
* If this is `null`, cannot send.
|
||||
* If this is `process.stdout`, inherits it.
|
||||
* Otherwise, makes a pipe.
|
||||
* Default is `null`.
|
||||
* @param {stream.Writable|null} options.stderr -
|
||||
* A writable stream to receive messages from stderr of child process.
|
||||
* If this is `null`, cannot send.
|
||||
* If this is `process.stderr`, inherits it.
|
||||
* Otherwise, makes a pipe.
|
||||
* Default is `null`.
|
||||
* @param {string[]} options.taskList -
|
||||
* Actual name list of npm-scripts.
|
||||
* This function search npm-script names in this list.
|
||||
* If this is `null`, this function reads `package.json` of current directly.
|
||||
* @param {object|null} options.packageConfig -
|
||||
* A map-like object to overwrite package configs.
|
||||
* Keys are package names.
|
||||
* Every value is a map-like object (Pairs of variable name and value).
|
||||
* e.g. `{"npm-run-all": {"test": 777}}`
|
||||
* Default is `null`.
|
||||
* @param {boolean} options.silent -
|
||||
* The flag to set `silent` to the log level of npm.
|
||||
* Default is `false`.
|
||||
* @param {boolean} options.continueOnError -
|
||||
* The flag to ignore errors.
|
||||
* Default is `false`.
|
||||
* @param {boolean} options.printLabel -
|
||||
* The flag to print task names at the head of each line.
|
||||
* Default is `false`.
|
||||
* @param {boolean} options.printName -
|
||||
* The flag to print task names before running each task.
|
||||
* Default is `false`.
|
||||
* @param {number} options.maxParallel -
|
||||
* The maximum number of parallelism.
|
||||
* Default is unlimited.
|
||||
* @param {string} options.npmPath -
|
||||
* The path to npm.
|
||||
* Default is `process.env.npm_execpath`.
|
||||
* @returns {Promise}
|
||||
* A promise object which becomes fullfilled when all npm-scripts are completed.
|
||||
*/
|
||||
module.exports = function npmRunAll (patternOrPatterns, options) {
|
||||
const stdin = (options && options.stdin) || null
|
||||
const stdout = (options && options.stdout) || null
|
||||
const stderr = (options && options.stderr) || null
|
||||
const taskList = (options && options.taskList) || null
|
||||
const config = (options && options.config) || null
|
||||
const packageConfig = (options && options.packageConfig) || null
|
||||
const args = (options && options.arguments) || []
|
||||
const parallel = Boolean(options && options.parallel)
|
||||
const silent = Boolean(options && options.silent)
|
||||
const continueOnError = Boolean(options && options.continueOnError)
|
||||
const printLabel = Boolean(options && options.printLabel)
|
||||
const printName = Boolean(options && options.printName)
|
||||
const race = Boolean(options && options.race)
|
||||
const maxParallel = parallel ? ((options && options.maxParallel) || 0) : 1
|
||||
const aggregateOutput = Boolean(options && options.aggregateOutput)
|
||||
const npmPath = options && options.npmPath
|
||||
try {
|
||||
const patterns = parsePatterns(patternOrPatterns, args)
|
||||
if (patterns.length === 0) {
|
||||
return Promise.resolve(null)
|
||||
}
|
||||
if (taskList != null && Array.isArray(taskList) === false) {
|
||||
throw new Error('Invalid options.taskList')
|
||||
}
|
||||
if (typeof maxParallel !== 'number' || !(maxParallel >= 0)) {
|
||||
throw new Error('Invalid options.maxParallel')
|
||||
}
|
||||
if (!parallel && aggregateOutput) {
|
||||
throw new Error('Invalid options.aggregateOutput; It requires options.parallel')
|
||||
}
|
||||
if (!parallel && race) {
|
||||
throw new Error('Invalid options.race; It requires options.parallel')
|
||||
}
|
||||
|
||||
const prefixOptions = [].concat(
|
||||
silent ? ['--silent'] : [],
|
||||
packageConfig ? toOverwriteOptions(packageConfig) : [],
|
||||
config ? toConfigOptions(config) : []
|
||||
)
|
||||
|
||||
return Promise.resolve()
|
||||
.then(() => {
|
||||
if (taskList != null) {
|
||||
return { taskList, packageInfo: null }
|
||||
}
|
||||
return readPackageJson()
|
||||
})
|
||||
.then(x => {
|
||||
const tasks = matchTasks(x.taskList, patterns)
|
||||
const labelWidth = tasks.reduce(maxLength, 0)
|
||||
|
||||
return runTasks(tasks, {
|
||||
stdin,
|
||||
stdout,
|
||||
stderr,
|
||||
prefixOptions,
|
||||
continueOnError,
|
||||
labelState: {
|
||||
enabled: printLabel,
|
||||
width: labelWidth,
|
||||
lastPrefix: null,
|
||||
lastIsLinebreak: true,
|
||||
},
|
||||
printName,
|
||||
packageInfo: x.packageInfo,
|
||||
race,
|
||||
maxParallel,
|
||||
npmPath,
|
||||
aggregateOutput,
|
||||
})
|
||||
})
|
||||
} catch (err) {
|
||||
return Promise.reject(new Error(err.message))
|
||||
}
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* @module match-tasks
|
||||
* @author Toru Nagashima
|
||||
* @copyright 2015 Toru Nagashima. All rights reserved.
|
||||
* See LICENSE file in root directory for full license.
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
const picomatch = require('picomatch')
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
const COLON_OR_SLASH = /[:/]/g
|
||||
const CONVERT_MAP = { ':': '/', '/': ':' }
|
||||
|
||||
/**
|
||||
* Swaps ":" and "/", in order to use ":" as the separator in picomatch.
|
||||
*
|
||||
* @param {string} s - A text to swap.
|
||||
* @returns {string} The text which was swapped.
|
||||
*/
|
||||
function swapColonAndSlash (s) {
|
||||
return s.replace(COLON_OR_SLASH, (matched) => CONVERT_MAP[matched])
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a filter from user-specified pattern text.
|
||||
*
|
||||
* The task name is the part until the first space.
|
||||
* The rest part is the arguments for this task.
|
||||
*
|
||||
* @param {string} pattern - A pattern to create filter.
|
||||
* @returns {{match: function, task: string, args: string}} The filter object of the pattern.
|
||||
*/
|
||||
function createFilter (pattern) {
|
||||
const trimmed = pattern.trim()
|
||||
const spacePos = trimmed.indexOf(' ')
|
||||
const task = spacePos < 0 ? trimmed : trimmed.slice(0, spacePos)
|
||||
const args = spacePos < 0 ? '' : trimmed.slice(spacePos)
|
||||
const match = picomatch(swapColonAndSlash(task), {
|
||||
nonegate: true,
|
||||
strictSlashes: true,
|
||||
})
|
||||
|
||||
return { match, task, args }
|
||||
}
|
||||
|
||||
/**
|
||||
* The set to remove overlapped task.
|
||||
*/
|
||||
class TaskSet {
|
||||
/**
|
||||
* Creates a instance.
|
||||
*/
|
||||
constructor () {
|
||||
this.result = []
|
||||
this.sourceMap = Object.create(null)
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a command (a pattern) into this set if it's not overlapped.
|
||||
* "Overlapped" is meaning that the command was added from a different source.
|
||||
*
|
||||
* @param {string} command - A pattern text to add.
|
||||
* @param {string} source - A task name to check.
|
||||
* @returns {void}
|
||||
*/
|
||||
add (command, source) {
|
||||
const sourceList = this.sourceMap[command] || (this.sourceMap[command] = [])
|
||||
if (sourceList.length === 0 || sourceList.indexOf(source) !== -1) {
|
||||
this.result.push(command)
|
||||
}
|
||||
sourceList.push(source)
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Enumerates tasks which matches with given patterns.
|
||||
*
|
||||
* @param {string[]} taskList - A list of actual task names.
|
||||
* @param {string[]} patterns - Pattern texts to match.
|
||||
* @returns {string[]} Tasks which matches with the patterns.
|
||||
* @private
|
||||
*/
|
||||
module.exports = function matchTasks (taskList, patterns) {
|
||||
const filters = patterns.map(createFilter)
|
||||
const candidates = taskList.map(swapColonAndSlash)
|
||||
const taskSet = new TaskSet()
|
||||
const unknownSet = Object.create(null)
|
||||
|
||||
// Take tasks while keep the order of patterns.
|
||||
for (const filter of filters) {
|
||||
let found = false
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (filter.match(candidate)) {
|
||||
found = true
|
||||
taskSet.add(
|
||||
swapColonAndSlash(candidate) + filter.args,
|
||||
filter.task
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Built-in tasks should be allowed.
|
||||
if (!found && (filter.task === 'restart' || filter.task === 'env')) {
|
||||
taskSet.add(filter.task + filter.args, filter.task)
|
||||
found = true
|
||||
}
|
||||
if (!found) {
|
||||
unknownSet[filter.task] = true
|
||||
}
|
||||
}
|
||||
|
||||
const unknownTasks = Object.keys(unknownSet)
|
||||
if (unknownTasks.length > 0) {
|
||||
throw new Error(`Task not found: "${unknownTasks.join('", ')}"`)
|
||||
}
|
||||
return taskSet.result
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* @module npm-run-all-error
|
||||
* @author Toru Nagashima
|
||||
* @copyright 2016 Toru Nagashima. All rights reserved.
|
||||
* See LICENSE file in root directory for full license.
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Error object with some additional info.
|
||||
*/
|
||||
module.exports = class NpmRunAllError extends Error {
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param {{name: string, code: number}} causeResult -
|
||||
* The result item of the npm-script which causes an error.
|
||||
* @param {Array.<{name: string, code: (number|undefined)}>} allResults -
|
||||
* All result items of npm-scripts.
|
||||
*/
|
||||
constructor (causeResult, allResults) {
|
||||
super(`"${causeResult.task}" exited with ${causeResult.code}.`)
|
||||
|
||||
/**
|
||||
* The name of a npm-script which exited with a non-zero code.
|
||||
* @type {string}
|
||||
*/
|
||||
this.name = causeResult.name
|
||||
|
||||
/**
|
||||
* The code of a npm-script which exited with a non-zero code.
|
||||
* This can be `undefined`.
|
||||
* @type {number}
|
||||
*/
|
||||
this.code = causeResult.code
|
||||
|
||||
/**
|
||||
* All result items of npm-scripts.
|
||||
* @type {Array.<{name: string, code: (number|undefined)}>}
|
||||
*/
|
||||
this.results = allResults
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* @module read-package-json
|
||||
* @author Toru Nagashima
|
||||
* @copyright 2016 Toru Nagashima. All rights reserved.
|
||||
* See LICENSE file in root directory for full license.
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
const readPackage = require('read-package-json-fast')
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
const joinPath = require('path').join
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Reads the package.json in the current directory.
|
||||
*
|
||||
* @returns {object} package.json's information.
|
||||
*/
|
||||
module.exports = function readPackageJson () {
|
||||
const path = joinPath(process.cwd(), 'package.json')
|
||||
return readPackage(path).then(body => ({
|
||||
taskList: Object.keys(body.scripts || {}),
|
||||
packageInfo: { path, body },
|
||||
}))
|
||||
}
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* @module run-task
|
||||
* @author Toru Nagashima
|
||||
* @copyright 2015 Toru Nagashima. All rights reserved.
|
||||
* See LICENSE file in root directory for full license.
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
|
||||
const ansiStylesPromise = import('ansi-styles')
|
||||
const parseArgs = require('shell-quote').parse
|
||||
const which = require('which')
|
||||
|
||||
const createHeader = require('./create-header')
|
||||
const createPrefixTransform = require('./create-prefix-transform-stream')
|
||||
const spawn = require('./spawn')
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
const colors = ['cyan', 'green', 'magenta', 'yellow', 'red']
|
||||
|
||||
let colorIndex = 0
|
||||
const taskNamesToColors = new Map()
|
||||
|
||||
/**
|
||||
* Select a color from given task name.
|
||||
*
|
||||
* @param {string} taskName - The task name.
|
||||
* @returns {function} A colorize function that provided by `chalk`
|
||||
*/
|
||||
function selectColor (taskName) {
|
||||
let color = taskNamesToColors.get(taskName)
|
||||
if (!color) {
|
||||
color = colors[colorIndex]
|
||||
colorIndex = (colorIndex + 1) % colors.length
|
||||
taskNamesToColors.set(taskName, color)
|
||||
}
|
||||
return color
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps stdout/stderr with a transform stream to add the task name as prefix.
|
||||
*
|
||||
* @param {string} taskName - The task name.
|
||||
* @param {stream.Writable} source - An output stream to be wrapped.
|
||||
* @param {object} labelState - An label state for the transform stream.
|
||||
* @returns {stream.Writable} `source` or the created wrapped stream.
|
||||
*/
|
||||
function wrapLabeling (taskName, source, labelState, ansiStyles) {
|
||||
if (source == null || !labelState.enabled) {
|
||||
return source
|
||||
}
|
||||
|
||||
const label = taskName.padEnd(labelState.width)
|
||||
const color = source.isTTY ? ansiStyles[selectColor(taskName)] : { open: '', close: '' }
|
||||
const prefix = `${color.open}[${label}]${color.close} `
|
||||
const stream = createPrefixTransform(prefix, labelState)
|
||||
|
||||
stream.pipe(source)
|
||||
|
||||
return stream
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a given stream to an option for `child_process.spawn`.
|
||||
*
|
||||
* @param {stream.Readable|stream.Writable|null} stream - An original stream to convert.
|
||||
* @param {process.stdin|process.stdout|process.stderr} std - A standard stream for this option.
|
||||
* @returns {string|stream.Readable|stream.Writable} An option for `child_process.spawn`.
|
||||
*/
|
||||
function detectStreamKind (stream, std) {
|
||||
return (
|
||||
stream == null
|
||||
? 'ignore' // `|| !std.isTTY` is needed for the workaround of https://github.com/nodejs/node/issues/5620
|
||||
: stream !== std || !std.isTTY
|
||||
? 'pipe'
|
||||
: stream
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the output of shell-quote's `parse()` is acceptable input to npm-cli.
|
||||
*
|
||||
* The `parse()` method of shell-quote sometimes returns special objects in its
|
||||
* output array, e.g. if it thinks some elements should be globbed. But npm-cli
|
||||
* only accepts strings and will throw an error otherwise.
|
||||
*
|
||||
* See https://github.com/substack/node-shell-quote#parsecmd-env
|
||||
*
|
||||
* @param {object|string} arg - Item in the output of shell-quote's `parse()`.
|
||||
* @returns {string} A valid argument for npm-cli.
|
||||
*/
|
||||
function cleanTaskArg (arg) {
|
||||
return arg.pattern || arg.op || arg
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Interface
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Run a npm-script of a given name.
|
||||
* The return value is a promise which has an extra method: `abort()`.
|
||||
* The `abort()` kills the child process to run the npm-script.
|
||||
*
|
||||
* @param {string} task - A npm-script name to run.
|
||||
* @param {object} options - An option object.
|
||||
* @param {stream.Readable|null} options.stdin -
|
||||
* A readable stream to send messages to stdin of child process.
|
||||
* If this is `null`, ignores it.
|
||||
* If this is `process.stdin`, inherits it.
|
||||
* Otherwise, makes a pipe.
|
||||
* @param {stream.Writable|null} options.stdout -
|
||||
* A writable stream to receive messages from stdout of child process.
|
||||
* If this is `null`, cannot send.
|
||||
* If this is `process.stdout`, inherits it.
|
||||
* Otherwise, makes a pipe.
|
||||
* @param {stream.Writable|null} options.stderr -
|
||||
* A writable stream to receive messages from stderr of child process.
|
||||
* If this is `null`, cannot send.
|
||||
* If this is `process.stderr`, inherits it.
|
||||
* Otherwise, makes a pipe.
|
||||
* @param {string[]} options.prefixOptions -
|
||||
* An array of options which are inserted before the task name.
|
||||
* @param {object} options.labelState - A state object for printing labels.
|
||||
* @param {boolean} options.printName - The flag to print task names before running each task.
|
||||
* @param {object} options.packageInfo - A package.json's information.
|
||||
* @param {object} options.packageInfo.body - A package.json's JSON object.
|
||||
* @param {string} options.packageInfo.path - A package.json's file path.
|
||||
* @returns {Promise}
|
||||
* A promise object which becomes fullfilled when the npm-script is completed.
|
||||
* This promise object has an extra method: `abort()`.
|
||||
* @private
|
||||
*/
|
||||
module.exports = function runTask (task, options) {
|
||||
let cp = null
|
||||
|
||||
async function asyncRunTask () {
|
||||
const { default: ansiStyles } = await ansiStylesPromise
|
||||
|
||||
const stdin = options.stdin
|
||||
const stdout = wrapLabeling(task, options.stdout, options.labelState, ansiStyles)
|
||||
const stderr = wrapLabeling(task, options.stderr, options.labelState, ansiStyles)
|
||||
const stdinKind = detectStreamKind(stdin, process.stdin)
|
||||
const stdoutKind = detectStreamKind(stdout, process.stdout)
|
||||
const stderrKind = detectStreamKind(stderr, process.stderr)
|
||||
const spawnOptions = { stdio: [stdinKind, stdoutKind, stderrKind] }
|
||||
|
||||
// Print task name.
|
||||
if (options.printName && stdout != null) {
|
||||
stdout.write(createHeader(
|
||||
task,
|
||||
options.packageInfo,
|
||||
options.stdout.isTTY,
|
||||
ansiStyles
|
||||
))
|
||||
}
|
||||
|
||||
// Execute.
|
||||
let npmPath = options.npmPath
|
||||
if (!npmPath && process.env.npm_execpath) {
|
||||
const basename = path.basename(process.env.npm_execpath)
|
||||
let newBasename = basename
|
||||
if (basename.startsWith('npx')) {
|
||||
newBasename = basename.replace('npx', 'npm')
|
||||
} else if (basename.startsWith('pnpx')) {
|
||||
newBasename = basename.replace('pnpx', 'pnpm')
|
||||
}
|
||||
|
||||
npmPath = newBasename !== basename
|
||||
? path.join(path.dirname(process.env.npm_execpath), newBasename)
|
||||
: process.env.npm_execpath
|
||||
}
|
||||
|
||||
const npmPathIsJs = typeof npmPath === 'string' && /\.(c|m)?js/.test(path.extname(npmPath))
|
||||
let execPath = (npmPathIsJs ? process.execPath : npmPath || 'npm')
|
||||
|
||||
if (!npmPath && !process.env.npm_execpath) {
|
||||
// When a script is being run via pnpm, npmPath and npm_execpath will be null or undefined
|
||||
// Attempt to figure out whether we're running via pnpm
|
||||
const projectRoot = path.dirname(options.packageInfo.path)
|
||||
const hasPnpmLockfile = fs.existsSync(path.join(projectRoot, 'pnpm-lock.yaml'))
|
||||
const whichPnpmResults = await which('pnpm', { nothrow: true })
|
||||
const pnpmFound = whichPnpmResults?.status
|
||||
const pnpmWhichOutput = whichPnpmResults?.output
|
||||
if (hasPnpmLockfile && __dirname.split(path.delimiter).includes('.pnpm') && pnpmFound) {
|
||||
execPath = pnpmWhichOutput
|
||||
}
|
||||
}
|
||||
|
||||
const isYarn = process.env.npm_config_user_agent && process.env.npm_config_user_agent.startsWith('yarn')
|
||||
const isPnpm = Boolean(process.env.PNPM_SCRIPT_SRC_DIR)
|
||||
const isNpm = !isYarn && !isPnpm
|
||||
|
||||
const spawnArgs = ['run']
|
||||
|
||||
if (npmPathIsJs) {
|
||||
spawnArgs.unshift(npmPath)
|
||||
}
|
||||
if (isNpm) {
|
||||
Array.prototype.push.apply(spawnArgs, options.prefixOptions)
|
||||
} else if (options.prefixOptions.indexOf('--silent') !== -1) {
|
||||
spawnArgs.push('--silent')
|
||||
}
|
||||
Array.prototype.push.apply(spawnArgs, parseArgs(task).map(cleanTaskArg))
|
||||
|
||||
cp = spawn(execPath, spawnArgs, spawnOptions)
|
||||
|
||||
// Piping stdio.
|
||||
if (stdinKind === 'pipe') {
|
||||
stdin.pipe(cp.stdin)
|
||||
}
|
||||
if (stdoutKind === 'pipe') {
|
||||
cp.stdout.pipe(stdout, { end: false })
|
||||
}
|
||||
if (stderrKind === 'pipe') {
|
||||
cp.stderr.pipe(stderr, { end: false })
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// Register
|
||||
cp.on('error', (err) => {
|
||||
cp = null
|
||||
reject(err)
|
||||
})
|
||||
cp.on('close', (code, signal) => {
|
||||
cp = null
|
||||
resolve({ task, code, signal })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const promise = asyncRunTask()
|
||||
|
||||
promise.abort = function abort () {
|
||||
if (cp != null) {
|
||||
cp.kill()
|
||||
cp = null
|
||||
}
|
||||
}
|
||||
|
||||
return promise
|
||||
}
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
/**
|
||||
* @module run-tasks-in-parallel
|
||||
* @author Toru Nagashima
|
||||
* @copyright 2015 Toru Nagashima. All rights reserved.
|
||||
* See LICENSE file in root directory for full license.
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
const MemoryStream = require('memorystream')
|
||||
const NpmRunAllError = require('./npm-run-all-error')
|
||||
const runTask = require('./run-task')
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Remove the given value from the array.
|
||||
* @template T
|
||||
* @param {T[]} array - The array to remove.
|
||||
* @param {T} x - The item to be removed.
|
||||
* @returns {void}
|
||||
*/
|
||||
function remove (array, x) {
|
||||
const index = array.indexOf(x)
|
||||
if (index !== -1) {
|
||||
array.splice(index, 1)
|
||||
}
|
||||
}
|
||||
|
||||
const signals = {
|
||||
SIGABRT: 6,
|
||||
SIGALRM: 14,
|
||||
SIGBUS: 10,
|
||||
SIGCHLD: 20,
|
||||
SIGCONT: 19,
|
||||
SIGFPE: 8,
|
||||
SIGHUP: 1,
|
||||
SIGILL: 4,
|
||||
SIGINT: 2,
|
||||
SIGKILL: 9,
|
||||
SIGPIPE: 13,
|
||||
SIGQUIT: 3,
|
||||
SIGSEGV: 11,
|
||||
SIGSTOP: 17,
|
||||
SIGTERM: 15,
|
||||
SIGTRAP: 5,
|
||||
SIGTSTP: 18,
|
||||
SIGTTIN: 21,
|
||||
SIGTTOU: 22,
|
||||
SIGUSR1: 30,
|
||||
SIGUSR2: 31,
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a signal name to a number.
|
||||
* @param {string} signal - the signal name to convert into a number
|
||||
* @returns {number} - the return code for the signal
|
||||
*/
|
||||
function convert (signal) {
|
||||
return signals[signal] || 0
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Run npm-scripts of given names in parallel.
|
||||
*
|
||||
* If a npm-script exited with a non-zero code, this aborts other all npm-scripts.
|
||||
*
|
||||
* @param {string} tasks - A list of npm-script name to run in parallel.
|
||||
* @param {object} options - An option object.
|
||||
* @returns {Promise} A promise object which becomes fullfilled when all npm-scripts are completed.
|
||||
* @private
|
||||
*/
|
||||
module.exports = function runTasks (tasks, options) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (tasks.length === 0) {
|
||||
resolve([])
|
||||
return
|
||||
}
|
||||
|
||||
const results = tasks.map(task => ({ name: task, code: undefined }))
|
||||
const queue = tasks.map((task, index) => ({ name: task, index }))
|
||||
const promises = []
|
||||
let error = null
|
||||
let aborted = false
|
||||
|
||||
/**
|
||||
* Done.
|
||||
* @returns {void}
|
||||
*/
|
||||
function done () {
|
||||
if (error == null) {
|
||||
resolve(results)
|
||||
} else {
|
||||
reject(error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Aborts all tasks.
|
||||
* @returns {void}
|
||||
*/
|
||||
function abort () {
|
||||
if (aborted) {
|
||||
return
|
||||
}
|
||||
aborted = true
|
||||
|
||||
if (promises.length === 0) {
|
||||
done()
|
||||
} else {
|
||||
for (const p of promises) {
|
||||
p.abort()
|
||||
}
|
||||
Promise.all(promises).then(done, reject)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a next task.
|
||||
* @returns {void}
|
||||
*/
|
||||
function next () {
|
||||
if (aborted) {
|
||||
return
|
||||
}
|
||||
if (queue.length === 0) {
|
||||
if (promises.length === 0) {
|
||||
done()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const originalOutputStream = options.stdout
|
||||
const optionsClone = Object.assign({}, options)
|
||||
const writer = new MemoryStream(null, {
|
||||
readable: false,
|
||||
})
|
||||
|
||||
if (options.aggregateOutput) {
|
||||
optionsClone.stdout = writer
|
||||
}
|
||||
|
||||
const task = queue.shift()
|
||||
const promise = runTask(task.name, optionsClone)
|
||||
|
||||
promises.push(promise)
|
||||
promise.then(
|
||||
(result) => {
|
||||
remove(promises, promise)
|
||||
if (aborted) {
|
||||
return
|
||||
}
|
||||
|
||||
if (options.aggregateOutput) {
|
||||
originalOutputStream.write(writer.toString())
|
||||
}
|
||||
|
||||
// Check if the task failed as a result of a signal, and
|
||||
// amend the exit code as a result.
|
||||
if (result.code === null && result.signal !== null) {
|
||||
// An exit caused by a signal must return a status code
|
||||
// of 128 plus the value of the signal code.
|
||||
// Ref: https://nodejs.org/api/process.html#process_exit_codes
|
||||
result.code = 128 + convert(result.signal)
|
||||
}
|
||||
|
||||
// Save the result.
|
||||
results[task.index].code = result.code
|
||||
|
||||
// Aborts all tasks if it's an error.
|
||||
if (result.code) {
|
||||
error = new NpmRunAllError(result, results)
|
||||
if (!options.continueOnError) {
|
||||
abort()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Aborts all tasks if options.race is true.
|
||||
if (options.race && !result.code) {
|
||||
abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Call the next task.
|
||||
next()
|
||||
},
|
||||
(thisError) => {
|
||||
remove(promises, promise)
|
||||
if (!options.continueOnError || options.race) {
|
||||
error = thisError
|
||||
abort()
|
||||
return
|
||||
}
|
||||
next()
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
const max = options.maxParallel
|
||||
const end = (typeof max === 'number' && max > 0)
|
||||
? Math.min(tasks.length, max)
|
||||
: tasks.length
|
||||
for (let i = 0; i < end; ++i) {
|
||||
next()
|
||||
}
|
||||
})
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* @module spawn-posix
|
||||
* @author Toru Nagashima
|
||||
* @copyright 2015 Toru Nagashima. All rights reserved.
|
||||
* See LICENSE file in root directory for full license.
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
const crossSpawn = require('cross-spawn')
|
||||
const getDescendentProcessInfo = require('pidtree')
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Kills the new process and its sub processes.
|
||||
* @this ChildProcess
|
||||
* @returns {void}
|
||||
*/
|
||||
function kill () {
|
||||
getDescendentProcessInfo(this.pid, { root: true }, (err, pids) => {
|
||||
if (err) {
|
||||
return
|
||||
}
|
||||
|
||||
for (const pid of pids) {
|
||||
try {
|
||||
process.kill(pid)
|
||||
} catch (_err) {
|
||||
// ignore.
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Launches a new process with the given command.
|
||||
* This is almost same as `child_process.spawn`.
|
||||
*
|
||||
* This returns a `ChildProcess` instance.
|
||||
* `kill` method of the instance kills the new process and its sub processes.
|
||||
*
|
||||
* @param {string} command - The command to run.
|
||||
* @param {string[]} args - List of string arguments.
|
||||
* @param {object} options - Options.
|
||||
* @returns {ChildProcess} A ChildProcess instance of new process.
|
||||
* @private
|
||||
*/
|
||||
module.exports = function spawn (command, args, options) {
|
||||
const child = crossSpawn(command, args, options)
|
||||
child.kill = kill
|
||||
|
||||
return child
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* @module spawn-win32
|
||||
* @author Toru Nagashima
|
||||
* @copyright 2015 Toru Nagashima. All rights reserved.
|
||||
* See LICENSE file in root directory for full license.
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Requirements
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
const crossSpawn = require('cross-spawn')
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Kills the new process and its sub processes forcibly.
|
||||
* @this ChildProcess
|
||||
* @returns {void}
|
||||
*/
|
||||
function kill () {
|
||||
crossSpawn('taskkill', ['/F', '/T', '/PID', this.pid])
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Launches a new process with the given command.
|
||||
* This is almost same as `child_process.spawn`.
|
||||
*
|
||||
* This returns a `ChildProcess` instance.
|
||||
* `kill` method of the instance kills the new process and its sub processes forcibly.
|
||||
*
|
||||
* @param {string} command - The command to run.
|
||||
* @param {string[]} args - List of string arguments.
|
||||
* @param {object} options - Options.
|
||||
* @returns {ChildProcess} A ChildProcess instance of new process.
|
||||
* @private
|
||||
*/
|
||||
module.exports = function spawn (command, args, options) {
|
||||
const child = crossSpawn(command, args, options)
|
||||
child.kill = kill
|
||||
|
||||
return child
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* @module spawn
|
||||
* @author Toru Nagashima
|
||||
* @copyright 2015 Toru Nagashima. All rights reserved.
|
||||
* See LICENSE file in root directory for full license.
|
||||
*/
|
||||
'use strict'
|
||||
|
||||
// ------------------------------------------------------------------------------
|
||||
// Public Interface
|
||||
// ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Launches a new process with the given command.
|
||||
* This is {@link ./spawn-posix.js:spawn} or {@link ./spawn-win32.js:spawn}
|
||||
* @private
|
||||
*/
|
||||
module.exports = process.platform === 'win32' ? require('./spawn-win32') : require('./spawn-posix')
|
||||
Reference in New Issue
Block a user