Skip to content

Commit

Permalink
refactor: prefer Uint8Array & early filename validation
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW authored and outloudvi committed Jan 27, 2024
1 parent cc739b4 commit ee1562d
Showing 1 changed file with 16 additions and 21 deletions.
37 changes: 16 additions & 21 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const core = require("@actions/core");
const fs = require("node:fs");
const path = require("node:path");
const { Buffer } = require("node:buffer");

function getFilenameFromUrl(url) {
const u = new URL(url);
Expand All @@ -18,11 +17,10 @@ async function tryFetch(url, retryTimes) {
for (let i = 0; i <= retryTimes; i++) {
result = await fetch(url)
.then((x) => x.arrayBuffer())
.then((x) => Buffer.from(x))
.then((x) => new Uint8Array(x))
.catch((err) => {
console.error(
`${
i === 0 ? "" : `[Retry ${i}/${retryTimes}]`
`${i === 0 ? "" : `[Retry ${i}/${retryTimes}]`
}Fail to download file ${url}: ${err}`
);
if (i === retryTimes) {
Expand Down Expand Up @@ -54,17 +52,25 @@ async function main() {
}
const url = (() => {
if (!autoMatch) return text;
if (autoMatch) {
const match = text.match(/\((.*)\)/);
if (match === null) return "";
return match[1] || "";
}
// 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,
Expand All @@ -76,18 +82,7 @@ async function main() {
const body = await tryFetch(url, retryTimes);
if (body === FetchFailure) return;
console.log("Download completed.");
let finalFilename = "";
if (filename) {
finalFilename = String(filename);
} else {
finalFilename = getFilenameFromUrl(url);
}
if (finalFilename === "") {
core.setFailed(
"Filename not found. Please indicate it in the URL or set `filename` in the workflow."
);
return;
}

fs.writeFileSync(path.join(target, finalFilename), body);
console.log("File saved.");
core.setOutput("filename", finalFilename);
Expand Down

0 comments on commit ee1562d

Please sign in to comment.