From 897c5f67c80d1f729cc0caa8d896feeabffd63f7 Mon Sep 17 00:00:00 2001 From: Amin Yahyaabadi Date: Sun, 7 Aug 2022 17:34:40 -0700 Subject: [PATCH] feat: add async execRoot --- packages/exec-powershell/src/index.ts | 2 +- packages/sudo-tools/src/index.ts | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/exec-powershell/src/index.ts b/packages/exec-powershell/src/index.ts index 5e70618c..2fe2cb89 100644 --- a/packages/exec-powershell/src/index.ts +++ b/packages/exec-powershell/src/index.ts @@ -5,7 +5,7 @@ import which from "which" let powershell: string | undefined /** - * Execute a powershell command. + * Asynchronously execute a powershell command. * * @param command The powershell command to execute * @param startupFlags The optional startup flags to be passed to powershell. diff --git a/packages/sudo-tools/src/index.ts b/packages/sudo-tools/src/index.ts index f0fd3d8d..022abef7 100644 --- a/packages/sudo-tools/src/index.ts +++ b/packages/sudo-tools/src/index.ts @@ -39,3 +39,20 @@ export function execRootSync( return execa.sync(program, args, execOptions) } } + +/** + * Asynchronously execute a command as root if sudo is available. Otherwise executes the command normally without sudo. + * + * @param program The program to spawn + * @param args The command arguments + * @param execOptions The options passed to `execa`. + * + * Defaults to `{ stdio: "inherit" }` + */ +export function execRoot(program: string, args: string[] = [], execOptions: execa.Options = { stdio: "inherit" }) { + if (isSudo()) { + return execa.command(`sudo ${[program, ...args].map((arg) => `'${arg}'`).join(" ")}`, execOptions) + } else { + return execa(program, args, execOptions) + } +}