-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathconvert-markdown.mjs
More file actions
67 lines (50 loc) · 1.92 KB
/
convert-markdown.mjs
File metadata and controls
67 lines (50 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
function convertMarkdownFile(filePath) {
const content = fs.readFileSync(filePath, 'utf-8');
// Normalize line endings
const normalizedContent = content.replace(/\r\n/g, '\n');
// Parse frontmatter
const frontmatterMatch = normalizedContent.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
if (!frontmatterMatch) {
console.log(`No frontmatter found in ${filePath}`);
return false;
}
const [, frontmatter, markdownContent] = frontmatterMatch;
// Check if it has setup frontmatter
const setupMatch = frontmatter.match(/setup:\s*\|\s*\n([\s\S]*?)(?=\n\w+:|$)/);
if (!setupMatch) {
console.log(`No setup found in ${filePath}`);
return false;
}
const setupCode = setupMatch[1].trim();
// Remove setup from frontmatter
const newFrontmatter = frontmatter.replace(/setup:\s*\|\s*\n([\s\S]*?)(?=\n\w+:|$)/, '').trim();
// Create new content with imports at the top
const newContent = `---\n${newFrontmatter}\n---\n${setupCode}\n\n${markdownContent}`;
// Write to .mdx file
const mdxPath = filePath.replace('.md', '.mdx');
fs.writeFileSync(mdxPath, newContent);
// Remove old .md file
fs.unlinkSync(filePath);
console.log(`Converted ${filePath} to ${mdxPath}`);
return true;
}
function processDirectory(dirPath) {
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dirPath, entry.name);
if (entry.isDirectory()) {
processDirectory(fullPath);
} else if (entry.isFile() && entry.name.endsWith('.md')) {
convertMarkdownFile(fullPath);
}
}
}
// Process src/pages directory
const pagesDir = path.join(__dirname, 'src', 'pages');
processDirectory(pagesDir);
console.log('Conversion complete!');