Compare commits

..
1 Commits
Author SHA1 Message Date
Diogenes Fernandes 92343fa204 fix: wrapper with a signal
Signed-off-by: Diogenes Fernandes <diofeher@gmail.com>
2026-03-11 23:34:50 -03:00
25 changed files with 43867 additions and 46510 deletions

No files matched your search

-26
View File
@@ -1,26 +0,0 @@
## Releasing
Releases are made on a reasonably regular basis by the maintainers. The following notes are only relevant to maintainers.
Release process:
1. Create a PR against `main` with the following changes:
- Update the version in `package.json`:
```shell
npm version patch|minor|major --no-git-tag-version
```
- Run the build to update the `dist/` directory:
```shell
npm run build
```
2. Review and merge the PR.
3. [Create and publish a GitHub release](https://github.com/opentofu/setup-opentofu/releases/new) with tag `vX.Y.Z`, using the auto-generated release notes as the release body.
4. Update the rolling major version tag to point to the new release:
```shell
git tag -f v2 vX.Y.Z
git push --force origin v2
```
This allows users to pin to `opentofu/setup-opentofu@v2` and always get the latest version of the rolling tag.
-6
View File
@@ -6,9 +6,3 @@ updates:
directory: "/" directory: "/"
schedule: schedule:
interval: "weekly" interval: "weekly"
- package-ecosystem: "github-actions"
cooldown:
default-days: 7
directory: "/"
schedule:
interval: "weekly"
+2 -2
View File
@@ -11,9 +11,9 @@ jobs:
name: Check dist/ directory name: Check dist/ directory
uses: actions/reusable-workflows/.github/workflows/check-dist.yml@2826fb8353263a138210fc017301ce5767a9c0d4 uses: actions/reusable-workflows/.github/workflows/check-dist.yml@2826fb8353263a138210fc017301ce5767a9c0d4
with: with:
node-version: "24.14.0" node-version: "20.19.1"
test: test:
name: Test name: Test
uses: actions/reusable-workflows/.github/workflows/basic-validation.yml@2826fb8353263a138210fc017301ce5767a9c0d4 uses: actions/reusable-workflows/.github/workflows/basic-validation.yml@2826fb8353263a138210fc017301ce5767a9c0d4
with: with:
node-version: "24.14.0" node-version: "20.19.1"
+21
View File
@@ -0,0 +1,21 @@
name: Retag
on:
push:
tags:
- 'v[1-2].[0-9]+.[0-9]+*'
defaults:
run:
shell: bash
jobs:
tag:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: |
set -o pipefail
git tag --force "$(grep '^v[1-2]\.[0-9]\+\.[0-9]\+\(.*\)\?$' <<< ${GITHUB_REF#refs/*/} | sed 's/^v\([1-2]\)\..*/v\1/')"
git push --tag --force
+7 -7
View File
@@ -23,7 +23,7 @@ jobs:
tofu-version-files: ['./.github/workflows/data/local/.opentofu-version'] tofu-version-files: ['./.github/workflows/data/local/.opentofu-version']
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v6.0.3 uses: actions/checkout@v4
- name: Setup OpenTofu - ${{ matrix['tofu-version-files'] }} - name: Setup OpenTofu - ${{ matrix['tofu-version-files'] }}
uses: ./ uses: ./
@@ -43,7 +43,7 @@ jobs:
tofu-wrapper: [true, false] tofu-wrapper: [true, false]
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v6.0.3 uses: actions/checkout@v4
- name: Setup OpenTofu - ${{ matrix['tofu-versions'] }} - name: Setup OpenTofu - ${{ matrix['tofu-versions'] }}
uses: ./ uses: ./
@@ -66,7 +66,7 @@ jobs:
tofu-wrapper: [true, false] tofu-wrapper: [true, false]
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v6.0.3 uses: actions/checkout@v4
- name: Setup OpenTofu - name: Setup OpenTofu
uses: ./ uses: ./
@@ -103,7 +103,7 @@ jobs:
working-directory: ./.github/workflows/data/local working-directory: ./.github/workflows/data/local
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v6.0.3 uses: actions/checkout@v4
- name: Setup OpenTofu - name: Setup OpenTofu
uses: ./ uses: ./
@@ -133,7 +133,7 @@ jobs:
TF_CLOUD_API_TOKEN: 'XXXXXXXXXXXXXX.atlasv1.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' TF_CLOUD_API_TOKEN: 'XXXXXXXXXXXXXX.atlasv1.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v6.0.3 uses: actions/checkout@v4
- name: Setup OpenTofu - name: Setup OpenTofu
uses: ./ uses: ./
@@ -162,7 +162,7 @@ jobs:
TF_CLOUD_API_TOKEN: 'XXXXXXXXXXXXXX.atlasv1.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' TF_CLOUD_API_TOKEN: 'XXXXXXXXXXXXXX.atlasv1.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v6.0.3 uses: actions/checkout@v4
- name: Setup OpenTofu - name: Setup OpenTofu
uses: ./ uses: ./
@@ -190,7 +190,7 @@ jobs:
os: [ubuntu-latest, windows-latest, macos-latest] os: [ubuntu-latest, windows-latest, macos-latest]
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v6.0.3 uses: actions/checkout@v4
- name: Setup OpenTofu - name: Setup OpenTofu
uses: ./ uses: ./
+3
View File
@@ -1,3 +1,6 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm run lint || (npm install && npm run lint) npm run lint || (npm install && npm run lint)
npm run test npm run test
npm audit --audit-level=high npm audit --audit-level=high
+12 -43
View File
@@ -16,14 +16,14 @@ The default configuration installs the latest version of OpenTofu CLI and instal
```yaml ```yaml
steps: steps:
- uses: opentofu/setup-opentofu@v2 - uses: opentofu/setup-opentofu@v1
``` ```
A specific version of OpenTofu CLI can be installed: A specific version of OpenTofu CLI can be installed:
```yaml ```yaml
steps: steps:
- uses: opentofu/setup-opentofu@v2 - uses: opentofu/setup-opentofu@v1
with: with:
tofu_version: 1.6.0 tofu_version: 1.6.0
``` ```
@@ -32,7 +32,7 @@ You can also specify the version in a file (e.g., `.opentofu-version`):
```yaml ```yaml
steps: steps:
- uses: opentofu/setup-opentofu@v2 - uses: opentofu/setup-opentofu@v1
with: with:
tofu_version_file: .opentofu-version tofu_version_file: .opentofu-version
``` ```
@@ -43,7 +43,7 @@ Credentials for Terraform Cloud ([app.terraform.io](https://app.terraform.io/))
```yaml ```yaml
steps: steps:
- uses: opentofu/setup-opentofu@v2 - uses: opentofu/setup-opentofu@v1
with: with:
cli_config_credentials_token: ${{ secrets.TF_API_TOKEN }} cli_config_credentials_token: ${{ secrets.TF_API_TOKEN }}
``` ```
@@ -52,7 +52,7 @@ Credentials for Terraform Enterprise (TFE) can be configured:
```yaml ```yaml
steps: steps:
- uses: opentofu/setup-opentofu@v2 - uses: opentofu/setup-opentofu@v1
with: with:
cli_config_credentials_hostname: 'tofu.example.com' cli_config_credentials_hostname: 'tofu.example.com'
cli_config_credentials_token: ${{ secrets.TF_API_TOKEN }} cli_config_credentials_token: ${{ secrets.TF_API_TOKEN }}
@@ -62,7 +62,7 @@ The wrapper script installation can be skipped by setting the `tofu_wrapper` var
```yaml ```yaml
steps: steps:
- uses: opentofu/setup-opentofu@v2 - uses: opentofu/setup-opentofu@v1
with: with:
tofu_wrapper: false tofu_wrapper: false
``` ```
@@ -71,42 +71,16 @@ Caching can be enabled to reduce download time on subsequent workflow runs by st
```yaml ```yaml
steps: steps:
- uses: opentofu/setup-opentofu@v2 - uses: opentofu/setup-opentofu@v1
with: with:
cache: true cache: true
``` ```
Provider acceptance test environment variables can be configured automatically by setting `provider_acceptance_tests` to `true`. This exports `TF_ACC`, `TF_ACC_PROVIDER_NAMESPACE`, `TF_ACC_PROVIDER_HOST`, and `TF_ACC_TERRAFORM_PATH` so you don't need to set them manually:
```yaml
steps:
- uses: opentofu/setup-opentofu@v2
with:
tofu_wrapper: false
provider_acceptance_tests: true
- run: go mod download
- run: go test -v -cover ./...
timeout-minutes: 10
```
By default, the action verifies the downloaded OpenTofu CLI ZIP against the SHA-256 checksum published in the release's `SHA256SUMS` file, so the default install path is verified out of the box. Verification is skipped (with a warning) only when the published checksum cannot be retrieved.
To pin the expected hashes yourself instead, pass a newline-delimited list of checksums. When set, this list takes precedence over the published `SHA256SUMS`:
```yaml
steps:
- uses: opentofu/setup-opentofu@v2
with:
checksums: |
933b060ab1cf05b106e94af1d370fd14b3006a6845495a67c68734269cc705ad
d3d29f51e75a701fc7cf67c0644a8c883a85f36cf1621461988baffd88e7f361
```
Subsequent steps can access outputs when the wrapper script is installed: Subsequent steps can access outputs when the wrapper script is installed:
```yaml ```yaml
steps: steps:
- uses: opentofu/setup-opentofu@v2 - uses: opentofu/setup-opentofu@v1
- run: tofu init - run: tofu init
@@ -133,8 +107,8 @@ defaults:
permissions: permissions:
pull-requests: write pull-requests: write
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v3
- uses: opentofu/setup-opentofu@v2 - uses: opentofu/setup-opentofu@v1
- name: OpenTofu fmt - name: OpenTofu fmt
id: fmt id: fmt
@@ -201,8 +175,8 @@ defaults:
permissions: permissions:
pull-requests: write pull-requests: write
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v3
- uses: opentofu/setup-opentofu@v2 - uses: opentofu/setup-opentofu@v1
- name: OpenTofu fmt - name: OpenTofu fmt
id: fmt id: fmt
@@ -300,12 +274,7 @@ The action supports the following inputs:
the `tofu` binary and expose its STDOUT, STDERR, and exit code as outputs the `tofu` binary and expose its STDOUT, STDERR, and exit code as outputs
named `stdout`, `stderr`, and `exitcode` respectively. Defaults to `true`. named `stdout`, `stderr`, and `exitcode` respectively. Defaults to `true`.
- `cache` - (optional) Whether to use GitHub Actions tool-cache to store and reuse downloaded OpenTofu binaries. Defaults to `false`. - `cache` - (optional) Whether to use GitHub Actions tool-cache to store and reuse downloaded OpenTofu binaries. Defaults to `false`.
- `provider_acceptance_tests` - (optional) Whether to automatically set environment variables for running
OpenTofu provider acceptance tests. When set to `true`, the following environment variables are exported:
`TF_ACC=1`, `TF_ACC_PROVIDER_NAMESPACE=hashicorp`, `TF_ACC_PROVIDER_HOST=registry.opentofu.org`, and
`TF_ACC_TERRAFORM_PATH=<path to tofu binary>`. Defaults to `false`.
- `github_token` - (optional) Override the GitHub token read from the environment variable. Defaults to the value of the `GITHUB_TOKEN` environment variable unless running on Forgejo or Gitea. - `github_token` - (optional) Override the GitHub token read from the environment variable. Defaults to the value of the `GITHUB_TOKEN` environment variable unless running on Forgejo or Gitea.
- `checksums` - (optional) A newline-delimited list of valid checksums (SHA256) for the downloaded OpenTofu CLI ZIP. When set, the action will verify the ZIP matches one of the checksums before proceeding. When unset, the action verifies the ZIP against the SHA-256 checksum published in the release's `SHA256SUMS` file by default. Defaults to `[]`
## Outputs ## Outputs
+1 -8
View File
@@ -28,13 +28,6 @@ inputs:
description: 'API token for GitHub to increase the rate limit. Defaults to the GITHUB_TOKEN environment variable unless running on Forgejo/Gitea.' description: 'API token for GitHub to increase the rate limit. Defaults to the GITHUB_TOKEN environment variable unless running on Forgejo/Gitea.'
default: '' default: ''
required: false required: false
provider_acceptance_tests:
description: 'Whether to automatically set environment variables for running OpenTofu provider acceptance tests (TF_ACC, TF_ACC_PROVIDER_NAMESPACE, TF_ACC_PROVIDER_HOST, TF_ACC_TERRAFORM_PATH). Defaults to `false`.'
default: 'false'
required: false
checksums:
description: Newline-delimited list of valid checksums (SHA256 hashes) for the downloaded OpenTofu binary. When set, the action verifies the binary matches one of these checksums before proceeding. When unset, the action verifies the binary against the SHA-256 checksum published in the release's SHA256SUMS file by default.
required: false
outputs: outputs:
stdout: stdout:
description: 'The STDOUT stream of the call to the `tofu` binary.' description: 'The STDOUT stream of the call to the `tofu` binary.'
@@ -50,5 +43,5 @@ branding:
icon: 'box' icon: 'box'
color: 'yellow' color: 'yellow'
runs: runs:
using: 'node24' using: 'node20'
main: 'dist/index.js' main: 'dist/index.js'
+21110 -19853
View File
File diff suppressed because it is too large. Load diff
+15138 -18377
View File
File diff suppressed because it is too large. Load diff
-3
View File
@@ -1,3 +0,0 @@
{
"type": "module"
}
+3 -7
View File
@@ -1,20 +1,16 @@
/** /**
* Copyright (c) HashiCorp, Inc. * Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0 * SPDX-License-Identifier: MPL-2.0
*/ */
import { setFailed, debug } from '@actions/core'; const core = require('@actions/core');
import setup from './lib/setup-tofu.js'; const setup = require('./lib/setup-tofu');
import { getErrorMessage, getErrorDetail } from './lib/error-utils.js';
(async () => { (async () => {
try { try {
await setup(); await setup();
} catch (error) { } catch (error) {
const message = getErrorMessage(error); core.setFailed(error.message);
debug(getErrorDetail(error));
setFailed(message);
} }
})(); })();
-75
View File
@@ -1,75 +0,0 @@
/**
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*
* Normalizes errors (including AggregateError from fetch/undici) into
* a single, actionable message for GitHub Actions logs.
*/
/**
* Get a user-friendly message from any error.
* - AggregateError: flattens error.errors so network/download causes are visible.
* - Standard Error: returns message; includes cause if present (Node 16+).
*
* @param {unknown} error - Caught value (Error, AggregateError, or other).
* @returns {string} Single-line message suitable for core.setFailed().
*/
function getErrorMessage (error) {
if (error instanceof AggregateError && Array.isArray(error.errors)) {
if (error.errors.length === 0) {
return 'AggregateError (one or more operations failed)';
}
const parts = error.errors.map((e) => (e && typeof e.message === 'string' ? e.message : String(e)));
const combined = parts.join('; ');
return combined || 'AggregateError (one or more operations failed)';
}
if (error instanceof Error) {
if (error.cause instanceof Error) {
return `${error.message}: ${error.cause.message}`;
}
return error.message;
}
return String(error);
}
/**
* Get a detailed string for logging (e.g. core.debug or core.error).
* Includes stack and, for AggregateError, each nested error.
*
* @param {unknown} error - Caught value.
* @returns {string} Multi-line detail string.
*/
function getErrorDetail (error) {
const lines = [];
if (error instanceof AggregateError && Array.isArray(error.errors)) {
lines.push(`AggregateError (${error.errors.length} error(s)):`);
error.errors.forEach((e, i) => {
lines.push(` [${i + 1}] ${e instanceof Error ? e.message : String(e)}`);
if (e instanceof Error && e.stack) {
lines.push(e.stack.split('\n').map((l) => ' ' + l).join('\n'));
}
});
if (error.stack) {
lines.push('Outer stack:');
lines.push(error.stack);
}
return lines.join('\n');
}
if (error instanceof Error) {
lines.push(error.message);
if (error.stack) lines.push(error.stack);
if (error.cause) {
lines.push('Caused by:');
lines.push(getErrorDetail(error.cause));
}
return lines.join('\n');
}
return String(error);
}
export { getErrorMessage, getErrorDetail };
+29 -146
View File
@@ -1,31 +1,24 @@
/** /**
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu * Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0 * SPDX-License-Identifier: MPL-2.0
*/ */
import { HttpClient, HttpCodes } from '@actions/http-client';
import semver from 'semver';
import { getErrorMessage } from './error-utils.js';
class Build { class Build {
constructor (version, name) { constructor (version, name) {
this.name = name; this.name = name;
this.url = `https://github.com/opentofu/opentofu/releases/download/v${version}/${name}`; this.url = 'https://github.com/opentofu/opentofu/releases/download/v' + version + '/' + name;
} }
} }
class Release { class Release {
constructor (releaseMeta) { constructor (releaseMeta) {
this.version = releaseMeta.id.replace('v', ''); this.version = releaseMeta.id.replace('v', '');
this.builds = releaseMeta.files.map( this.builds = releaseMeta.files.map(asset => new Build(this.version, asset));
(asset) => new Build(this.version, asset)
);
} }
getBuild (platform, arch) { getBuild (platform, arch) {
const requiredName = `tofu_${this.version}_${platform}_${arch}.zip`; const requiredName = `tofu_${this.version}_${platform}_${arch}.zip`;
return this.builds.find((build) => build.name === requiredName); return this.builds.find(build => build.name === requiredName);
} }
} }
@@ -35,9 +28,10 @@ class Release {
* @return {Array<Release>} Releases. * @return {Array<Release>} Releases.
*/ */
async function fetchReleases (githubToken) { async function fetchReleases (githubToken) {
const hc = require('@actions/http-client');
const userAgent = 'opentofu/setup-opentofu'; const userAgent = 'opentofu/setup-opentofu';
const http = new HttpClient(userAgent); const http = new hc.HttpClient(userAgent);
const url = 'https://get.opentofu.org/tofu/api.json'; const url = 'https://get.opentofu.org/tofu/api.json';
@@ -45,135 +39,31 @@ async function fetchReleases (githubToken) {
Accept: 'application/json' Accept: 'application/json'
}; };
let resp; const resp = await http.get(url, headers);
try {
resp = await http.get(url, headers); if (resp.message.statusCode !== hc.HttpCodes.OK) {
} catch (error) { throw new Error('failed fetching releases (' + resp.message.statusCode + ')');
const cause = getErrorMessage(error);
throw new Error(`Failed to fetch OpenTofu releases from ${url}: ${cause}`);
} }
if (resp.message.statusCode !== HttpCodes.OK) { const body = await resp.readBody();
throw new Error( const releasesMeta = JSON.parse(body);
'failed fetching releases (' + resp.message.statusCode + ')'
);
}
let body;
try {
body = await resp.readBody();
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to read releases response: ${cause}`);
}
let releasesMeta;
try {
releasesMeta = JSON.parse(body);
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Invalid releases JSON from ${url}: ${cause}`);
}
/** /**
* @type {Array} * @type {Array}
*/ */
const versions = releasesMeta.versions; const versions = releasesMeta.versions;
return versions.map((releaseMeta) => new Release(releaseMeta)); return versions.map(releaseMeta => new Release(releaseMeta));
} }
/** const semver = require('semver');
* Fetches the raw SHA256SUMS file published alongside an OpenTofu release.
*
* @param {string} version: Release version (without the leading `v`).
* @return {string} Raw SHA256SUMS file body.
*/
async function fetchSHA256SUMS (version) {
const userAgent = 'opentofu/setup-opentofu';
const http = new HttpClient(userAgent);
const url = `https://github.com/opentofu/opentofu/releases/download/v${version}/tofu_${version}_SHA256SUMS`;
let resp;
try {
resp = await http.get(url);
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to fetch SHA256SUMS from ${url}: ${cause}`);
}
if (resp.message.statusCode !== HttpCodes.OK) {
throw new Error(
`failed fetching SHA256SUMS for ${url} (${resp.message.statusCode})`
);
}
return resp.readBody();
}
/**
* Parses a SHA256SUMS file body and returns the checksum for a given file name.
*
* Each line follows the `sha256sum` format: a lowercase hex digest, whitespace,
* then the file name (binary-mode lines prefix the name with `*`).
*
* @param {string} body: Raw SHA256SUMS file body.
* @param {string} fileName: Asset file name to look up.
* @return {string|null} Lowercase hex SHA-256 checksum, or null when not found.
*/
function parseChecksum (body, fileName) {
for (const line of body.split('\n')) {
const trimmed = line.trim();
if (trimmed === '') {
continue;
}
const separatorIndex = trimmed.search(/\s/);
if (separatorIndex === -1) {
continue;
}
const checksum = trimmed.slice(0, separatorIndex);
const name = trimmed.slice(separatorIndex).trim().replace(/^\*/, '');
if (name === fileName) {
return checksum.toLowerCase();
}
}
return null;
}
/**
* Resolves the published SHA-256 checksum for a release asset by fetching the
* release's SHA256SUMS file and looking up the asset's file name.
*
* @param {string} version: Release version (without the leading `v`).
* @param {string} fileName: Asset file name to look up.
* @param {function} fetchSumsFn: Optional fetcher for the SHA256SUMS body (for testing).
* @return {string|null} Lowercase hex SHA-256 checksum, or null when not found.
*/
async function getDownloadChecksum (
version,
fileName,
fetchSumsFn = fetchSHA256SUMS
) {
const body = await fetchSumsFn(version);
return parseChecksum(body, fileName);
}
async function findLatestVersion (versions) { async function findLatestVersion (versions) {
return versions return versions.filter((v) => semver.prerelease(v) === null).sort((a, b) => semver.rcompare(a, b))[0];
.filter((v) => semver.prerelease(v) === null)
.sort((a, b) => semver.rcompare(a, b))[0];
} }
async function findLatestVersionInRange (versions, range) { async function findLatestVersionInRange (versions, range) {
return semver.maxSatisfying(versions, range, { return semver.maxSatisfying(versions, range, { prerelease: true, loose: true });
prerelease: true,
loose: true
});
} }
/** /**
@@ -184,21 +74,12 @@ async function findLatestVersionInRange (versions, range) {
* @param {function} fetchReleasesFn: Optional function to fetch releases. * @param {function} fetchReleasesFn: Optional function to fetch releases.
* @return {Release} Release. * @return {Release} Release.
*/ */
async function getRelease ( async function getRelease (version, githubToken, fetchReleasesFn = fetchReleases) {
version,
githubToken,
fetchReleasesFn = fetchReleases
) {
const latestVersionLabel = 'latest'; const latestVersionLabel = 'latest';
const versionsRange = semver.validRange(version, { const versionsRange = semver.validRange(version, { prerelease: true, loose: true });
prerelease: true,
loose: true
});
if (versionsRange === null && version !== latestVersionLabel) { if (versionsRange === null && version !== latestVersionLabel) {
throw new Error( throw new Error('Input version cannot be used, see semver: https://semver.org/spec/v2.0.0.html');
'Input version cannot be used, see semver: https://semver.org/spec/v2.0.0.html'
);
} }
const releases = await fetchReleasesFn(githubToken); const releases = await fetchReleasesFn(githubToken);
@@ -207,22 +88,24 @@ async function getRelease (
throw new Error('No tofu releases found, please contact OpenTofu'); throw new Error('No tofu releases found, please contact OpenTofu');
} }
const versionsFound = releases.map((release) => release.version); const versionsFound = releases.map(release => release.version);
let versionSelected; let versionSelected;
if (version === latestVersionLabel) { if (version === latestVersionLabel) {
versionSelected = await findLatestVersion(versionsFound); versionSelected = await findLatestVersion(versionsFound);
} else { } else {
versionSelected = await findLatestVersionInRange( versionSelected = await findLatestVersionInRange(versionsFound, versionsRange);
versionsFound,
versionsRange
);
} }
if (versionSelected === null) { if (versionSelected === null) {
throw new Error('No matching version found'); throw new Error('No matching version found');
} }
return releases.find((release) => release.version === versionSelected); return releases.find(release => release.version === versionSelected);
} }
export { getRelease, getDownloadChecksum, parseChecksum, Release }; // Note that the export is defined as adaptor to replace hashicorp/js-releases
// See: https://github.com/hashicorp/setup-terraform/blob/e192cfcbae6c6ed207c277ed7624131996c9bf13/lib/setup-terraform.js#L15
module.exports = {
getRelease,
Release
};
+71 -170
View File
@@ -5,29 +5,15 @@
*/ */
// Node.js core // Node.js core
import { promises as fs } from 'fs'; const fs = require('fs').promises;
import { platform, arch } from 'os'; const os = require('os');
import { sep, join, resolve, dirname } from 'path'; const path = require('path');
import { fileURLToPath } from 'url';
// External // External
import { const core = require('@actions/core');
debug, const tc = require('@actions/tool-cache');
error as logError, const io = require('@actions/io');
exportVariable, const releases = require('./releases');
getInput,
getMultilineInput,
warning,
addPath
} from '@actions/core';
import { downloadTool, extractZip, find, cacheDir } from '@actions/tool-cache';
import { mv, cp, mkdirP } from '@actions/io';
import { getRelease, getDownloadChecksum } from './releases.js';
import { getErrorMessage } from './error-utils.js';
import { fileSHA256 } from './util.js';
// __dirname is not available in ES modules, so we need to construct it ourselves
const __dirname = dirname(fileURLToPath(import.meta.url));
// arch in [arm, x32, x64...] (https://nodejs.org/api/os.html#os_os_arch) // arch in [arm, x32, x64...] (https://nodejs.org/api/os.html#os_os_arch)
// return value in [amd64, 386, arm] // return value in [amd64, 386, arm]
@@ -48,29 +34,9 @@ function mapOS (os) {
return os; return os;
} }
async function downloadAndExtractCLI (url, checksums) { async function downloadAndExtractCLI (url) {
debug(`Downloading OpenTofu CLI from ${url}`); core.debug(`Downloading OpenTofu CLI from ${url}`);
let pathToCLIZip; const pathToCLIZip = await tc.downloadTool(url);
try {
pathToCLIZip = await downloadTool(url);
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to download OpenTofu from ${url}: ${cause}`);
}
if (checksums.length > 0) {
let checksum;
try {
checksum = await fileSHA256(pathToCLIZip);
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to calculate the checksum for the OpenTofu CLI zip: ${cause}`);
}
if (!checksums.includes(checksum)) {
throw new Error(`Failed to validate OpenTofu CLI zip checksum. Received: ${checksum}. Valid checksums: ${checksums.join(', ')}`);
}
}
if (!pathToCLIZip) { if (!pathToCLIZip) {
throw new Error(`Unable to download OpenTofu from ${url}`); throw new Error(`Unable to download OpenTofu from ${url}`);
@@ -78,23 +44,18 @@ async function downloadAndExtractCLI (url, checksums) {
let pathToCLI; let pathToCLI;
debug('Extracting OpenTofu CLI zip file'); core.debug('Extracting OpenTofu CLI zip file');
try { if (os.platform().startsWith('win')) {
if (platform().startsWith('win')) { core.debug(`OpenTofu CLI Download Path is ${pathToCLIZip}`);
debug(`OpenTofu CLI Download Path is ${pathToCLIZip}`); const fixedPathToCLIZip = `${pathToCLIZip}.zip`;
const fixedPathToCLIZip = `${pathToCLIZip}.zip`; await io.mv(pathToCLIZip, fixedPathToCLIZip);
await mv(pathToCLIZip, fixedPathToCLIZip); core.debug(`Moved download to ${fixedPathToCLIZip}`);
debug(`Moved download to ${fixedPathToCLIZip}`); pathToCLI = await tc.extractZip(fixedPathToCLIZip);
pathToCLI = await extractZip(fixedPathToCLIZip); } else {
} else { pathToCLI = await tc.extractZip(pathToCLIZip);
pathToCLI = await extractZip(pathToCLIZip);
}
} catch (error) {
const cause = getErrorMessage(error);
throw new Error(`Failed to extract OpenTofu archive: ${cause}`);
} }
debug(`OpenTofu CLI path is ${pathToCLI}.`); core.debug(`OpenTofu CLI path is ${pathToCLI}.`);
if (!pathToCLI) { if (!pathToCLI) {
throw new Error('Unable to unzip OpenTofu'); throw new Error('Unable to unzip OpenTofu');
@@ -103,74 +64,36 @@ async function downloadAndExtractCLI (url, checksums) {
return pathToCLI; return pathToCLI;
} }
// Resolve the checksums to validate the downloaded archive against. An explicit
// `checksums` input always wins. Otherwise the action falls back to the SHA-256
// checksum published in the release's SHA256SUMS file, so the default install
// path is verified rather than left unchecked. Verification is skipped (with a
// warning) only when no published checksum can be retrieved.
async function resolveChecksums (checksums, version, fileName) {
if (checksums.length > 0) {
return checksums;
}
debug(
`No checksums input provided; fetching published SHA256SUMS for ${fileName}`
);
let publishedChecksum;
try {
publishedChecksum = await getDownloadChecksum(version, fileName);
} catch (error) {
warning(
`Failed to fetch published SHA256SUMS for OpenTofu ${version}: ${getErrorMessage(
error
)}. Proceeding without checksum verification.`
);
return [];
}
if (!publishedChecksum) {
warning(
`Could not find a published SHA256 checksum for ${fileName}. Proceeding without checksum verification.`
);
return [];
}
return [publishedChecksum];
}
async function installWrapper (pathToCLI) { async function installWrapper (pathToCLI) {
let source, target; let source, target;
// If we're on Windows, then the executable ends with .exe // If we're on Windows, then the executable ends with .exe
const exeSuffix = platform().startsWith('win') ? '.exe' : ''; const exeSuffix = os.platform().startsWith('win') ? '.exe' : '';
// Rename tofu(.exe) to tofu-bin(.exe) // Rename tofu(.exe) to tofu-bin(.exe)
try { try {
source = [pathToCLI, `tofu${exeSuffix}`].join(sep); source = [pathToCLI, `tofu${exeSuffix}`].join(path.sep);
target = [pathToCLI, `tofu-bin${exeSuffix}`].join(sep); target = [pathToCLI, `tofu-bin${exeSuffix}`].join(path.sep);
debug(`Moving ${source} to ${target}.`); core.debug(`Moving ${source} to ${target}.`);
await mv(source, target); await io.mv(source, target);
} catch (e) { } catch (e) {
logError(`Unable to move ${source} to ${target}.`); core.error(`Unable to move ${source} to ${target}.`);
throw e; throw e;
} }
// Install our wrapper as tofu // Install our wrapper as tofu
try { try {
source = resolve( source = path.resolve([__dirname, '..', 'wrapper', 'dist', 'index.js'].join(path.sep));
[__dirname, '..', 'wrapper', 'dist', 'index.js'].join(sep) target = [pathToCLI, 'tofu'].join(path.sep);
); core.debug(`Copying ${source} to ${target}.`);
target = [pathToCLI, 'tofu'].join(sep); await io.cp(source, target);
debug(`Copying ${source} to ${target}.`);
await cp(source, target);
} catch (e) { } catch (e) {
logError(`Unable to copy ${source} to ${target}.`); core.error(`Unable to copy ${source} to ${target}.`);
throw e; throw e;
} }
// Export a new environment variable, so our wrapper can locate the binary // Export a new environment variable, so our wrapper can locate the binary
exportVariable('TOFU_CLI_PATH', pathToCLI); core.exportVariable('TOFU_CLI_PATH', pathToCLI);
} }
// Add credentials to CLI Configuration File // Add credentials to CLI Configuration File
@@ -182,45 +105,37 @@ async function addCredentials (credentialsHostname, credentialsToken, osPlat) {
credentials "${credentialsHostname}" { credentials "${credentialsHostname}" {
token = "${credentialsToken}" token = "${credentialsToken}"
}`.trim(); }`.trim();
// eslint-enable // eslint-enable
// default to OS-specific path // default to OS-specific path
let credsFile = let credsFile = osPlat === 'win32'
osPlat === 'win32' ? `${process.env.APPDATA}/tofu.rc`
? `${process.env.APPDATA}/tofu.rc` : `${process.env.HOME}/.tofurc`;
: `${process.env.HOME}/.tofurc`;
// override with TF_CLI_CONFIG_FILE environment variable // override with TF_CLI_CONFIG_FILE environment variable
credsFile = process.env.TF_CLI_CONFIG_FILE credsFile = process.env.TF_CLI_CONFIG_FILE ? process.env.TF_CLI_CONFIG_FILE : credsFile;
? process.env.TF_CLI_CONFIG_FILE
: credsFile;
// get containing folder // get containing folder
const credsFolder = dirname(credsFile); const credsFolder = path.dirname(credsFile);
debug(`Creating ${credsFolder}`); core.debug(`Creating ${credsFolder}`);
await mkdirP(credsFolder); await io.mkdirP(credsFolder);
debug(`Adding credentials to ${credsFile}`); core.debug(`Adding credentials to ${credsFile}`);
await fs.writeFile(credsFile, creds); await fs.writeFile(credsFile, creds);
} }
async function run () { async function run () {
try { try {
// Gather GitHub Actions inputs // Gather GitHub Actions inputs
let version = getInput('tofu_version'); let version = core.getInput('tofu_version');
const versionFile = getInput('tofu_version_file'); const versionFile = core.getInput('tofu_version_file');
const credentialsHostname = getInput('cli_config_credentials_hostname'); const credentialsHostname = core.getInput('cli_config_credentials_hostname');
const credentialsToken = getInput('cli_config_credentials_token'); const credentialsToken = core.getInput('cli_config_credentials_token');
const wrapper = getInput('tofu_wrapper') === 'true'; const wrapper = core.getInput('tofu_wrapper') === 'true';
const providerAcceptanceTest = getInput('provider_acceptance_tests') === 'true'; const useCache = core.getInput('cache') === 'true';
const useCache = getInput('cache') === 'true'; let githubToken = core.getInput('github_token');
const checksums = getMultilineInput('checksums'); if (githubToken === '' && !(process.env.FORGEJO_ACTIONS || process.env.GITEA_ACTIONS)) {
let githubToken = getInput('github_token');
if (
githubToken === '' &&
!(process.env.FORGEJO_ACTIONS || process.env.GITEA_ACTIONS)
) {
// Only default to the environment variable when running in GitHub Actions. Don't do this for other CI systems // Only default to the environment variable when running in GitHub Actions. Don't do this for other CI systems
// that may set the GITHUB_TOKEN environment variable. // that may set the GITHUB_TOKEN environment variable.
githubToken = process.env.GITHUB_TOKEN; githubToken = process.env.GITHUB_TOKEN;
@@ -229,56 +144,52 @@ async function run () {
// If tofu_version_file is provided, read the version from the file // If tofu_version_file is provided, read the version from the file
if (versionFile) { if (versionFile) {
try { try {
debug(`Reading OpenTofu version from file: ${versionFile}`); core.debug(`Reading OpenTofu version from file: ${versionFile}`);
const fileVersion = await fs.readFile(versionFile, 'utf8'); const fileVersion = await fs.readFile(versionFile, 'utf8');
const trimmedVersion = fileVersion.trim(); const trimmedVersion = fileVersion.trim();
if (trimmedVersion) { if (trimmedVersion) {
version = trimmedVersion; version = trimmedVersion;
debug(`Using version from file: ${version}`); core.debug(`Using version from file: ${version}`);
} else { } else {
warning( core.warning(
`Version file ${versionFile} is empty, using tofu_version input: ${version}` `Version file ${versionFile} is empty, using tofu_version input: ${version}`
); );
} }
} catch (error) { } catch (error) {
warning( core.warning(
`Failed to read version from file ${versionFile}: ${error.message}. Using tofu_version input: ${version}` `Failed to read version from file ${versionFile}: ${error.message}. Using tofu_version input: ${version}`
); );
} }
} }
// Gather OS details // Gather OS details
const osPlatform = platform(); const osPlatform = os.platform();
const osArch = arch(); const osArch = os.arch();
debug(`Finding releases for OpenTofu version ${version}`); core.debug(`Finding releases for OpenTofu version ${version}`);
const release = await getRelease(version, githubToken); const release = await releases.getRelease(version, githubToken);
const buildPlatform = mapOS(osPlatform); const platform = mapOS(osPlatform);
const buildArch = mapArch(osArch); const arch = mapArch(osArch);
const build = release.getBuild(buildPlatform, buildArch); const build = release.getBuild(platform, arch);
if (!build) { if (!build) {
throw new Error( throw new Error(`OpenTofu version ${version} not available for ${platform} and ${arch}`);
`OpenTofu version ${version} not available for ${buildPlatform} and ${buildArch}`
);
} }
// Download requested version if not cached // Download requested version if not cached
let pathToCLI; let pathToCLI;
if (useCache) { if (useCache) {
const cachedPath = find('tofu', release.version, buildArch); const cachedPath = tc.find('tofu', release.version, arch);
if (cachedPath) { if (cachedPath) {
debug(`Using cached OpenTofu version ${release.version} from ${cachedPath}`); core.debug(`Using cached OpenTofu version ${release.version} from ${cachedPath}`);
pathToCLI = cachedPath; pathToCLI = cachedPath;
} else { } else {
debug(`OpenTofu version ${release.version} not found in cache, downloading...`); core.debug(`OpenTofu version ${release.version} not found in cache, downloading...`);
const effectiveChecksums = await resolveChecksums(checksums, release.version, build.name); const extractedPath = await downloadAndExtractCLI(build.url);
const extractedPath = await downloadAndExtractCLI(build.url, effectiveChecksums); core.debug(`Caching OpenTofu version ${release.version} to tool cache`);
debug(`Caching OpenTofu version ${release.version} to tool cache`); pathToCLI = await tc.cacheDir(extractedPath, 'tofu', release.version, arch);
pathToCLI = await cacheDir(extractedPath, 'tofu', release.version, buildArch);
} }
} else { } else {
const effectiveChecksums = await resolveChecksums(checksums, release.version, build.name); pathToCLI = await downloadAndExtractCLI(build.url);
pathToCLI = await downloadAndExtractCLI(build.url, effectiveChecksums);
} }
// Install our wrapper // Install our wrapper
@@ -287,17 +198,7 @@ async function run () {
} }
// Add to path // Add to path
addPath(pathToCLI); core.addPath(pathToCLI);
// Set up provider acceptance test environment variables
if (providerAcceptanceTest) {
const exeSuffix = platform().startsWith('win') ? '.exe' : '';
const binaryName = wrapper ? `tofu-bin${exeSuffix}` : `tofu${exeSuffix}`;
exportVariable('TF_ACC', '1');
exportVariable('TF_ACC_PROVIDER_NAMESPACE', 'hashicorp');
exportVariable('TF_ACC_PROVIDER_HOST', 'registry.opentofu.org');
exportVariable('TF_ACC_TERRAFORM_PATH', join(pathToCLI, binaryName));
}
// Add credentials to file if they are provided // Add credentials to file if they are provided
if (credentialsHostname && credentialsToken) { if (credentialsHostname && credentialsToken) {
@@ -305,9 +206,9 @@ async function run () {
} }
return release; return release;
} catch (error) { } catch (error) {
logError(getErrorMessage(error)); core.error(error);
throw error; throw error;
} }
} }
export default run; module.exports = run;
-62
View File
@@ -1,62 +0,0 @@
/**
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import { getErrorMessage, getErrorDetail } from '../error-utils.js';
describe('error-utils', () => {
describe('getErrorMessage', () => {
it('returns message for standard Error', () => {
expect(getErrorMessage(new Error('Something failed'))).toBe('Something failed');
});
it('includes cause for Error with cause (Node 16+)', () => {
const cause = new Error('Network timeout');
const err = new Error('Download failed');
err.cause = cause;
expect(getErrorMessage(err)).toBe('Download failed: Network timeout');
});
it('flattens AggregateError into a single message', () => {
const err = new AggregateError(
[new Error('ECONNREFUSED'), new Error('getaddrinfo ENOTFOUND')],
'AggregateError'
);
const msg = getErrorMessage(err);
expect(msg).toContain('ECONNREFUSED');
expect(msg).toContain('getaddrinfo ENOTFOUND');
expect(msg).not.toBe('AggregateError');
});
it('returns fallback for AggregateError with empty errors', () => {
const err = new AggregateError([], 'AggregateError');
expect(getErrorMessage(err)).toBe('AggregateError (one or more operations failed)');
});
it('coerces non-Error to string', () => {
expect(getErrorMessage('oops')).toBe('oops');
expect(getErrorMessage(123)).toBe('123');
});
});
describe('getErrorDetail', () => {
it('includes stack for Error', () => {
const err = new Error('test');
const detail = getErrorDetail(err);
expect(detail).toContain('test');
expect(detail).toContain('Error');
});
it('includes each nested error for AggregateError', () => {
const err = new AggregateError(
[new Error('A'), new Error('B')],
'AggregateError'
);
const detail = getErrorDetail(err);
expect(detail).toContain('A');
expect(detail).toContain('B');
expect(detail).toContain('2 error(s)');
});
});
});
+159 -250
View File
@@ -1,266 +1,175 @@
/** const pkg = require('../releases');
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import { Release, getRelease, getDownloadChecksum, parseChecksum } from '../releases.js';
describe('getRelease', () => { describe('getRelease', () => {
function mockFetchReleases () { function mockFetchReleases () {
const mockReleasesMeta = [ const mockReleasesMeta = [{
{ id: 'v1.7.0-alpha2',
id: 'v1.7.0-alpha2', files: [
files: [ 'tofu_1.7.0-alpha2_386.apk',
'tofu_1.7.0-alpha2_386.apk', 'tofu_1.7.0-alpha2_386.deb',
'tofu_1.7.0-alpha2_386.deb', 'tofu_1.7.0-alpha2_386.rpm',
'tofu_1.7.0-alpha2_386.rpm', 'tofu_1.7.0-alpha2_amd64.apk',
'tofu_1.7.0-alpha2_amd64.apk', 'tofu_1.7.0-alpha2_amd64.deb',
'tofu_1.7.0-alpha2_amd64.deb', 'tofu_1.7.0-alpha2_amd64.rpm',
'tofu_1.7.0-alpha2_amd64.rpm', 'tofu_1.7.0-alpha2_arm.apk',
'tofu_1.7.0-alpha2_arm.apk', 'tofu_1.7.0-alpha2_arm.deb',
'tofu_1.7.0-alpha2_arm.deb', 'tofu_1.7.0-alpha2_arm.rpm',
'tofu_1.7.0-alpha2_arm.rpm', 'tofu_1.7.0-alpha2_arm64.apk',
'tofu_1.7.0-alpha2_arm64.apk', 'tofu_1.7.0-alpha2_arm64.deb',
'tofu_1.7.0-alpha2_arm64.deb', 'tofu_1.7.0-alpha2_arm64.rpm',
'tofu_1.7.0-alpha2_arm64.rpm', 'tofu_1.7.0-alpha2_darwin_arm64.zip',
'tofu_1.7.0-alpha2_darwin_arm64.zip', 'tofu_1.7.0-alpha2_freebsd_386.zip',
'tofu_1.7.0-alpha2_freebsd_386.zip', 'tofu_1.7.0-alpha2_freebsd_amd64.zip',
'tofu_1.7.0-alpha2_freebsd_amd64.zip', 'tofu_1.7.0-alpha2_freebsd_arm.zip',
'tofu_1.7.0-alpha2_freebsd_arm.zip', 'tofu_1.7.0-alpha2_linux_386.zip',
'tofu_1.7.0-alpha2_linux_386.zip', 'tofu_1.7.0-alpha2_linux_amd64.zip',
'tofu_1.7.0-alpha2_linux_amd64.zip', 'tofu_1.7.0-alpha2_linux_arm.zip',
'tofu_1.7.0-alpha2_linux_arm.zip', 'tofu_1.7.0-alpha2_linux_arm64.zip',
'tofu_1.7.0-alpha2_linux_arm64.zip', 'tofu_1.7.0-alpha2_openbsd_386.zip',
'tofu_1.7.0-alpha2_openbsd_386.zip', 'tofu_1.7.0-alpha2_openbsd_amd64.zip',
'tofu_1.7.0-alpha2_openbsd_amd64.zip', 'tofu_1.7.0-alpha2_SHA256SUMS',
'tofu_1.7.0-alpha2_SHA256SUMS', 'tofu_1.7.0-alpha2_SHA256SUMS.pem',
'tofu_1.7.0-alpha2_SHA256SUMS.pem', 'tofu_1.7.0-alpha2_SHA256SUMS.sig',
'tofu_1.7.0-alpha2_SHA256SUMS.sig', 'tofu_1.7.0-alpha2_solaris_amd64.zip',
'tofu_1.7.0-alpha2_solaris_amd64.zip', 'tofu_1.7.0-alpha2_windows_386.zip',
'tofu_1.7.0-alpha2_windows_386.zip', 'tofu_1.7.0-alpha2_windows_amd64.zip'
'tofu_1.7.0-alpha2_windows_amd64.zip' ]
] }, {
}, id: 'v1.6.0',
{ files: [
id: 'v1.6.0', 'tofu_1.6.0_386.apk',
files: [ 'tofu_1.6.0_386.deb',
'tofu_1.6.0_386.apk', 'tofu_1.6.0_386.rpm',
'tofu_1.6.0_386.deb', 'tofu_1.6.0_amd64.apk',
'tofu_1.6.0_386.rpm', 'tofu_1.6.0_amd64.deb',
'tofu_1.6.0_amd64.apk', 'tofu_1.6.0_amd64.rpm',
'tofu_1.6.0_amd64.deb', 'tofu_1.6.0_arm.apk',
'tofu_1.6.0_amd64.rpm', 'tofu_1.6.0_arm.deb',
'tofu_1.6.0_arm.apk', 'tofu_1.6.0_arm.rpm',
'tofu_1.6.0_arm.deb', 'tofu_1.6.0_arm64.apk',
'tofu_1.6.0_arm.rpm', 'tofu_1.6.0_arm64.deb',
'tofu_1.6.0_arm64.apk', 'tofu_1.6.0_arm64.rpm',
'tofu_1.6.0_arm64.deb', 'tofu_1.6.0_darwin_arm64.zip',
'tofu_1.6.0_arm64.rpm', 'tofu_1.6.0_freebsd_386.zip',
'tofu_1.6.0_darwin_arm64.zip', 'tofu_1.6.0_freebsd_amd64.zip',
'tofu_1.6.0_freebsd_386.zip', 'tofu_1.6.0_freebsd_arm.zip',
'tofu_1.6.0_freebsd_amd64.zip', 'tofu_1.6.0_linux_386.zip',
'tofu_1.6.0_freebsd_arm.zip', 'tofu_1.6.0_linux_amd64.zip',
'tofu_1.6.0_linux_386.zip', 'tofu_1.6.0_linux_arm.zip',
'tofu_1.6.0_linux_amd64.zip', 'tofu_1.6.0_linux_arm64.zip',
'tofu_1.6.0_linux_arm.zip', 'tofu_1.6.0_openbsd_386.zip',
'tofu_1.6.0_linux_arm64.zip', 'tofu_1.6.0_openbsd_amd64.zip',
'tofu_1.6.0_openbsd_386.zip', 'tofu_1.6.0_SHA256SUMS',
'tofu_1.6.0_openbsd_amd64.zip', 'tofu_1.6.0_SHA256SUMS.pem',
'tofu_1.6.0_SHA256SUMS', 'tofu_1.6.0_SHA256SUMS.sig',
'tofu_1.6.0_SHA256SUMS.pem', 'tofu_1.6.0_solaris_amd64.zip',
'tofu_1.6.0_SHA256SUMS.sig', 'tofu_1.6.0_windows_386.zip',
'tofu_1.6.0_solaris_amd64.zip', 'tofu_1.6.0_windows_amd64.zip']
'tofu_1.6.0_windows_386.zip', }, {
'tofu_1.6.0_windows_amd64.zip' id: 'v1.6.0-alpha2',
] files: [
}, 'tofu_1.6.0-alpha2_386.apk',
{ 'tofu_1.6.0-alpha2_386.deb',
id: 'v1.6.0-alpha2', 'tofu_1.6.0-alpha2_386.rpm',
files: [ 'tofu_1.6.0-alpha2_amd64.apk',
'tofu_1.6.0-alpha2_386.apk', 'tofu_1.6.0-alpha2_amd64.deb',
'tofu_1.6.0-alpha2_386.deb', 'tofu_1.6.0-alpha2_amd64.rpm',
'tofu_1.6.0-alpha2_386.rpm', 'tofu_1.6.0-alpha2_arm.apk',
'tofu_1.6.0-alpha2_amd64.apk', 'tofu_1.6.0-alpha2_arm.deb',
'tofu_1.6.0-alpha2_amd64.deb', 'tofu_1.6.0-alpha2_arm.rpm',
'tofu_1.6.0-alpha2_amd64.rpm', 'tofu_1.6.0-alpha2_arm64.apk',
'tofu_1.6.0-alpha2_arm.apk', 'tofu_1.6.0-alpha2_arm64.deb',
'tofu_1.6.0-alpha2_arm.deb', 'tofu_1.6.0-alpha2_arm64.rpm',
'tofu_1.6.0-alpha2_arm.rpm', 'tofu_1.6.0-alpha2_darwin_arm64.zip',
'tofu_1.6.0-alpha2_arm64.apk', 'tofu_1.6.0-alpha2_freebsd_386.zip',
'tofu_1.6.0-alpha2_arm64.deb', 'tofu_1.6.0-alpha2_freebsd_amd64.zip',
'tofu_1.6.0-alpha2_arm64.rpm', 'tofu_1.6.0-alpha2_freebsd_arm.zip',
'tofu_1.6.0-alpha2_darwin_arm64.zip', 'tofu_1.6.0-alpha2_linux_386.zip',
'tofu_1.6.0-alpha2_freebsd_386.zip', 'tofu_1.6.0-alpha2_linux_amd64.zip',
'tofu_1.6.0-alpha2_freebsd_amd64.zip', 'tofu_1.6.0-alpha2_linux_arm.zip',
'tofu_1.6.0-alpha2_freebsd_arm.zip', 'tofu_1.6.0-alpha2_linux_arm64.zip',
'tofu_1.6.0-alpha2_linux_386.zip', 'tofu_1.6.0-alpha2_openbsd_386.zip',
'tofu_1.6.0-alpha2_linux_amd64.zip', 'tofu_1.6.0-alpha2_openbsd_amd64.zip',
'tofu_1.6.0-alpha2_linux_arm.zip', 'tofu_1.6.0-alpha2_SHA256SUMS',
'tofu_1.6.0-alpha2_linux_arm64.zip', 'tofu_1.6.0-alpha2_SHA256SUMS.pem',
'tofu_1.6.0-alpha2_openbsd_386.zip', 'tofu_1.6.0-alpha2_SHA256SUMS.sig',
'tofu_1.6.0-alpha2_openbsd_amd64.zip', 'tofu_1.6.0-alpha2_solaris_amd64.zip',
'tofu_1.6.0-alpha2_SHA256SUMS', 'tofu_1.6.0-alpha2_windows_386.zip',
'tofu_1.6.0-alpha2_SHA256SUMS.pem', 'tofu_1.6.0-alpha2_windows_amd64.zip'
'tofu_1.6.0-alpha2_SHA256SUMS.sig', ]
'tofu_1.6.0-alpha2_solaris_amd64.zip', }, {
'tofu_1.6.0-alpha2_windows_386.zip', id: 'v1.6.0-alpha1',
'tofu_1.6.0-alpha2_windows_amd64.zip' files: [
] 'tofu_1.6.0-alpha1_386.apk',
}, 'tofu_1.6.0-alpha1_386.deb',
{ 'tofu_1.6.0-alpha1_386.rpm',
id: 'v1.6.0-alpha1', 'tofu_1.6.0-alpha1_amd64.apk',
files: [ 'tofu_1.6.0-alpha1_amd64.deb',
'tofu_1.6.0-alpha1_386.apk', 'tofu_1.6.0-alpha1_amd64.rpm',
'tofu_1.6.0-alpha1_386.deb', 'tofu_1.6.0-alpha1_arm.apk',
'tofu_1.6.0-alpha1_386.rpm', 'tofu_1.6.0-alpha1_arm.deb',
'tofu_1.6.0-alpha1_amd64.apk', 'tofu_1.6.0-alpha1_arm.rpm',
'tofu_1.6.0-alpha1_amd64.deb', 'tofu_1.6.0-alpha1_arm64.apk',
'tofu_1.6.0-alpha1_amd64.rpm', 'tofu_1.6.0-alpha1_arm64.deb',
'tofu_1.6.0-alpha1_arm.apk', 'tofu_1.6.0-alpha1_arm64.rpm',
'tofu_1.6.0-alpha1_arm.deb', 'tofu_1.6.0-alpha1_darwin_amd64.zip',
'tofu_1.6.0-alpha1_arm.rpm', 'tofu_1.6.0-alpha1_darwin_arm64.zip',
'tofu_1.6.0-alpha1_arm64.apk', 'tofu_1.6.0-alpha1_freebsd_386.zip',
'tofu_1.6.0-alpha1_arm64.deb', 'tofu_1.6.0-alpha1_freebsd_amd64.zip',
'tofu_1.6.0-alpha1_arm64.rpm', 'tofu_1.6.0-alpha1_freebsd_arm.zip',
'tofu_1.6.0-alpha1_darwin_amd64.zip', 'tofu_1.6.0-alpha1_linux_386.zip',
'tofu_1.6.0-alpha1_darwin_arm64.zip', 'tofu_1.6.0-alpha1_linux_amd64.zip',
'tofu_1.6.0-alpha1_freebsd_386.zip', 'tofu_1.6.0-alpha1_linux_arm.zip',
'tofu_1.6.0-alpha1_freebsd_amd64.zip', 'tofu_1.6.0-alpha1_linux_arm64.zip',
'tofu_1.6.0-alpha1_freebsd_arm.zip', 'tofu_1.6.0-alpha1_openbsd_386.zip',
'tofu_1.6.0-alpha1_linux_386.zip', 'tofu_1.6.0-alpha1_openbsd_amd64.zip',
'tofu_1.6.0-alpha1_linux_amd64.zip', 'tofu_1.6.0-alpha1_SHA256SUMS',
'tofu_1.6.0-alpha1_linux_arm.zip', 'tofu_1.6.0-alpha1_SHA256SUMS.pem',
'tofu_1.6.0-alpha1_linux_arm64.zip', 'tofu_1.6.0-alpha1_SHA256SUMS.sig',
'tofu_1.6.0-alpha1_openbsd_386.zip', 'tofu_1.6.0-alpha1_solaris_amd64.zip',
'tofu_1.6.0-alpha1_openbsd_amd64.zip', 'tofu_1.6.0-alpha1_windows_386.zip',
'tofu_1.6.0-alpha1_SHA256SUMS', 'tofu_1.6.0-alpha1_windows_amd64.zip'
'tofu_1.6.0-alpha1_SHA256SUMS.pem', ]
'tofu_1.6.0-alpha1_SHA256SUMS.sig', }];
'tofu_1.6.0-alpha1_solaris_amd64.zip',
'tofu_1.6.0-alpha1_windows_386.zip',
'tofu_1.6.0-alpha1_windows_amd64.zip'
]
}
];
return mockReleasesMeta.map((el) => new Release(el)); return mockReleasesMeta.map(el => new pkg.Release(el));
} }
it.each([ it.each(
['latest', '1.6.0'], [
['<1.6.0-beta', '1.6.0-alpha2'], ['latest', '1.6.0'],
['>1.6.0-alpha1', '1.6.0'], ['<1.6.0-beta', '1.6.0-alpha2'],
['>1.6.0-alpha1 <1.6.0', '1.6.0-alpha2'], ['>1.6.0-alpha1', '1.6.0'],
['~1.6.0-alpha', '1.6.0'], ['>1.6.0-alpha1 <1.6.0', '1.6.0-alpha2'],
['<=1.6.0-alpha1', '1.6.0-alpha1'], ['~1.6.0-alpha', '1.6.0'],
['>1.5.0', '1.6.0'], ['<=1.6.0-alpha1', '1.6.0-alpha1'],
['>1.5.0', '1.6.0'], ['>1.5.0', '1.6.0'],
['>1.7.0-alpha', '1.7.0-alpha2'] ['>1.5.0', '1.6.0'],
])("happy path: getRelease('%s') -> '%s'", async (input, wantVersion) => { ['>1.7.0-alpha', '1.7.0-alpha2']
const want = mockFetchReleases().find((el) => el.version === wantVersion); ]
const gotRelease = await getRelease(input, '', mockFetchReleases); )('happy path: getRelease(\'%s\') -> \'%s\'', async (input, wantVersion) => {
const want = mockFetchReleases().find(el => el.version === wantVersion);
const gotRelease = await pkg.getRelease(input, '', mockFetchReleases);
expect(gotRelease).toEqual(want); expect(gotRelease).toEqual(want);
}); });
it.each([ it.each(
[ [
'foo', ['foo', 'Input version cannot be used, see semver: https://semver.org/spec/v2.0.0.html', mockFetchReleases],
'Input version cannot be used, see semver: https://semver.org/spec/v2.0.0.html', ['2.0', 'No matching version found', mockFetchReleases],
mockFetchReleases ['latest', 'No tofu releases found, please contact OpenTofu', async () => {
],
['2.0', 'No matching version found', mockFetchReleases],
[
'latest',
'No tofu releases found, please contact OpenTofu',
async () => {
return null; return null;
} }],
], ['latest', 'No tofu releases found, please contact OpenTofu', async () => {
[
'latest',
'No tofu releases found, please contact OpenTofu',
async () => {
return []; return [];
} }]
] ]
])( )('unhappy path: getRelease(\'%s\') -> throw Error(\'%s\')', async (input, wantErrorMessage, mockFetchReleasesFn) => {
"unhappy path: getRelease('%s') -> throw Error('%s')", try {
async (input, wantErrorMessage, mockFetchReleasesFn) => { await pkg.getRelease(input, '', mockFetchReleasesFn);
try { expect(true).toBe(false);
await getRelease(input, '', mockFetchReleasesFn); } catch (e) {
expect(true).toBe(false); expect(e.message).toBe(wantErrorMessage);
} catch (e) {
expect(e.message).toBe(wantErrorMessage);
}
} }
);
});
describe('parseChecksum', () => {
const sums = [
'933b060ab1cf05b106e94af1d370fd14b3006a6845495a67c68734269cc705ad tofu_1.6.0_linux_amd64.zip',
'd3d29f51e75a701fc7cf67c0644a8c883a85f36cf1621461988baffd88e7f361 tofu_1.6.0_darwin_arm64.zip'
].join('\n') + '\n';
it('returns the lowercase checksum for a matching file name', () => {
expect(parseChecksum(sums, 'tofu_1.6.0_darwin_arm64.zip')).toBe(
'd3d29f51e75a701fc7cf67c0644a8c883a85f36cf1621461988baffd88e7f361'
);
});
it('returns null when the file name is not listed', () => {
expect(parseChecksum(sums, 'tofu_1.6.0_windows_amd64.zip')).toBeNull();
});
it('ignores blank lines and binary-mode "*" prefixes', () => {
const body = '\nABCDEF0123456789 *tofu_1.6.0_linux_arm64.zip\n\n';
expect(parseChecksum(body, 'tofu_1.6.0_linux_arm64.zip')).toBe(
'abcdef0123456789'
);
});
it('returns null for an empty body', () => {
expect(parseChecksum('', 'tofu_1.6.0_linux_amd64.zip')).toBeNull();
});
});
describe('getDownloadChecksum', () => {
it('fetches the SHA256SUMS and returns the matching checksum', async () => {
const fetchSumsFn = async (version) => {
expect(version).toBe('1.6.0');
return '933b060ab1cf05b106e94af1d370fd14b3006a6845495a67c68734269cc705ad tofu_1.6.0_linux_amd64.zip\n';
};
const got = await getDownloadChecksum(
'1.6.0',
'tofu_1.6.0_linux_amd64.zip',
fetchSumsFn
);
expect(got).toBe(
'933b060ab1cf05b106e94af1d370fd14b3006a6845495a67c68734269cc705ad'
);
});
it('returns null when the asset is absent from the SHA256SUMS', async () => {
const fetchSumsFn = async () =>
'933b060ab1cf05b106e94af1d370fd14b3006a6845495a67c68734269cc705ad tofu_1.6.0_linux_amd64.zip\n';
const got = await getDownloadChecksum(
'1.6.0',
'tofu_1.6.0_windows_amd64.zip',
fetchSumsFn
);
expect(got).toBeNull();
});
it('propagates fetch errors', async () => {
const fetchSumsFn = async () => {
throw new Error('boom');
};
await expect(
getDownloadChecksum('1.6.0', 'tofu_1.6.0_linux_amd64.zip', fetchSumsFn)
).rejects.toThrow('boom');
}); });
}); });
+44 -246
View File
@@ -1,59 +1,31 @@
/**
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import { jest } from '@jest/globals';
// Node.js core // Node.js core
import { promises as fs } from 'fs'; const fs = require('fs').promises;
import { tmpdir } from 'os'; const os = require('os');
import { join } from 'path'; const path = require('path');
// Set up mocks BEFORE dynamic imports // External
jest.unstable_mockModule('@actions/core', () => ({ const core = require('@actions/core');
getInput: jest.fn(),
getMultilineInput: jest.fn(),
setOutput: jest.fn(),
setFailed: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
warning: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn()
}));
jest.unstable_mockModule('@actions/io', () => ({ // First party
const releases = require('../releases');
const setup = require('../setup-tofu');
// Mock dependencies
jest.mock('@actions/core');
jest.mock('@actions/io', () => ({
mv: jest.fn(), mv: jest.fn(),
cp: jest.fn(), cp: jest.fn(),
mkdirP: jest.fn() mkdirP: jest.fn()
})); }));
jest.mock('@actions/tool-cache', () => ({
jest.unstable_mockModule('@actions/tool-cache', () => ({
downloadTool: jest.fn(), downloadTool: jest.fn(),
extractZip: jest.fn(), extractZip: jest.fn(),
find: jest.fn(), find: jest.fn(),
cacheDir: jest.fn() cacheDir: jest.fn()
})); }));
jest.unstable_mockModule('../releases.js', () => ({ // Mock releases.js so setup-tofu.js can be tested in isolation
getRelease: jest.fn(), jest.mock('../releases');
getDownloadChecksum: jest.fn(),
Release: jest.fn()
}));
jest.unstable_mockModule('../util.js', () => ({
fileSHA256: jest.fn()
}));
// Dynamic imports pick up the mocks
const { getInput, warning, exportVariable, getMultilineInput } = await import('@actions/core');
const tc = await import('@actions/tool-cache');
const io = await import('@actions/io');
const { getRelease, getDownloadChecksum } = await import('../releases.js');
const { default: setup } = await import('../setup-tofu.js');
const { fileSHA256 } = await import('../util.js');
// Set up global test fixtures // Set up global test fixtures
const fallbackVersion = 'latest'; const fallbackVersion = 'latest';
@@ -66,56 +38,43 @@ let versionFileName = '.opentofu-version';
describe('setup-tofu', () => { describe('setup-tofu', () => {
beforeAll(async () => { beforeAll(async () => {
// Mock dependencies // Mock dependencies
const tc = require('@actions/tool-cache');
tc.downloadTool.mockResolvedValue('/mock/download/path'); tc.downloadTool.mockResolvedValue('/mock/download/path');
tc.extractZip.mockResolvedValue('/mock/extract/path'); tc.extractZip.mockResolvedValue('/mock/extract/path');
tc.find.mockReturnValue(null); // Default to cache miss tc.find.mockReturnValue(null); // Default to cache miss
tc.cacheDir.mockResolvedValue('/mock/cached/path'); tc.cacheDir.mockResolvedValue('/mock/cached/path');
const io = require('@actions/io');
io.mv.mockResolvedValue(); io.mv.mockResolvedValue();
io.cp.mockResolvedValue(); io.cp.mockResolvedValue();
io.mkdirP.mockResolvedValue(); io.mkdirP.mockResolvedValue();
const mockRelease = { const mockRelease = {
version: '1.10.5', version: '1.10.5',
getBuild: jest.fn().mockReturnValue({ getBuild: jest.fn().mockReturnValue({ url: 'mock-url' })
url: 'mock-url',
name: 'tofu_1.10.5_linux_amd64.zip'
})
}; };
getRelease.mockResolvedValue(mockRelease); releases.getRelease.mockResolvedValue(mockRelease);
// Default to "no published checksum retrievable" so tests that don't
// exercise checksum behaviour keep skipping verification, as before.
getDownloadChecksum.mockResolvedValue(null);
// Write version file to temporary directory // Write version file to temporary directory
tempDirPath = join(tmpdir(), 'setup-tofu-'); tempDirPath = path.join(os.tmpdir(), 'setup-tofu-');
tempDir = await fs.mkdtemp(tempDirPath); tempDir = await fs.mkdtemp(tempDirPath);
versionFile = join(tempDir, versionFileName); versionFile = path.join(tempDir, versionFileName);
await fs.writeFile(versionFile, `${version}\n`); await fs.writeFile(versionFile, `${version}\n`);
// Mock action inputs to return default values // Mock action inputs to return default values
getInput.mockImplementation((name) => { core.getInput.mockImplementation((name) => {
const defaults = { const defaults = {
tofu_version: fallbackVersion, tofu_version: fallbackVersion,
tofu_version_file: versionFile, tofu_version_file: versionFile,
cli_config_credentials_hostname: '', cli_config_credentials_hostname: '',
cli_config_credentials_token: '', cli_config_credentials_token: '',
tofu_wrapper: 'true', tofu_wrapper: 'true',
provider_acceptance_tests: 'false',
cache: 'false', cache: 'false',
github_token: '' github_token: ''
}; };
return defaults[name] || ''; return defaults[name] || '';
}); });
getMultilineInput.mockImplementation((name) => {
const defaults = {
checksums: []
};
return defaults[name] || [];
});
// Mock environment variables // Mock environment variables
process.env.GITHUB_TOKEN = 'mock-github-token'; process.env.GITHUB_TOKEN = 'mock-github-token';
}); });
@@ -134,9 +93,8 @@ describe('setup-tofu', () => {
await setup(); await setup();
expect(getRelease).toHaveBeenCalledWith( expect(releases.getRelease).toHaveBeenCalledWith(
version, version, process.env.GITHUB_TOKEN
process.env.GITHUB_TOKEN
); );
expect(fs.readFile).toHaveBeenCalled(); expect(fs.readFile).toHaveBeenCalled();
@@ -147,10 +105,10 @@ describe('setup-tofu', () => {
version = ' '; version = ' ';
versionFileName = '.opentofu-version-empty'; versionFileName = '.opentofu-version-empty';
versionFile = join(tempDir, versionFileName); versionFile = path.join(tempDir, versionFileName);
await fs.writeFile(versionFile, `${version}\n`); await fs.writeFile(versionFile, `${version}\n`);
getInput.mockImplementation((name) => { core.getInput.mockImplementation((name) => {
if (name === 'tofu_version_file') { if (name === 'tofu_version_file') {
return versionFile; return versionFile;
} }
@@ -162,12 +120,11 @@ describe('setup-tofu', () => {
await setup(); await setup();
expect(getRelease).toHaveBeenCalledWith( expect(releases.getRelease).toHaveBeenCalledWith(
fallbackVersion, fallbackVersion, process.env.GITHUB_TOKEN
process.env.GITHUB_TOKEN
); );
expect(warning).toHaveBeenCalledWith( expect(core.warning).toHaveBeenCalledWith(
expect.stringContaining(`Version file ${versionFile} is empty`) expect.stringContaining(`Version file ${versionFile} is empty`)
); );
@@ -178,9 +135,9 @@ describe('setup-tofu', () => {
jest.spyOn(fs, 'readFile'); jest.spyOn(fs, 'readFile');
versionFileName = '.opentofu-version-file-does-not-exist'; versionFileName = '.opentofu-version-file-does-not-exist';
versionFile = join(tempDir, versionFileName); versionFile = path.join(tempDir, versionFileName);
getInput.mockImplementation((name) => { core.getInput.mockImplementation((name) => {
if (name === 'tofu_version_file') { if (name === 'tofu_version_file') {
return versionFile; return versionFile;
} }
@@ -192,15 +149,12 @@ describe('setup-tofu', () => {
await setup(); await setup();
expect(getRelease).toHaveBeenCalledWith( expect(releases.getRelease).toHaveBeenCalledWith(
fallbackVersion, fallbackVersion, process.env.GITHUB_TOKEN
process.env.GITHUB_TOKEN
); );
expect(warning).toHaveBeenCalledWith( expect(core.warning).toHaveBeenCalledWith(
expect.stringContaining( expect.stringContaining(`Failed to read version from file ${versionFile}`)
`Failed to read version from file ${versionFile}`
)
); );
expect(fs.readFile).toHaveBeenCalled(); expect(fs.readFile).toHaveBeenCalled();
@@ -209,7 +163,7 @@ describe('setup-tofu', () => {
it('should not read file when tofu_version_file is not provided', async () => { it('should not read file when tofu_version_file is not provided', async () => {
jest.spyOn(fs, 'readFile'); jest.spyOn(fs, 'readFile');
getInput.mockImplementation((name) => { core.getInput.mockImplementation((name) => {
if (name === 'tofu_version') { if (name === 'tofu_version') {
return fallbackVersion; return fallbackVersion;
} }
@@ -218,9 +172,8 @@ describe('setup-tofu', () => {
await setup(); await setup();
expect(getRelease).toHaveBeenCalledWith( expect(releases.getRelease).toHaveBeenCalledWith(
fallbackVersion, fallbackVersion, process.env.GITHUB_TOKEN
process.env.GITHUB_TOKEN
); );
expect(fs.readFile).not.toHaveBeenCalled(); expect(fs.readFile).not.toHaveBeenCalled();
@@ -229,9 +182,10 @@ describe('setup-tofu', () => {
describe('caching functionality', () => { describe('caching functionality', () => {
it('should use cached version when cache is enabled and found', async () => { it('should use cached version when cache is enabled and found', async () => {
const tc = require('@actions/tool-cache');
tc.find.mockReturnValue('/mock/cached/path'); tc.find.mockReturnValue('/mock/cached/path');
getInput.mockImplementation((name) => { core.getInput.mockImplementation((name) => {
const defaults = { const defaults = {
tofu_version: fallbackVersion, tofu_version: fallbackVersion,
tofu_version_file: '', tofu_version_file: '',
@@ -253,9 +207,10 @@ describe('setup-tofu', () => {
}); });
it('should download and cache when cache is enabled but not found', async () => { it('should download and cache when cache is enabled but not found', async () => {
const tc = require('@actions/tool-cache');
tc.find.mockReturnValue(null); // Cache miss tc.find.mockReturnValue(null); // Cache miss
getInput.mockImplementation((name) => { core.getInput.mockImplementation((name) => {
const defaults = { const defaults = {
tofu_version: fallbackVersion, tofu_version: fallbackVersion,
tofu_version_file: '', tofu_version_file: '',
@@ -277,16 +232,16 @@ describe('setup-tofu', () => {
}); });
it('should not use cache when cache is disabled', async () => { it('should not use cache when cache is disabled', async () => {
const tc = require('@actions/tool-cache');
tc.find.mockReturnValue('/mock/cached/path'); tc.find.mockReturnValue('/mock/cached/path');
getInput.mockImplementation((name) => { core.getInput.mockImplementation((name) => {
const defaults = { const defaults = {
tofu_version: fallbackVersion, tofu_version: fallbackVersion,
tofu_version_file: '', tofu_version_file: '',
cli_config_credentials_hostname: '', cli_config_credentials_hostname: '',
cli_config_credentials_token: '', cli_config_credentials_token: '',
tofu_wrapper: 'true', tofu_wrapper: 'true',
provider_acceptance_tests: 'false',
cache: 'false', cache: 'false',
github_token: '' github_token: ''
}; };
@@ -301,161 +256,4 @@ describe('setup-tofu', () => {
expect(tc.cacheDir).not.toHaveBeenCalled(); expect(tc.cacheDir).not.toHaveBeenCalled();
}); });
}); });
describe('provider_acceptance_tests functionality', () => {
it('should export acceptance test env vars when enabled without wrapper', async () => {
getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'false',
provider_acceptance_tests: 'true',
cache: 'false',
github_token: ''
};
return defaults[name] || '';
});
await setup();
expect(exportVariable).toHaveBeenCalledWith('TF_ACC', '1');
expect(exportVariable).toHaveBeenCalledWith('TF_ACC_PROVIDER_NAMESPACE', 'hashicorp');
expect(exportVariable).toHaveBeenCalledWith('TF_ACC_PROVIDER_HOST', 'registry.opentofu.org');
expect(exportVariable).toHaveBeenCalledWith(
'TF_ACC_TERRAFORM_PATH',
expect.stringContaining('tofu')
);
expect(exportVariable).not.toHaveBeenCalledWith(
'TF_ACC_TERRAFORM_PATH',
expect.stringContaining('tofu-bin')
);
});
it('should point TF_ACC_TERRAFORM_PATH to tofu-bin when wrapper is enabled', async () => {
getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'true',
provider_acceptance_tests: 'true',
cache: 'false',
github_token: ''
};
return defaults[name] || '';
});
await setup();
expect(exportVariable).toHaveBeenCalledWith('TF_ACC', '1');
expect(exportVariable).toHaveBeenCalledWith('TF_ACC_PROVIDER_NAMESPACE', 'hashicorp');
expect(exportVariable).toHaveBeenCalledWith('TF_ACC_PROVIDER_HOST', 'registry.opentofu.org');
expect(exportVariable).toHaveBeenCalledWith(
'TF_ACC_TERRAFORM_PATH',
expect.stringContaining('tofu-bin')
);
});
it('should not export acceptance test env vars when disabled', async () => {
getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
cli_config_credentials_hostname: '',
cli_config_credentials_token: '',
tofu_wrapper: 'false',
provider_acceptance_tests: 'false',
cache: 'false',
github_token: ''
};
return defaults[name] || '';
});
await setup();
expect(exportVariable).not.toHaveBeenCalledWith('TF_ACC', expect.anything());
expect(exportVariable).not.toHaveBeenCalledWith('TF_ACC_PROVIDER_NAMESPACE', expect.anything());
expect(exportVariable).not.toHaveBeenCalledWith('TF_ACC_PROVIDER_HOST', expect.anything());
expect(exportVariable).not.toHaveBeenCalledWith('TF_ACC_TERRAFORM_PATH', expect.anything());
});
});
describe('checksum validation', () => {
const mockChecksum = 'a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6';
const mockChecksum2 = 'fcfac0a865b57e0711cb8bae47c8fc70ad93198fa6146a40020ea459715fda83';
const mockInvalidChecksum = 'invalidchecksuminvalidchecksuminvalidchecksuminvalidchecksum';
fileSHA256.mockResolvedValue(mockChecksum);
it('should validate checksum when checksums are provided', async () => {
getMultilineInput.mockImplementation((name) => {
const defaults = {
checksums: [mockInvalidChecksum, mockChecksum]
};
return defaults[name] ?? [];
});
await setup();
expect(fileSHA256).toHaveBeenCalled();
// An explicit checksums input wins; the published SHA256SUMS is not fetched.
expect(getDownloadChecksum).not.toHaveBeenCalled();
});
it('should validate against the published SHA256SUMS when no checksums input is provided', async () => {
fileSHA256.mockResolvedValue(mockChecksum);
getDownloadChecksum.mockResolvedValue(mockChecksum);
getMultilineInput.mockImplementation((name) => {
const defaults = {
checksums: []
};
return defaults[name] ?? [];
});
await setup();
expect(getDownloadChecksum).toHaveBeenCalledWith(
'1.10.5',
'tofu_1.10.5_linux_amd64.zip'
);
expect(fileSHA256).toHaveBeenCalled();
});
it('should skip verification when no published checksum can be retrieved', async () => {
getDownloadChecksum.mockResolvedValue(null);
getMultilineInput.mockImplementation((name) => {
const defaults = {
checksums: []
};
return defaults[name] ?? [];
});
await setup();
expect(getDownloadChecksum).toHaveBeenCalled();
expect(fileSHA256).not.toHaveBeenCalled();
expect(warning).toHaveBeenCalledWith(
expect.stringContaining('Proceeding without checksum verification')
);
});
it('should throw error when checksum validation fails', async () => {
fileSHA256.mockResolvedValue(mockInvalidChecksum);
getMultilineInput.mockImplementation((name) => {
const defaults = {
checksums: [mockChecksum, mockChecksum2]
};
return defaults[name] ?? [];
});
await expect(setup()).rejects.toMatchObject(new Error(
`Failed to validate OpenTofu CLI zip checksum. Received: ${mockInvalidChecksum}. Valid checksums: ${mockChecksum}, ${mockChecksum2}`));
expect(fileSHA256).toHaveBeenCalled();
});
});
}); });
-16
View File
@@ -1,16 +0,0 @@
/**
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import { createHash } from 'crypto';
import { createReadStream } from 'fs';
import { pipeline } from 'stream/promises';
export async function fileSHA256 (filePath) {
const hash = createHash('sha256');
const fileStream = createReadStream(filePath);
await pipeline(fileStream, hash);
return hash.digest('hex');
}
+7191 -7140
View File
File diff suppressed because it is too large. Load diff
+37 -39
View File
@@ -1,41 +1,39 @@
{ {
"name": "setup-opentofu", "name": "setup-opentofu",
"version": "2.0.2", "version": "1.0.1",
"description": "Setup OpenTofu CLI for GitHub Actions", "description": "Setup OpenTofu CLI for GitHub Actions",
"type": "module", "license": "MPL-2.0",
"license": "MPL-2.0", "publisher": "OpenTofu",
"publisher": "OpenTofu", "main": "index.js",
"main": "index.js", "repository": {
"repository": { "type": "git",
"type": "git", "url": "https://github.com/opentofu/setup-opentofu.git"
"url": "https://github.com/opentofu/setup-opentofu.git" },
}, "scripts": {
"scripts": { "test": "semistandard --env jest && jest --coverage",
"test": "semistandard --env jest && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --coverage", "lint": "semistandard --env jest --fix",
"lint": "semistandard --env jest --fix", "build": "ncc build wrapper/tofu.js --out wrapper/dist && ncc build index.js --out dist",
"build": "ncc build wrapper/tofu.js --out wrapper/dist && ncc build index.js --out dist", "prepare": "husky install",
"prepare": "husky install", "format-check": "echo \"unimplemented for actions/reusable-workflows basic-validation\""
"format-check": "echo \"unimplemented for actions/reusable-workflows basic-validation\"" },
}, "keywords": [],
"keywords": [], "author": "",
"author": "", "dependencies": {
"dependencies": { "@actions/core": "2.0.2",
"@actions/core": "^3.0.1", "@actions/exec": "2.0.0",
"@actions/exec": "^3.0.0", "@actions/io": "2.0.0",
"@actions/http-client": "4.0.1", "@actions/tool-cache": "2.0.2",
"@actions/io": "^3.0.2", "semver": "7.7.3"
"@actions/tool-cache": "^4.0.0", },
"semver": "^7.8.3" "devDependencies": {
}, "@vercel/ncc": "0.38.4",
"devDependencies": { "husky": "9.1.7",
"@vercel/ncc": "0.38.4", "jest": "30.2.0",
"husky": "9.1.7", "semistandard": "17.0.0"
"jest": "^30.4.2", },
"semistandard": "17.0.0" "semistandard": {
}, "ignore": [
"semistandard": { "**/dist/**"
"ignore": [ ]
"**/dist/**" }
]
}
} }
+6 -3
View File
@@ -1,6 +1,5 @@
/** /**
* Copyright (c) HashiCorp, Inc. * Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0 * SPDX-License-Identifier: MPL-2.0
*/ */
@@ -21,7 +20,7 @@
* // Log out STDOUT contents * // Log out STDOUT contents
* console.log(listener.contents); * console.log(listener.contents);
*/ */
export default class OutputListener { class OutputListener {
constructor (stream) { constructor (stream) {
this._buff = []; this._buff = [];
this._stream = stream; this._stream = stream;
@@ -36,6 +35,10 @@ export default class OutputListener {
} }
get contents () { get contents () {
return this._buff.map((chunk) => chunk.toString()).join(''); return this._buff
.map(chunk => chunk.toString())
.join('');
} }
} }
module.exports = OutputListener;
+3 -6
View File
@@ -1,17 +1,14 @@
/** /**
* Copyright (c) HashiCorp, Inc. * Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0 * SPDX-License-Identifier: MPL-2.0
*/ */
import os from 'os'; const os = require('os');
import path from 'path'; const path = require('path');
const tofuBin = (() => { module.exports = (() => {
// If we're on Windows, then the executable ends with .exe // If we're on Windows, then the executable ends with .exe
const exeSuffix = os.platform().startsWith('win') ? '.exe' : ''; const exeSuffix = os.platform().startsWith('win') ? '.exe' : '';
return [process.env.TOFU_CLI_PATH, `tofu-bin${exeSuffix}`].join(path.sep); return [process.env.TOFU_CLI_PATH, `tofu-bin${exeSuffix}`].join(path.sep);
})(); })();
export default tofuBin;
+2 -4
View File
@@ -1,12 +1,10 @@
/** /**
* Copyright (c) HashiCorp, Inc. * Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0 * SPDX-License-Identifier: MPL-2.0
*/ */
import OutputListener from '../lib/output-listener.js'; const OutputListener = require('../lib/output-listener');
import { PassThrough } from 'stream'; const { PassThrough } = require('stream');
describe('output-listener', () => { describe('output-listener', () => {
it('receives and exposes data', () => { it('receives and exposes data', () => {
const stream = new PassThrough(); const stream = new PassThrough();
+28 -21
View File
@@ -1,21 +1,20 @@
#!/usr/bin/env node #!/usr/bin/env node
/** /**
* Copyright (c) HashiCorp, Inc. * Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0 * SPDX-License-Identifier: MPL-2.0
*/ */
import { which } from '@actions/io'; const io = require('@actions/io');
import { setOutput, setFailed } from '@actions/core'; const core = require('@actions/core');
import { exec } from '@actions/exec'; const { spawn } = require('child_process');
import OutputListener from './lib/output-listener.js'; const OutputListener = require('./lib/output-listener');
import pathToCLI from './lib/tofu-bin.js'; const pathToCLI = require('./lib/tofu-bin');
async function checkTofu () { async function checkTofu () {
// Setting check to `true` will cause `which` to throw if tofu isn't found // Setting check to `true` will cause `which` to throw if tofu isn't found
const check = true; const check = true;
return which(pathToCLI, check); return io.which(pathToCLI, check);
} }
(async () => { (async () => {
@@ -25,24 +24,32 @@ async function checkTofu () {
// Create listeners to receive output (in memory) as well // Create listeners to receive output (in memory) as well
const stdout = new OutputListener(process.stdout); const stdout = new OutputListener(process.stdout);
const stderr = new OutputListener(process.stderr); const stderr = new OutputListener(process.stderr);
const listeners = {
stdout: stdout.listener,
stderr: stderr.listener
};
// Execute tofu and capture output // Execute tofu and capture output
const args = process.argv.slice(2); const args = process.argv.slice(2);
const options = { const child = spawn(pathToCLI, args, { stdio: ['inherit', 'pipe', 'pipe'] });
listeners,
ignoreReturnCode: true, // Forward signals to child so tofu can release state locks on cancellation
silent: true // don't print "[command...]" into stdout: https://github.com/actions/toolkit/issues/649 const forwardSigterm = () => { child.kill('SIGTERM'); };
}; const forwardSigint = () => { child.kill('SIGINT'); };
const exitCode = await exec(pathToCLI, args, options); process.on('SIGTERM', forwardSigterm);
process.on('SIGINT', forwardSigint);
child.stdout.on('data', stdout.listener);
child.stderr.on('data', stderr.listener);
const exitCode = await new Promise((resolve) => {
// code is null when the process is killed by a signal; treat as failure
child.on('close', (code) => resolve(code ?? 1));
});
process.removeListener('SIGTERM', forwardSigterm);
process.removeListener('SIGINT', forwardSigint);
// Set outputs, result, exitcode, and stderr // Set outputs, result, exitcode, and stderr
setOutput('stdout', stdout.contents); core.setOutput('stdout', stdout.contents);
setOutput('stderr', stderr.contents); core.setOutput('stderr', stderr.contents);
setOutput('exitcode', exitCode.toString(10)); core.setOutput('exitcode', exitCode.toString(10));
if (exitCode === 0 || exitCode === 2) { if (exitCode === 0 || exitCode === 2) {
// A exitCode of 0 is considered a success // A exitCode of 0 is considered a success
@@ -53,5 +60,5 @@ async function checkTofu () {
} }
// A non-zero exitCode is considered an error // A non-zero exitCode is considered an error
setFailed(`OpenTofu exited with code ${exitCode}.`); core.setFailed(`OpenTofu exited with code ${exitCode}.`);
})(); })();