refactor: improve robustness and security of theme update script

This commit is contained in:
KozakLordOfMatrix 2026-06-14 21:10:06 +03:00
parent 1dc5811b7a
commit a9416c02da

View file

@ -1,19 +1,39 @@
const { exec } = require("child_process");
const { execSync } = require("child_process");
const fs = require("fs");
const path = require("path");
const os = require("os");
const repositoryUrl = "https://github.com/zeon-studio/hugoplate";
const localDirectory = "./themes/hugoplate";
const localDirectory = path.join(__dirname, "../themes/hugoplate");
const foldersToFetch = ["assets", "layouts"];
const foldersToSkip = ["exampleSite"];
const fetchFolder = (folder) => {
exec(
`curl -L ${repositoryUrl}/tarball/main | tar -xz --strip-components=1 --directory=${localDirectory} --exclude=$(curl -sL ${repositoryUrl}/tarball/main | tar -tz | grep -E "/(${foldersToSkip.join(
"|",
)})/") */${folder}`,
);
};
// Create a temporary directory for the update process
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "hugoplate-update-"));
// Fetch each specified folder
foldersToFetch.forEach((folder) => {
fetchFolder(folder);
});
try {
// Download and extract the repository once to a temporary directory
// to improve performance and avoid fragile shell piping.
execSync(`curl -L ${repositoryUrl}/tarball/main | tar -xz -C ${tempDir} --strip-components=1`);
foldersToFetch.forEach((folder) => {
const sourceFolder = path.join(tempDir, folder);
const destinationFolder = path.join(localDirectory, folder);
if (fs.existsSync(sourceFolder)) {
console.log(`Updating ${folder}...`);
if (fs.existsSync(destinationFolder)) {
fs.rmSync(destinationFolder, { recursive: true, force: true });
}
fs.mkdirSync(destinationFolder, { recursive: true });
// Use fs.cpSync for recursive copy
fs.cpSync(sourceFolder, destinationFolder, { recursive: true });
}
});
console.log("Update complete.");
} catch (error) {
console.error("Update failed:", error.message);
process.exit(1);
} finally {
// Cleanup the temporary directory
fs.rmSync(tempDir, { recursive: true, force: true });
}