Compare 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
19 changed files with 43764 additions and 44794 deletions

No files matched your search

+2 -2
View File
@@ -11,9 +11,9 @@ jobs:
name: Check dist/ directory
uses: actions/reusable-workflows/.github/workflows/check-dist.yml@2826fb8353263a138210fc017301ce5767a9c0d4
with:
node-version: "24.14.0"
node-version: "20.19.1"
test:
name: Test
uses: actions/reusable-workflows/.github/workflows/basic-validation.yml@2826fb8353263a138210fc017301ce5767a9c0d4
with:
node-version: "24.14.0"
node-version: "20.19.1"
+1 -1
View File
@@ -13,7 +13,7 @@ jobs:
tag:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- 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/')"
+7 -7
View File
@@ -23,7 +23,7 @@ jobs:
tofu-version-files: ['./.github/workflows/data/local/.opentofu-version']
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- name: Setup OpenTofu - ${{ matrix['tofu-version-files'] }}
uses: ./
@@ -43,7 +43,7 @@ jobs:
tofu-wrapper: [true, false]
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- name: Setup OpenTofu - ${{ matrix['tofu-versions'] }}
uses: ./
@@ -66,7 +66,7 @@ jobs:
tofu-wrapper: [true, false]
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- name: Setup OpenTofu
uses: ./
@@ -103,7 +103,7 @@ jobs:
working-directory: ./.github/workflows/data/local
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- name: Setup OpenTofu
uses: ./
@@ -133,7 +133,7 @@ jobs:
TF_CLOUD_API_TOKEN: 'XXXXXXXXXXXXXX.atlasv1.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- name: Setup OpenTofu
uses: ./
@@ -162,7 +162,7 @@ jobs:
TF_CLOUD_API_TOKEN: 'XXXXXXXXXXXXXX.atlasv1.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- name: Setup OpenTofu
uses: ./
@@ -190,7 +190,7 @@ jobs:
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- name: Setup OpenTofu
uses: ./
+3
View File
@@ -1,3 +1,6 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm run lint || (npm install && npm run lint)
npm run test
npm audit --audit-level=high
+1 -1
View File
@@ -43,5 +43,5 @@ branding:
icon: 'box'
color: 'yellow'
runs:
using: 'node24'
using: 'node20'
main: 'dist/index.js'
+21075 -19177
View File
File diff suppressed because it is too large. Load diff
+15110 -18066
View File
File diff suppressed because it is too large. Load diff
-3
View File
@@ -1,3 +0,0 @@
{
"type": "module"
}
+3 -4
View File
@@ -1,17 +1,16 @@
/**
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import { setFailed } from '@actions/core';
const core = require('@actions/core');
import setup from './lib/setup-tofu.js';
const setup = require('./lib/setup-tofu');
(async () => {
try {
await setup();
} catch (error) {
setFailed(error.message);
core.setFailed(error.message);
}
})();
+26 -43
View File
@@ -1,30 +1,24 @@
/**
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import { HttpClient, HttpCodes } from '@actions/http-client';
import semver from 'semver';
class Build {
constructor (version, 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 {
constructor (releaseMeta) {
this.version = releaseMeta.id.replace('v', '');
this.builds = releaseMeta.files.map(
(asset) => new Build(this.version, asset)
);
this.builds = releaseMeta.files.map(asset => new Build(this.version, asset));
}
getBuild (platform, arch) {
const requiredName = `tofu_${this.version}_${platform}_${arch}.zip`;
return this.builds.find((build) => build.name === requiredName);
return this.builds.find(build => build.name === requiredName);
}
}
@@ -34,9 +28,10 @@ class Release {
* @return {Array<Release>} Releases.
*/
async function fetchReleases (githubToken) {
const hc = require('@actions/http-client');
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';
@@ -46,34 +41,29 @@ async function fetchReleases (githubToken) {
const resp = await http.get(url, headers);
if (resp.message.statusCode !== HttpCodes.OK) {
throw new Error(
'failed fetching releases (' + resp.message.statusCode + ')'
);
if (resp.message.statusCode !== hc.HttpCodes.OK) {
throw new Error('failed fetching releases (' + resp.message.statusCode + ')');
}
const body = await resp.readBody();
const releasesMeta = JSON.parse(body);
/**
* @type {Array}
*/
* @type {Array}
*/
const versions = releasesMeta.versions;
return versions.map((releaseMeta) => new Release(releaseMeta));
return versions.map(releaseMeta => new Release(releaseMeta));
}
const semver = require('semver');
async function findLatestVersion (versions) {
return versions
.filter((v) => semver.prerelease(v) === null)
.sort((a, b) => semver.rcompare(a, b))[0];
return versions.filter((v) => semver.prerelease(v) === null).sort((a, b) => semver.rcompare(a, b))[0];
}
async function findLatestVersionInRange (versions, range) {
return semver.maxSatisfying(versions, range, {
prerelease: true,
loose: true
});
return semver.maxSatisfying(versions, range, { prerelease: true, loose: true });
}
/**
@@ -84,21 +74,12 @@ async function findLatestVersionInRange (versions, range) {
* @param {function} fetchReleasesFn: Optional function to fetch releases.
* @return {Release} Release.
*/
async function getRelease (
version,
githubToken,
fetchReleasesFn = fetchReleases
) {
async function getRelease (version, githubToken, fetchReleasesFn = fetchReleases) {
const latestVersionLabel = 'latest';
const versionsRange = semver.validRange(version, {
prerelease: true,
loose: true
});
const versionsRange = semver.validRange(version, { prerelease: true, loose: true });
if (versionsRange === null && version !== latestVersionLabel) {
throw new Error(
'Input version cannot be used, see semver: https://semver.org/spec/v2.0.0.html'
);
throw new Error('Input version cannot be used, see semver: https://semver.org/spec/v2.0.0.html');
}
const releases = await fetchReleasesFn(githubToken);
@@ -107,22 +88,24 @@ async function getRelease (
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;
if (version === latestVersionLabel) {
versionSelected = await findLatestVersion(versionsFound);
} else {
versionSelected = await findLatestVersionInRange(
versionsFound,
versionsRange
);
versionSelected = await findLatestVersionInRange(versionsFound, versionsRange);
}
if (versionSelected === null) {
throw new Error('No matching version found');
}
return releases.find((release) => release.version === versionSelected);
return releases.find(release => release.version === versionSelected);
}
export { getRelease, 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
};
+66 -87
View File
@@ -5,26 +5,15 @@
*/
// Node.js core
import { promises as fs } from 'fs';
import { platform, arch } from 'os';
import { sep, resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
const fs = require('fs').promises;
const os = require('os');
const path = require('path');
// External
import {
debug,
error as logError,
exportVariable,
getInput,
warning,
addPath
} from '@actions/core';
import { downloadTool, extractZip, find, cacheDir } from '@actions/tool-cache';
import { mv, cp, mkdirP } from '@actions/io';
import { getRelease } from './releases.js';
// __dirname is not available in ES modules, so we need to construct it ourselves
const __dirname = dirname(fileURLToPath(import.meta.url));
const core = require('@actions/core');
const tc = require('@actions/tool-cache');
const io = require('@actions/io');
const releases = require('./releases');
// arch in [arm, x32, x64...] (https://nodejs.org/api/os.html#os_os_arch)
// return value in [amd64, 386, arm]
@@ -46,8 +35,8 @@ function mapOS (os) {
}
async function downloadAndExtractCLI (url) {
debug(`Downloading OpenTofu CLI from ${url}`);
const pathToCLIZip = await downloadTool(url);
core.debug(`Downloading OpenTofu CLI from ${url}`);
const pathToCLIZip = await tc.downloadTool(url);
if (!pathToCLIZip) {
throw new Error(`Unable to download OpenTofu from ${url}`);
@@ -55,18 +44,18 @@ async function downloadAndExtractCLI (url) {
let pathToCLI;
debug('Extracting OpenTofu CLI zip file');
if (platform().startsWith('win')) {
debug(`OpenTofu CLI Download Path is ${pathToCLIZip}`);
core.debug('Extracting OpenTofu CLI zip file');
if (os.platform().startsWith('win')) {
core.debug(`OpenTofu CLI Download Path is ${pathToCLIZip}`);
const fixedPathToCLIZip = `${pathToCLIZip}.zip`;
await mv(pathToCLIZip, fixedPathToCLIZip);
debug(`Moved download to ${fixedPathToCLIZip}`);
pathToCLI = await extractZip(fixedPathToCLIZip);
await io.mv(pathToCLIZip, fixedPathToCLIZip);
core.debug(`Moved download to ${fixedPathToCLIZip}`);
pathToCLI = await tc.extractZip(fixedPathToCLIZip);
} else {
pathToCLI = await extractZip(pathToCLIZip);
pathToCLI = await tc.extractZip(pathToCLIZip);
}
debug(`OpenTofu CLI path is ${pathToCLI}.`);
core.debug(`OpenTofu CLI path is ${pathToCLI}.`);
if (!pathToCLI) {
throw new Error('Unable to unzip OpenTofu');
@@ -79,34 +68,32 @@ async function installWrapper (pathToCLI) {
let source, target;
// 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)
try {
source = [pathToCLI, `tofu${exeSuffix}`].join(sep);
target = [pathToCLI, `tofu-bin${exeSuffix}`].join(sep);
debug(`Moving ${source} to ${target}.`);
await mv(source, target);
source = [pathToCLI, `tofu${exeSuffix}`].join(path.sep);
target = [pathToCLI, `tofu-bin${exeSuffix}`].join(path.sep);
core.debug(`Moving ${source} to ${target}.`);
await io.mv(source, target);
} catch (e) {
logError(`Unable to move ${source} to ${target}.`);
core.error(`Unable to move ${source} to ${target}.`);
throw e;
}
// Install our wrapper as tofu
try {
source = resolve(
[__dirname, '..', 'wrapper', 'dist', 'index.js'].join(sep)
);
target = [pathToCLI, 'tofu'].join(sep);
debug(`Copying ${source} to ${target}.`);
await cp(source, target);
source = path.resolve([__dirname, '..', 'wrapper', 'dist', 'index.js'].join(path.sep));
target = [pathToCLI, 'tofu'].join(path.sep);
core.debug(`Copying ${source} to ${target}.`);
await io.cp(source, target);
} catch (e) {
logError(`Unable to copy ${source} to ${target}.`);
core.error(`Unable to copy ${source} to ${target}.`);
throw e;
}
// 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
@@ -118,43 +105,37 @@ async function addCredentials (credentialsHostname, credentialsToken, osPlat) {
credentials "${credentialsHostname}" {
token = "${credentialsToken}"
}`.trim();
// eslint-enable
// eslint-enable
// default to OS-specific path
let credsFile =
osPlat === 'win32'
? `${process.env.APPDATA}/tofu.rc`
: `${process.env.HOME}/.tofurc`;
let credsFile = osPlat === 'win32'
? `${process.env.APPDATA}/tofu.rc`
: `${process.env.HOME}/.tofurc`;
// override with TF_CLI_CONFIG_FILE environment variable
credsFile = process.env.TF_CLI_CONFIG_FILE
? process.env.TF_CLI_CONFIG_FILE
: credsFile;
credsFile = process.env.TF_CLI_CONFIG_FILE ? process.env.TF_CLI_CONFIG_FILE : credsFile;
// get containing folder
const credsFolder = dirname(credsFile);
const credsFolder = path.dirname(credsFile);
debug(`Creating ${credsFolder}`);
await mkdirP(credsFolder);
core.debug(`Creating ${credsFolder}`);
await io.mkdirP(credsFolder);
debug(`Adding credentials to ${credsFile}`);
core.debug(`Adding credentials to ${credsFile}`);
await fs.writeFile(credsFile, creds);
}
async function run () {
try {
// Gather GitHub Actions inputs
let version = getInput('tofu_version');
const versionFile = getInput('tofu_version_file');
const credentialsHostname = getInput('cli_config_credentials_hostname');
const credentialsToken = getInput('cli_config_credentials_token');
const wrapper = getInput('tofu_wrapper') === 'true';
const useCache = getInput('cache') === 'true';
let githubToken = getInput('github_token');
if (
githubToken === '' &&
!(process.env.FORGEJO_ACTIONS || process.env.GITEA_ACTIONS)
) {
let version = core.getInput('tofu_version');
const versionFile = core.getInput('tofu_version_file');
const credentialsHostname = core.getInput('cli_config_credentials_hostname');
const credentialsToken = core.getInput('cli_config_credentials_token');
const wrapper = core.getInput('tofu_wrapper') === 'true';
const useCache = core.getInput('cache') === 'true';
let githubToken = core.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
// that may set the GITHUB_TOKEN environment variable.
githubToken = process.env.GITHUB_TOKEN;
@@ -163,51 +144,49 @@ async function run () {
// If tofu_version_file is provided, read the version from the file
if (versionFile) {
try {
debug(`Reading OpenTofu version from file: ${versionFile}`);
core.debug(`Reading OpenTofu version from file: ${versionFile}`);
const fileVersion = await fs.readFile(versionFile, 'utf8');
const trimmedVersion = fileVersion.trim();
if (trimmedVersion) {
version = trimmedVersion;
debug(`Using version from file: ${version}`);
core.debug(`Using version from file: ${version}`);
} else {
warning(
core.warning(
`Version file ${versionFile} is empty, using tofu_version input: ${version}`
);
}
} catch (error) {
warning(
core.warning(
`Failed to read version from file ${versionFile}: ${error.message}. Using tofu_version input: ${version}`
);
}
}
// Gather OS details
const osPlatform = platform();
const osArch = arch();
const osPlatform = os.platform();
const osArch = os.arch();
debug(`Finding releases for OpenTofu version ${version}`);
const release = await getRelease(version, githubToken);
const buildPlatform = mapOS(osPlatform);
const buildArch = mapArch(osArch);
const build = release.getBuild(buildPlatform, buildArch);
core.debug(`Finding releases for OpenTofu version ${version}`);
const release = await releases.getRelease(version, githubToken);
const platform = mapOS(osPlatform);
const arch = mapArch(osArch);
const build = release.getBuild(platform, arch);
if (!build) {
throw new Error(
`OpenTofu version ${version} not available for ${buildPlatform} and ${buildArch}`
);
throw new Error(`OpenTofu version ${version} not available for ${platform} and ${arch}`);
}
// Download requested version if not cached
let pathToCLI;
if (useCache) {
const cachedPath = find('tofu', release.version, buildArch);
const cachedPath = tc.find('tofu', release.version, arch);
if (cachedPath) {
debug(`Using cached OpenTofu version ${release.version} from ${cachedPath}`);
core.debug(`Using cached OpenTofu version ${release.version} from ${cachedPath}`);
pathToCLI = cachedPath;
} else {
debug(`OpenTofu version ${release.version} not found in cache, downloading...`);
core.debug(`OpenTofu version ${release.version} not found in cache, downloading...`);
const extractedPath = await downloadAndExtractCLI(build.url);
debug(`Caching OpenTofu version ${release.version} to tool cache`);
pathToCLI = await cacheDir(extractedPath, 'tofu', release.version, buildArch);
core.debug(`Caching OpenTofu version ${release.version} to tool cache`);
pathToCLI = await tc.cacheDir(extractedPath, 'tofu', release.version, arch);
}
} else {
pathToCLI = await downloadAndExtractCLI(build.url);
@@ -219,7 +198,7 @@ async function run () {
}
// Add to path
addPath(pathToCLI);
core.addPath(pathToCLI);
// Add credentials to file if they are provided
if (credentialsHostname && credentialsToken) {
@@ -227,9 +206,9 @@ async function run () {
}
return release;
} catch (error) {
logError(error);
core.error(error);
throw error;
}
}
export default run;
module.exports = run;
+160 -183
View File
@@ -1,198 +1,175 @@
/**
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import { Release, getRelease } from '../releases.js';
const pkg = require('../releases');
describe('getRelease', () => {
function mockFetchReleases () {
const mockReleasesMeta = [
{
id: 'v1.7.0-alpha2',
files: [
'tofu_1.7.0-alpha2_386.apk',
'tofu_1.7.0-alpha2_386.deb',
'tofu_1.7.0-alpha2_386.rpm',
'tofu_1.7.0-alpha2_amd64.apk',
'tofu_1.7.0-alpha2_amd64.deb',
'tofu_1.7.0-alpha2_amd64.rpm',
'tofu_1.7.0-alpha2_arm.apk',
'tofu_1.7.0-alpha2_arm.deb',
'tofu_1.7.0-alpha2_arm.rpm',
'tofu_1.7.0-alpha2_arm64.apk',
'tofu_1.7.0-alpha2_arm64.deb',
'tofu_1.7.0-alpha2_arm64.rpm',
'tofu_1.7.0-alpha2_darwin_arm64.zip',
'tofu_1.7.0-alpha2_freebsd_386.zip',
'tofu_1.7.0-alpha2_freebsd_amd64.zip',
'tofu_1.7.0-alpha2_freebsd_arm.zip',
'tofu_1.7.0-alpha2_linux_386.zip',
'tofu_1.7.0-alpha2_linux_amd64.zip',
'tofu_1.7.0-alpha2_linux_arm.zip',
'tofu_1.7.0-alpha2_linux_arm64.zip',
'tofu_1.7.0-alpha2_openbsd_386.zip',
'tofu_1.7.0-alpha2_openbsd_amd64.zip',
'tofu_1.7.0-alpha2_SHA256SUMS',
'tofu_1.7.0-alpha2_SHA256SUMS.pem',
'tofu_1.7.0-alpha2_SHA256SUMS.sig',
'tofu_1.7.0-alpha2_solaris_amd64.zip',
'tofu_1.7.0-alpha2_windows_386.zip',
'tofu_1.7.0-alpha2_windows_amd64.zip'
]
},
{
id: 'v1.6.0',
files: [
'tofu_1.6.0_386.apk',
'tofu_1.6.0_386.deb',
'tofu_1.6.0_386.rpm',
'tofu_1.6.0_amd64.apk',
'tofu_1.6.0_amd64.deb',
'tofu_1.6.0_amd64.rpm',
'tofu_1.6.0_arm.apk',
'tofu_1.6.0_arm.deb',
'tofu_1.6.0_arm.rpm',
'tofu_1.6.0_arm64.apk',
'tofu_1.6.0_arm64.deb',
'tofu_1.6.0_arm64.rpm',
'tofu_1.6.0_darwin_arm64.zip',
'tofu_1.6.0_freebsd_386.zip',
'tofu_1.6.0_freebsd_amd64.zip',
'tofu_1.6.0_freebsd_arm.zip',
'tofu_1.6.0_linux_386.zip',
'tofu_1.6.0_linux_amd64.zip',
'tofu_1.6.0_linux_arm.zip',
'tofu_1.6.0_linux_arm64.zip',
'tofu_1.6.0_openbsd_386.zip',
'tofu_1.6.0_openbsd_amd64.zip',
'tofu_1.6.0_SHA256SUMS',
'tofu_1.6.0_SHA256SUMS.pem',
'tofu_1.6.0_SHA256SUMS.sig',
'tofu_1.6.0_solaris_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',
'tofu_1.6.0-alpha2_386.rpm',
'tofu_1.6.0-alpha2_amd64.apk',
'tofu_1.6.0-alpha2_amd64.deb',
'tofu_1.6.0-alpha2_amd64.rpm',
'tofu_1.6.0-alpha2_arm.apk',
'tofu_1.6.0-alpha2_arm.deb',
'tofu_1.6.0-alpha2_arm.rpm',
'tofu_1.6.0-alpha2_arm64.apk',
'tofu_1.6.0-alpha2_arm64.deb',
'tofu_1.6.0-alpha2_arm64.rpm',
'tofu_1.6.0-alpha2_darwin_arm64.zip',
'tofu_1.6.0-alpha2_freebsd_386.zip',
'tofu_1.6.0-alpha2_freebsd_amd64.zip',
'tofu_1.6.0-alpha2_freebsd_arm.zip',
'tofu_1.6.0-alpha2_linux_386.zip',
'tofu_1.6.0-alpha2_linux_amd64.zip',
'tofu_1.6.0-alpha2_linux_arm.zip',
'tofu_1.6.0-alpha2_linux_arm64.zip',
'tofu_1.6.0-alpha2_openbsd_386.zip',
'tofu_1.6.0-alpha2_openbsd_amd64.zip',
'tofu_1.6.0-alpha2_SHA256SUMS',
'tofu_1.6.0-alpha2_SHA256SUMS.pem',
'tofu_1.6.0-alpha2_SHA256SUMS.sig',
'tofu_1.6.0-alpha2_solaris_amd64.zip',
'tofu_1.6.0-alpha2_windows_386.zip',
'tofu_1.6.0-alpha2_windows_amd64.zip'
]
},
{
id: 'v1.6.0-alpha1',
files: [
'tofu_1.6.0-alpha1_386.apk',
'tofu_1.6.0-alpha1_386.deb',
'tofu_1.6.0-alpha1_386.rpm',
'tofu_1.6.0-alpha1_amd64.apk',
'tofu_1.6.0-alpha1_amd64.deb',
'tofu_1.6.0-alpha1_amd64.rpm',
'tofu_1.6.0-alpha1_arm.apk',
'tofu_1.6.0-alpha1_arm.deb',
'tofu_1.6.0-alpha1_arm.rpm',
'tofu_1.6.0-alpha1_arm64.apk',
'tofu_1.6.0-alpha1_arm64.deb',
'tofu_1.6.0-alpha1_arm64.rpm',
'tofu_1.6.0-alpha1_darwin_amd64.zip',
'tofu_1.6.0-alpha1_darwin_arm64.zip',
'tofu_1.6.0-alpha1_freebsd_386.zip',
'tofu_1.6.0-alpha1_freebsd_amd64.zip',
'tofu_1.6.0-alpha1_freebsd_arm.zip',
'tofu_1.6.0-alpha1_linux_386.zip',
'tofu_1.6.0-alpha1_linux_amd64.zip',
'tofu_1.6.0-alpha1_linux_arm.zip',
'tofu_1.6.0-alpha1_linux_arm64.zip',
'tofu_1.6.0-alpha1_openbsd_386.zip',
'tofu_1.6.0-alpha1_openbsd_amd64.zip',
'tofu_1.6.0-alpha1_SHA256SUMS',
'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'
]
}
];
const mockReleasesMeta = [{
id: 'v1.7.0-alpha2',
files: [
'tofu_1.7.0-alpha2_386.apk',
'tofu_1.7.0-alpha2_386.deb',
'tofu_1.7.0-alpha2_386.rpm',
'tofu_1.7.0-alpha2_amd64.apk',
'tofu_1.7.0-alpha2_amd64.deb',
'tofu_1.7.0-alpha2_amd64.rpm',
'tofu_1.7.0-alpha2_arm.apk',
'tofu_1.7.0-alpha2_arm.deb',
'tofu_1.7.0-alpha2_arm.rpm',
'tofu_1.7.0-alpha2_arm64.apk',
'tofu_1.7.0-alpha2_arm64.deb',
'tofu_1.7.0-alpha2_arm64.rpm',
'tofu_1.7.0-alpha2_darwin_arm64.zip',
'tofu_1.7.0-alpha2_freebsd_386.zip',
'tofu_1.7.0-alpha2_freebsd_amd64.zip',
'tofu_1.7.0-alpha2_freebsd_arm.zip',
'tofu_1.7.0-alpha2_linux_386.zip',
'tofu_1.7.0-alpha2_linux_amd64.zip',
'tofu_1.7.0-alpha2_linux_arm.zip',
'tofu_1.7.0-alpha2_linux_arm64.zip',
'tofu_1.7.0-alpha2_openbsd_386.zip',
'tofu_1.7.0-alpha2_openbsd_amd64.zip',
'tofu_1.7.0-alpha2_SHA256SUMS',
'tofu_1.7.0-alpha2_SHA256SUMS.pem',
'tofu_1.7.0-alpha2_SHA256SUMS.sig',
'tofu_1.7.0-alpha2_solaris_amd64.zip',
'tofu_1.7.0-alpha2_windows_386.zip',
'tofu_1.7.0-alpha2_windows_amd64.zip'
]
}, {
id: 'v1.6.0',
files: [
'tofu_1.6.0_386.apk',
'tofu_1.6.0_386.deb',
'tofu_1.6.0_386.rpm',
'tofu_1.6.0_amd64.apk',
'tofu_1.6.0_amd64.deb',
'tofu_1.6.0_amd64.rpm',
'tofu_1.6.0_arm.apk',
'tofu_1.6.0_arm.deb',
'tofu_1.6.0_arm.rpm',
'tofu_1.6.0_arm64.apk',
'tofu_1.6.0_arm64.deb',
'tofu_1.6.0_arm64.rpm',
'tofu_1.6.0_darwin_arm64.zip',
'tofu_1.6.0_freebsd_386.zip',
'tofu_1.6.0_freebsd_amd64.zip',
'tofu_1.6.0_freebsd_arm.zip',
'tofu_1.6.0_linux_386.zip',
'tofu_1.6.0_linux_amd64.zip',
'tofu_1.6.0_linux_arm.zip',
'tofu_1.6.0_linux_arm64.zip',
'tofu_1.6.0_openbsd_386.zip',
'tofu_1.6.0_openbsd_amd64.zip',
'tofu_1.6.0_SHA256SUMS',
'tofu_1.6.0_SHA256SUMS.pem',
'tofu_1.6.0_SHA256SUMS.sig',
'tofu_1.6.0_solaris_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',
'tofu_1.6.0-alpha2_386.rpm',
'tofu_1.6.0-alpha2_amd64.apk',
'tofu_1.6.0-alpha2_amd64.deb',
'tofu_1.6.0-alpha2_amd64.rpm',
'tofu_1.6.0-alpha2_arm.apk',
'tofu_1.6.0-alpha2_arm.deb',
'tofu_1.6.0-alpha2_arm.rpm',
'tofu_1.6.0-alpha2_arm64.apk',
'tofu_1.6.0-alpha2_arm64.deb',
'tofu_1.6.0-alpha2_arm64.rpm',
'tofu_1.6.0-alpha2_darwin_arm64.zip',
'tofu_1.6.0-alpha2_freebsd_386.zip',
'tofu_1.6.0-alpha2_freebsd_amd64.zip',
'tofu_1.6.0-alpha2_freebsd_arm.zip',
'tofu_1.6.0-alpha2_linux_386.zip',
'tofu_1.6.0-alpha2_linux_amd64.zip',
'tofu_1.6.0-alpha2_linux_arm.zip',
'tofu_1.6.0-alpha2_linux_arm64.zip',
'tofu_1.6.0-alpha2_openbsd_386.zip',
'tofu_1.6.0-alpha2_openbsd_amd64.zip',
'tofu_1.6.0-alpha2_SHA256SUMS',
'tofu_1.6.0-alpha2_SHA256SUMS.pem',
'tofu_1.6.0-alpha2_SHA256SUMS.sig',
'tofu_1.6.0-alpha2_solaris_amd64.zip',
'tofu_1.6.0-alpha2_windows_386.zip',
'tofu_1.6.0-alpha2_windows_amd64.zip'
]
}, {
id: 'v1.6.0-alpha1',
files: [
'tofu_1.6.0-alpha1_386.apk',
'tofu_1.6.0-alpha1_386.deb',
'tofu_1.6.0-alpha1_386.rpm',
'tofu_1.6.0-alpha1_amd64.apk',
'tofu_1.6.0-alpha1_amd64.deb',
'tofu_1.6.0-alpha1_amd64.rpm',
'tofu_1.6.0-alpha1_arm.apk',
'tofu_1.6.0-alpha1_arm.deb',
'tofu_1.6.0-alpha1_arm.rpm',
'tofu_1.6.0-alpha1_arm64.apk',
'tofu_1.6.0-alpha1_arm64.deb',
'tofu_1.6.0-alpha1_arm64.rpm',
'tofu_1.6.0-alpha1_darwin_amd64.zip',
'tofu_1.6.0-alpha1_darwin_arm64.zip',
'tofu_1.6.0-alpha1_freebsd_386.zip',
'tofu_1.6.0-alpha1_freebsd_amd64.zip',
'tofu_1.6.0-alpha1_freebsd_arm.zip',
'tofu_1.6.0-alpha1_linux_386.zip',
'tofu_1.6.0-alpha1_linux_amd64.zip',
'tofu_1.6.0-alpha1_linux_arm.zip',
'tofu_1.6.0-alpha1_linux_arm64.zip',
'tofu_1.6.0-alpha1_openbsd_386.zip',
'tofu_1.6.0-alpha1_openbsd_amd64.zip',
'tofu_1.6.0-alpha1_SHA256SUMS',
'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([
['latest', '1.6.0'],
['<1.6.0-beta', '1.6.0-alpha2'],
['>1.6.0-alpha1', '1.6.0'],
['>1.6.0-alpha1 <1.6.0', '1.6.0-alpha2'],
['~1.6.0-alpha', '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']
])("happy path: getRelease('%s') -> '%s'", async (input, wantVersion) => {
const want = mockFetchReleases().find((el) => el.version === wantVersion);
const gotRelease = await getRelease(input, '', mockFetchReleases);
it.each(
[
['latest', '1.6.0'],
['<1.6.0-beta', '1.6.0-alpha2'],
['>1.6.0-alpha1', '1.6.0'],
['>1.6.0-alpha1 <1.6.0', '1.6.0-alpha2'],
['~1.6.0-alpha', '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']
]
)('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);
});
it.each([
it.each(
[
'foo',
'Input version cannot be used, see semver: https://semver.org/spec/v2.0.0.html',
mockFetchReleases
],
['2.0', 'No matching version found', mockFetchReleases],
[
'latest',
'No tofu releases found, please contact OpenTofu',
async () => {
['foo', 'Input version cannot be used, see semver: https://semver.org/spec/v2.0.0.html', mockFetchReleases],
['2.0', 'No matching version found', mockFetchReleases],
['latest', 'No tofu releases found, please contact OpenTofu', async () => {
return null;
}
],
[
'latest',
'No tofu releases found, please contact OpenTofu',
async () => {
}],
['latest', 'No tofu releases found, please contact OpenTofu', async () => {
return [];
}
}]
]
])(
"unhappy path: getRelease('%s') -> throw Error('%s')",
async (input, wantErrorMessage, mockFetchReleasesFn) => {
try {
await getRelease(input, '', mockFetchReleasesFn);
expect(true).toBe(false);
} catch (e) {
expect(e.message).toBe(wantErrorMessage);
}
)('unhappy path: getRelease(\'%s\') -> throw Error(\'%s\')', async (input, wantErrorMessage, mockFetchReleasesFn) => {
try {
await pkg.getRelease(input, '', mockFetchReleasesFn);
expect(true).toBe(false);
} catch (e) {
expect(e.message).toBe(wantErrorMessage);
}
);
});
});
+43 -65
View File
@@ -1,52 +1,31 @@
/**
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import { jest } from '@jest/globals';
// Node.js core
import { promises as fs } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
const fs = require('fs').promises;
const os = require('os');
const path = require('path');
// Set up mocks BEFORE dynamic imports
jest.unstable_mockModule('@actions/core', () => ({
getInput: jest.fn(),
setOutput: jest.fn(),
setFailed: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
warning: jest.fn(),
addPath: jest.fn(),
exportVariable: jest.fn()
}));
// External
const core = require('@actions/core');
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(),
cp: jest.fn(),
mkdirP: jest.fn()
}));
jest.unstable_mockModule('@actions/tool-cache', () => ({
jest.mock('@actions/tool-cache', () => ({
downloadTool: jest.fn(),
extractZip: jest.fn(),
find: jest.fn(),
cacheDir: jest.fn()
}));
jest.unstable_mockModule('../releases.js', () => ({
getRelease: jest.fn(),
Release: jest.fn()
}));
// Dynamic imports pick up the mocks
const { getInput, warning } = await import('@actions/core');
const tc = await import('@actions/tool-cache');
const io = await import('@actions/io');
const { getRelease } = await import('../releases.js');
const { default: setup } = await import('../setup-tofu.js');
// Mock releases.js so setup-tofu.js can be tested in isolation
jest.mock('../releases');
// Set up global test fixtures
const fallbackVersion = 'latest';
@@ -59,11 +38,13 @@ let versionFileName = '.opentofu-version';
describe('setup-tofu', () => {
beforeAll(async () => {
// Mock dependencies
const tc = require('@actions/tool-cache');
tc.downloadTool.mockResolvedValue('/mock/download/path');
tc.extractZip.mockResolvedValue('/mock/extract/path');
tc.find.mockReturnValue(null); // Default to cache miss
tc.cacheDir.mockResolvedValue('/mock/cached/path');
const io = require('@actions/io');
io.mv.mockResolvedValue();
io.cp.mockResolvedValue();
io.mkdirP.mockResolvedValue();
@@ -72,16 +53,16 @@ describe('setup-tofu', () => {
version: '1.10.5',
getBuild: jest.fn().mockReturnValue({ url: 'mock-url' })
};
getRelease.mockResolvedValue(mockRelease);
releases.getRelease.mockResolvedValue(mockRelease);
// Write version file to temporary directory
tempDirPath = join(tmpdir(), 'setup-tofu-');
tempDirPath = path.join(os.tmpdir(), 'setup-tofu-');
tempDir = await fs.mkdtemp(tempDirPath);
versionFile = join(tempDir, versionFileName);
versionFile = path.join(tempDir, versionFileName);
await fs.writeFile(versionFile, `${version}\n`);
// Mock action inputs to return default values
getInput.mockImplementation((name) => {
core.getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: versionFile,
@@ -112,9 +93,8 @@ describe('setup-tofu', () => {
await setup();
expect(getRelease).toHaveBeenCalledWith(
version,
process.env.GITHUB_TOKEN
expect(releases.getRelease).toHaveBeenCalledWith(
version, process.env.GITHUB_TOKEN
);
expect(fs.readFile).toHaveBeenCalled();
@@ -125,10 +105,10 @@ describe('setup-tofu', () => {
version = ' ';
versionFileName = '.opentofu-version-empty';
versionFile = join(tempDir, versionFileName);
versionFile = path.join(tempDir, versionFileName);
await fs.writeFile(versionFile, `${version}\n`);
getInput.mockImplementation((name) => {
core.getInput.mockImplementation((name) => {
if (name === 'tofu_version_file') {
return versionFile;
}
@@ -140,12 +120,11 @@ describe('setup-tofu', () => {
await setup();
expect(getRelease).toHaveBeenCalledWith(
fallbackVersion,
process.env.GITHUB_TOKEN
expect(releases.getRelease).toHaveBeenCalledWith(
fallbackVersion, process.env.GITHUB_TOKEN
);
expect(warning).toHaveBeenCalledWith(
expect(core.warning).toHaveBeenCalledWith(
expect.stringContaining(`Version file ${versionFile} is empty`)
);
@@ -156,9 +135,9 @@ describe('setup-tofu', () => {
jest.spyOn(fs, 'readFile');
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') {
return versionFile;
}
@@ -170,15 +149,12 @@ describe('setup-tofu', () => {
await setup();
expect(getRelease).toHaveBeenCalledWith(
fallbackVersion,
process.env.GITHUB_TOKEN
expect(releases.getRelease).toHaveBeenCalledWith(
fallbackVersion, process.env.GITHUB_TOKEN
);
expect(warning).toHaveBeenCalledWith(
expect.stringContaining(
`Failed to read version from file ${versionFile}`
)
expect(core.warning).toHaveBeenCalledWith(
expect.stringContaining(`Failed to read version from file ${versionFile}`)
);
expect(fs.readFile).toHaveBeenCalled();
@@ -187,7 +163,7 @@ describe('setup-tofu', () => {
it('should not read file when tofu_version_file is not provided', async () => {
jest.spyOn(fs, 'readFile');
getInput.mockImplementation((name) => {
core.getInput.mockImplementation((name) => {
if (name === 'tofu_version') {
return fallbackVersion;
}
@@ -196,9 +172,8 @@ describe('setup-tofu', () => {
await setup();
expect(getRelease).toHaveBeenCalledWith(
fallbackVersion,
process.env.GITHUB_TOKEN
expect(releases.getRelease).toHaveBeenCalledWith(
fallbackVersion, process.env.GITHUB_TOKEN
);
expect(fs.readFile).not.toHaveBeenCalled();
@@ -207,9 +182,10 @@ describe('setup-tofu', () => {
describe('caching functionality', () => {
it('should use cached version when cache is enabled and found', async () => {
const tc = require('@actions/tool-cache');
tc.find.mockReturnValue('/mock/cached/path');
getInput.mockImplementation((name) => {
core.getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
@@ -231,9 +207,10 @@ describe('setup-tofu', () => {
});
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
getInput.mockImplementation((name) => {
core.getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
@@ -255,9 +232,10 @@ describe('setup-tofu', () => {
});
it('should not use cache when cache is disabled', async () => {
const tc = require('@actions/tool-cache');
tc.find.mockReturnValue('/mock/cached/path');
getInput.mockImplementation((name) => {
core.getInput.mockImplementation((name) => {
const defaults = {
tofu_version: fallbackVersion,
tofu_version_file: '',
+7191 -7082
View File
File diff suppressed because it is too large. Load diff
+37 -39
View File
@@ -1,41 +1,39 @@
{
"name": "setup-opentofu",
"version": "1.0.1",
"description": "Setup OpenTofu CLI for GitHub Actions",
"type": "module",
"license": "MPL-2.0",
"publisher": "OpenTofu",
"main": "index.js",
"repository": {
"type": "git",
"url": "https://github.com/opentofu/setup-opentofu.git"
},
"scripts": {
"test": "semistandard --env jest && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --coverage",
"lint": "semistandard --env jest --fix",
"build": "ncc build wrapper/tofu.js --out wrapper/dist && ncc build index.js --out dist",
"prepare": "husky install",
"format-check": "echo \"unimplemented for actions/reusable-workflows basic-validation\""
},
"keywords": [],
"author": "",
"dependencies": {
"@actions/core": "^3.0.0",
"@actions/exec": "^3.0.0",
"@actions/http-client": "^4.0.0",
"@actions/io": "^3.0.2",
"@actions/tool-cache": "^4.0.0",
"semver": "^7.7.4"
},
"devDependencies": {
"@vercel/ncc": "0.38.4",
"husky": "9.1.7",
"jest": "^30.3.0",
"semistandard": "17.0.0"
},
"semistandard": {
"ignore": [
"**/dist/**"
]
}
"name": "setup-opentofu",
"version": "1.0.1",
"description": "Setup OpenTofu CLI for GitHub Actions",
"license": "MPL-2.0",
"publisher": "OpenTofu",
"main": "index.js",
"repository": {
"type": "git",
"url": "https://github.com/opentofu/setup-opentofu.git"
},
"scripts": {
"test": "semistandard --env jest && jest --coverage",
"lint": "semistandard --env jest --fix",
"build": "ncc build wrapper/tofu.js --out wrapper/dist && ncc build index.js --out dist",
"prepare": "husky install",
"format-check": "echo \"unimplemented for actions/reusable-workflows basic-validation\""
},
"keywords": [],
"author": "",
"dependencies": {
"@actions/core": "2.0.2",
"@actions/exec": "2.0.0",
"@actions/io": "2.0.0",
"@actions/tool-cache": "2.0.2",
"semver": "7.7.3"
},
"devDependencies": {
"@vercel/ncc": "0.38.4",
"husky": "9.1.7",
"jest": "30.2.0",
"semistandard": "17.0.0"
},
"semistandard": {
"ignore": [
"**/dist/**"
]
}
}
+6 -3
View File
@@ -1,6 +1,5 @@
/**
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
@@ -21,7 +20,7 @@
* // Log out STDOUT contents
* console.log(listener.contents);
*/
export default class OutputListener {
class OutputListener {
constructor (stream) {
this._buff = [];
this._stream = stream;
@@ -36,6 +35,10 @@ export default class OutputListener {
}
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) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import os from 'os';
import path from 'path';
const os = require('os');
const path = require('path');
const tofuBin = (() => {
module.exports = (() => {
// If we're on Windows, then the executable ends with .exe
const exeSuffix = os.platform().startsWith('win') ? '.exe' : '';
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) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import OutputListener from '../lib/output-listener.js';
import { PassThrough } from 'stream';
const OutputListener = require('../lib/output-listener');
const { PassThrough } = require('stream');
describe('output-listener', () => {
it('receives and exposes data', () => {
const stream = new PassThrough();
+28 -21
View File
@@ -1,21 +1,20 @@
#!/usr/bin/env node
/**
* Copyright (c) HashiCorp, Inc.
* Copyright (c) OpenTofu
* SPDX-License-Identifier: MPL-2.0
*/
import { which } from '@actions/io';
import { setOutput, setFailed } from '@actions/core';
import { exec } from '@actions/exec';
const io = require('@actions/io');
const core = require('@actions/core');
const { spawn } = require('child_process');
import OutputListener from './lib/output-listener.js';
import pathToCLI from './lib/tofu-bin.js';
const OutputListener = require('./lib/output-listener');
const pathToCLI = require('./lib/tofu-bin');
async function checkTofu () {
// Setting check to `true` will cause `which` to throw if tofu isn't found
const check = true;
return which(pathToCLI, check);
return io.which(pathToCLI, check);
}
(async () => {
@@ -25,24 +24,32 @@ async function checkTofu () {
// Create listeners to receive output (in memory) as well
const stdout = new OutputListener(process.stdout);
const stderr = new OutputListener(process.stderr);
const listeners = {
stdout: stdout.listener,
stderr: stderr.listener
};
// Execute tofu and capture output
const args = process.argv.slice(2);
const options = {
listeners,
ignoreReturnCode: true,
silent: true // don't print "[command...]" into stdout: https://github.com/actions/toolkit/issues/649
};
const exitCode = await exec(pathToCLI, args, options);
const child = spawn(pathToCLI, args, { stdio: ['inherit', 'pipe', 'pipe'] });
// Forward signals to child so tofu can release state locks on cancellation
const forwardSigterm = () => { child.kill('SIGTERM'); };
const forwardSigint = () => { child.kill('SIGINT'); };
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
setOutput('stdout', stdout.contents);
setOutput('stderr', stderr.contents);
setOutput('exitcode', exitCode.toString(10));
core.setOutput('stdout', stdout.contents);
core.setOutput('stderr', stderr.contents);
core.setOutput('exitcode', exitCode.toString(10));
if (exitCode === 0 || exitCode === 2) {
// A exitCode of 0 is considered a success
@@ -53,5 +60,5 @@ async function checkTofu () {
}
// A non-zero exitCode is considered an error
setFailed(`OpenTofu exited with code ${exitCode}.`);
core.setFailed(`OpenTofu exited with code ${exitCode}.`);
})();