Compare commits
13
Commits
v1
...
26ef54930a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
26ef54930a | ||
|
|
e7e7ee53f6 | ||
|
|
d2f1cb9c1a | ||
|
|
1a01c8fa5f | ||
|
|
cbfadf3488 | ||
|
|
01d844f6d9 | ||
|
|
e50ae03336 | ||
|
|
1896949b27 | ||
|
|
d9d7f67247 | ||
|
|
0132ee6665 | ||
|
|
89ea0cecb0 | ||
|
|
3a75adedc6 | ||
|
|
dfa641afd4 |
@@ -28,19 +28,23 @@ jobs:
|
||||
with:
|
||||
repository: 'go-acme/lego'
|
||||
token: ${{ secrets.GH_TOKEN }}
|
||||
update-cache: 'always'
|
||||
|
||||
- name: Setup Hugo
|
||||
uses: ./
|
||||
with:
|
||||
repository: 'gohugoio/hugo'
|
||||
file-name: '~hugo_extended_[^a-z]'
|
||||
file-type: 'archive'
|
||||
token: ${{ secrets.GH_TOKEN }}
|
||||
update-cache: 'always'
|
||||
|
||||
- name: Setup RClone
|
||||
uses: ./
|
||||
with:
|
||||
repository: 'rclone/rclone'
|
||||
token: ${{ secrets.GH_TOKEN }}
|
||||
update-cache: 'always'
|
||||
|
||||
- name: Verify Installation
|
||||
run: |
|
||||
|
||||
@@ -4,3 +4,4 @@ lib/
|
||||
*.map
|
||||
.DS_Store
|
||||
.github/*.md
|
||||
dist/cli.js
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Slawomir Koszewski
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -115,11 +115,12 @@ The following inputs are available for the GitHub Action, and as options for the
|
||||
- `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:
|
||||
- `file-type` (optional): Asset type selector.
|
||||
|
||||
- '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.
|
||||
- known values: `archive`, `package`, `linux`, `macos`, `targz`.
|
||||
- custom values:
|
||||
`~<regex>` for regular expression matching (anchored to the end of file name), or
|
||||
extension form such as `zip` or `.tar.gz`.
|
||||
|
||||
- `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.
|
||||
@@ -139,10 +140,20 @@ Arguments:
|
||||
repository The GitHub repository (owner/repo)
|
||||
|
||||
Options:
|
||||
--dry-run [level] Run in test mode (default level: 1)
|
||||
Or set TEST_MODE environment variable to a value > 0
|
||||
-l, --list [repository] List available assets from latest release and exit
|
||||
-a, --app-name <name> Application name (optional, for output messages)
|
||||
-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)
|
||||
-b, --binary-name <name> Binary name (supports source:destination form)
|
||||
-t, --file-type <type> Known: archive|package|linux|macos|targz
|
||||
Or custom: ~<regex> (end-of-string match) or extension (e.g. zip, .tar.gz)
|
||||
-p, --install-path <path> Custom installation directory
|
||||
-o, --output-directory <path>
|
||||
Only download selected asset to the specified directory
|
||||
-j, --releases-json Download latest release JSON only
|
||||
--system <name> Override detected system for asset matching
|
||||
--arch <name> Override detected architecture for asset matching
|
||||
-k, --token <token> GitHub token
|
||||
-d, --debug Enable debug logging
|
||||
-h, --help Show this help message
|
||||
@@ -178,11 +189,14 @@ If the `token` input is not provided, it will read from the `GITHUB_TOKEN` envir
|
||||
|
||||
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:
|
||||
1. If neither `file-name` nor `file-type` is provided, the tool defaults to selecting assets with an OS-aware extension pattern and this regular expression shape: `{{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).
|
||||
- `{{EXT_PATTERN}}` is selected by OS:
|
||||
Linux: `\.(deb|rpm|zip|tar\.gz|tgz)$`
|
||||
macOS: `\.(pkg|zip|tar\.gz|tgz)$`
|
||||
other: `\.(zip|tar\.gz|tgz)$`
|
||||
|
||||
2. If `file-name` is provided literally, the tool uses it directly to match the asset name by using exact string comparison.
|
||||
|
||||
@@ -192,7 +206,11 @@ The list of assets from the latest release is filtered based on the following ru
|
||||
- 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.
|
||||
4. If `file-type` is provided:
|
||||
|
||||
- known values are: `archive`, `package`, `linux`, `macos`, `targz`.
|
||||
- `~<regex>` is treated as a regex and matched at the end of the file name.
|
||||
- any other value is treated as an extension selector (for example `zip` or `.tar.gz`).
|
||||
|
||||
5. The tool applies the constructed regex pattern to filter the assets from the latest release.
|
||||
|
||||
|
||||
+1
-2
@@ -12,9 +12,8 @@ inputs:
|
||||
description: 'The name or regex pattern (prefixed with ~) of the binary to search for within the asset. Defaults to the repository name.'
|
||||
required: false
|
||||
file-type:
|
||||
description: 'The type of the file to be downloaded (archive, package, or custom regex).'
|
||||
description: 'Asset type selector. Known values: archive, package, linux, macos, targz. Custom values: ~<regex> or extension (e.g. zip, .tar.gz).'
|
||||
required: false
|
||||
default: 'archive'
|
||||
update-cache:
|
||||
description: 'How to handle the tool cache (false, true, or always). Defaults to false.'
|
||||
required: false
|
||||
|
||||
Vendored
+19849
-58
File diff suppressed because one or more lines are too long
+48
-1
@@ -1,2 +1,49 @@
|
||||
#!/usr/bin/env node
|
||||
"use strict";var n=require("util");async function i(t,e){let s=`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 o=await fetch(s,{headers:r});if(!o.ok){let a=await o.text();throw new Error(`Failed to fetch latest release for ${t}: ${o.statusText}. ${a}`)}return await o.json()}async function c(){let{positionals:t}=(0,n.parseArgs)({allowPositionals:!0}),e=t[0]||process.env.GITHUB_TOKEN;e||(console.error("Error: No GitHub token provided as an argument or found in GITHUB_TOKEN environment variable."),process.exit(1));try{console.log("Verifying GitHub token..."),await i("actions/checkout",e),console.log("\x1B[32mSuccess: The provided GitHub token is valid and has sufficient permissions to access public repositories.\x1B[0m")}catch(s){console.error("\x1B[31mError: GitHub token verification failed.\x1B[0m"),console.error(`Reason: ${s.message}`),process.exit(1)}}c();
|
||||
"use strict";
|
||||
|
||||
// src/check-token.ts
|
||||
var import_util = require("util");
|
||||
|
||||
// src/core/downloader.ts
|
||||
function getGithubApiHeaders(token) {
|
||||
const headers = {
|
||||
"Accept": "application/vnd.github.v3+json",
|
||||
"User-Agent": "setup-github-release-action"
|
||||
};
|
||||
if (token) {
|
||||
headers["Authorization"] = `token ${token}`;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
async function fetchLatestRelease(repository, token) {
|
||||
const url = `https://api.github.com/repos/${repository}/releases/latest`;
|
||||
const headers = getGithubApiHeaders(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();
|
||||
}
|
||||
|
||||
// src/check-token.ts
|
||||
async function run() {
|
||||
const { positionals } = (0, import_util.parseArgs)({
|
||||
allowPositionals: true
|
||||
});
|
||||
const token = positionals[0] || process.env.GITHUB_TOKEN;
|
||||
if (!token) {
|
||||
console.error("Error: No GitHub token provided as an argument or found in GITHUB_TOKEN environment variable.");
|
||||
process.exit(1);
|
||||
}
|
||||
try {
|
||||
console.log("Verifying GitHub token...");
|
||||
await fetchLatestRelease("actions/checkout", token);
|
||||
console.log("\x1B[32mSuccess: The provided GitHub token is valid and has sufficient permissions to access public repositories.\x1B[0m");
|
||||
} catch (error) {
|
||||
console.error("\x1B[31mError: GitHub token verification failed.\x1B[0m");
|
||||
console.error(`Reason: ${error.message}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
run();
|
||||
|
||||
Vendored
-16
@@ -1,16 +0,0 @@
|
||||
#!/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();
|
||||
Vendored
+23844
-59
File diff suppressed because one or more lines are too long
Generated
+54
-3
@@ -1,16 +1,22 @@
|
||||
{
|
||||
"name": "setup-github-release",
|
||||
"name": "install-github-release",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "setup-github-release",
|
||||
"name": "install-github-release",
|
||||
"version": "1.0.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.11.0",
|
||||
"@actions/tool-cache": "^2.0.2"
|
||||
"@actions/tool-cache": "^2.0.2",
|
||||
"commander": "^14.0.3",
|
||||
"minimatch": "^10.2.5"
|
||||
},
|
||||
"bin": {
|
||||
"check-github-token": "dist/check-token.js",
|
||||
"install-github-release": "dist/cli.js"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.0.0",
|
||||
@@ -530,6 +536,36 @@
|
||||
"undici-types": "~7.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/balanced-match": {
|
||||
"version": "4.0.4",
|
||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz",
|
||||
"integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "5.0.5",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz",
|
||||
"integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^4.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/commander": {
|
||||
"version": "14.0.3",
|
||||
"resolved": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz",
|
||||
"integrity": "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/esbuild": {
|
||||
"version": "0.27.2",
|
||||
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz",
|
||||
@@ -572,6 +608,21 @@
|
||||
"@esbuild/win32-x64": "0.27.2"
|
||||
}
|
||||
},
|
||||
"node_modules/minimatch": {
|
||||
"version": "10.2.5",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz",
|
||||
"integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==",
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"brace-expansion": "^5.0.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": "18 || 20 || >=22"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/semver": {
|
||||
"version": "6.3.1",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
|
||||
|
||||
+9
-13
@@ -8,31 +8,27 @@
|
||||
"check-github-token": "dist/check-token.js"
|
||||
},
|
||||
"scripts": {
|
||||
"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:check-token": "esbuild src/check-token.ts --bundle --platform=node --target=node24 --outfile=dist/check-token.js --minify --banner:js=\"#!/usr/bin/env node\"",
|
||||
"build:check-token-action": "esbuild src/check-token-action.ts --bundle --platform=node --target=node24 --outfile=dist/check-token-action.js --minify",
|
||||
"build": "npm run build:action && npm run build:cli && npm run build:check-token && npm run build:check-token-action",
|
||||
"format": "prettier --write '**/*.ts'",
|
||||
"format-check": "prettier --check '**/*.ts'",
|
||||
"lint": "eslint src/**/*.ts",
|
||||
"package": "npm run build",
|
||||
"test": "jest",
|
||||
"all": "npm run format && npm run lint && npm run test && npm run package"
|
||||
"build:action": "esbuild src/index.ts --bundle --platform=node --target=node24 --outfile=dist/index.js",
|
||||
"build:cli": "esbuild src/cli.ts --bundle --platform=node --target=node24 --outfile=dist/cli.js --banner:js=\"#!/usr/bin/env node\" && chmod +x dist/cli.js",
|
||||
"build:check-token": "esbuild src/check-token.ts --bundle --platform=node --target=node24 --outfile=dist/check-token.js --banner:js=\"#!/usr/bin/env node\" && chmod +x dist/check-token.js",
|
||||
"build:check-token-action": "esbuild src/check-token-action.ts --bundle --platform=node --target=node24 --outfile=dist/check-token-action.js",
|
||||
"build": "npm run build:action && npm run build:cli && npm run build:check-token && npm run build:check-token-action"
|
||||
},
|
||||
"keywords": [
|
||||
"actions",
|
||||
"node",
|
||||
"setup"
|
||||
],
|
||||
"author": "",
|
||||
"author": "Sławomir Koszewski",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
},
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.11.0",
|
||||
"@actions/tool-cache": "^2.0.2"
|
||||
"@actions/tool-cache": "^2.0.2",
|
||||
"commander": "^14.0.3",
|
||||
"minimatch": "^10.2.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^25.0.0",
|
||||
|
||||
+237
-127
@@ -1,151 +1,261 @@
|
||||
import { parseArgs } from 'util';
|
||||
import * as path from 'path';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import { spawnSync } from 'child_process';
|
||||
import { Command } from 'commander';
|
||||
import { getPlatformInfo } from './core/platform';
|
||||
import { getMatchingAsset } from './core/matcher';
|
||||
import { findBinary } from './core/finder';
|
||||
import { fetchLatestRelease, downloadAsset } from './core/downloader';
|
||||
import { fetchLatestRelease, fetchLatestReleaseRaw, 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
|
||||
});
|
||||
interface CliOptions {
|
||||
appName?: string;
|
||||
fileName?: string;
|
||||
binaryName?: string;
|
||||
fileType?: string;
|
||||
installPath?: string;
|
||||
outputDirectory?: string;
|
||||
releasesJsonOnly: boolean;
|
||||
listOnly: boolean;
|
||||
token?: string;
|
||||
debug: boolean;
|
||||
dryRun: boolean;
|
||||
systemOverride?: string;
|
||||
archOverride?: string;
|
||||
listRepo?: string;
|
||||
positionals: string[];
|
||||
}
|
||||
|
||||
if (values.help || positionals.length === 0) {
|
||||
console.log(`
|
||||
Usage: install-github-release [options] <repository>
|
||||
function validateOutputDirectory(outputDirectory: string): string {
|
||||
const resolvedPath = path.resolve(outputDirectory);
|
||||
if (!fs.existsSync(resolvedPath) || !fs.statSync(resolvedPath).isDirectory()) {
|
||||
throw new Error(`Output directory "${resolvedPath}" does not exist.`);
|
||||
}
|
||||
return resolvedPath;
|
||||
}
|
||||
|
||||
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);
|
||||
function getInstallDir(installPath?: string): string {
|
||||
if (installPath) {
|
||||
return path.resolve(installPath);
|
||||
}
|
||||
|
||||
const repository = positionals[0];
|
||||
if (!repository) {
|
||||
console.error('Error: Repository is required.');
|
||||
process.exit(1);
|
||||
if (process.platform === 'win32') {
|
||||
const localAppData = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
|
||||
return path.join(localAppData, 'bin');
|
||||
}
|
||||
|
||||
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;
|
||||
const isRoot = process.getuid && process.getuid() === 0;
|
||||
if (isRoot) {
|
||||
return '/usr/local/bin';
|
||||
}
|
||||
|
||||
try {
|
||||
const platformInfo = getPlatformInfo();
|
||||
const toolName = repository.split('/').pop() || repository;
|
||||
const homeBin = path.join(os.homedir(), 'bin');
|
||||
if (fs.existsSync(homeBin)) {
|
||||
return homeBin;
|
||||
}
|
||||
|
||||
console.log(`Fetching latest release for ${repository}...`);
|
||||
const release = await fetchLatestRelease(repository, token);
|
||||
const asset = getMatchingAsset(release.assets, platformInfo, {
|
||||
fileName: fileNameInput,
|
||||
fileType: fileType
|
||||
});
|
||||
return '/usr/local/bin';
|
||||
}
|
||||
|
||||
console.log(`Selected asset: ${asset.name}`);
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'setup-gh-release-'));
|
||||
const downloadPath = path.join(tempDir, asset.name);
|
||||
function installSystemPackage(downloadPath: string): void {
|
||||
const fileName = path.basename(downloadPath).toLowerCase();
|
||||
|
||||
console.log(`Downloading ${asset.name}...`);
|
||||
await downloadAsset(asset.browser_download_url, downloadPath, token);
|
||||
const command: { binary: string; args: string[] } | undefined = fileName.endsWith('.deb')
|
||||
? { binary: 'dpkg', args: ['-i', downloadPath] }
|
||||
: fileName.endsWith('.pkg')
|
||||
? { binary: 'installer', args: ['-pkg', downloadPath, '-target', '/'] }
|
||||
: fileName.endsWith('.rpm')
|
||||
? { binary: 'rpm', args: ['-i', downloadPath] }
|
||||
: undefined;
|
||||
|
||||
const extractDir = path.join(tempDir, 'extract');
|
||||
console.log(`Extracting ${asset.name}...`);
|
||||
await extractAsset(downloadPath, extractDir);
|
||||
if (!command) {
|
||||
throw new Error(`Unsupported package type: ${fileName}`);
|
||||
}
|
||||
|
||||
const binaryName = binaryInput || toolName;
|
||||
let binaryPattern: string | RegExp;
|
||||
if (binaryName.startsWith('~')) {
|
||||
binaryPattern = new RegExp(binaryName.substring(1), 'i');
|
||||
} else {
|
||||
binaryPattern = binaryName;
|
||||
}
|
||||
const isRoot = process.getuid && process.getuid() === 0;
|
||||
const commandToRun = isRoot ? command.binary : 'sudo';
|
||||
const argsToRun = isRoot ? command.args : [command.binary, ...command.args];
|
||||
|
||||
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);
|
||||
const result = spawnSync(commandToRun, argsToRun, { stdio: 'inherit' });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`Failed to install package using ${commandToRun} ${argsToRun.join(' ')}.`);
|
||||
}
|
||||
}
|
||||
|
||||
run();
|
||||
async function run() {
|
||||
let tempDir: string | undefined;
|
||||
const program = new Command();
|
||||
program
|
||||
.name('install-github-release')
|
||||
.usage('[options] <repository>')
|
||||
.argument('[repository]', 'The GitHub repository (owner/repo)')
|
||||
.option('--dry-run', 'Run in test mode')
|
||||
.option('-l, --list [repository]', 'List available assets from latest release and exit')
|
||||
.option('-a, --app-name <name>', 'Application name (optional, for output messages)')
|
||||
.option('-f, --file-name <name>', 'Asset file name or regex pattern (prefixed with ~)')
|
||||
.option('-b, --binary-name <name>', 'Binary name (supports source:destination form)')
|
||||
.option('-t, --file-type <type>', 'Known: archive|package|linux|macos|targz; custom: ~<regex> or extension')
|
||||
.option('-p, --install-path <path>', 'Custom installation directory')
|
||||
.option('-o, --output-directory <path>', 'Only download selected asset to the specified directory')
|
||||
.option('-j, --releases-json', 'Download latest release JSON only')
|
||||
.option('--system <name>', 'Override detected system for asset matching')
|
||||
.option('--arch <name>', 'Override detected architecture for asset matching')
|
||||
.option('-k, --token <token>', 'GitHub token')
|
||||
.option('-d, --debug', 'Enable debug logging')
|
||||
.allowUnknownOption(false);
|
||||
|
||||
const cleanupTempDir = () => {
|
||||
if (tempDir && fs.existsSync(tempDir)) {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
|
||||
program.parse(process.argv);
|
||||
const parsedOptions = program.opts();
|
||||
const rawFileType = parsedOptions.fileType;
|
||||
const fileType = typeof rawFileType === 'string' ? rawFileType.trim() : undefined;
|
||||
if (rawFileType !== undefined && !fileType) {
|
||||
throw new Error(`Unknown asset type: ${rawFileType}`);
|
||||
}
|
||||
|
||||
const listValue = parsedOptions.list as string | boolean | undefined;
|
||||
const options: CliOptions = {
|
||||
appName: parsedOptions.appName as string | undefined,
|
||||
fileName: parsedOptions.fileName as string | undefined,
|
||||
binaryName: parsedOptions.binaryName as string | undefined,
|
||||
fileType,
|
||||
installPath: parsedOptions.installPath as string | undefined,
|
||||
outputDirectory: parsedOptions.outputDirectory as string | undefined,
|
||||
releasesJsonOnly: Boolean(parsedOptions.releasesJson),
|
||||
listOnly: listValue !== undefined,
|
||||
token: parsedOptions.token as string | undefined,
|
||||
debug: Boolean(parsedOptions.debug),
|
||||
dryRun: Boolean(parsedOptions.dryRun),
|
||||
systemOverride: parsedOptions.system as string | undefined,
|
||||
archOverride: parsedOptions.arch as string | undefined,
|
||||
listRepo: typeof listValue === 'string' ? listValue : undefined,
|
||||
positionals: program.args
|
||||
};
|
||||
|
||||
const repository = options.listRepo || options.positionals[0];
|
||||
if (!repository) {
|
||||
program.outputHelp();
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const token = options.token;
|
||||
|
||||
if (options.listOnly) {
|
||||
const release = await fetchLatestRelease(repository, token);
|
||||
release.assets.forEach((asset) => console.log(`- ${asset.browser_download_url}`));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const toolName = repository.split('/').pop() || repository;
|
||||
const appName = options.appName || (toolName.charAt(0).toUpperCase() + toolName.slice(1));
|
||||
|
||||
const binaryOption = options.binaryName || toolName;
|
||||
const [binarySource, binaryDestination] = binaryOption.includes(':')
|
||||
? [binaryOption.split(':')[0], binaryOption.split(':')[1]]
|
||||
: [binaryOption, binaryOption];
|
||||
|
||||
if (options.releasesJsonOnly) {
|
||||
const rawRelease = await fetchLatestReleaseRaw(repository, token);
|
||||
const outputBase = binaryDestination || toolName;
|
||||
const outputName = `${outputBase}.releases.json`;
|
||||
const outputPath = options.outputDirectory
|
||||
? path.join(validateOutputDirectory(options.outputDirectory), outputName)
|
||||
: outputName;
|
||||
|
||||
fs.writeFileSync(outputPath, rawRelease, 'utf8');
|
||||
console.log(`Downloaded GitHub releases to ${outputPath}.`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const platformInfo = getPlatformInfo({
|
||||
system: options.systemOverride,
|
||||
arch: options.archOverride
|
||||
});
|
||||
|
||||
console.log(`Fetching latest release for ${repository}...`);
|
||||
const release = await fetchLatestRelease(repository, token);
|
||||
const asset = getMatchingAsset(release.assets, platformInfo, options.fileName, options.fileType, options.dryRun);
|
||||
|
||||
const version = release.tag_name.replace(/^v/i, '');
|
||||
const downloadUrl = asset.browser_download_url;
|
||||
console.log(`Will download '${appName}' version: ${version}`);
|
||||
console.log(`Download URL: "${downloadUrl}".`);
|
||||
|
||||
if (options.dryRun) {
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (options.outputDirectory) {
|
||||
const outputDir = validateOutputDirectory(options.outputDirectory);
|
||||
const outputPath = path.join(outputDir, path.basename(downloadUrl));
|
||||
console.log(`Downloading '${appName}' version ${version} to '${outputPath}'...`);
|
||||
await downloadAsset(downloadUrl, outputPath, token);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'setup-gh-release-'));
|
||||
process.once('exit', cleanupTempDir);
|
||||
const downloadPath = path.join(tempDir, asset.name);
|
||||
await downloadAsset(downloadUrl, downloadPath, token);
|
||||
|
||||
if (/\.(deb|pkg|rpm)$/i.test(asset.name)) {
|
||||
installSystemPackage(downloadPath);
|
||||
console.log('Installation successful!');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const extractDir = path.join(tempDir, 'extract');
|
||||
console.log(`Extracting ${asset.name}...`);
|
||||
await extractAsset(downloadPath, extractDir);
|
||||
|
||||
let binaryPattern: string | RegExp;
|
||||
if (binarySource.startsWith('~')) {
|
||||
const binaryRegex = binarySource
|
||||
.substring(1)
|
||||
.replace(/{{SYSTEM}}/g, platformInfo.systemPattern)
|
||||
.replace(/{{ARCH}}/g, platformInfo.archPattern);
|
||||
binaryPattern = new RegExp(binaryRegex, 'i');
|
||||
} else {
|
||||
binaryPattern = binarySource
|
||||
.replace(/{{SYSTEM}}/g, platformInfo.system)
|
||||
.replace(/{{ARCH}}/g, platformInfo.arch);
|
||||
}
|
||||
|
||||
const binaryPath = findBinary(extractDir, binaryPattern, options.debug, console.log);
|
||||
if (!binaryPath) {
|
||||
throw new Error(`Could not find binary "${binarySource}" in the extracted asset.`);
|
||||
}
|
||||
|
||||
const installDir = getInstallDir(options.installPath);
|
||||
if (!fs.existsSync(installDir)) {
|
||||
fs.mkdirSync(installDir, { recursive: true });
|
||||
}
|
||||
|
||||
const finalName = binaryDestination || path.basename(binaryPath);
|
||||
const destPath = path.join(installDir, finalName);
|
||||
|
||||
console.log(`Installing ${finalName} to ${destPath}...`);
|
||||
fs.copyFileSync(binaryPath, destPath);
|
||||
|
||||
if (process.platform !== 'win32') {
|
||||
fs.chmodSync(destPath, '755');
|
||||
}
|
||||
|
||||
console.log('Installation successful!');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
void run().catch((error: unknown) => {
|
||||
if (error instanceof Error && error.message) {
|
||||
console.error(`Error: ${error.message}`);
|
||||
} else {
|
||||
console.error('Error: Unknown failure.');
|
||||
}
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
+19
-5
@@ -1,6 +1,3 @@
|
||||
import { getMatchingAsset } from './matcher';
|
||||
import { PlatformInfo } from './platform';
|
||||
|
||||
export interface ReleaseAsset {
|
||||
name: string;
|
||||
browser_download_url: string;
|
||||
@@ -11,8 +8,7 @@ export interface ReleaseInfo {
|
||||
assets: ReleaseAsset[];
|
||||
}
|
||||
|
||||
export async function fetchLatestRelease(repository: string, token?: string): Promise<ReleaseInfo> {
|
||||
const url = `https://api.github.com/repos/${repository}/releases/latest`;
|
||||
function getGithubApiHeaders(token?: string): Record<string, string> {
|
||||
const headers: Record<string, string> = {
|
||||
'Accept': 'application/vnd.github.v3+json',
|
||||
'User-Agent': 'setup-github-release-action'
|
||||
@@ -20,6 +16,12 @@ export async function fetchLatestRelease(repository: string, token?: string): Pr
|
||||
if (token) {
|
||||
headers['Authorization'] = `token ${token}`;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
export async function fetchLatestRelease(repository: string, token?: string): Promise<ReleaseInfo> {
|
||||
const url = `https://api.github.com/repos/${repository}/releases/latest`;
|
||||
const headers = getGithubApiHeaders(token);
|
||||
|
||||
const response = await fetch(url, { headers });
|
||||
if (!response.ok) {
|
||||
@@ -30,6 +32,18 @@ export async function fetchLatestRelease(repository: string, token?: string): Pr
|
||||
return await response.json() as ReleaseInfo;
|
||||
}
|
||||
|
||||
export async function fetchLatestReleaseRaw(repository: string, token?: string): Promise<string> {
|
||||
const url = `https://api.github.com/repos/${repository}/releases/latest`;
|
||||
const headers = getGithubApiHeaders(token);
|
||||
|
||||
const response = await fetch(url, { headers });
|
||||
const body = await response.text();
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch latest release for ${repository}: ${response.statusText}. ${body}`);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
export async function downloadAsset(url: string, destPath: string, token?: string): Promise<void> {
|
||||
const headers: Record<string, string> = {
|
||||
'User-Agent': 'setup-github-release-action'
|
||||
|
||||
+83
-61
@@ -1,67 +1,89 @@
|
||||
import { PlatformInfo } from './platform';
|
||||
import { minimatch } from 'minimatch';
|
||||
|
||||
export interface MatchOptions {
|
||||
fileName?: string;
|
||||
fileType?: string;
|
||||
}
|
||||
type ReleaseAsset = { name: string; browser_download_url: 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;
|
||||
}
|
||||
const knownFileTypes: Record<string, string> = {
|
||||
archive: '*.{zip,tar.gz,tgz}',
|
||||
package: '*.{deb,pkg,rpm}',
|
||||
linux: '*.{deb,rpm}',
|
||||
macos: '*.pkg',
|
||||
targz: '*.{tgz,tar.gz}',
|
||||
};
|
||||
|
||||
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;
|
||||
function debugAssetList(label: string, assets: ReleaseAsset[]): void {
|
||||
console.debug(label);
|
||||
for (const asset of assets) {
|
||||
console.debug(`- ${asset.name}`);
|
||||
}
|
||||
}
|
||||
|
||||
function filterByRegex(assets: ReleaseAsset[], pattern: string, dryRun?: boolean): ReleaseAsset[] {
|
||||
const regex = new RegExp(pattern, 'i');
|
||||
const filtered = assets.filter((asset) => regex.test(asset.name));
|
||||
if (dryRun) {
|
||||
console.debug(`Filtering assets with regex: ${pattern}`);
|
||||
debugAssetList('Assets:', assets);
|
||||
debugAssetList('Matched assets:', filtered);
|
||||
}
|
||||
return filtered;
|
||||
}
|
||||
|
||||
function replacePlatformPlaceholders(pattern: string, platform: PlatformInfo): string {
|
||||
return pattern
|
||||
.replace(/{{SYSTEM}}/g, platform.systemPattern)
|
||||
.replace(/{{ARCH}}/g, platform.archPattern);
|
||||
}
|
||||
|
||||
export function getMatchingAsset(assets: ReleaseAsset[], platform: PlatformInfo, fileName?: string, fileType?: string, dryRun?: boolean): ReleaseAsset {
|
||||
// Filename provided as literal string (no ~): exact match.
|
||||
if (fileName && !fileName.startsWith('~')) {
|
||||
const exactMatches = assets.filter((asset) => asset.name === fileName);
|
||||
if (exactMatches.length !== 1) {
|
||||
throw new Error(`Expected exactly one asset to match the provided filename, matched: ${exactMatches.length}`);
|
||||
}
|
||||
return exactMatches[0];
|
||||
}
|
||||
|
||||
// Filetype filtering stage (or passthrough when not provided).
|
||||
let fileTypeFilteredAssets: ReleaseAsset[] = assets;
|
||||
if (fileType) {
|
||||
if (Object.hasOwn(knownFileTypes, fileType)) {
|
||||
// 2. Known fileType key: use predefined glob.
|
||||
const fileTypeGlob = knownFileTypes[fileType];
|
||||
fileTypeFilteredAssets = assets.filter((asset) => minimatch(asset.name, fileTypeGlob, { nocase: true }));
|
||||
} else if (fileType.startsWith('~')) {
|
||||
// 3. Custom regex fileType: match regex at end of string.
|
||||
const fileTypeRegex = `${fileType.substring(1)}$`;
|
||||
fileTypeFilteredAssets = filterByRegex(assets, fileTypeRegex, dryRun);
|
||||
} else {
|
||||
// 4. Custom extension fileType: treat as plain extension glob.
|
||||
const extension = fileType.replace(/^\./, '');
|
||||
const fileTypeGlob = `*.${extension}`;
|
||||
fileTypeFilteredAssets = assets.filter((asset) => minimatch(asset.name, fileTypeGlob, { nocase: true }));
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Filename provided with ~: platform placeholder expansion and regex filtering.
|
||||
if (fileName && fileName.startsWith('~')) {
|
||||
const fileNamePattern = replacePlatformPlaceholders(fileName.substring(1), platform);
|
||||
const fileNameFilteredAssets = filterByRegex(fileTypeFilteredAssets, fileNamePattern, dryRun);
|
||||
if (fileNameFilteredAssets.length !== 1) {
|
||||
throw new Error(`Expected exactly one asset to match the filename regex, matched: ${fileNameFilteredAssets.length}`);
|
||||
}
|
||||
return fileNameFilteredAssets[0];
|
||||
}
|
||||
|
||||
// 5. No filename: use default {{SYSTEM}}-{{ARCH}} regex.
|
||||
const defaultPattern = replacePlatformPlaceholders('{{SYSTEM}}[_-]{{ARCH}}', platform);
|
||||
const defaultFilteredAssets = filterByRegex(fileTypeFilteredAssets, defaultPattern, dryRun);
|
||||
|
||||
// 6. Zero or multiple matches are errors.
|
||||
if (defaultFilteredAssets.length !== 1) {
|
||||
const errorMessage = defaultFilteredAssets.length === 0
|
||||
? `No assets matched the default criteria: ${defaultPattern}`
|
||||
: `Multiple assets matched the default criteria: ${defaultFilteredAssets.map((asset) => asset.name).join(', ')}`;
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
return defaultFilteredAssets[0];
|
||||
}
|
||||
|
||||
+10
-5
@@ -7,6 +7,11 @@ export interface PlatformInfo {
|
||||
archPattern: string;
|
||||
}
|
||||
|
||||
export interface PlatformOverrides {
|
||||
system?: string;
|
||||
arch?: string;
|
||||
}
|
||||
|
||||
export const systemPatterns: Record<string, string> = {
|
||||
linux: 'linux',
|
||||
darwin: '(darwin|macos|mac|osx)',
|
||||
@@ -14,13 +19,13 @@ export const systemPatterns: Record<string, string> = {
|
||||
};
|
||||
|
||||
export const archPatterns: Record<string, string> = {
|
||||
x64: '(x86_64|x64|amd64)',
|
||||
arm64: '(aarch64|arm64)'
|
||||
x64: '(x86_64|x64|amd64|universal)',
|
||||
arm64: '(aarch64|arm64|universal)'
|
||||
};
|
||||
|
||||
export function getPlatformInfo(): PlatformInfo {
|
||||
const system = os.platform();
|
||||
const arch = os.arch();
|
||||
export function getPlatformInfo(overrides?: PlatformOverrides): PlatformInfo {
|
||||
const system = (overrides?.system || os.platform()).toLowerCase();
|
||||
const arch = (overrides?.arch || os.arch()).toLowerCase();
|
||||
|
||||
return {
|
||||
system,
|
||||
|
||||
+70
-6
@@ -1,19 +1,71 @@
|
||||
import * as core from '@actions/core';
|
||||
import * as tc from '@actions/tool-cache';
|
||||
import * as path from 'path';
|
||||
import * as os from 'os';
|
||||
import * as fs from 'fs';
|
||||
import { spawnSync } from 'child_process';
|
||||
import { getPlatformInfo } from './core/platform';
|
||||
import { getMatchingAsset } from './core/matcher';
|
||||
import { findBinary } from './core/finder';
|
||||
import { fetchLatestRelease } from './core/downloader';
|
||||
|
||||
function installSystemPackage(downloadPath: string): void {
|
||||
const fileName = path.basename(downloadPath).toLowerCase();
|
||||
|
||||
const command: { binary: string; args: string[] } | undefined = fileName.endsWith('.deb')
|
||||
? { binary: 'dpkg', args: ['-i', downloadPath] }
|
||||
: fileName.endsWith('.pkg')
|
||||
? { binary: 'installer', args: ['-pkg', downloadPath, '-target', '/'] }
|
||||
: fileName.endsWith('.rpm')
|
||||
? { binary: 'rpm', args: ['-i', downloadPath] }
|
||||
: undefined;
|
||||
|
||||
if (!command) {
|
||||
throw new Error(`Unsupported package type: ${fileName}`);
|
||||
}
|
||||
|
||||
const isRoot = process.getuid && process.getuid() === 0;
|
||||
const commandToRun = isRoot ? command.binary : 'sudo';
|
||||
const argsToRun = isRoot ? command.args : [command.binary, ...command.args];
|
||||
|
||||
const result = spawnSync(commandToRun, argsToRun, { stdio: 'inherit' });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`Failed to install package using ${commandToRun} ${argsToRun.join(' ')}.`);
|
||||
}
|
||||
}
|
||||
|
||||
function findInstalledBinary(binaryName: string): string | undefined {
|
||||
const isRegex = binaryName.startsWith('~');
|
||||
if (!isRegex) {
|
||||
const whichResult = spawnSync('which', [binaryName], { encoding: 'utf8' });
|
||||
if (whichResult.status === 0) {
|
||||
const resolvedPath = (whichResult.stdout || '').trim();
|
||||
if (resolvedPath) {
|
||||
return resolvedPath;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const candidates = ['/usr/local/bin', '/usr/bin', '/opt/homebrew/bin', '/opt/local/bin'];
|
||||
const pattern: string | RegExp = isRegex ? new RegExp(binaryName.substring(1), 'i') : binaryName;
|
||||
for (const candidateDir of candidates) {
|
||||
if (!fs.existsSync(candidateDir)) {
|
||||
continue;
|
||||
}
|
||||
const candidatePath = findBinary(candidateDir, pattern, false, () => undefined);
|
||||
if (candidatePath) {
|
||||
return candidatePath;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function run() {
|
||||
try {
|
||||
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 fileType = core.getInput('file-type');
|
||||
const updateCache = core.getInput('update-cache') || 'false';
|
||||
const debug = core.getBooleanInput('debug');
|
||||
const token = core.getInput('token') || process.env.GITHUB_TOKEN;
|
||||
@@ -39,10 +91,7 @@ async function run() {
|
||||
|
||||
core.info(`Fetching latest release information for ${repository}...`);
|
||||
const release = await fetchLatestRelease(repository, token);
|
||||
const asset = getMatchingAsset(release.assets, platformInfo, {
|
||||
fileName: fileNameInput,
|
||||
fileType: fileType
|
||||
});
|
||||
const asset = getMatchingAsset(release.assets, platformInfo, fileNameInput, fileType);
|
||||
|
||||
core.info(`Selected asset: ${asset.name}`);
|
||||
|
||||
@@ -67,6 +116,21 @@ async function run() {
|
||||
const nameLower = asset.name.toLowerCase();
|
||||
let toolDir: string;
|
||||
|
||||
if (/\.(deb|pkg|rpm)$/i.test(nameLower)) {
|
||||
core.info(`Installing package asset ${asset.name}...`);
|
||||
installSystemPackage(downloadPath);
|
||||
|
||||
const binaryPath = findInstalledBinary(binaryName);
|
||||
if (!binaryPath) {
|
||||
throw new Error(`Package installed, but binary "${binaryName}" could not be located in common executable paths.`);
|
||||
}
|
||||
|
||||
const binaryDir = path.dirname(binaryPath);
|
||||
core.addPath(binaryDir);
|
||||
core.info(`Binary found at ${binaryPath}. Added ${binaryDir} to PATH.`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine extraction method based on extension
|
||||
if (/\.(tar\.gz|tar|tgz)$/i.test(nameLower)) {
|
||||
toolDir = await tc.extractTar(downloadPath);
|
||||
|
||||
Reference in New Issue
Block a user