add-frontmatter.js 1.1 KB
const fs = require('fs');
const path = require('path');

const docsDir = 'd:/Code/knowledgebase/knowledgebase-site/docs';

function walk(dir) {
  fs.readdirSync(dir).forEach(f => {
    const fp = path.join(dir, f);
    if (fs.statSync(fp).isDirectory() && f !== '_assets') {
      walk(fp);
    } else if (f.endsWith('.md') && f !== 'README.md') {
      const rel = path.relative(docsDir, fp).replace(/\\/g, '/');
      // Remove number prefixes from path segments: 01-产品总览 -> 产品总览
      const slug = '/' + rel
        .replace(/\.md$/, '')
        .split('/')
        .map(seg => seg.replace(/^\d+-/, ''))
        .join('/');

      const content = fs.readFileSync(fp, 'utf8');
      if (!content.startsWith('---')) {
        const titleMatch = content.match(/^#\s+(.+)/m);
        const t = titleMatch ? titleMatch[1] : path.basename(f, '.md');
        const frontmatter = `---\nslug: "${slug}"\ntitle: "${t.replace(/"/g, '\\"')}"\n---\n\n`;
        fs.writeFileSync(fp, frontmatter + content);
        console.log('Added: ' + slug + ' -> ' + f);
      }
    }
  });
}

walk(docsDir);
console.log('Done!');