Files
klz-cables.com/scripts/fix-mdx-frontmatter.js
2026-01-17 01:22:01 +01:00

88 lines
2.4 KiB
JavaScript

const fs = require('fs');
const path = require('path');
const blogDir = path.join(process.cwd(), 'data', 'blog');
function fixFile(filePath) {
const content = fs.readFileSync(filePath, 'utf8');
const lines = content.split('\n');
if (lines[0].trim() !== '---') {
return; // Not a frontmatter file or already fixed/different format
}
let newLines = [];
let inFrontmatter = false;
let frontmatterLines = [];
let contentLines = [];
// Separate frontmatter and content
if (lines[0].trim() === '---') {
inFrontmatter = true;
let i = 1;
// Skip empty line after first ---
if (lines[1].trim() === '') {
i = 2;
}
for (; i < lines.length; i++) {
if (lines[i].trim() === '---') {
inFrontmatter = false;
contentLines = lines.slice(i + 1);
break;
}
frontmatterLines.push(lines[i]);
}
}
// Process frontmatter lines to fix multiline strings
let fixedFrontmatter = [];
for (let i = 0; i < frontmatterLines.length; i++) {
let line = frontmatterLines[i];
// Check for multiline indicator >-
if (line.includes('>-')) {
const [key, ...rest] = line.split(':');
if (rest.join(':').trim() === '>-') {
// It's a multiline start
let value = '';
let j = i + 1;
while (j < frontmatterLines.length) {
const nextLine = frontmatterLines[j];
// If next line is a new key (contains : and doesn't start with space), stop
if (nextLine.includes(':') && !nextLine.startsWith(' ')) {
break;
}
value += (value ? ' ' : '') + nextLine.trim();
j++;
}
fixedFrontmatter.push(`${key}: '${value.replace(/'/g, "''")}'`);
i = j - 1; // Skip processed lines
} else {
fixedFrontmatter.push(line);
}
} else {
fixedFrontmatter.push(line);
}
}
const newContent = `---\n${fixedFrontmatter.join('\n')}\n---\n${contentLines.join('\n')}`;
fs.writeFileSync(filePath, newContent);
console.log(`Fixed ${filePath}`);
}
function processDir(dir) {
const files = fs.readdirSync(dir);
for (const file of files) {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
processDir(filePath);
} else if (file.endsWith('.mdx')) {
fixFile(filePath);
}
}
}
processDir(blogDir);