12 Commits

Author SHA1 Message Date
120b16b56e Update: Eliminated minor formatting issues.
All checks were successful
Test Action / test (push) Successful in 3s
2026-01-11 14:03:36 +01:00
4ee62009bb Fix: Windows decompression and installation paths. 2026-01-11 14:03:10 +01:00
b20a066030 Added test workflow for Github. 2026-01-11 11:38:24 +01:00
c8669a3a66 Update: Add 'install-path' option for custom installation directory in CLI and documentation
All checks were successful
Test Action / test (push) Successful in 3s
2026-01-11 11:12:06 +01:00
66bc2b3acd Update: Refactor trigger events in test workflow to specify push conditions and paths
All checks were successful
Test Action / test (push) Successful in 3s
2026-01-11 11:04:29 +01:00
41c3945650 Fix: Updated README to include correct CLI installation procedure.
All checks were successful
Test Action / test (push) Successful in 5s
2026-01-11 11:02:44 +01:00
620da93338 Rearranged the code and added CLI that installs tools locally.
All checks were successful
Test Action / test (push) Successful in 3s
2026-01-11 10:54:25 +01:00
ef971a6da4 Update: Added option update-cache, and changed default action behavior to always use cached version without checking for a new one.
All checks were successful
Test Action / test (push) Successful in 3s
2026-01-11 08:05:18 +01:00
03b8e6fa3b Update: Renmaed input repo-name to repository.
All checks were successful
Test Action / test (push) Successful in 5s
2026-01-11 07:37:07 +01:00
a6029b9169 Update: Revise README to clarify usage and enhance examples for GitHub Release Action
All checks were successful
Test Action / test (push) Successful in 5s
2026-01-11 02:23:41 +01:00
a397455fd8 Update: Enhance verification output for installed tools in test workflow
All checks were successful
Test Action / test (push) Successful in 6s
2026-01-11 01:55:22 +01:00
15d244166d Update: Add Go ACME setup step to test workflow
All checks were successful
Test Action / test (push) Successful in 7s
2026-01-11 01:52:55 +01:00
15 changed files with 747 additions and 201 deletions

View File

@@ -1,5 +1,15 @@
name: Test Action
on: [push, workflow_dispatch]
on:
push:
branches:
- main
paths:
- '.gitea/workflows/test.yml'
- 'action.yml'
- 'src/**'
- 'dist/**'
- 'package.json'
- 'package-lock.json'
jobs:
test:
@@ -8,20 +18,31 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
- name: Go ACME Setup
uses: ./
with:
repository: 'go-acme/lego'
token: ${{ secrets.GH_TOKEN }}
- name: Setup Hugo
uses: ./
with:
repo-name: 'gohugoio/hugo'
repository: 'gohugoio/hugo'
file-name: '~hugo_extended_[^a-z]'
token: ${{ secrets.GH_TOKEN }}
- name: Setup RClone
uses: ./
with:
repo-name: 'rclone/rclone'
repository: 'rclone/rclone'
token: ${{ secrets.GH_TOKEN }}
- name: Verify Installation
run: |
echo "Verifying installed tools..."
printf "\nGo ACME Lego:\n"
lego -v
printf "\nHugo:\n"
hugo version
printf "\nRClone:\n"
rclone version

45
.github/workflows/test.yml vendored Normal file
View File

@@ -0,0 +1,45 @@
name: Test Action
on:
push:
branches:
- main
paths:
- '.github/workflows/test.yml'
- 'action.yml'
- 'src/**'
- 'dist/**'
- 'package.json'
- 'package-lock.json'
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Go ACME Setup
uses: skoszewski/setup-github-release@v1
with:
repository: 'go-acme/lego'
- name: Setup Hugo
uses: skoszewski/setup-github-release@v1
with:
repository: 'gohugoio/hugo'
file-name: '~hugo_extended_[^a-z]'
- name: Setup RClone
uses: skoszewski/setup-github-release@v1
with:
repository: 'rclone/rclone'
- name: Verify Installation
run: |
echo "Verifying installed tools..."
printf "\nGo ACME Lego:\n"
lego -v
printf "\nHugo:\n"
hugo version
printf "\nRClone:\n"
rclone version

2
.gitignore vendored
View File

@@ -3,4 +3,4 @@ lib/
*.log
*.map
.DS_Store
Notes.md
.github/*.md

192
README.md
View File

@@ -1,37 +1,193 @@
# Setup GitHub Release Action
This GitHub/Gitea Action downloads a tool from a GitHub release based on platform-aware selection rules and adds it to the system PATH.
This project implements a GitHub Action (`setup-github-release`) and a CLI tool (`install-github-release`) that downloads a release asset from a specified GitHub repository, extracts it, searches for a binary within the extracted files, and prepares the runtime environment.
## Installation / Setup
### GitHub/Gitea Action
Add the action to your workflow. Authenticate with `github.token` (default) or a custom token for Gitea/private repos.
```yaml
- name: Install Tool
uses: koszewscy/setup-github-release@v1
with:
repository: 'owner/repo'
```
### CLI Tool
Install the CLI tool on any destination system with Node.js 24 or newer.
**From Source:**
1. Clone the repository:
```bash
git clone https://github.com/koszewscy/setup-github-release
cd setup-github-release
```
2. Install dependencies and build the project:
```bash
npm install
npm run build
```
3. Install the tool locally:
```bash
npm install -g .
```
After installation, the tool will be available as `install-github-release`. By default, it installs binaries to:
- Linux/macOS (root): `/usr/local/bin`
- Linux/macOS (user): `~/bin` (if exists) or `/usr/local/bin`
- Windows: `%LOCALAPPDATA%\bin`
```bash
install-github-release rclone/rclone
```
## Features
- **Automatic Platform Detection**: Detects OS and Architecture to find the right asset.
- **Recursive Binary Search**: Finds the executable even if it's nested deep inside an archive.
- **Tool Caching**: Uses the standard runner tool cache to speed up subsequent runs.
- **Flexible Matching**: Supports literal names, regex patterns, and custom file types.
## Usage
### Simple (Automatic Selection)
The action will automatically detect your OS and ARCH and look for a matching archive.
The action will automatically detect your OS (Linux, Windows, macOS) and architecture (x64, ARM64) and look for a matching archive. It will search for a binary named after the repository.
```yaml
- uses: ./
- name: Install Hugo
uses: koszewscy/setup-github-release@v1
with:
repo-name: 'gohugoio/hugo'
repository: 'go-acme/lego'
```
### Regex Search
You can use a regex pattern (prefixed with `~`) to narrow down the asset.
> **Note:** RClone is an example of a project that provides a binary in a subdirectory inside the archive. The action will find it automatically.
### Advanced Asset Selection
For projects with multiple binary versions, you can use a regex pattern (prefixed with `~`) to narrow down the asset. Hugo is an example where you have to choose between one of the three versions: standard, extended, or extended with deploy support.
```yaml
- uses: ./
- name: Install Extended Hugo
uses: koszewscy/setup-github-release@v1
with:
repo-name: 'gohugoio/hugo'
file-name: '~hugo_extended'
repository: 'gohugoio/hugo'
file-name: '~hugo_extended_[^a-z]' # Regex to match extended version
```
### Custom File Type
### Specific Binary Finding
If the binary name is different from the repository name, like in the example of GitHub CLI, you can specify the `binary-name` input to locate the correct executable inside the downloaded asset:
```yaml
- uses: ./
- name: Install GitHub CLI
uses: koszewscy/setup-github-release@v1
with:
repo-name: 'some/repo'
file-type: 'package' # Matches .deb, .rpm, .pkg
repository: 'cli/cli'
binary-name: 'gh' # Searches for 'gh' (or 'gh.exe') inside the extracted release
```
## Inputs
### Debugging Archive Content
If you are unsure how the binary is named, use the `debug` flag to list all files in the unpacked asset, or download the asset manually to inspect its structure.
```yaml
- uses: koszewscy/setup-github-release@v1
with:
repository: 'owner/repo'
debug: true
```
## Inputs / Options
The following inputs are available for the GitHub Action, and as options for the CLI tool:
- `repository` (required): The GitHub repository in the format `owner/repo` from which to download the release.
- `file-name` (optional): The name or the regex pattern (prefixed with `~`) of the asset file to download from the release.
- `binary-name` (optional): The name or regex pattern (prefixed with `~`) of the binary to search for within the downloaded asset. Defaults to the repository name.
- `file-type` (optional, default: 'archive'): The regex pattern to identify the type of the file to be downloaded. There are two predefined keywords:
- 'archive': matches common archive file extensions like .zip, .tar.gz, .tar, .tgz, .7z.
- 'package': matches common package file extensions like .deb, .rpm, .pkg.
- or a custom regex pattern can be provided to match specific file types.
- `install-path` (optional, CLI only): Custom installation directory for the CLI tool.
- `update-cache` (optional, default: 'false', Action only): When set to 'false', the action will use the cached version of the tool if it is already available. If set to 'true', the action will check the latest release and update the cache if a newer version is found. If set to 'always', it will always download and install, updating the cache regardless.
- `debug` (optional, default: 'false'): When set to `true`, the action will log the contents of the unpacked directory to the console.
- `token` (optional): A GitHub token for authentication, useful for accessing private repositories or increasing rate limits.
> **Important:** Default authentication will only work if the action is used within GitHub workflow. For Gitea or the CLI, you must provide a token explicitly (e.g. `GITHUB_TOKEN` environment variable).
## CLI Usage
The `install-github-release` tool follows the same logic as the Action.
```bash
Usage: install-github-release [options] <repository>
Arguments:
repository The GitHub repository (owner/repo)
Options:
-f, --file-name <name> Asset file name or regex pattern (prefixed with ~)
-b, --binary-name <name> Binary to search for (prefixed with ~ for regex)
-t, --file-type <type> 'archive', 'package', or custom regex (default: archive)
-p, --install-path <path> Custom installation directory
-k, --token <token> GitHub token
-d, --debug Enable debug logging
-h, --help Show this help message
```
## Asset Selection Procedure
The list of assets from the latest release is filtered based on the following rules:
1. If neither `file-name` nor `file-type` is provided, the tool defaults to selecting assets that match the following regular expression: `{{SYSTEM}}[_-]{{ARCH}}.*{{EXT_PATTERN}}$`, where:
- `{{SYSTEM}}` is replaced with the detected operating system regex.
- `{{ARCH}}` is replaced with the detected architecture regex.
- `{{EXT_PATTERN}}` is a regex pattern defined by the `file-type` input (defaulting to 'archive' if not specified).
2. If `file-name` is provided literally, the tool uses it directly to match the asset name by using exact string comparison.
3. If `file-name` is provided as a regex pattern (prefixed with `~`), then:
- If the pattern does not end with `$` and does not include any placeholders, the tool appends `.*{{SYSTEM}}[_-]{{ARCH}}.*{{EXT_PATTERN}}$` to the provided pattern.
- If it already ends with `$` or includes all three placeholders, the tool uses it as-is to match the asset name using regex.
- If only `{{SYSTEM}}` and `{{ARCH}}` placeholders are included, the tool appends `.*{{EXT_PATTERN}}$`.
4. If `file-type` is not equal to 'archive' or 'package', it is treated as a custom regex pattern to match the file extension.
5. The tool applies the constructed regex pattern to filter the assets from the latest release.
6. If multiple assets match the criteria, the tool fails.
7. After download and extraction, the tool recursively searches for the binary specified by `binary-name` (or the repository name). If found, the directory containing the binary is used as the tool directory and added to the PATH (or used for installation). If the binary is not found, the tool fails.
8. `{{SYSTEM}}` is replaced with the detected operating system regex:
- For Linux: `linux`.
- For MacOS: `(darwin|macos|mac|osx)`.
- For Windows: `(windows|win)`.
9. `{{ARCH}}` is replaced with the detected architecture regex:
- For x64: `(x86_64|x64|amd64)`.
- For arm64: `(aarch64|arm64)`.
10. All regular expression matches are case-insensitive.
## License
MIT
- `repo-name` (required): GitHub repository in `owner/repo` format.
- `file-name` (optional): Literal name or regex pattern (if starts with `~`) to match the asset.
- `file-type` (optional, default: `archive`): Predefined keywords `archive`, `package`, or a custom regex extension pattern.
- `token` (optional): GitHub token for authentication.

View File

@@ -2,7 +2,7 @@ name: 'setup-github-release'
description: 'Install a tool from a GitHub release and add it to the PATH'
author: 'Slawomir Koszewski with GitHub Copilot assistance'
inputs:
repo-name:
repository:
description: 'The GitHub repository name (e.g., owner/repo)'
required: true
file-name:
@@ -15,6 +15,10 @@ inputs:
description: 'The type of the file to be downloaded (archive, package, or custom regex).'
required: false
default: 'archive'
update-cache:
description: 'How to handle the tool cache (false, true, or always). Defaults to false.'
required: false
default: 'false'
debug:
description: 'When set to true, displays the contents of the unpacked archive or directory.'
required: false

16
dist/cli.js vendored Executable file
View File

@@ -0,0 +1,16 @@
#!/usr/bin/env node
"use strict";var O=Object.create;var z=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var D=Object.getPrototypeOf,X=Object.prototype.hasOwnProperty;var Y=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of U(e))!X.call(t,s)&&s!==i&&z(t,s,{get:()=>e[s],enumerable:!(r=H(e,s))||r.enumerable});return t};var p=(t,e,i)=>(i=t!=null?O(D(t)):{},Y(e||!t||!t.__esModule?z(i,"default",{value:t,enumerable:!0}):i,t));var F=require("util"),f=p(require("path")),l=p(require("fs")),P=p(require("os"));var T=p(require("os")),G={linux:"linux",darwin:"(darwin|macos|mac|osx)",win32:"(windows|win)"},q={x64:"(x86_64|x64|amd64)",arm64:"(aarch64|arm64)"};function M(){let t=T.platform(),e=T.arch();return{system:t,arch:e,systemPattern:G[t]||t,archPattern:q[e]||e}}function j(t,e,i){let{fileName:r,fileType:s="archive"}=i,o;if(s==="archive"?o="\\.(zip|tar\\.gz|tar|tgz|7z)":s==="package"?o="\\.(deb|rpm|pkg)":o=s,r)if(r.startsWith("~")){let a=r.substring(1),c=a.includes("{{SYSTEM}}"),n=a.includes("{{ARCH}}"),m=a.includes("{{EXT_PATTERN}}"),S=a.endsWith("$");!c&&!n&&!m&&!S?a+=".*{{SYSTEM}}[_-]{{ARCH}}.*{{EXT_PATTERN}}$":c&&n&&!m&&!S&&(a+=".*{{EXT_PATTERN}}$");let h=a.replace(/{{SYSTEM}}/g,e.systemPattern).replace(/{{ARCH}}/g,e.archPattern).replace(/{{EXT_PATTERN}}/g,o),b=new RegExp(h,"i"),u=t.filter(w=>b.test(w.name));if(u.length===0)throw new Error(`No assets matched the regex: ${h}`);if(u.length>1)throw new Error(`Multiple assets matched the criteria: ${u.map(w=>w.name).join(", ")}`);return u[0]}else{let a=t.find(c=>c.name===r);if(!a)throw new Error(`No asset found matching the exact name: ${r}`);return a}else{let a=`${e.systemPattern}[_-]${e.archPattern}.*${o}$`,c=new RegExp(a,"i"),n=t.filter(m=>c.test(m.name));if(n.length===0)throw new Error(`No assets matched the default criteria: ${a}`);if(n.length>1)throw new Error(`Multiple assets matched the default criteria: ${n.map(m=>m.name).join(", ")}`);return n[0]}}var A=p(require("fs")),_=p(require("path"));function I(t,e,i,r){let s=A.readdirSync(t);i&&(r(`Searching for binary in ${t}...`),s.forEach(o=>r(` - ${o}`)));for(let o of s){let a=_.join(t,o);if(A.statSync(a).isDirectory()){let n=I(a,e,i,r);if(n)return n}else{let n=!1;if(e instanceof RegExp?n=e.test(o):(n=o===e,!n&&process.platform==="win32"&&!e.toLowerCase().endsWith(".exe")&&(n=o.toLowerCase()===`${e.toLowerCase()}.exe`)),n)return a}}}async function W(t,e){let i=`https://api.github.com/repos/${t}/releases/latest`,r={Accept:"application/vnd.github.v3+json","User-Agent":"setup-github-release-action"};e&&(r.Authorization=`token ${e}`);let s=await fetch(i,{headers:r});if(!s.ok){let o=await s.text();throw new Error(`Failed to fetch latest release for ${t}: ${s.statusText}. ${o}`)}return await s.json()}async function L(t,e,i){let r={"User-Agent":"setup-github-release-action"};i&&(r.Authorization=`token ${i}`);let s=await fetch(t,{headers:r});if(!s.ok)throw new Error(`Failed to download asset: ${s.statusText}`);let o=await import("fs"),{Readable:a}=await import("stream"),{finished:c}=await import("stream/promises"),n=o.createWriteStream(e);await c(a.fromWeb(s.body).pipe(n))}var x=require("child_process"),y=p(require("path")),E=p(require("fs"));async function B(t,e){let i=y.extname(t).toLowerCase(),r=y.basename(t).toLowerCase();if(E.existsSync(e)||E.mkdirSync(e,{recursive:!0}),r.endsWith(".tar.gz")||r.endsWith(".tgz")||r.endsWith(".tar")){let o=(0,x.spawnSync)("tar",["-xf",t,"-C",e]);if(o.status!==0)throw new Error(`tar failed with status ${o.status}: ${o.stderr.toString()}`)}else if(r.endsWith(".zip"))if(process.platform==="win32"){if((0,x.spawnSync)("tar",["-xf",t,"-C",e]).status===0)return;let o=t.replace(/'/g,"''"),a=e.replace(/'/g,"''"),c=`Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory('${o}', '${a}')`;for(let n of["pwsh","powershell"])if((0,x.spawnSync)(n,["-NoProfile","-ExecutionPolicy","Bypass","-Command",c]).status===0)return;throw new Error("Extraction failed: Both tar and PowerShell fallback failed. Make sure your system can extract ZIP files.")}else{let s=(0,x.spawnSync)("unzip",["-q",t,"-d",e]);if(s.status!==0)throw new Error(`unzip failed with status ${s.status}: ${s.stderr.toString()}`)}else if(r.endsWith(".7z")){let s=(0,x.spawnSync)("7z",["x",t,`-o${e}`,"-y"]);if(s.status!==0)throw new Error(`7z failed with status ${s.status}. Make sure 7z is installed.`)}else{let s=y.join(e,y.basename(t));E.copyFileSync(t,s)}}async function Z(){let{values:t,positionals:e}=(0,F.parseArgs)({options:{"file-name":{type:"string",short:"f"},"binary-name":{type:"string",short:"b"},"file-type":{type:"string",short:"t",default:"archive"},"install-path":{type:"string",short:"p"},token:{type:"string",short:"k"},debug:{type:"boolean",short:"d",default:!1},help:{type:"boolean",short:"h"}},allowPositionals:!0});(t.help||e.length===0)&&(console.log(`
Usage: install-github-release [options] <repository>
Arguments:
repository The GitHub repository (owner/repo)
Options:
-f, --file-name <name> Asset file name or regex pattern (prefixed with ~)
-b, --binary-name <name> Binary to search for (prefixed with ~ for regex)
-t, --file-type <type> 'archive', 'package', or custom regex (default: archive)
-p, --install-path <path> Custom installation directory
-k, --token <token> GitHub token
-d, --debug Enable debug logging
-h, --help Show this help message
`),process.exit(0));let i=e[0];i||(console.error("Error: Repository is required."),process.exit(1));let r=t["file-name"],s=t["binary-name"],o=t["file-type"],a=!!t.debug,c=t.token||process.env.GITHUB_TOKEN;try{let n=M(),m=i.split("/").pop()||i;console.log(`Fetching latest release for ${i}...`);let S=await W(i,c),h=j(S.assets,n,{fileName:r,fileType:o});console.log(`Selected asset: ${h.name}`);let b=l.mkdtempSync(f.join(P.tmpdir(),"setup-gh-release-")),u=f.join(b,h.name);console.log(`Downloading ${h.name}...`),await L(h.browser_download_url,u,c);let w=f.join(b,"extract");console.log(`Extracting ${h.name}...`),await B(u,w);let R=s||m,k;R.startsWith("~")?k=new RegExp(R.substring(1),"i"):k=R;let C=I(w,k,a,console.log);if(!C)throw new Error(`Could not find binary "${R}" in the extracted asset.`);let g;if(t["install-path"])g=f.resolve(t["install-path"]);else if(process.platform==="win32"){let d=process.env.LOCALAPPDATA||f.join(P.homedir(),"AppData","Local");g=f.join(d,"bin")}else if(process.getuid&&process.getuid()===0)g="/usr/local/bin";else{let N=f.join(P.homedir(),"bin");l.existsSync(N)?g=N:g="/usr/local/bin"}l.existsSync(g)||l.mkdirSync(g,{recursive:!0});let v=f.basename(C),$=f.join(g,v);console.log(`Installing ${v} to ${$}...`);try{l.copyFileSync(C,$)}catch(d){throw d.code==="EBUSY"?new Error(`The file ${$} is currently in use. Please close any running instances and try again.`):d.code==="EACCES"||d.code==="EPERM"?new Error(`Permission denied while installing to ${$}. Try running with sudo or as administrator, or use -p to specify a custom path.`):d}process.platform!=="win32"&&l.chmodSync($,"755"),l.rmSync(b,{recursive:!0,force:!0}),console.log("Installation successful!")}catch(n){console.error(`Error: ${n.message}`),process.exit(1)}}Z();

76
dist/index.js vendored

File diff suppressed because one or more lines are too long

View File

@@ -1,10 +1,15 @@
{
"name": "setup-github-release",
"name": "install-github-release",
"version": "1.0.0",
"description": "A GitHub Action to download a tool",
"description": "A GitHub Action and CLI tool to download and install binaries from GitHub releases",
"main": "dist/index.js",
"bin": {
"install-github-release": "dist/cli.js"
},
"scripts": {
"build": "esbuild src/index.ts --bundle --platform=node --target=node24 --outfile=dist/index.js --minify",
"build:action": "esbuild src/index.ts --bundle --platform=node --target=node24 --outfile=dist/index.js --minify",
"build:cli": "esbuild src/cli.ts --bundle --platform=node --target=node24 --outfile=dist/cli.js --minify --banner:js=\"#!/usr/bin/env node\"",
"build": "npm run build:action && npm run build:cli",
"format": "prettier --write '**/*.ts'",
"format-check": "prettier --check '**/*.ts'",
"lint": "eslint src/**/*.ts",

151
src/cli.ts Normal file
View File

@@ -0,0 +1,151 @@
import { parseArgs } from 'util';
import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
import { getPlatformInfo } from './core/platform';
import { getMatchingAsset } from './core/matcher';
import { findBinary } from './core/finder';
import { fetchLatestRelease, downloadAsset } from './core/downloader';
import { extractAsset } from './core/extractor';
async function run() {
const { values, positionals } = parseArgs({
options: {
'file-name': { type: 'string', short: 'f' },
'binary-name': { type: 'string', short: 'b' },
'file-type': { type: 'string', short: 't', default: 'archive' },
'install-path': { type: 'string', short: 'p' },
'token': { type: 'string', short: 'k' },
'debug': { type: 'boolean', short: 'd', default: false },
'help': { type: 'boolean', short: 'h' }
},
allowPositionals: true
});
if (values.help || positionals.length === 0) {
console.log(`
Usage: install-github-release [options] <repository>
Arguments:
repository The GitHub repository (owner/repo)
Options:
-f, --file-name <name> Asset file name or regex pattern (prefixed with ~)
-b, --binary-name <name> Binary to search for (prefixed with ~ for regex)
-t, --file-type <type> 'archive', 'package', or custom regex (default: archive)
-p, --install-path <path> Custom installation directory
-k, --token <token> GitHub token
-d, --debug Enable debug logging
-h, --help Show this help message
`);
process.exit(0);
}
const repository = positionals[0];
if (!repository) {
console.error('Error: Repository is required.');
process.exit(1);
}
const fileNameInput = values['file-name'];
const binaryInput = values['binary-name'];
const fileType = values['file-type'];
const debug = !!values.debug;
const token = values.token || process.env.GITHUB_TOKEN;
try {
const platformInfo = getPlatformInfo();
const toolName = repository.split('/').pop() || repository;
console.log(`Fetching latest release for ${repository}...`);
const release = await fetchLatestRelease(repository, token);
const asset = getMatchingAsset(release.assets, platformInfo, {
fileName: fileNameInput,
fileType: fileType
});
console.log(`Selected asset: ${asset.name}`);
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'setup-gh-release-'));
const downloadPath = path.join(tempDir, asset.name);
console.log(`Downloading ${asset.name}...`);
await downloadAsset(asset.browser_download_url, downloadPath, token);
const extractDir = path.join(tempDir, 'extract');
console.log(`Extracting ${asset.name}...`);
await extractAsset(downloadPath, extractDir);
const binaryName = binaryInput || toolName;
let binaryPattern: string | RegExp;
if (binaryName.startsWith('~')) {
binaryPattern = new RegExp(binaryName.substring(1), 'i');
} else {
binaryPattern = binaryName;
}
const binaryPath = findBinary(extractDir, binaryPattern, debug, console.log);
if (!binaryPath) {
throw new Error(`Could not find binary "${binaryName}" in the extracted asset.`);
}
// Determine install directory
let installDir: string;
if (values['install-path']) {
installDir = path.resolve(values['install-path']);
} else {
if (process.platform === 'win32') {
const localAppData = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
installDir = path.join(localAppData, 'bin');
} else {
const isRoot = process.getuid && process.getuid() === 0;
if (isRoot) {
installDir = '/usr/local/bin';
} else {
const homeBin = path.join(os.homedir(), 'bin');
if (fs.existsSync(homeBin)) {
installDir = homeBin;
} else {
installDir = '/usr/local/bin';
}
}
}
}
if (!fs.existsSync(installDir)) {
fs.mkdirSync(installDir, { recursive: true });
}
const finalName = path.basename(binaryPath);
const destPath = path.join(installDir, finalName);
console.log(`Installing ${finalName} to ${destPath}...`);
try {
fs.copyFileSync(binaryPath, destPath);
} catch (err: any) {
if (err.code === 'EBUSY') {
throw new Error(`The file ${destPath} is currently in use. Please close any running instances and try again.`);
}
if (err.code === 'EACCES' || err.code === 'EPERM') {
throw new Error(`Permission denied while installing to ${destPath}. Try running with sudo or as administrator, or use -p to specify a custom path.`);
}
throw err;
}
if (process.platform !== 'win32') {
fs.chmodSync(destPath, '755');
}
// Cleanup
fs.rmSync(tempDir, { recursive: true, force: true });
console.log('Installation successful!');
} catch (error: any) {
console.error(`Error: ${error.message}`);
process.exit(1);
}
}
run();

52
src/core/downloader.ts Normal file
View File

@@ -0,0 +1,52 @@
import { getMatchingAsset } from './matcher';
import { PlatformInfo } from './platform';
export interface ReleaseAsset {
name: string;
browser_download_url: string;
}
export interface ReleaseInfo {
tag_name: string;
assets: ReleaseAsset[];
}
export async function fetchLatestRelease(repository: string, token?: string): Promise<ReleaseInfo> {
const url = `https://api.github.com/repos/${repository}/releases/latest`;
const headers: Record<string, string> = {
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'setup-github-release-action'
};
if (token) {
headers['Authorization'] = `token ${token}`;
}
const response = await fetch(url, { headers });
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`Failed to fetch latest release for ${repository}: ${response.statusText}. ${errorBody}`);
}
return await response.json() as ReleaseInfo;
}
export async function downloadAsset(url: string, destPath: string, token?: string): Promise<void> {
const headers: Record<string, string> = {
'User-Agent': 'setup-github-release-action'
};
if (token) {
headers['Authorization'] = `token ${token}`;
}
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(`Failed to download asset: ${response.statusText}`);
}
const fs = await import('fs');
const { Readable } = await import('stream');
const { finished } = await import('stream/promises');
const fileStream = fs.createWriteStream(destPath);
await finished(Readable.fromWeb(response.body as any).pipe(fileStream));
}

54
src/core/extractor.ts Normal file
View File

@@ -0,0 +1,54 @@
import { spawnSync } from 'child_process';
import * as path from 'path';
import * as fs from 'fs';
export async function extractAsset(filePath: string, destDir: string): Promise<void> {
const ext = path.extname(filePath).toLowerCase();
const name = path.basename(filePath).toLowerCase();
if (!fs.existsSync(destDir)) {
fs.mkdirSync(destDir, { recursive: true });
}
if (name.endsWith('.tar.gz') || name.endsWith('.tgz') || name.endsWith('.tar')) {
const args = ['-xf', filePath, '-C', destDir];
const result = spawnSync('tar', args);
if (result.status !== 0) {
throw new Error(`tar failed with status ${result.status}: ${result.stderr.toString()}`);
}
} else if (name.endsWith('.zip')) {
if (process.platform === 'win32') {
// Modern Windows 10/11 has tar that handles zip
const tarResult = spawnSync('tar', ['-xf', filePath, '-C', destDir]);
if (tarResult.status === 0) return;
// Fallback: Use .NET ZipFile class to bypass PowerShell module trust issues (Microsoft.PowerShell.Archive)
// We escape single quotes for PowerShell.
const escapedFilePath = filePath.replace(/'/g, "''");
const escapedDestDir = destDir.replace(/'/g, "''");
const dotNetCommand = `Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory('${escapedFilePath}', '${escapedDestDir}')`;
// Try pwsh (PowerShell 7) then powershell (Windows PowerShell)
for (const shell of ['pwsh', 'powershell']) {
const result = spawnSync(shell, ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', dotNetCommand]);
if (result.status === 0) return;
}
throw new Error(`Extraction failed: Both tar and PowerShell fallback failed. Make sure your system can extract ZIP files.`);
} else {
const result = spawnSync('unzip', ['-q', filePath, '-d', destDir]);
if (result.status !== 0) {
throw new Error(`unzip failed with status ${result.status}: ${result.stderr.toString()}`);
}
}
} else if (name.endsWith('.7z')) {
const result = spawnSync('7z', ['x', filePath, `-o${destDir}`, '-y']);
if (result.status !== 0) {
throw new Error(`7z failed with status ${result.status}. Make sure 7z is installed.`);
}
} else {
// For other files, we just copy them to the destination directory
const destPath = path.join(destDir, path.basename(filePath));
fs.copyFileSync(filePath, destPath);
}
}

38
src/core/finder.ts Normal file
View File

@@ -0,0 +1,38 @@
import * as fs from 'fs';
import * as path from 'path';
export function findBinary(dir: string, pattern: string | RegExp, debug: boolean, logger: (msg: string) => void): string | undefined {
const items = fs.readdirSync(dir);
if (debug) {
logger(`Searching for binary in ${dir}...`);
items.forEach(item => logger(` - ${item}`));
}
for (const item of items) {
const fullPath = path.join(dir, item);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
const found = findBinary(fullPath, pattern, debug, logger);
if (found) return found;
} else {
let isMatch = false;
if (pattern instanceof RegExp) {
isMatch = pattern.test(item);
} else {
isMatch = item === pattern;
// On Windows, also check for .exe extension if the pattern doesn't have it
if (!isMatch && process.platform === 'win32' && !pattern.toLowerCase().endsWith('.exe')) {
isMatch = item.toLowerCase() === `${pattern.toLowerCase()}.exe`;
}
}
if (isMatch) return fullPath;
}
}
return undefined;
}
export function setExecutable(filePath: string): void {
if (process.platform !== 'win32') {
fs.chmodSync(filePath, '755');
}
}

67
src/core/matcher.ts Normal file
View File

@@ -0,0 +1,67 @@
import { PlatformInfo } from './platform';
export interface MatchOptions {
fileName?: string;
fileType?: string;
}
export function getMatchingAsset(assets: any[], platform: PlatformInfo, options: MatchOptions): any {
const { fileName, fileType = 'archive' } = options;
let extPattern: string;
if (fileType === 'archive') {
extPattern = '\\.(zip|tar\\.gz|tar|tgz|7z)';
} else if (fileType === 'package') {
extPattern = '\\.(deb|rpm|pkg)';
} else {
extPattern = fileType;
}
if (!fileName) {
// Rule 1: Default matching rule
const pattern = `${platform.systemPattern}[_-]${platform.archPattern}.*${extPattern}$`;
const regex = new RegExp(pattern, 'i');
const matchingAssets = assets.filter((a: any) => regex.test(a.name));
if (matchingAssets.length === 0) {
throw new Error(`No assets matched the default criteria: ${pattern}`);
}
if (matchingAssets.length > 1) {
throw new Error(`Multiple assets matched the default criteria: ${matchingAssets.map((a: any) => a.name).join(', ')}`);
}
return matchingAssets[0];
} else if (fileName.startsWith('~')) {
// Rule 3: Regex matching rule
let pattern = fileName.substring(1);
const hasSystem = pattern.includes('{{SYSTEM}}');
const hasArch = pattern.includes('{{ARCH}}');
const hasExt = pattern.includes('{{EXT_PATTERN}}');
const hasEnd = pattern.endsWith('$');
if (!hasSystem && !hasArch && !hasExt && !hasEnd) {
pattern += `.*{{SYSTEM}}[_-]{{ARCH}}.*{{EXT_PATTERN}}$`;
} else if (hasSystem && hasArch && !hasExt && !hasEnd) {
pattern += `.*{{EXT_PATTERN}}$`;
}
const finalPattern = pattern
.replace(/{{SYSTEM}}/g, platform.systemPattern)
.replace(/{{ARCH}}/g, platform.archPattern)
.replace(/{{EXT_PATTERN}}/g, extPattern);
const regex = new RegExp(finalPattern, 'i');
const matchingAssets = assets.filter((a: any) => regex.test(a.name));
if (matchingAssets.length === 0) {
throw new Error(`No assets matched the regex: ${finalPattern}`);
}
if (matchingAssets.length > 1) {
throw new Error(`Multiple assets matched the criteria: ${matchingAssets.map((a: any) => a.name).join(', ')}`);
}
return matchingAssets[0];
} else {
// Rule 2: Literal matching rule
const asset = assets.find((a: any) => a.name === fileName);
if (!asset) {
throw new Error(`No asset found matching the exact name: ${fileName}`);
}
return asset;
}
}

31
src/core/platform.ts Normal file
View File

@@ -0,0 +1,31 @@
import * as os from 'os';
export interface PlatformInfo {
system: string;
arch: string;
systemPattern: string;
archPattern: string;
}
export const systemPatterns: Record<string, string> = {
linux: 'linux',
darwin: '(darwin|macos|mac|osx)',
win32: '(windows|win)'
};
export const archPatterns: Record<string, string> = {
x64: '(x86_64|x64|amd64)',
arm64: '(aarch64|arm64)'
};
export function getPlatformInfo(): PlatformInfo {
const system = os.platform();
const arch = os.arch();
return {
system,
arch,
systemPattern: systemPatterns[system] || system,
archPattern: archPatterns[arch] || arch
};
}

View File

@@ -3,159 +3,66 @@ import * as tc from '@actions/tool-cache';
import * as path from 'path';
import * as os from 'os';
import * as fs from 'fs';
function findBinary(dir: string, pattern: string | RegExp, debug: boolean): string | undefined {
const items = fs.readdirSync(dir);
if (debug) {
core.info(`Searching for binary in ${dir}...`);
items.forEach(item => core.info(` - ${item}`));
}
for (const item of items) {
const fullPath = path.join(dir, item);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
const found = findBinary(fullPath, pattern, debug);
if (found) return found;
} else {
let isMatch = false;
if (pattern instanceof RegExp) {
isMatch = pattern.test(item);
} else {
isMatch = item === pattern;
// On Windows, also check for .exe extension if the pattern doesn't have it
if (!isMatch && process.platform === 'win32' && !pattern.toLowerCase().endsWith('.exe')) {
isMatch = item.toLowerCase() === `${pattern.toLowerCase()}.exe`;
}
}
if (isMatch) return fullPath;
}
}
return undefined;
}
import { getPlatformInfo } from './core/platform';
import { getMatchingAsset } from './core/matcher';
import { findBinary } from './core/finder';
import { fetchLatestRelease } from './core/downloader';
async function run() {
try {
const repoName = core.getInput('repo-name', { required: true });
let fileName = core.getInput('file-name');
const repository = core.getInput('repository', { required: true });
const fileNameInput = core.getInput('file-name');
const binaryInput = core.getInput('binary-name');
const fileType = core.getInput('file-type') || 'archive';
const updateCache = core.getInput('update-cache') || 'false';
const debug = core.getBooleanInput('debug');
const token = core.getInput('token') || process.env.GITHUB_TOKEN;
// Detect system and architecture
const platform = os.platform(); // 'linux', 'darwin', 'win32'
const arch = os.arch(); // 'x64', 'arm64'
const platformInfo = getPlatformInfo();
const toolName = repository.split('/').pop() || repository;
const systemPatterns: Record<string, string> = {
linux: 'linux',
darwin: '(darwin|macos|mac)',
win32: '(windows|win)'
};
const archPatterns: Record<string, string> = {
x64: '(x86_64|x64|amd64)',
arm64: '(aarch64|arm64)'
};
const systemPattern = systemPatterns[platform] || platform;
const archPattern = archPatterns[arch] || arch;
let extPattern: string;
if (fileType === 'archive') {
extPattern = '\\.(zip|tar\\.gz|tar|tgz|7z)';
} else if (fileType === 'package') {
extPattern = '\\.(deb|rpm|pkg)';
} else {
extPattern = fileType;
// Rule for update-cache: 'false' means use ANY cached version if available
if (updateCache === 'false') {
const allVersions = tc.findAllVersions(toolName, platformInfo.arch);
if (allVersions.length > 0) {
const latestVersion = allVersions.sort().pop();
if (latestVersion) {
const cachedDir = tc.find(toolName, latestVersion, platformInfo.arch);
if (cachedDir) {
core.info(`Found ${toolName} version ${latestVersion} in local cache (update-cache: false)`);
core.addPath(cachedDir);
return;
}
}
}
}
const url = `https://api.github.com/repos/${repoName}/releases/latest`;
const headers: Record<string, string> = {
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'setup-github-release-action'
};
if (token) {
headers['Authorization'] = `token ${token}`;
}
core.info(`Fetching latest release information for ${repository}...`);
const release = await fetchLatestRelease(repository, token);
const asset = getMatchingAsset(release.assets, platformInfo, {
fileName: fileNameInput,
fileType: fileType
});
core.info(`Fetching latest release information for ${repoName}...`);
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(`Failed to fetch release: ${response.statusText} (${response.status})`);
}
core.info(`Selected asset: ${asset.name}`);
const data: any = await response.json();
let asset;
if (!fileName) {
// Rule 1: Default matching rule
const pattern = `${systemPattern}[_-]${archPattern}.*${extPattern}$`;
const regex = new RegExp(pattern, 'i');
core.info(`No file-name provided. Using default pattern: ${pattern}`);
const matchingAssets = data.assets.filter((a: any) => regex.test(a.name));
if (matchingAssets.length === 0) {
throw new Error(`No assets matched the default criteria: ${pattern}`);
}
if (matchingAssets.length > 1) {
throw new Error(`Multiple assets matched the default criteria: ${matchingAssets.map((a: any) => a.name).join(', ')}`);
}
asset = matchingAssets[0];
} else if (fileName.startsWith('~')) {
// Rule 3: Regex matching rule
let pattern = fileName.substring(1);
const hasSystem = pattern.includes('{{SYSTEM}}');
const hasArch = pattern.includes('{{ARCH}}');
const hasExt = pattern.includes('{{EXT_PATTERN}}');
const hasEnd = pattern.endsWith('$');
if (!hasSystem && !hasArch && !hasExt && !hasEnd) {
pattern += `.*{{SYSTEM}}[_-]{{ARCH}}.*{{EXT_PATTERN}}$`;
} else if (hasSystem && hasArch && !hasExt && !hasEnd) {
pattern += `.*{{EXT_PATTERN}}$`;
}
const finalPattern = pattern
.replace(/{{SYSTEM}}/g, systemPattern)
.replace(/{{ARCH}}/g, archPattern)
.replace(/{{EXT_PATTERN}}/g, extPattern);
const regex = new RegExp(finalPattern, 'i');
core.info(`Using regex pattern: ${finalPattern}`);
const matchingAssets = data.assets.filter((a: any) => regex.test(a.name));
if (matchingAssets.length === 0) {
throw new Error(`No assets matched the regex: ${finalPattern}`);
}
if (matchingAssets.length > 1) {
throw new Error(`Multiple assets matched the criteria: ${matchingAssets.map((a: any) => a.name).join(', ')}`);
}
asset = matchingAssets[0];
} else {
// Literal matching rule
core.info(`Using literal match for: ${fileName}`);
asset = data.assets.find((a: any) => a.name === fileName);
}
if (!asset) {
throw new Error(`No asset found matching the criteria in release ${data.tag_name}`);
}
const version = data.tag_name.replace(/^v/, '');
const toolName = repoName.split('/').pop() || repoName;
const version = release.tag_name.replace(/^v/, '');
const binaryName = binaryInput || toolName;
// Check if the tool is already in the cache
const cachedDir = tc.find(toolName, version, arch);
// Check if the tool is already in the cache (if not 'always' update)
if (updateCache !== 'always') {
const cachedDir = tc.find(toolName, version, platformInfo.arch);
if (cachedDir) {
core.info(`Found ${toolName} version ${version} in cache at ${cachedDir}`);
core.addPath(cachedDir);
return;
}
}
const downloadUrl = asset.browser_download_url;
core.info(`Downloading ${asset.name} from ${downloadUrl}...`);
const downloadPath = await tc.downloadTool(downloadUrl);
const downloadPath = await tc.downloadTool(downloadUrl, undefined, token ? `token ${token}` : undefined);
const nameLower = asset.name.toLowerCase();
let toolDir: string;
@@ -179,7 +86,6 @@ async function run() {
}
fs.renameSync(downloadPath, destPath);
// Make it executable on Linux/macOS
if (process.platform !== 'win32') {
fs.chmodSync(destPath, '755');
}
@@ -195,14 +101,14 @@ async function run() {
core.info(`Searching for binary named: ${binaryName}`);
}
const binaryPath = findBinary(toolDir, binaryPattern, debug);
const binaryPath = findBinary(toolDir, binaryPattern, debug, (msg) => core.info(msg));
if (!binaryPath) {
throw new Error(`Could not find binary "${binaryName}" in the extracted asset.`);
}
// The tool directory is the one containing the binary
toolDir = path.dirname(binaryPath);
core.info(`Binary found at ${binaryPath}. Setting tool directory to ${toolDir}`);
core.info(`Binary found at ${binaryPath}.`);
// Make binary executable just in case it's not
if (process.platform !== 'win32') {
@@ -210,7 +116,7 @@ async function run() {
}
// Cache the tool
const finalCachedDir = await tc.cacheDir(toolDir, toolName, version, arch);
const finalCachedDir = await tc.cacheDir(toolDir, toolName, version, platformInfo.arch);
core.info(`Cached ${toolName} version ${version} to ${finalCachedDir}`);
core.addPath(finalCachedDir);