-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgen-codes.ts
More file actions
executable file
·251 lines (216 loc) · 6.78 KB
/
gen-codes.ts
File metadata and controls
executable file
·251 lines (216 loc) · 6.78 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
#!/usr/bin/env bun
import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { Code, type Kind } from "../src/utils/code";
const CONTENT_DIR = `${import.meta.dir}/../src/content`;
const DEFAULT_DIRS = ["blog", "games", "research", "projects", "talks"];
/**
* Infer kind prefix from directory name
*/
function inferKind(dir: string): Kind {
switch (dir) {
case "blog":
return "B";
case "games":
return "G";
case "research":
return "R";
case "projects":
return "P";
case "talks":
return "T";
case "micro":
return "M";
default:
throw new Error(`Unknown content directory: ${dir}`);
}
}
/**
* Parse frontmatter from MDX content
*/
function parseFrontmatter(content: string): { data: Record<string, any>; body: string } {
const match = content.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
if (!match) {
return { data: {}, body: content };
}
const yamlStr = match[1];
const body = match[2];
const data = Bun.YAML.parse(yamlStr) as Record<string, any>;
return { data, body };
}
/**
* Stringify a YAML value with proper indentation
*/
function stringifyYAMLValue(value: any, indent: number): string[] {
const lines: string[] = [];
const indentStr = " ".repeat(indent);
if (Array.isArray(value)) {
for (const item of value) {
if (typeof item === "object" && item !== null) {
lines.push(`${indentStr}-`);
for (const [k, v] of Object.entries(item)) {
if (typeof v === "object" && v !== null && !Array.isArray(v)) {
lines.push(`${indentStr} ${k}:`);
lines.push(...stringifyYAMLValue(v, indent + 2));
} else if (Array.isArray(v)) {
lines.push(`${indentStr} ${k}:`);
lines.push(...stringifyYAMLValue(v, indent + 2));
} else {
lines.push(`${indentStr} ${k}: ${v}`);
}
}
} else {
lines.push(`${indentStr}- ${item}`);
}
}
} else if (typeof value === "object" && value !== null) {
for (const [k, v] of Object.entries(value)) {
if (typeof v === "object" && v !== null && !Array.isArray(v)) {
lines.push(`${indentStr}${k}:`);
lines.push(...stringifyYAMLValue(v, indent + 1));
} else if (Array.isArray(v)) {
lines.push(`${indentStr}${k}:`);
lines.push(...stringifyYAMLValue(v, indent + 1));
} else {
lines.push(`${indentStr}${k}: ${v}`);
}
}
}
return lines;
}
/**
* Stringify frontmatter data into YAML format
*/
function stringifyFrontmatter(data: Record<string, any>): string {
const lines: string[] = [];
for (const [key, value] of Object.entries(data)) {
if (Array.isArray(value)) {
lines.push(`${key}:`);
lines.push(...stringifyYAMLValue(value, 1));
} else if (typeof value === "object" && value !== null) {
lines.push(`${key}:`);
lines.push(...stringifyYAMLValue(value, 1));
} else {
lines.push(`${key}: ${value}`);
}
}
return lines.join("\n");
}
/**
* Extract the date from MDX frontmatter
*/
function extractDate(content: string): string | null {
const { data } = parseFrontmatter(content);
return data.date ? String(data.date) : null;
}
/**
* Update or add the code field in frontmatter
*/
function updateFrontmatterCode(content: string, code: string): string {
const { data, body } = parseFrontmatter(content);
data.code = code;
const frontmatter = stringifyFrontmatter(data);
return `---\n${frontmatter}\n---\n${body}`;
}
/**
* Process files in a single directory
*/
function processDirectory(dir: string) {
const dirPath = join(CONTENT_DIR, dir);
const kind = inferKind(dir);
// Check if directory exists
if (!existsSync(dirPath)) {
console.log(`⚠️ Directory ${dir} does not exist, skipping...\n`);
return { processed: 0, skipped: 0, errors: 0, total: 0 };
}
console.log(`Processing files in: ${dir} (kind: ${kind})\n`);
// Get all .mdx files
const allFiles = readdirSync(dirPath);
const mdxFiles = allFiles
.filter((file) => file.endsWith(".mdx"))
.map((file) => join(dirPath, file));
if (mdxFiles.length === 0) {
console.log(`No .mdx files found in ${dir}\n`);
return { processed: 0, skipped: 0, errors: 0, total: 0 };
}
let processedCount = 0;
let skippedCount = 0;
let errorCount = 0;
for (const filePath of mdxFiles) {
const filename = filePath.split("/").pop()!;
try {
// Read file content
const content = readFileSync(filePath, "utf-8");
const { data } = parseFrontmatter(content);
// Check if code already exists in frontmatter
if (data.code) {
console.log(`⏭ Skipping ${filename} (code already in frontmatter)`);
skippedCount++;
continue;
}
// Generate code from date
const dateString = extractDate(content);
if (!dateString) {
console.log(`❌ No date found in ${filename}`);
errorCount++;
continue;
}
// Generate code from date with kind prefix (lowercase)
const code = Code.fromDateString(dateString, kind);
const codeStr = code.toString().toLowerCase();
// Update frontmatter with code
const updatedContent = updateFrontmatterCode(content, codeStr);
writeFileSync(filePath, updatedContent);
console.log(`✅ ${filename} (added code ${codeStr} to frontmatter)`);
processedCount++;
} catch (error) {
console.error(
`❌ Error processing ${filename}:`,
error instanceof Error ? error.message : error,
);
errorCount++;
}
}
console.log();
return {
processed: processedCount,
skipped: skippedCount,
errors: errorCount,
total: mdxFiles.length,
};
}
/**
* Main function to generate codes for all content files
*/
function genCodes(dirs: string[]) {
console.log(`Content directory: ${CONTENT_DIR}`);
console.log(`Directories to process: ${dirs.join(", ")}\n`);
console.log("=".repeat(50) + "\n");
let totalProcessed = 0;
let totalSkipped = 0;
let totalErrors = 0;
let totalFiles = 0;
for (const dir of dirs) {
const result = processDirectory(dir);
totalProcessed += result.processed;
totalSkipped += result.skipped;
totalErrors += result.errors;
totalFiles += result.total;
}
// Summary
console.log("=".repeat(50));
console.log("Overall Summary:");
console.log(` Processed: ${totalProcessed}`);
console.log(` Skipped: ${totalSkipped}`);
console.log(` Errors: ${totalErrors}`);
console.log(` Total: ${totalFiles}`);
}
// Parse command line arguments or use defaults
const dirs = process.argv.slice(2).length > 0 ? process.argv.slice(2) : DEFAULT_DIRS;
// Run the script
try {
genCodes(dirs);
} catch (error) {
console.error("Fatal error:", error);
process.exit(1);
}