setup-cpp/src/utils/setup/setupBin.ts

69 lines
2.2 KiB
TypeScript
Raw Normal View History

import { find, downloadTool, cacheDir } from "@actions/tool-cache"
import { addPath, group, startGroup, endGroup } from "@actions/core"
2021-09-14 17:23:38 +08:00
import { join } from "path"
import { existsSync } from "fs"
import * as hasha from "hasha"
2021-09-14 19:38:58 +08:00
import { tmpdir } from "os"
2021-09-14 17:26:33 +08:00
/** A type that describes a package */
export type PackageInfo = {
2021-09-14 17:27:55 +08:00
/** Url to download the package */
url: string
2021-09-14 17:26:33 +08:00
/** The top folder name once it is extracted. It can be `""` if there is no top folder */
2021-09-14 17:23:38 +08:00
extractedFolderName: string
2021-09-14 17:26:33 +08:00
/** The relative directory in which the binary is located. It can be `""` if the exe is in the top folder */
binRelativeDir: string
2021-09-14 17:27:55 +08:00
/** The function to extract the downloaded archive. It can be `undefined`, if the binary itself is downloaded directly. */
extractFunction?: {
(url: string, outputPath: string): Promise<string>
}
}
/** A function that downloads and installs a tool. Then it caches it in the tool-cache. */
export async function setupBin(
name: string,
version: string,
getPackageInfo: (version: string, platform: NodeJS.Platform) => PackageInfo,
setupCppDir: string
): Promise<string> {
2021-09-14 19:38:58 +08:00
process.env.RUNNER_TEMP = process.env.RUNNER_TEMP ?? tmpdir()
process.env.RUNNER_TOOL_CACHE = process.env.RUNNER_TOOL_CACH ?? join(setupCppDir, "ToolCache")
// Build artifact name
const binName = process.platform === "win32" ? `${name}.exe` : name
// Restore from cache (if found).
const dir = find(name, version)
if (dir) {
addPath(dir)
return join(dir, binName)
}
2021-09-14 17:23:38 +08:00
const { url, binRelativeDir, extractedFolderName, extractFunction } = getPackageInfo(version, process.platform)
// Get an unique output directory name from the URL.
const key: string = await hasha.async(url)
2021-09-14 19:38:58 +08:00
const workDir = join(setupCppDir, key)
/** The directory which the tool is installed to */
2021-09-14 17:23:38 +08:00
const binDir = join(workDir, extractedFolderName, binRelativeDir)
if (!existsSync(workDir)) {
await group(`Download and extract ${name}`, async () => {
const downloaded = await downloadTool(url)
2021-09-14 17:27:55 +08:00
await extractFunction?.(downloaded, workDir)
})
}
try {
startGroup(`Add ${name} to PATH`)
addPath(binDir)
} finally {
endGroup()
}
await cacheDir(workDir, name, version)
return join(binDir, binName)
}