diff --git a/.coderabbit.yaml b/.coderabbit.yaml new file mode 100644 index 0000000..5c881dd --- /dev/null +++ b/.coderabbit.yaml @@ -0,0 +1,5 @@ +# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json +inheritance: true +reviews: + auto_approvals: + enabled: true diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 2b896c3..6234cca 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -18,7 +18,7 @@ jobs: - uses: actions/setup-node@v6 with: - node-version-file: package.json + node-version: "24" cache: yarn - name: Install Dependencies diff --git a/README.md b/README.md index 99a42b8..93e0321 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,47 @@ steps: atmos-version: 0.15.0 ```` +After checkout, setup reads the first version listed for `atmos` or `cloudposse/atmos` in the workspace’s `.tool-versions`. +If the file or Atmos entry is absent, setup uses `latest`. Set `atmos-version-file` to select another file, such as `.atmos-version`. + +```yaml +steps: + - uses: actions/checkout@v4 + + - name: Setup atmos + uses: cloudposse/github-action-setup-atmos@v3 + with: + install-toolchain: true +``` + +Set `install-toolchain: true` to run `atmos toolchain install` after setup. This option defaults to `false` and works independently of `atmos-version-file`. + +When both `atmos-version` and `atmos-version-file` are set, `atmos-version` takes precedence. + +To select a job container from `.tool-versions`, resolve the image in a preceding job. +Setting `install: false` skips both Atmos and toolchain installation. + +```yaml +jobs: + setup: + runs-on: ubuntu-latest + outputs: + image: ${{ steps.atmos.outputs.atmos-image }} + steps: + - uses: actions/checkout@v6 + - id: atmos + uses: cloudposse/github-action-setup-atmos@v3 + with: + install: false + plan: + needs: setup + runs-on: ubuntu-latest + container: + image: ${{ needs.setup.outputs.image }} + steps: + - run: atmos version +``` + The wrapper script installation can be skipped by setting the `install-wrapper` input to `false`: ```yaml @@ -117,8 +158,11 @@ steps: | Name | Description | Default | Required | |------|-------------|---------|----------| -| atmos-version | Version Spec of the version to use. Examples: 1.x, 10.15.1, >=10.15.0. | latest | false | +| atmos-version | Version Spec of the version to use. Defaults to the workspace .tool-versions pin, then latest. Examples: 1.x, 10.15.1, >=10.15.0. | | false | +| atmos-version-file | Optional override for the automatically discovered workspace .tool-versions file. Supports the asdf/mise `.tool-versions` format (the first version listed for `atmos` or `cloudposse/atmos`) and a plain version file whose contents are the version (e.g. `.atmos-version`). When both `atmos-version` and `atmos-version-file` are set, `atmos-version` takes precedence. | | false | | checksum-validation | Controls SHA256SUMS validation. Use `warn` to validate when checksums are published and warn when they are missing, `enforce` to fail when checksums are missing, or `skip` to disable checksum validation. Checksum mismatches always fail when validation runs. | warn | false | +| install | Install Atmos on the runner. Set to false to return the version and container image and skip all installation. | true | false | +| install-toolchain | Run `atmos toolchain install` after setting up Atmos to install tools declared in the repository’s `.tool-versions` file. | false | false | | install-wrapper | Flag to indicate if the wrapper script will be installed to wrap subsequent calls of the `atmos` binary and expose its STDOUT, STDERR, and exit code as outputs named `stdout`, `stderr`, and `exitcode` respectively. Defaults to `true`. | true | false | | token | Used to pull atmos distributions from Cloud Posse's GitHub repository. Since there's a default, this is typically not supplied by the user. When running this action on github.com, the default value is sufficient. When running on GHES, you can pass a personal access token for github.com if you are experiencing rate limiting. | ${{ github.server\_url == 'https://github.com' && github.token \|\| '' }} | false | @@ -128,7 +172,8 @@ steps: | Name | Description | |------|-------------| -| atmos-version | The installed atmos version. | +| atmos-image | The official Atmos container image reference for the resolved version. | +| atmos-version | The resolved Atmos release version. | diff --git a/README.yaml b/README.yaml index e02313d..232df2f 100644 --- a/README.yaml +++ b/README.yaml @@ -73,6 +73,47 @@ usage: |- atmos-version: 0.15.0 ```` + After checkout, setup reads the first version listed for `atmos` or `cloudposse/atmos` in the workspace’s `.tool-versions`. + If the file or Atmos entry is absent, setup uses `latest`. Set `atmos-version-file` to select another file, such as `.atmos-version`. + + ```yaml + steps: + - uses: actions/checkout@v4 + + - name: Setup atmos + uses: cloudposse/github-action-setup-atmos@v3 + with: + install-toolchain: true + ``` + + Set `install-toolchain: true` to run `atmos toolchain install` after setup. This option defaults to `false` and works independently of `atmos-version-file`. + + When both `atmos-version` and `atmos-version-file` are set, `atmos-version` takes precedence. + + To select a job container from `.tool-versions`, resolve the image in a preceding job. + Setting `install: false` skips both Atmos and toolchain installation. + + ```yaml + jobs: + setup: + runs-on: ubuntu-latest + outputs: + image: ${{ steps.atmos.outputs.atmos-image }} + steps: + - uses: actions/checkout@v6 + - id: atmos + uses: cloudposse/github-action-setup-atmos@v3 + with: + install: false + plan: + needs: setup + runs-on: ubuntu-latest + container: + image: ${{ needs.setup.outputs.image }} + steps: + - run: atmos version + ``` + The wrapper script installation can be skipped by setting the `install-wrapper` input to `false`: ```yaml diff --git a/action.yml b/action.yml index 8453848..593f0b5 100644 --- a/action.yml +++ b/action.yml @@ -6,8 +6,20 @@ branding: color: "blue" inputs: atmos-version: - description: "Version Spec of the version to use. Examples: 1.x, 10.15.1, >=10.15.0." - default: "latest" + description: "Version Spec of the version to use. Defaults to the workspace .tool-versions pin, then latest. Examples: 1.x, 10.15.1, >=10.15.0." + atmos-version-file: + description: + Optional override for the automatically discovered workspace .tool-versions file. Supports the asdf/mise `.tool-versions` format (the first + version listed for `atmos` or `cloudposse/atmos`) and a plain version file whose contents are the version (e.g. `.atmos-version`). When both + `atmos-version` and `atmos-version-file` are set, `atmos-version` takes precedence. + required: false + install: + description: "Install Atmos on the runner. Set to false to return the version and container image and skip all installation." + default: "true" + install-toolchain: + description: "Run `atmos toolchain install` after setting up Atmos to install tools declared in the repository’s `.tool-versions` file." + required: false + default: "false" install-wrapper: description: Flag to indicate if the wrapper script will be installed to wrap subsequent calls of the `atmos` binary and expose @@ -29,8 +41,10 @@ inputs: GHES, you can pass a personal access token for github.com if you are experiencing rate limiting. default: ${{ github.server_url == 'https://github.com' && github.token || '' }} outputs: + atmos-image: + description: "The official Atmos container image reference for the resolved version." atmos-version: - description: "The installed atmos version." + description: "The resolved Atmos release version." runs: using: "node24" main: "dist/index.js" diff --git a/dist/index.js b/dist/index.js index befee12..6dae365 100644 --- a/dist/index.js +++ b/dist/index.js @@ -49015,25 +49015,19 @@ var __webpack_exports__ = {}; // ESM COMPAT FLAG __nccwpck_require__.r(__webpack_exports__); -// EXTERNAL MODULE: external "os" -var external_os_ = __nccwpck_require__(2037); -var external_os_default = /*#__PURE__*/__nccwpck_require__.n(external_os_); -// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js -var core = __nccwpck_require__(2186); -// EXTERNAL MODULE: external "crypto" -var external_crypto_ = __nccwpck_require__(6113); -var external_crypto_default = /*#__PURE__*/__nccwpck_require__.n(external_crypto_); +// EXTERNAL MODULE: external "child_process" +var external_child_process_ = __nccwpck_require__(2081); // EXTERNAL MODULE: external "fs" var external_fs_ = __nccwpck_require__(7147); var external_fs_default = /*#__PURE__*/__nccwpck_require__.n(external_fs_); +// EXTERNAL MODULE: external "os" +var external_os_ = __nccwpck_require__(2037); +var external_os_default = /*#__PURE__*/__nccwpck_require__.n(external_os_); // EXTERNAL MODULE: external "path" var external_path_ = __nccwpck_require__(1017); -// EXTERNAL MODULE: ./node_modules/@actions/io/lib/io.js -var io = __nccwpck_require__(7436); -// EXTERNAL MODULE: ./node_modules/@actions/tool-cache/lib/tool-cache.js -var tool_cache = __nccwpck_require__(7784); -// EXTERNAL MODULE: ./node_modules/octokit/dist-node/index.js -var dist_node = __nccwpck_require__(7467); +var external_path_default = /*#__PURE__*/__nccwpck_require__.n(external_path_); +// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js +var core = __nccwpck_require__(2186); // EXTERNAL MODULE: ./node_modules/semver/index.js var semver = __nccwpck_require__(1383); ;// CONCATENATED MODULE: ./src/system.ts @@ -49068,6 +49062,15 @@ const getAtmosBinaryName = (wrapped = false) => { const getAtmosWrappedBinaryName = () => getAtmosBinaryName(true); const getAtmosWrappedPath = () => [process.env.ATMOS_CLI_PATH, getAtmosWrappedBinaryName()].join(sep); +// EXTERNAL MODULE: external "crypto" +var external_crypto_ = __nccwpck_require__(6113); +var external_crypto_default = /*#__PURE__*/__nccwpck_require__.n(external_crypto_); +// EXTERNAL MODULE: ./node_modules/@actions/io/lib/io.js +var io = __nccwpck_require__(7436); +// EXTERNAL MODULE: ./node_modules/@actions/tool-cache/lib/tool-cache.js +var tool_cache = __nccwpck_require__(7784); +// EXTERNAL MODULE: ./node_modules/octokit/dist-node/index.js +var dist_node = __nccwpck_require__(7467); ;// CONCATENATED MODULE: ./src/installer.ts @@ -49357,6 +49360,13 @@ const installAtmosVersion = async (info, auth, arch, installWrapper, checksumVal core.info(`Successfully installed atmos to ${atmosInstallPath}`); return atmosInstallPath; }; +const resolveAtmosVersion = async (versionSpec, auth, arch) => { + const info = await getMatchingVersion(versionSpec, auth, arch); + if (!info) { + throw new Error(`Unable to find atmos version '${versionSpec}' for platform ${external_os_default().platform()} and architecture ${arch}.`); + } + return info; +}; const getAtmos = async (versionSpec, auth, arch = external_os_default().arch(), installWrapper, checksumValidation = "warn") => { const osPlat = external_os_default().platform(); const toolCacheName = getToolCacheName(installWrapper); @@ -49376,10 +49386,7 @@ const getAtmos = async (versionSpec, auth, arch = external_os_default().arch(), }); } } - const info = await getMatchingVersion(versionSpec, auth, arch); - if (!info) { - throw new Error(`Unable to find atmos version '${versionSpec}' for platform ${osPlat} and architecture ${arch}.`); - } + const info = await resolveAtmosVersion(versionSpec, auth, arch); const { resolvedVersion } = info; const cachedPath = tool_cache.find(toolCacheName, resolvedVersion, arch); if (cachedPath) { @@ -49401,18 +49408,101 @@ const getAtmos = async (versionSpec, auth, arch = external_os_default().arch(), + + + + + +// Parses `.tool-versions` content (asdf/mise format) and returns the atmos +// version, or an empty string when none is declared. Lines look like +// `atmos 1.15.0`; comments (`#`) and blank lines are ignored. +const parseToolVersions = (content) => { + for (const line of content.split(/\r?\n/)) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith("#")) { + continue; + } + const [tool, version] = trimmed.split("#", 1)[0].trim().split(/\s+/); + if ((tool === "atmos" || tool === "cloudposse/atmos") && version) { + return version; + } + } + return ""; +}; +// Returns the first non-empty, non-comment line of a plain version file +// (e.g. `.atmos-version`), or an empty string when there is none. +const parsePlainVersion = (content) => { + for (const line of content.split(/\r?\n/)) { + const trimmed = line.trim(); + if (trimmed && !trimmed.startsWith("#")) { + return trimmed === "latest" || semver.validRange(trimmed) ? trimmed : ""; + } + } + return ""; +}; +// Reads an atmos version from a version file. Supports the asdf/mise +// `.tool-versions` format (an `atmos ` line) and a plain version file +// whose contents are the version string (e.g. `.atmos-version`). +const getVersionFromFile = (filePath, required = true) => { + let content; + try { + content = external_fs_default().readFileSync(filePath, "utf8"); + } + catch (error) { + if (error.code === "ENOENT") { + if (!required) + return ""; + throw new Error(`The atmos-version-file '${filePath}' does not exist`); + } + throw error; + } + let version = parseToolVersions(content); + if (!version && external_path_default().basename(filePath) !== ".tool-versions") { + version = parsePlainVersion(content); + } + if (!version && required) { + throw new Error(`No atmos version found in '${filePath}'`); + } + return version; +}; +const setVersionOutputs = (version) => { + core.setOutput("atmos-version", version); + core.setOutput("atmos-image", `ghcr.io/cloudposse/atmos:${version.replace(/^v/, "")}`); +}; const run = async () => { try { - const versionSpec = core.getInput("atmos-version"); + let versionSpec = core.getInput("atmos-version"); + const versionFile = core.getInput("atmos-version-file"); + if (versionSpec && versionFile) { + core.warning("Both 'atmos-version' and 'atmos-version-file' inputs are specified, only 'atmos-version' will be used."); + } + if (!versionSpec) { + const file = versionFile || external_path_default().resolve(process.env.GITHUB_WORKSPACE || ".", ".tool-versions"); + versionSpec = getVersionFromFile(file, Boolean(versionFile)); + if (versionSpec) + core.info(`Resolved atmos version '${versionSpec}' from '${file}'`); + } + versionSpec ||= "latest"; core.info(`Setup atmos version spec ${versionSpec}`); const arch = core.getInput("architecture") || external_os_default().arch(); const installWrapper = core.getInput("install-wrapper") === "true"; const checksumValidation = parseChecksumValidationMode(core.getInput("checksum-validation")); const token = core.getInput("token"); const auth = !token ? undefined : `token ${token}`; + if (!core.getBooleanInput("install")) { + const info = await resolveAtmosVersion(versionSpec, auth, arch); + setVersionOutputs(info.resolvedVersion); + return; + } const { toolPath, info } = await getAtmos(versionSpec, auth, arch, installWrapper, checksumValidation); core.info(`Successfully set up Atmos version ${versionSpec} in ${toolPath}`); - core.setOutput("atmos-version", info?.resolvedVersion); + if (core.getBooleanInput("install-toolchain")) { + core.info("Running atmos toolchain install"); + (0,external_child_process_.execFileSync)(external_path_default().join(toolPath, getAtmosBinaryName(installWrapper)), ["toolchain", "install"], { + stdio: "inherit" + }); + } + setVersionOutputs(info.resolvedVersion); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error) { diff --git a/src/__tests__/setup-atmos.test.ts b/src/__tests__/setup-atmos.test.ts index 2ad9835..6c795b2 100644 --- a/src/__tests__/setup-atmos.test.ts +++ b/src/__tests__/setup-atmos.test.ts @@ -1,3 +1,4 @@ +import childProcess from "child_process"; import fs from "fs"; import os from "os"; import path from "path"; @@ -127,10 +128,10 @@ describe("Setup Atmos", () => { describe("release assets", () => { it.each` - version | expected - ${"1.10beta1"} | ${"1.10.0-beta.1"} - ${"1.10rc1"} | ${"1.10.0-rc.1"} - ${"v1.222.0-rc.1"} | ${"1.222.0-rc.1"} + version | expected + ${"1.10beta1"} | ${"1.10.0-beta.1"} + ${"1.10rc1"} | ${"1.10.0-rc.1"} + ${"v1.222.0-rc.1"} | ${"1.222.0-rc.1"} `("normalizes $version to semver", ({ version, expected }) => { expect(installer.makeSemver(version)).toEqual(expected); }); @@ -235,14 +236,13 @@ describe("Setup Atmos", () => { }); it("rejects missing checksum entries", () => { - expect(() => installer.getExpectedChecksum("", "atmos_1.222.0_linux_amd64")).toThrow( - "Unable to find checksum" - ); + expect(() => installer.getExpectedChecksum("", "atmos_1.222.0_linux_amd64")).toThrow("Unable to find checksum"); }); it("rejects invalid checksum entries", () => { - expect(() => installer.getExpectedChecksum("not-a-sha atmos_1.222.0_linux_amd64", "atmos_1.222.0_linux_amd64")) - .toThrow("Invalid SHA256 checksum"); + expect(() => + installer.getExpectedChecksum("not-a-sha atmos_1.222.0_linux_amd64", "atmos_1.222.0_linux_amd64") + ).toThrow("Invalid SHA256 checksum"); }); it("verifies a downloaded file against SHA256SUMS", () => { @@ -539,11 +539,85 @@ describe("Setup Atmos", () => { }); describe("run", () => { + beforeEach(() => { + jest.mocked(core.getBooleanInput).mockImplementation((name) => name === "install"); + }); + + it.each([ + ["", ".tool-versions", "1.2.3"], + ["latest", ".tool-versions", "latest"], + ["", "", "1.2.3"] + ])("resolves version %j with file %j to %j", async (explicit, file, expected) => { + jest.spyOn(core, "getInput").mockImplementation((name) => { + if (name === "atmos-version") return explicit; + if (name === "atmos-version-file") return file; + return ""; + }); + mockReadFileSync(() => "atmos 1.2.3"); + const install = jest + .spyOn(installer, "getAtmos") + .mockResolvedValue({ toolPath: "/cache/atmos", info: versionInfo }); + + await run(); + + expect(install.mock.calls[0][0]).toBe(expected); + if (explicit) expect(fs.readFileSync).not.toHaveBeenCalled(); + }); + + it.each([false, true])("runs toolchain install with wrapper=%s", async (wrapped) => { + jest.spyOn(core, "getInput").mockImplementation((name) => (name === "install-wrapper" ? String(wrapped) : "")); + jest.spyOn(core, "getBooleanInput").mockReturnValue(true); + const toolPath = path.resolve("tool cache"); + jest.spyOn(installer, "getAtmos").mockResolvedValue({ toolPath, info: versionInfo }); + const execute = jest.spyOn(childProcess, "execFileSync").mockReturnValue(Buffer.alloc(0)); + + await run(); + + const name = wrapped ? "atmos-bin" : "atmos"; + expect(execute).toHaveBeenCalledWith( + path.join(toolPath, process.platform === "win32" ? name + ".exe" : name), + ["toolchain", "install"], + { stdio: "inherit" } + ); + }); + + it("fails setup if toolchain installation fails", async () => { + jest.mocked(core.getBooleanInput).mockReturnValue(true); + jest.spyOn(core, "getInput").mockReturnValue(""); + jest.spyOn(installer, "getAtmos").mockResolvedValue({ toolPath: "/cache/atmos", info: versionInfo }); + jest.spyOn(childProcess, "execFileSync").mockImplementation(() => { + throw new Error("toolchain install failed"); + }); + + await run(); + + expect(core.setFailed).toHaveBeenCalledWith("toolchain install failed"); + }); + + it("resolves the image from .tool-versions without installing anything", async () => { + jest.mocked(core.getBooleanInput).mockImplementation((name) => name === "install-toolchain"); + jest.mocked(core.getInput).mockReturnValue(""); + mockReadFileSync(() => "atmos 1.222.0"); + const resolve = jest.spyOn(installer, "resolveAtmosVersion").mockResolvedValue(versionInfo); + const install = jest.spyOn(installer, "getAtmos"); + const execute = jest.spyOn(childProcess, "execFileSync"); + + await run(); + + expect(resolve).toHaveBeenCalledWith("1.222.0", undefined, os.arch()); + expect(core.setOutput).toHaveBeenCalledWith("atmos-version", "v1.222.0"); + expect(core.setOutput).toHaveBeenCalledWith("atmos-image", "ghcr.io/cloudposse/atmos:1.222.0"); + expect(install).not.toHaveBeenCalled(); + expect(execute).not.toHaveBeenCalled(); + }); + it("sets the resolved version output", async () => { + const execute = jest.spyOn(childProcess, "execFileSync").mockReturnValue(Buffer.alloc(0)); jest .spyOn(core, "getInput") .mockReturnValueOnce("latest") .mockReturnValueOnce("") + .mockReturnValueOnce("") .mockReturnValueOnce("false") .mockReturnValueOnce(""); jest.spyOn(os, "arch").mockReturnValue("x64"); @@ -554,6 +628,7 @@ describe("Setup Atmos", () => { await run(); + expect(execute).not.toHaveBeenCalled(); expect(core.setOutput).toHaveBeenCalledWith("atmos-version", "v1.222.0"); }); @@ -562,6 +637,7 @@ describe("Setup Atmos", () => { .spyOn(core, "getInput") .mockReturnValueOnce("latest") .mockReturnValueOnce("") + .mockReturnValueOnce("") .mockReturnValueOnce("true") .mockReturnValueOnce(""); jest.spyOn(os, "arch").mockReturnValue("x64"); @@ -576,6 +652,7 @@ describe("Setup Atmos", () => { jest .spyOn(core, "getInput") .mockReturnValueOnce("latest") + .mockReturnValueOnce("") .mockReturnValueOnce("arm64") .mockReturnValueOnce("true") .mockReturnValueOnce("enforce") diff --git a/src/__tests__/version-file.test.ts b/src/__tests__/version-file.test.ts new file mode 100644 index 0000000..35ce829 --- /dev/null +++ b/src/__tests__/version-file.test.ts @@ -0,0 +1,87 @@ +import fs from "fs"; +import os from "os"; +import path from "path"; + +import { getVersionFromFile, parseToolVersions } from "../main"; + +describe("parseToolVersions", () => { + it("returns the atmos version from a .tool-versions file", () => { + expect(parseToolVersions("terraform 1.7.0\natmos 1.15.0\n")).toBe("1.15.0"); + }); + + it("selects the first version of the qualified Atmos tool", () => { + const content = "hashicorp/terraform 1.9.8\nother/atmos 9.0.0\ncloudposse/atmos v1.235.0 1.234.0\nhelm/helm 3.0.0"; + expect(parseToolVersions(content)).toBe("v1.235.0"); + }); + + it("ignores comments and blank lines", () => { + expect(parseToolVersions("# pinned tools\n\n atmos 1.13.0 \n")).toBe("1.13.0"); + }); + + it("returns an empty string when atmos is not declared", () => { + expect(parseToolVersions("terraform 1.7.0\nhelm 3.14.0\n")).toBe(""); + }); + + it("does not match a tool whose name only contains 'atmos'", () => { + expect(parseToolVersions("atmos-pro 2.0.0\n")).toBe(""); + }); +}); + +describe("getVersionFromFile", () => { + let dir: string; + + beforeEach(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "atmos-version-file-")); + }); + + afterEach(() => { + fs.rmSync(dir, { force: true, recursive: true }); + }); + + const write = (name: string, content: string): string => { + const filePath = path.join(dir, name); + fs.writeFileSync(filePath, content); + + return filePath; + }; + + it("reads the atmos version from a .tool-versions file", () => { + const filePath = write(".tool-versions", "atmos 1.15.0\n"); + expect(getVersionFromFile(filePath)).toBe("1.15.0"); + }); + + it("reads the Atmos entry from a renamed tool manifest", () => { + const file = write(".tool-versions.ci", "terraform 1.7.0\ncloudposse/atmos v1.222.0 1.221.0"); + expect(getVersionFromFile(file)).toBe("v1.222.0"); + }); + + it("rejects a renamed manifest containing only other tools", () => { + expect(() => getVersionFromFile(write("ci.versions", "terraform 1.7.0"))).toThrow("No atmos version found"); + }); + + it.each(["latest", ">=1.2.0 <2"])("preserves the plain version selector %s", (spec) => { + expect(getVersionFromFile(write("ci.version", spec))).toBe(spec); + }); + + it("reads a plain version file as the version", () => { + const filePath = write(".atmos-version", "1.14.0\n"); + expect(getVersionFromFile(filePath)).toBe("1.14.0"); + }); + + it("falls back when the discovered file is missing or contains only other tools", () => { + expect(getVersionFromFile(path.join(dir, ".tool-versions"), false)).toBe(""); + expect(getVersionFromFile(write(".tool-versions", "terraform 1.7.0"), false)).toBe(""); + }); + + it("throws when the file does not exist", () => { + expect(() => getVersionFromFile(path.join(dir, "missing"))).toThrow("does not exist"); + }); + + it.each(["# only comments\n", "terraform 1.7.0\n", "atmos # unpinned\n"])( + "throws when no Atmos version is declared in %j", + (content) => { + const filePath = write(".tool-versions", content); + expect(() => getVersionFromFile(filePath)).toThrow("No atmos version found"); + } + ); +}); diff --git a/src/installer.ts b/src/installer.ts index 582ae79..c535825 100644 --- a/src/installer.ts +++ b/src/installer.ts @@ -396,13 +396,23 @@ export const installAtmosVersion = async ( return atmosInstallPath; }; +export const resolveAtmosVersion = async (versionSpec: string, auth: string | undefined, arch: string) => { + const info = await getMatchingVersion(versionSpec, auth, arch); + if (!info) { + throw new Error( + `Unable to find atmos version '${versionSpec}' for platform ${os.platform()} and architecture ${arch}.` + ); + } + return info; +}; + export const getAtmos = async ( versionSpec: string, auth: string | undefined, arch: string = os.arch(), installWrapper: boolean, checksumValidation: ChecksumValidationMode = "warn" -): Promise<{ toolPath: string; info: IAtmosVersionInfo | null }> => { +): Promise<{ toolPath: string; info: IAtmosVersionInfo }> => { const osPlat: string = os.platform(); const toolCacheName = getToolCacheName(installWrapper); @@ -426,10 +436,7 @@ export const getAtmos = async ( } } - const info: IAtmosVersionInfo | null = await getMatchingVersion(versionSpec, auth, arch); - if (!info) { - throw new Error(`Unable to find atmos version '${versionSpec}' for platform ${osPlat} and architecture ${arch}.`); - } + const info = await resolveAtmosVersion(versionSpec, auth, arch); const { resolvedVersion } = info; diff --git a/src/main.ts b/src/main.ts index ce6615e..aaeb715 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,12 +1,97 @@ +import { execFileSync } from "child_process"; +import fs from "fs"; import os from "os"; +import path from "path"; import * as core from "@actions/core"; +import * as semver from "semver"; +import { getAtmosBinaryName } from "./atmos-bin"; import * as installer from "./installer"; +// Parses `.tool-versions` content (asdf/mise format) and returns the atmos +// version, or an empty string when none is declared. Lines look like +// `atmos 1.15.0`; comments (`#`) and blank lines are ignored. +export const parseToolVersions = (content: string): string => { + for (const line of content.split(/\r?\n/)) { + const trimmed = line.trim(); + + if (!trimmed || trimmed.startsWith("#")) { + continue; + } + + const [tool, version] = trimmed.split("#", 1)[0].trim().split(/\s+/); + + if ((tool === "atmos" || tool === "cloudposse/atmos") && version) { + return version; + } + } + + return ""; +}; + +// Returns the first non-empty, non-comment line of a plain version file +// (e.g. `.atmos-version`), or an empty string when there is none. +const parsePlainVersion = (content: string): string => { + for (const line of content.split(/\r?\n/)) { + const trimmed = line.trim(); + + if (trimmed && !trimmed.startsWith("#")) { + return trimmed === "latest" || semver.validRange(trimmed) ? trimmed : ""; + } + } + + return ""; +}; + +// Reads an atmos version from a version file. Supports the asdf/mise +// `.tool-versions` format (an `atmos ` line) and a plain version file +// whose contents are the version string (e.g. `.atmos-version`). +export const getVersionFromFile = (filePath: string, required = true): string => { + let content: string; + try { + content = fs.readFileSync(filePath, "utf8"); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") { + if (!required) return ""; + throw new Error(`The atmos-version-file '${filePath}' does not exist`); + } + throw error; + } + let version = parseToolVersions(content); + if (!version && path.basename(filePath) !== ".tool-versions") { + version = parsePlainVersion(content); + } + + if (!version && required) { + throw new Error(`No atmos version found in '${filePath}'`); + } + + return version; +}; + +const setVersionOutputs = (version: string) => { + core.setOutput("atmos-version", version); + core.setOutput("atmos-image", `ghcr.io/cloudposse/atmos:${version.replace(/^v/, "")}`); +}; + export const run = async () => { try { - const versionSpec = core.getInput("atmos-version"); + let versionSpec = core.getInput("atmos-version"); + const versionFile = core.getInput("atmos-version-file"); + + if (versionSpec && versionFile) { + core.warning( + "Both 'atmos-version' and 'atmos-version-file' inputs are specified, only 'atmos-version' will be used." + ); + } + if (!versionSpec) { + const file = versionFile || path.resolve(process.env.GITHUB_WORKSPACE || ".", ".tool-versions"); + versionSpec = getVersionFromFile(file, Boolean(versionFile)); + if (versionSpec) core.info(`Resolved atmos version '${versionSpec}' from '${file}'`); + } + + versionSpec ||= "latest"; core.info(`Setup atmos version spec ${versionSpec}`); const arch = core.getInput("architecture") || os.arch(); @@ -16,11 +101,24 @@ export const run = async () => { const token = core.getInput("token"); const auth = !token ? undefined : `token ${token}`; + if (!core.getBooleanInput("install")) { + const info = await installer.resolveAtmosVersion(versionSpec, auth, arch); + setVersionOutputs(info.resolvedVersion); + return; + } + const { toolPath, info } = await installer.getAtmos(versionSpec, auth, arch, installWrapper, checksumValidation); core.info(`Successfully set up Atmos version ${versionSpec} in ${toolPath}`); - core.setOutput("atmos-version", info?.resolvedVersion); + if (core.getBooleanInput("install-toolchain")) { + core.info("Running atmos toolchain install"); + execFileSync(path.join(toolPath, getAtmosBinaryName(installWrapper)), ["toolchain", "install"], { + stdio: "inherit" + }); + } + + setVersionOutputs(info.resolvedVersion); // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (error: any) { core.setFailed(error instanceof Error ? error.message : `${error}`);