From 1e5552f09ccb212bf5b77cdb3963625734abc73c Mon Sep 17 00:00:00 2001 From: "J.W. Jagersma" Date: Sun, 9 Feb 2020 00:40:58 +0100 Subject: [PATCH] Run tar with sudo [actions/cache#133] --- __tests__/tar.test.ts | 31 ++++++++++++++++--------------- src/tar.ts | 10 ++++++++-- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/__tests__/tar.test.ts b/__tests__/tar.test.ts index 55ff4c7..11820a1 100644 --- a/__tests__/tar.test.ts +++ b/__tests__/tar.test.ts @@ -25,14 +25,15 @@ test("extract tar", async () => { const tarPath = IS_WINDOWS ? `${process.env["windir"]}\\System32\\tar.exe` : "tar"; + let tarParams = ["-xz", "-f", archivePath, "-C", targetDirectory]; + let tarExec = `${tarPath}`; + if (!IS_WINDOWS) { + tarExec = "sudo"; + tarParams = [`${tarPath}`, ...tarParams]; + } + expect(execMock).toHaveBeenCalledTimes(1); - expect(execMock).toHaveBeenCalledWith(`"${tarPath}"`, [ - "-xz", - "-f", - archivePath, - "-C", - targetDirectory - ]); + expect(execMock).toHaveBeenCalledWith(`"${tarExec}"`, tarParams); }); test("create tar", async () => { @@ -46,13 +47,13 @@ test("create tar", async () => { const tarPath = IS_WINDOWS ? `${process.env["windir"]}\\System32\\tar.exe` : "tar"; + let tarParams = ["-cz", "-f", archivePath, "-C", sourceDirectory, "."]; + let tarExec = `${tarPath}`; + if (!IS_WINDOWS) { + tarExec = "sudo"; + tarParams = [`${tarPath}`, ...tarParams]; + } + expect(execMock).toHaveBeenCalledTimes(1); - expect(execMock).toHaveBeenCalledWith(`"${tarPath}"`, [ - "-cz", - "-f", - archivePath, - "-C", - sourceDirectory, - "." - ]); + expect(execMock).toHaveBeenCalledWith(`"${tarExec}"`, tarParams); }); diff --git a/src/tar.ts b/src/tar.ts index 1f572d1..5f292c5 100644 --- a/src/tar.ts +++ b/src/tar.ts @@ -15,10 +15,16 @@ async function getTarPath(): Promise { } async function execTar(args: string[]): Promise { + const IS_WINDOWS = process.platform === "win32"; try { - await exec(`"${await getTarPath()}"`, args); + const tarPath = await getTarPath(); + let tarExec = tarPath; + if (!IS_WINDOWS) { + tarExec = "sudo"; + args = [`${tarPath}`, ...args]; + } + await exec(`"${tarExec}"`, args); } catch (error) { - const IS_WINDOWS = process.platform === "win32"; if (IS_WINDOWS) { throw new Error( `Tar failed with error: ${error?.message}. Ensure BSD tar is installed and on the PATH.`