import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { basename, dirname, join } from "node:path"; import { getuid } from "node:process"; import { execFile } from "./better-api.js"; export async function sudoChown(path: string, owner: string): Promise { await execFile("sudo", ["chown", owner, path]); } export async function sudoChownToRunningUser(path: string): Promise { if (getuid) { await sudoChown(path, "" + getuid()); } else throw new Error("No tengo getuid"); } export async function sudoChmod(path: string, mod: string): Promise { await execFile("sudo", ["chmod", mod, path]); } export async function sudoSymlink(target: string, path: string): Promise { await execFile("sudo", ["ln", "-s", target, path]); } export async function sudoRm(path: string): Promise { await execFile("sudo", ["rm", path]); } export async function sudoMkdirP(path: string): Promise { await execFile("sudo", ["mkdir", "-p", path]); } export async function sudoCopy(input: string, target: string): Promise { await execFile("sudo", ["cp", "--reflink=auto", input, target]); } export async function sudoReadFile(path: string): Promise { const { stdout } = await execFile("sudo", ["cat", path]); return stdout; } export async function sudoWriteFile( filePath: string, content: string ): Promise { const dir = await mkdtemp( join(tmpdir(), "define-alpine-sudoWriteExecutable-") ); try { const tmpFile = join(dir, basename(filePath)); await writeFile(tmpFile, content); await sudoMkdirP(dirname(filePath)); await execFile("sudo", ["mv", tmpFile, filePath]); } finally { await rm(dir, { recursive: true, force: true }); } } export async function sudoWriteExecutable( filePath: string, content: string ): Promise { await sudoWriteFile(filePath, content); await sudoChmod(filePath, "700"); }