-
Notifications
You must be signed in to change notification settings - Fork 26
/
main.js
286 lines (286 loc) · 12.6 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
const cache = __importStar(require("@actions/cache"));
const core = __importStar(require("@actions/core"));
const tc = __importStar(require("@actions/tool-cache"));
const utils_1 = require("@actions/github/lib/utils");
const plugin_throttling_1 = require("@octokit/plugin-throttling");
const ThrottlingOctokit = utils_1.GitHub.plugin(plugin_throttling_1.throttling);
function run() {
return __awaiter(this, void 0, void 0, function* () {
try {
// set up auth/environment
const token = process.env['GITHUB_TOKEN'] || core.getInput("token");
const octokit = new ThrottlingOctokit(Object.assign({ throttle: {
onRateLimit: (retryAfter, options) => {
core.warning(`RateLimit detected for request ${options.method} ${options.url}.`);
core.info(`Retrying after ${retryAfter} seconds.`);
return true;
},
onSecondaryRateLimit: (retryAfter, options) => {
core.warning(`SecondaryRateLimit detected for request ${options.method} ${options.url}.`);
core.info(`Retrying after ${retryAfter} seconds.`);
return true;
},
} }, utils_1.getOctokitOptions(token)));
const repo = core.getInput("repo");
if (!repo) {
throw new Error(`Repo was not specified`);
}
const tag = core.getInput("tag");
if (!tag) {
throw new Error(`Tag not specified`);
}
const cacheEnabled = (core.getInput("cache") === "enable")
&& tag !== "latest"
&& tag !== "";
const [owner, project] = repo.split("/");
let osMatch = [];
// Determine Platform
let osPlatform = core.getInput("platform");
if (osPlatform === "") {
switch (os.platform()) {
case "linux":
osPlatform = "linux";
break;
case "darwin":
osPlatform = "darwin";
break;
case "win32":
osPlatform = "windows";
break;
default:
core.setFailed("Unsupported operating system - $this action is only released for Darwin, Linux and Windows");
return;
}
}
osMatch.push(osPlatform);
core.info(`==> System reported platform: ${os.platform()}`);
core.info(`==> Using platform: ${osPlatform}`);
// Determine Architecture
let osArch = core.getInput("arch");
if (osArch === "") {
osArch = os.arch();
switch (os.arch()) {
case "x64":
osMatch.push("x86_64", "x64", "amd64");
break;
default:
osMatch.push(os.arch());
return;
}
}
else {
osMatch.push(osArch);
}
core.info(`==> System reported arch: ${os.arch()}`);
core.info(`==> Using arch: ${osArch}`);
// Determine File Extensions (if any)
const extMatching = core.getInput("extension-matching") === "enable";
let extension = core.getInput("extension");
let extMatchRegexForm = "";
if (extMatching) {
if (extension === "") {
extMatchRegexForm = "\.(tar.gz|zip)";
core.info(`==> Using default file extension matching: ${extMatchRegexForm}`);
}
else {
extMatchRegexForm = extension;
core.info(`==> Using custom file extension matching: ${extMatchRegexForm}`);
}
}
else {
core.info("==> File extension matching disabled");
}
// Determine whether renaming is in use
let renameTo = core.getInput("rename-to");
if (renameTo !== "") {
core.info(`==> Will rename downloaded release to ${renameTo}`);
}
let chmodTo = core.getInput("chmod");
if (chmodTo !== "") {
core.info(`==> Will chmod downloaded release asset to ${chmodTo}`);
}
let toolInfo = {
owner: owner,
project: project,
tag: tag,
osArch: osArch,
osPlatform: osPlatform
};
let dest = toolPath(toolInfo);
// Look in the cache first.
let cacheKey = cachePrimaryKey(toolInfo);
if (cacheEnabled && cacheKey !== undefined) {
let ok = yield cache.restoreCache([dest], cacheKey);
if (ok !== undefined) {
core.info(`Found ${project} in the cache: ${dest}`);
core.addPath(dest);
return;
}
}
let getReleaseUrl;
if (tag === "latest") {
getReleaseUrl = yield octokit.rest.repos.getLatestRelease({
owner: owner,
repo: project,
});
}
else {
getReleaseUrl = yield octokit.rest.repos.getReleaseByTag({
owner: owner,
repo: project,
tag: tag,
});
}
let osMatchRegexForm = `(${osMatch.join('|')})`;
let re = new RegExp(`${osMatchRegexForm}.*${osMatchRegexForm}.*${extMatchRegexForm}`);
let asset = getReleaseUrl.data.assets.find(obj => {
core.info(`searching for ${obj.name} with ${re.source}`);
let normalized_obj_name = obj.name.toLowerCase();
return re.test(normalized_obj_name);
});
if (!asset) {
const found = getReleaseUrl.data.assets.map(f => f.name);
throw new Error(`Could not find a release for ${tag}. Found: ${found}`);
}
const url = asset.url;
core.info(`Downloading ${project} from ${url}`);
const binPath = yield tc.downloadTool(url, undefined, `token ${token}`, {
accept: 'application/octet-stream'
});
const extractFn = getExtractFn(asset.name);
if (extractFn !== undefined) {
// Release is an archive file so extract it to the destination
yield extractFn(binPath, dest);
core.info(`Automatically extracted release asset ${asset.name} to ${dest}`);
if (renameTo !== "") {
core.warning("rename-to parameter ignored when installing a release from an archive");
}
if (chmodTo !== "") {
core.warning("chmod parameter ignored when installing a release from an archive");
}
}
else {
// As it wasn't an archive we've just downloaded it as a blob, this uses an auto-assigned name which will
// be a UUID which is likely meaningless to the caller. If they have specified a rename-to and a chmod
// parameter then this is where we apply those.
// Regardless of any rename-to parameter we still need to move the download to the actual destination
// otherwise it won't end up on the path as expected
core.warning(`Release asset ${asset.name} did not have a recognised file extension, unable to automatically extract it`);
try {
fs.mkdirSync(dest, { 'recursive': true });
const outputPath = path.join(dest, renameTo !== "" ? renameTo : path.basename(binPath));
core.info(`Created output directory ${dest}`);
try {
fs.renameSync(binPath, outputPath);
core.info(`Moved release asset ${asset.name} to ${outputPath}`);
if (chmodTo !== "") {
try {
fs.chmodSync(outputPath, chmodTo);
core.info(`chmod'd ${outputPath} to ${chmodTo}`);
}
catch (chmodErr) {
core.setFailed(`Failed to chmod ${outputPath} to ${chmodTo}: ${chmodErr}`);
}
}
}
catch (renameErr) {
core.setFailed(`Failed to move downloaded release asset ${asset.name} from ${binPath} to ${outputPath}: ${renameErr}`);
}
}
catch (err) {
core.setFailed(`Failed to create required output directory ${dest}`);
}
}
if (cacheEnabled && cacheKey !== undefined) {
try {
yield cache.saveCache([dest], cacheKey);
}
catch (error) {
const typedError = error;
if (typedError.name === cache.ValidationError.name) {
throw error;
}
else if (typedError.name === cache.ReserveCacheError.name) {
core.info(typedError.message);
}
else {
core.warning(typedError.message);
}
}
}
core.addPath(dest);
core.info(`Successfully installed ${project} to ${dest}`);
}
catch (error) {
if (error instanceof Error) {
core.setFailed(error.message);
}
else {
core.setFailed("catastrophic failure, please file an issue");
}
}
});
}
function cachePrimaryKey(info) {
// Currently not caching "latest" versions of the tool.
if (info.tag === "latest") {
return undefined;
}
return "action-install-gh-release/" +
`${info.owner}/${info.project}/${info.tag}/${info.osPlatform}-${info.osArch}`;
}
function toolPath(info) {
return path.join(getCacheDirectory(), info.owner, info.project, info.tag, `${info.osPlatform}-${info.osArch}`);
}
function getCacheDirectory() {
const cacheDirectory = process.env['RUNNER_TOOL_CACHE'] || '';
if (cacheDirectory === '') {
core.warning('Expected RUNNER_TOOL_CACHE to be defined');
}
return cacheDirectory;
}
function getExtractFn(assetName) {
if (assetName.endsWith('.tar.gz') || assetName.endsWith('.tar.bz2')) {
return tc.extractTar;
}
else if (assetName.endsWith('.zip')) {
return tc.extractZip;
}
else {
return undefined;
}
}
run();