add env and prefix output options to exec (#1217)

We make use of this `exec` function for the new huppy bot. For that, I
needed to support a couple of extra use-cases: extending the `env` used
to evaluate a command, and prefixing the command output with a string.

In use, these look something like this:
```ts
await exec('my', ['command'], {
    env: {HELLO: 'world'},
    ...prefixOutput('my prefix'),
})
```
This commit is contained in:
alex 2023-05-02 17:13:09 +01:00 committed by GitHub
parent bb1c84e101
commit 859fff480d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -4,6 +4,14 @@ type ExecOpts = {
pwd?: string pwd?: string
processStdoutLine?: (line: string) => void processStdoutLine?: (line: string) => void
processStderrLine?: (line: string) => void processStderrLine?: (line: string) => void
env?: Partial<NodeJS.ProcessEnv>
}
export function prefixOutput(prefix: string) {
return {
processStdoutLine: (line: string) => process.stdout.write(`${prefix}${line}\n`),
processStderrLine: (line: string) => process.stderr.write(`${prefix}${line}\n`),
}
} }
export async function exec( export async function exec(
@ -13,6 +21,7 @@ export async function exec(
pwd = process.cwd(), pwd = process.cwd(),
processStdoutLine = (line) => process.stdout.write(`${line}\n`), processStdoutLine = (line) => process.stdout.write(`${line}\n`),
processStderrLine = (line) => process.stderr.write(`${line}\n`), processStderrLine = (line) => process.stderr.write(`${line}\n`),
env,
}: ExecOpts = {} }: ExecOpts = {}
): Promise<string> { ): Promise<string> {
console.log(`> $ ${command} ${args.join(' ')} (in ${pwd}))`) console.log(`> $ ${command} ${args.join(' ')} (in ${pwd}))`)
@ -22,7 +31,7 @@ export async function exec(
const childProcess = execFile( const childProcess = execFile(
command, command,
args.filter((arg): arg is string => !!arg), args.filter((arg): arg is string => !!arg),
{ cwd: pwd }, { cwd: pwd, env: { ...process.env, ...env } },
(err) => { (err) => {
if (err) reject(err) if (err) reject(err)
else resolve(data.join('')) else resolve(data.join(''))