Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use execa 6.x in scripts #19759

Merged
merged 12 commits into from
Nov 21, 2022
2 changes: 1 addition & 1 deletion scripts/build-package.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ async function run() {
selection?.filter(Boolean).forEach(async (v) => {
const commmand = (await readJSON(resolve(v.location, 'package.json'))).scripts.prep;
const cwd = resolve(__dirname, '..', 'code', v.location);
const sub = require('execa').command(
const sub = await import('execa').execaCommand(
`${commmand}${watchMode ? ' --watch' : ''}${prodMode ? ' --optimized' : ''}`,
{
cwd,
Expand Down
2 changes: 1 addition & 1 deletion scripts/check-package.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ async function run() {
selection?.filter(Boolean).forEach(async (v) => {
const commmand = (await readJSON(resolve(v.location, 'package.json'))).scripts.check;
const cwd = resolve(__dirname, '..', 'code', v.location);
const sub = require('execa').command(`${commmand}${watchMode ? ' --watch' : ''}`, {
const sub = await import('execa').execaCommand(`${commmand}${watchMode ? ' --watch' : ''}`, {
cwd,
buffer: false,
shell: true,
Expand Down
4 changes: 2 additions & 2 deletions scripts/combine-compodoc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// then combine the results into one large documentation.json

import { join, resolve } from 'path';
import execa from 'execa';
import { execaCommand } from './utils/exec';
import { realpath, readFile, writeFile, lstat } from 'fs-extra';
import glob from 'glob';
import { directory } from 'tempy';
Expand Down Expand Up @@ -37,7 +37,7 @@ async function run(cwd: string) {
dirs.map(async (dir) => {
const outputDir = directory();
const resolvedDir = await realpath(dir);
await execa.command(
await execaCommand(
`yarn compodoc ${resolvedDir} -p ./tsconfig.json -e json -d ${outputDir}`,
{ cwd }
);
Expand Down
8 changes: 6 additions & 2 deletions scripts/next-repro-generators/generate-repros.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
/* eslint-disable no-console */
import { join, relative } from 'path';
import { command } from 'execa';
import type { Options as ExecaOptions } from 'execa';
import pLimit from 'p-limit';
import prettyTime from 'pretty-hrtime';
import { copy, emptyDir, ensureDir, move, remove, rename, writeFile } from 'fs-extra';
import { program } from 'commander';
import { directory } from 'tempy';
import { execaCommand } from '../utils/exec';

import type { OptionValues } from '../utils/options';
import { createOptions } from '../utils/options';
Expand Down Expand Up @@ -85,7 +85,11 @@ export const runCommand = async (script: string, options: ExecaOptions) => {
console.log(`Running command: ${script}`);
}

return command(script, { stdout: shouldDebug ? 'inherit' : 'ignore', shell: true, ...options });
return execaCommand(script, {
stdout: shouldDebug ? 'inherit' : 'ignore',
shell: true,
...options,
});
};

const addDocumentation = async (
Expand Down
8 changes: 4 additions & 4 deletions scripts/next-repro-generators/publish.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import program from 'commander';
import { join } from 'path';
import { existsSync } from 'fs';
import { command } from 'execa';
import { execaCommand } from '../utils/exec';
import * as tempy from 'tempy';
import { copy, emptyDir, readdir, remove, stat, writeFile } from 'fs-extra';

Expand All @@ -27,8 +27,8 @@ const publish = async (options: PublishOptions & { tmpFolder: string }) => {
const templatesData = await getTemplatesData();

logger.log(`👯‍♂️ Cloning the repository ${remote} in branch ${gitBranch}`);
await command(`git clone ${remote} .`, { cwd: tmpFolder });
await command(`git checkout ${gitBranch}`, { cwd: tmpFolder });
await execaCommand(`git clone ${remote} .`, { cwd: tmpFolder });
await execaCommand(`git checkout ${gitBranch}`, { cwd: tmpFolder });

// otherwise old files will stick around and result inconsistent states
logger.log(`🗑 Delete existing template dirs from clone`);
Expand Down Expand Up @@ -67,7 +67,7 @@ const publish = async (options: PublishOptions & { tmpFolder: string }) => {
`);

if (push) {
await command(`git push --set-upstream origin ${gitBranch}`, {
await execaCommand(`git push --set-upstream origin ${gitBranch}`, {
cwd: tmpFolder,
});
const remoteRepoUrl = `${remote.replace('.git', '')}/tree/${gitBranch}`;
Expand Down
8 changes: 4 additions & 4 deletions scripts/next-repro-generators/utils/git.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { command } from 'execa';
import { execaCommand } from '../../utils/exec';
import { logger } from '../publish';

export async function commitAllToGit(cwd: string) {
try {
logger.log(`💪 Committing everything to the repository`);

await command('git add .', { cwd });
await execaCommand('git add .', { cwd });

const currentCommitSHA = await command('git rev-parse HEAD');
await command(
const currentCommitSHA = await execaCommand('git rev-parse HEAD');
await execaCommand(
`git commit -m "Update examples - ${new Date().toDateString()} - ${currentCommitSHA.stdout
.toString()
.slice(0, 12)}"`,
Expand Down
3 changes: 1 addition & 2 deletions scripts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-react": "^7.31.10",
"eslint-plugin-storybook": "^0.6.6",
"execa": "^5.0.0",
"execa": "^6.1.0",
"express": "^4.17.1",
"find-up": "^5.0.0",
"fs-extra": "^9.0.1",
Expand All @@ -138,7 +138,6 @@
"lodash": "^4.17.21",
"memoizerific": "^1.11.3",
"mocha-list-tests": "^1.0.5",
"node-abort-controller": "^3.0.1",
"node-cleanup": "^2.1.2",
"node-fetch": "^2.6.1",
"node-gyp": "^8.4.0",
Expand Down
8 changes: 3 additions & 5 deletions scripts/task.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
/* eslint-disable no-await-in-loop */
import type { AbortController } from 'node-abort-controller';
import { getJunitXml } from 'junit-xml';
import { outputFile, readFile, pathExists } from 'fs-extra';
import { join, resolve } from 'path';
Expand Down Expand Up @@ -470,11 +469,10 @@ async function run() {
await new Promise(() => {});
}
}
controllers.forEach((controller) => {
controller.abort();
});
}

controllers.forEach((controller) => {
controller.abort();
});
return 0;
}

Expand Down
1 change: 0 additions & 1 deletion scripts/tasks/dev.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { AbortController } from 'node-abort-controller';
import detectFreePort from 'detect-port';

import type { Task } from '../task';
Expand Down
3 changes: 1 addition & 2 deletions scripts/tasks/run-registry.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { AbortController } from 'node-abort-controller';
import detectFreePort from 'detect-port';
import { resolve } from 'path';

Expand All @@ -13,7 +12,7 @@ export async function runRegistry({ dryRun, debug }: { dryRun?: boolean; debug?:
exec(
'CI=true yarn local-registry --open',
{ cwd: codeDir },
{ dryRun, debug, signal: controller.signal as AbortSignal }
{ dryRun, debug, signal: controller.signal }
).catch((err) => {
// If aborted, we want to make sure the rejection is handled.
if (!err.killed) throw err;
Expand Down
1 change: 0 additions & 1 deletion scripts/tasks/serve.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { AbortController } from 'node-abort-controller';
import detectFreePort from 'detect-port';

import type { Task } from '../task';
Expand Down
5 changes: 3 additions & 2 deletions scripts/utils/compile-babel.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* eslint-disable no-console */
const fs = require('fs-extra');
const path = require('path');
const execa = require('execa');
const { join } = require('path');

function getCommand(watch, dir) {
Expand Down Expand Up @@ -55,11 +54,13 @@ function handleExit(code, stderr, errorCallback) {
}

async function run({ watch, dir, silent, errorCallback }) {
const execa = await import('execa');

return new Promise((resolve, reject) => {
const command = getCommand(watch, dir);

if (command !== '') {
const child = execa.command(command, {
const child = execa.execaCommand(command, {
cwd: join(__dirname, '..'),
buffer: false,
env: { BABEL_MODE: path.basename(dir) },
Expand Down
5 changes: 3 additions & 2 deletions scripts/utils/compile-tsc.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* eslint-disable no-console */
const fs = require('fs-extra');
const path = require('path');
const execa = require('execa');

function getCommand(watch) {
const args = [
Expand Down Expand Up @@ -41,11 +40,13 @@ function handleExit(code, stderr, errorCallback) {
}

async function run({ optimized, watch, silent, errorCallback }) {
const execa = await import('execa');

return new Promise((resolve, reject) => {
const [command, tscOnly] = getCommand(watch);

if (tscOnly || optimized) {
const child = execa.command(command, {
const child = execa.execaCommand(command, {
buffer: false,
});
let stderr = '';
Expand Down
31 changes: 22 additions & 9 deletions scripts/utils/exec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/* eslint-disable no-await-in-loop, no-restricted-syntax */
import type { ExecaChildProcess, Options } from 'execa';
import execa from 'execa';
import chalk from 'chalk';

const logger = console;
Expand All @@ -13,11 +12,29 @@ type StepOptions = {
signal?: AbortSignal;
};

// Note this is to fool `ts-node` into not turning the `import()` into a `require()`.
// See: https://github.com/TypeStrong/ts-node/discussions/1290
// eslint-disable-next-line @typescript-eslint/no-implied-eval
const dynamicImport = new Function('specifier', 'return import(specifier)');
export const getExeca = async () => (await dynamicImport('execa')) as typeof import('execa');

// Reimplementation of `execaCommand` to use `getExeca`
export const execaCommand = async (
command: string,
options: Options = {}
): Promise<ExecaChildProcess<string>> => {
const execa = await getExeca();
// We await here because execaCommand returns a promise, but that's not what the user expects
// eslint-disable-next-line @typescript-eslint/return-await
return await execa.execaCommand(command, options);
};

export const exec = async (
command: string | string[],
options: Options = {},
{ startMessage, errorMessage, dryRun, debug, signal }: StepOptions = {}
): Promise<void> => {
const execa = await getExeca();
logger.info();
if (startMessage) logger.info(startMessage);

Expand All @@ -30,23 +47,19 @@ export const exec = async (
shell: true,
stdout: debug ? 'inherit' : 'pipe',
stderr: debug ? 'inherit' : 'pipe',
signal,
};
let currentChild: ExecaChildProcess;

// Newer versions of execa have explicit support for abort signals, but this works
if (signal) {
signal.addEventListener('abort', () => currentChild.kill());
}
let currentChild: ExecaChildProcess<string>;

try {
if (typeof command === 'string') {
logger.debug(`> ${command}`);
currentChild = execa.command(command, { ...defaultOptions, ...options });
currentChild = execa.execaCommand(command, { ...defaultOptions, ...options });
await currentChild;
} else {
for (const subcommand of command) {
logger.debug(`> ${subcommand}`);
currentChild = execa.command(subcommand, { ...defaultOptions, ...options });
currentChild = execa.execaCommand(subcommand, { ...defaultOptions, ...options });
await currentChild;
}
}
Expand Down
4 changes: 2 additions & 2 deletions scripts/utils/workspace.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import command from 'execa';
import { execaCommand } from './exec';
import memoize from 'memoizerific';
import { resolve } from 'path';

Expand All @@ -7,7 +7,7 @@ export type Workspace = { name: string; location: string };
const codeDir = resolve(__dirname, '../../code');

async function getWorkspaces() {
const { stdout } = await command('yarn workspaces list --json', {
const { stdout } = await execaCommand('yarn workspaces list --json', {
cwd: codeDir,
shell: true,
});
Expand Down
Loading