|
1 | 1 | import path from 'path';
|
| 2 | +import os from 'os'; |
| 3 | +import spawn from 'cross-spawn'; |
2 | 4 | import fs from 'fs-extra';
|
3 | 5 | import kleur from 'kleur';
|
4 | 6 | import dedent from 'dedent';
|
@@ -427,6 +429,58 @@ yargs
|
427 | 429 | }
|
428 | 430 | }
|
429 | 431 | })
|
| 432 | + .command( |
| 433 | + 'run [script...]', |
| 434 | + 'run a package.json script', |
| 435 | + { |
| 436 | + cwd: { |
| 437 | + type: 'string', |
| 438 | + describe: 'specify the working directory', |
| 439 | + }, |
| 440 | + script: { |
| 441 | + type: 'array', |
| 442 | + }, |
| 443 | + }, |
| 444 | + async (argv) => { |
| 445 | + const execpath = process.env.npm_execpath; |
| 446 | + const cli = execpath?.split('/').pop()?.includes('yarn') ? 'yarn' : 'npm'; |
| 447 | + const args = argv.script?.map((s) => String(s)) ?? []; |
| 448 | + const cwd = argv.cwd |
| 449 | + ? path.resolve(process.cwd(), argv.cwd) |
| 450 | + : process.cwd(); |
| 451 | + |
| 452 | + const scripts = Object.keys( |
| 453 | + JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf-8')) |
| 454 | + .scripts || {} |
| 455 | + ); |
| 456 | + |
| 457 | + if (args[0] && scripts.includes(args[0])) { |
| 458 | + // If the script exists in package.json, then prefix with `run` |
| 459 | + // e.g. `yarn run build` |
| 460 | + args.unshift('run'); |
| 461 | + } |
| 462 | + |
| 463 | + const options = { |
| 464 | + cwd, |
| 465 | + env: process.env, |
| 466 | + stdio: 'inherit', |
| 467 | + encoding: 'utf-8', |
| 468 | + shell: os.type() === 'Windows_NT', |
| 469 | + } as const; |
| 470 | + |
| 471 | + const dir = path.relative(process.cwd(), cwd); |
| 472 | + |
| 473 | + logger.info( |
| 474 | + `Running ${kleur.cyan(`${cli} ${args.join(' ')}`.trim())}${ |
| 475 | + dir ? ` at ${kleur.blue(dir)}` : '' |
| 476 | + }` |
| 477 | + ); |
| 478 | + |
| 479 | + const result = spawn.sync(cli, args, options); |
| 480 | + |
| 481 | + process.exitCode = result.status ?? undefined; |
| 482 | + } |
| 483 | + ) |
430 | 484 | .demandCommand()
|
431 | 485 | .recommendCommands()
|
432 | 486 | .strict().argv;
|
0 commit comments