// One-time move of a site from the database version of this blog to post // files. Reads every row of the old `posts` table and writes // content/blog/.md with the front matter the loader reads, keeping // each post's createdAt, publishedAt and updatedAt as stored. It parses every // file it writes back through readPostFile, so a file it reports as written // is one the loader accepts. // // pnpm tsx --env-file=.env.local scripts/export-posts.ts write files that do not exist yet // pnpm tsx --env-file=.env.local scripts/export-posts.ts --force also overwrite files that differ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { CONTENT_DIR, readPostFile } from "@/lib/blog/files"; import { neon } from "@neondatabase/serverless"; import { asc, sql } from "drizzle-orm"; import { drizzle } from "drizzle-orm/neon-http"; import { boolean, pgTable, text, timestamp } from "drizzle-orm/pg-core"; // The posts table as the database version of the blog defined it export const posts = pgTable("posts", { slug: text().primaryKey(), title: text().notNull(), description: text().notNull(), category: text().notNull(), primaryKeyword: text("primary_keyword").notNull().unique(), secondaryKeywords: text("secondary_keywords") .array() .notNull() .default(sql`'{}'::text[]`), length: text().notNull(), tags: text() .array() .notNull() .default(sql`'{}'::text[]`), author: text().notNull(), image: text(), body: text().notNull(), draft: boolean().notNull().default(true), createdAt: timestamp("created_at", { withTimezone: true }) .notNull() .defaultNow(), publishedAt: timestamp("published_at", { withTimezone: true }), updatedAt: timestamp("updated_at", { withTimezone: true }), seededHash: text("seeded_hash"), }); export type PostRow = typeof posts.$inferSelect; export type Outcome = "written" | "overwritten" | "unchanged" | "skipped"; /** One row as a post file. A row the old pages hid (draft, or no publish date) stays a draft. */ export function toFile(row: PostRow): string { const draft = row.draft || !row.publishedAt; const lines = [ `title: ${JSON.stringify(row.title)}`, `description: ${JSON.stringify(row.description)}`, `category: ${row.category}`, `primaryKeyword: ${JSON.stringify(row.primaryKeyword)}`, `secondaryKeywords: ${JSON.stringify(row.secondaryKeywords)}`, `length: ${row.length}`, `tags: ${JSON.stringify(row.tags)}`, `author: ${row.author}`, ...(row.image ? [`image: ${JSON.stringify(row.image)}`] : []), `createdAt: ${row.createdAt.toISOString()}`, ...(row.publishedAt ? [`publishedAt: ${row.publishedAt.toISOString()}`] : []), ...(row.updatedAt ? [`updatedAt: ${row.updatedAt.toISOString()}`] : []), `draft: ${draft}`, ]; return `---\n${lines.join("\n")}\n---\n\n${row.body.trim()}\n`; } export type ExportResult = { slug: string; outcome: Outcome; problem?: string }; export function exportRows( rows: PostRow[], { force = false } = {}, ): ExportResult[] { mkdirSync(CONTENT_DIR, { recursive: true }); return rows.map((row) => { const file = join(CONTENT_DIR, `${row.slug}.md`); const text = toFile(row); let outcome: Outcome = "written"; if (existsSync(file)) { if (readFileSync(file, "utf8") === text) return { slug: row.slug, outcome: "unchanged" }; if (!force) return { slug: row.slug, outcome: "skipped" }; outcome = "overwritten"; } writeFileSync(file, text); try { readPostFile(row.slug); return { slug: row.slug, outcome }; } catch (e) { return { slug: row.slug, outcome, problem: e instanceof Error ? e.message : String(e), }; } }); } /** Prints one line per changed file and the totals. Returns false when a written file needs fixing. */ export function summarize(results: ExportResult[]): boolean { for (const r of results) if (r.outcome !== "unchanged") console.log(`${r.outcome.padEnd(12)} ${r.slug}`); const problems = results.filter((r) => r.problem); const count = (o: Outcome) => results.filter((r) => r.outcome === o).length; console.log( `\n${results.length} rows: ${count("written")} written, ${count("overwritten")} overwritten, ${count("unchanged")} unchanged, ${count("skipped")} skipped because the file exists and differs`, ); if (count("skipped")) console.log( "Compare a skipped file with its row, then rerun with --force to take the database copy.", ); for (const r of problems) console.error(`fix before the loader can read it: ${r.problem}`); return problems.length === 0; } async function main() { const url = process.env.NEON_URL; if (!url) throw new Error("NEON_URL is not set"); const rows = await drizzle(neon(url)) .select() .from(posts) .orderBy(asc(posts.slug)); const ok = summarize( exportRows(rows, { force: process.argv.includes("--force") }), ); if (!ok) process.exitCode = 1; } if (process.argv[1]?.endsWith("export-posts.ts")) main().catch((e) => { console.error(e); process.exit(1); });