Files
rustycms/scripts/tag-add-prefix.mjs

67 lines
2.0 KiB
JavaScript

#!/usr/bin/env node
/**
* Fügt allen Tags das Präfix "tag-" hinzu: Dateiname und _slug werden zu "tag-" + bisheriger Slug.
* Aktualisiert alle Referenzen in content/de (postTag, filterByTag, tags, tagWhitelist).
*/
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const CONTENT_DE = path.join(__dirname, "..", "content", "de");
const TAG_DIR = path.join(CONTENT_DE, "tag");
function parseJson5(str) {
try {
return JSON.parse(str);
} catch {
return null;
}
}
const files = fs.readdirSync(TAG_DIR).filter((f) => f.endsWith(".json5"));
const oldToNew = new Map();
for (const file of files) {
const oldSlug = file.replace(/\.json5$/, "");
if (oldSlug.startsWith("tag-")) continue;
oldToNew.set(oldSlug, "tag-" + oldSlug);
}
console.log("Präfix tag- für", oldToNew.size, "Tags");
for (const [oldSlug, newSlug] of oldToNew) {
const filePath = path.join(TAG_DIR, oldSlug + ".json5");
const data = parseJson5(fs.readFileSync(filePath, "utf8"));
data._slug = newSlug;
const newPath = path.join(TAG_DIR, newSlug + ".json5");
fs.writeFileSync(newPath, JSON.stringify(data, null, 2) + "\n", "utf8");
fs.unlinkSync(filePath);
}
function walkDir(dir, fn) {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const e of entries) {
const full = path.join(dir, e.name);
if (e.isDirectory()) walkDir(full, fn);
else if (e.name.endsWith(".json5")) fn(full);
}
}
walkDir(CONTENT_DE, (filePath) => {
let content = fs.readFileSync(filePath, "utf8");
let changed = false;
for (const [oldSlug, newSlug] of oldToNew) {
const escaped = oldSlug.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const newContent = content.replace(new RegExp('"' + escaped + '"', "g"), '"' + newSlug + '"');
if (newContent !== content) {
content = newContent;
changed = true;
}
}
if (changed) fs.writeFileSync(filePath, content, "utf8");
});
console.log("Fertig. Tag-Präfix gesetzt und Referenzen aktualisiert.");