@ikona/cli
Version:
63 lines (60 loc) • 1.55 kB
JavaScript
// src/utils/validations.ts
import fsExtra from "fs-extra";
import { join, extname } from "node:path";
// src/utils/hash.ts
function addHashToSpritePath(path, hash) {
return path.replace(/\.svg$/, `.${hash}.svg`);
}
// src/utils/validations.ts
function validatePath(path, errorMessage) {
if (!path) {
throw new Error(errorMessage);
}
}
function clear(folderPath) {
fsExtra.readdir(folderPath, (err, files) => {
if (err) {
console.error("Error reading folder:", err);
return;
}
const svgFiles = files.filter(
(file) => extname(file).toLowerCase() === ".svg" && file.startsWith("sprite")
);
svgFiles.forEach((svgFile) => {
const filePath = join(folderPath, svgFile);
fsExtra.unlink(filePath, (err2) => {
if (err2) {
console.error(`Error removing file ${filePath}:`, err2);
} else {
console.log(`Removed file: ${filePath}`);
}
});
});
});
}
async function writeIfChanged({
filepath,
newContent,
hash,
force
}) {
let _filepath = filepath;
if (hash) {
_filepath = addHashToSpritePath(filepath, hash);
}
const currentContent = await fsExtra.readFile(_filepath, "utf8").catch(() => "");
const shouldSkip = currentContent === newContent && force !== true;
if (shouldSkip)
return false;
if (hash) {
const folder = filepath.replace(/sprite\.svg$/, ``);
clear(folder);
}
await fsExtra.writeFile(_filepath, newContent, "utf8");
return true;
}
export {
clear,
validatePath,
writeIfChanged
};