All files / owid-grapher/db execWrapper.ts

85.96% Statements 49/57
100% Branches 6/6
66.67% Functions 2/3
85.96% Lines 49/57

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 451x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x                 1x
import * as shell from "shelljs"
import * as util from "util"
import { quote } from "shell-quote"
 
interface ExecReturn {
    code: number
    stdout: string
    stderr: string
}
 
export class ExecError extends Error implements ExecReturn {
    code: number
    stdout: string
    stderr: string
 
    constructor(props: ExecReturn) {
        super(props.stderr)
        this.code = props.code
        this.stdout = props.stdout
        this.stderr = props.stderr
    }
}
 
export const execWrapper = (
    command: string,
    options?: shell.ExecOptions
): Promise<ExecReturn> =>
    new Promise((resolve, reject) => {
        shell.exec(command, options || {}, (code, stdout, stderr) =>
            code === 0
                ? resolve({ code, stdout, stderr })
                : reject(new ExecError({ code, stdout, stderr }))
        )
    })
 
export const execFormatted = async (
    cmd: string,
    args: string[],
    verbose = true
): Promise<ExecReturn> => {
    const formatCmd = util.format(cmd, ...args.map((word) => quote([word])))
    if (verbose) console.log(formatCmd)
    return await execWrapper(formatCmd, { silent: !verbose })
}