@@ -2,7 +2,7 @@ import cp from 'node:child_process';
22import { randomUUID } from 'node:crypto' ;
33import fs from 'node:fs' ;
44import fsPromises from 'node:fs/promises' ;
5- import { tmpdir } from 'node:os' ;
5+ import { cpus , tmpdir } from 'node:os' ;
66import path from 'node:path' ;
77import { debuglog , parseArgs , promisify } from 'node:util' ;
88
@@ -16,6 +16,35 @@ const exec = async (command: string, options: cp.ExecOptionsWithStringEncoding)
1616 process . platform === 'win32' ? { ...options , shell : 'pwsh.exe' } : options ,
1717 ) ;
1818
19+ /**
20+ * Run tasks with limited concurrency based on CPU count.
21+ * @param tasks Array of task functions to execute
22+ * @param maxConcurrency Maximum number of concurrent tasks (defaults to CPU count)
23+ */
24+ async function runWithConcurrencyLimit < T > (
25+ tasks : ( ( ) => Promise < T > ) [ ] ,
26+ maxConcurrency = cpus ( ) . length ,
27+ ) : Promise < T [ ] > {
28+ const results : T [ ] = [ ] ;
29+ const executing : Promise < void > [ ] = [ ] ;
30+
31+ for ( const task of tasks ) {
32+ const promise = task ( ) . then ( ( result ) => {
33+ results . push ( result ) ;
34+ executing . splice ( executing . indexOf ( promise ) , 1 ) ;
35+ } ) ;
36+
37+ executing . push ( promise ) ;
38+
39+ if ( executing . length >= maxConcurrency ) {
40+ await Promise . race ( executing ) ;
41+ }
42+ }
43+
44+ await Promise . all ( executing ) ;
45+ return results ;
46+ }
47+
1948export async function snapTest ( ) {
2049 const { positionals } = parseArgs ( {
2150 allowPositionals : true ,
@@ -41,16 +70,22 @@ export async function snapTest() {
4170
4271 const casesDir = path . resolve ( 'snap-tests' ) ;
4372
44- const tasks : Promise < void > [ ] = [ ] ;
73+ const taskFunctions : ( ( ) => Promise < void > ) [ ] = [ ] ;
4574 for ( const caseName of fs . readdirSync ( casesDir ) ) {
4675 if ( caseName . startsWith ( '.' ) ) continue ; // Skip hidden files like .DS_Store
4776 if ( caseName . includes ( filter ) ) {
48- tasks . push ( runTestCase ( caseName , tempTmpDir , casesDir ) ) ;
77+ taskFunctions . push ( ( ) => runTestCase ( caseName , tempTmpDir , casesDir ) ) ;
4978 }
5079 }
5180
52- if ( tasks . length > 0 ) {
53- await Promise . all ( tasks ) ;
81+ if ( taskFunctions . length > 0 ) {
82+ const cpuCount = cpus ( ) . length ;
83+ console . log (
84+ 'Running %d test cases with concurrency limit of %d (CPU count)' ,
85+ taskFunctions . length ,
86+ cpuCount ,
87+ ) ;
88+ await runWithConcurrencyLimit ( taskFunctions , cpuCount ) ;
5489 }
5590}
5691
0 commit comments