2022-08-08 08:18:49 +08:00
|
|
|
import which from "which"
|
|
|
|
import execa from "execa"
|
|
|
|
|
2022-08-08 08:31:14 +08:00
|
|
|
/** Detect if sudo is available and the user has root privileges */
|
2022-08-08 08:29:05 +08:00
|
|
|
export function isSudo(): boolean {
|
2022-08-08 08:31:51 +08:00
|
|
|
return isRoot() && which.sync("sudo", { nothrow: true }) !== null
|
2022-08-08 08:18:49 +08:00
|
|
|
}
|
|
|
|
|
2022-08-08 08:30:14 +08:00
|
|
|
/** Detect if the process has root privileges */
|
|
|
|
export function isRoot(): boolean {
|
|
|
|
return process.getuid?.() === 0
|
|
|
|
}
|
|
|
|
|
2022-08-08 08:18:49 +08:00
|
|
|
/** Prepend `sudo` to the command if sudo is available */
|
|
|
|
export function prependSudo(command: string) {
|
2022-08-08 08:29:05 +08:00
|
|
|
if (isSudo()) {
|
2022-08-08 08:18:49 +08:00
|
|
|
return `sudo ${command}`
|
|
|
|
}
|
|
|
|
return command
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2022-08-08 08:29:05 +08:00
|
|
|
* Execute a command as root if sudo is available. Otherwise executes the command normally without sudo.
|
2022-08-08 08:18:49 +08:00
|
|
|
*
|
2022-08-08 08:24:44 +08:00
|
|
|
* @param program The program to spawn
|
2022-08-08 08:18:49 +08:00
|
|
|
* @param args The command arguments
|
|
|
|
* @param execOptions The options passed to `execa`.
|
2022-08-08 08:24:44 +08:00
|
|
|
*
|
|
|
|
* Defaults to `{ stdio: "inherit" }`
|
2022-08-08 08:18:49 +08:00
|
|
|
*/
|
2022-08-08 08:29:05 +08:00
|
|
|
export function execRoot(program: string, args: string[] = [], execOptions: execa.SyncOptions = { stdio: "inherit" }) {
|
|
|
|
if (isSudo()) {
|
2022-08-08 08:24:44 +08:00
|
|
|
return execa.commandSync(`sudo ${[program, ...args].map((arg) => `'${arg}'`).join(" ")}`, execOptions)
|
2022-08-08 08:18:49 +08:00
|
|
|
} else {
|
2022-08-08 08:24:44 +08:00
|
|
|
return execa.sync(program, args, execOptions)
|
2022-08-08 08:18:49 +08:00
|
|
|
}
|
|
|
|
}
|