@@ -4,27 +4,53 @@ import { spawn } from './spawn.js'
44import { getArgs } from './args.js'
55
66/**
7- * Run package manager scripts serial .
7+ * Run package manager scripts parallel .
88 * @param {string } pm
99 * @param {string[][] } scripts
1010 * @param {{ scripts?: Record<string, string> } } pkg - package.json
11- * @returns Exit code
11+ * @param {number } concurrency - Number of concurrent processes.
12+ * @returns Exit code.
1213 */
13- export async function runSerial ( pm , scripts , pkg ) {
14- const cmds = scripts . map ( script => getArgs ( pm , script , pkg ) )
15- let exitCode = 0
16- let result
14+ export async function run ( pm , scripts , pkg , concurrency ) {
15+ const limit = pLimit ( concurrency )
16+ /** @type {Promise<ReturnType<typeof spawn>>[] } */
17+ const tasks = scripts . map ( script => new Promise (
18+ resolve => limit ( ( ) => {
19+ const [ bin , args ] = getArgs ( pm , script , pkg )
20+ const child = spawn ( bin , args )
21+
22+ resolve ( child )
1723
18- for ( const [ bin , args ] of cmds ) {
19- result = await spawn ( bin , args )
20- exitCode = exitCode || result . exitCode
24+ return child . exitCode
25+ } )
26+ ) )
27+ let finalExitCode = 0
2128
22- if ( result . output ) {
23- process . stdout . write ( result . output )
29+ for await ( const task of tasks ) {
30+ for await ( const data of task . output ) {
31+ if ( data . source === 'stdout' ) {
32+ process . stdout . write ( data . chunk )
33+ } else
34+ if ( data . source === 'stderr' ) {
35+ process . stderr . write ( data . chunk )
36+ }
2437 }
38+
39+ finalExitCode = finalExitCode || await task . exitCode
2540 }
2641
27- return exitCode
42+ return finalExitCode
43+ }
44+
45+ /**
46+ * Run package manager scripts serial.
47+ * @param {string } pm
48+ * @param {string[][] } scripts
49+ * @param {{ scripts?: Record<string, string> } } pkg - package.json
50+ * @returns Exit code
51+ */
52+ export function runSerial ( pm , scripts , pkg ) {
53+ return run ( pm , scripts , pkg , 1 )
2854}
2955
3056/**
@@ -34,19 +60,6 @@ export async function runSerial(pm, scripts, pkg) {
3460 * @param {{ scripts?: Record<string, string> } } pkg - package.json
3561 * @returns Exit code.
3662 */
37- export async function runParallel ( pm , scripts , pkg ) {
38- const limit = pLimit ( cpus ( ) . length )
39- const cmds = scripts . map ( script => getArgs ( pm , script , pkg ) )
40- const tasks = cmds . map ( ( [ bin , args ] ) => limit ( ( ) => spawn ( bin , args , false ) ) )
41- let exitCode = 0
42- /** @type {{ exitCode: number, output?: string | Error } } */
43- let result
44-
45- for ( const task of tasks ) {
46- result = await task
47- exitCode = exitCode || result . exitCode
48- process . stdout . write ( result . output )
49- }
50-
51- return exitCode
63+ export function runParallel ( pm , scripts , pkg ) {
64+ return run ( pm , scripts , pkg , cpus ( ) . length )
5265}
0 commit comments