-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
94 lines (87 loc) · 2.65 KB
/
index.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
const core = require("@actions/core");
const fs = require("node:fs");
const path = require("node:path");
function getFilenameFromUrl(url) {
const u = new URL(url);
const pathname = u.pathname;
const pathClips = pathname.split("/");
const filenameWithArgs = pathClips[pathClips.length - 1];
return filenameWithArgs.replace(/\?.*/, "");
}
const FetchFailure = Symbol("FetchFailure");
async function tryFetch(url, retryTimes) {
let result;
for (let i = 0; i <= retryTimes; i++) {
result = await fetch(url)
.then((x) => x.arrayBuffer())
.then((x) => new Uint8Array(x))
.catch((err) => {
console.error(
`${i === 0 ? "" : `[Retry ${i}/${retryTimes}]`
}Fail to download file ${url}: ${err}`
);
if (i === retryTimes) {
core.setFailed(`Fail to download file ${url}: ${err}`);
}
return FetchFailure;
});
if (result !== FetchFailure) return result;
}
return FetchFailure;
}
async function main() {
try {
const text = core.getInput("url");
const target = core.getInput("target");
const filename = core.getInput("filename");
let autoMatch = core.getInput("auto-match");
if (["false", "0"].includes(autoMatch.toLowerCase().trim())) {
autoMatch = false;
} else {
autoMatch = true;
}
const retryTimesValue = core.getInput("retry-times");
const retryTimes = Number(retryTimesValue);
if (Number.isNaN(retryTimes)) {
core.setFailed(`Invalid value for "retry-times": ${retryTimesValue}`);
return;
}
const url = (() => {
if (!autoMatch) return text;
// if (autoMatch) {
const match = text.match(/\((.*)\)/);
if (match === null) return "";
return match[1] || "";
// }
})();
if (url.trim() === "") {
core.setFailed("Failed to find a URL.");
return;
}
console.log(`URL found: ${url}`);
let finalFilename = filename ? String(filename) : getFilenameFromUrl(url);
if (finalFilename === "") {
core.setFailed(
"Filename not found. Please indicate it in the URL or set `filename` in the workflow."
);
return;
}
try {
fs.mkdirSync(target, {
recursive: true,
});
} catch (e) {
core.setFailed(`Failed to create target directory ${target}: ${e}`);
return;
}
const body = await tryFetch(url, retryTimes);
if (body === FetchFailure) return;
console.log("Download completed.");
fs.writeFileSync(path.join(target, finalFilename), body);
console.log("File saved.");
core.setOutput("filename", finalFilename);
} catch (error) {
core.setFailed(error.message);
}
}
main();