const fs = require('fs'); const path = require('path'); const CONTENT_DIR = path.join(__dirname, '../content/post'); async function processFiles(dir) { const files = await fs.promises.readdir(dir); for (const file of files) { const filePath = path.join(dir, file); const stats = await fs.promises.stat(filePath); if (stats.isDirectory()) { await processFiles(filePath); continue; } if (!file.endsWith('.md')) continue; let content = await fs.promises.readFile(filePath, 'utf8'); // Match Front Matter (handling BOM) const match = content.match(/^[\ufeff]?---\r?\n([\s\S]*?)\r?\n---/); if (!match) { // Try matching without BOM anchor if needed, or maybe just log // console.log(`[Skip] ${file}: No front matter found`); continue; } const fmContent = match[1]; const lines = fmContent.split(/\r?\n/); const keyMap = new Map(); const linesToDelete = new Set(); // Identify keys and their positions lines.forEach((line, index) => { const keyMatch = line.match(/^([a-zA-Z0-9_-]+):/); if (keyMatch) { const key = keyMatch[1]; if (!keyMap.has(key)) { keyMap.set(key, []); } keyMap.get(key).push(index); } }); let modified = false; // Check for duplicates for (const [key, indices] of keyMap.entries()) { if (indices.length > 1) { // Keep the LAST occurrence for (let i = 0; i < indices.length - 1; i++) { linesToDelete.add(indices[i]); } modified = true; console.log(`[Fixing] ${file}: Removing duplicate key '${key}' at lines ${indices.slice(0, -1).join(', ')} (keeping line ${indices[indices.length - 1]})`); } } if (modified) { const newFmLines = lines.filter((_, index) => !linesToDelete.has(index)); const newFm = newFmLines.join('\n'); // Reconstruct file const newContent = content.replace(match[0], `---\n${newFm}\n---`); await fs.promises.writeFile(filePath, newContent, 'utf8'); console.log(`[Success] Updated ${file}`); } } } console.log('Starting YAML Fixer...'); processFiles(CONTENT_DIR).catch(console.error);