33 lines
1.6 KiB
JavaScript
33 lines
1.6 KiB
JavaScript
import { readdir, readFile, mkdir, writeFile, unlink } from "node:fs/promises";
|
|
import { fileURLToPath } from "node:url";
|
|
import { join } from "node:path";
|
|
|
|
const source = fileURLToPath(new URL("../database/migrations/", import.meta.url));
|
|
const target = fileURLToPath(new URL("../backend/internal/migrations/sql/", import.meta.url));
|
|
const check = process.argv.includes("--check");
|
|
if (process.argv.length > 3 || (process.argv.length === 3 && !check)) {
|
|
throw new Error("Usage: node scripts/sync-go-migrations.mjs [--check]");
|
|
}
|
|
if (!check) await mkdir(target, { recursive: true });
|
|
const sourceFiles = (await readdir(source)).filter((name) => name.endsWith(".sql")).sort();
|
|
const targetFiles = (await readdir(target)).filter((name) => name.endsWith(".sql")).sort();
|
|
const sourceSet = new Set(sourceFiles);
|
|
const stale = targetFiles.filter((name) => !sourceSet.has(name));
|
|
if (check && stale.length) {
|
|
throw new Error(`Go migration bundle has stale files: ${stale.join(", ")}; run npm run db:bundle`);
|
|
}
|
|
for (const name of stale) await unlink(join(target, name));
|
|
for (const name of sourceFiles) {
|
|
const canonical = await readFile(join(source, name));
|
|
let bundled;
|
|
try {
|
|
bundled = await readFile(join(target, name));
|
|
} catch (error) {
|
|
if (error.code !== "ENOENT") throw error;
|
|
}
|
|
if (bundled?.equals(canonical)) continue;
|
|
if (check) throw new Error(`Go migration bundle differs at ${name}; run npm run db:bundle`);
|
|
await writeFile(join(target, name), canonical);
|
|
}
|
|
console.log(check ? `Go migration bundle current (${sourceFiles.length} files)` : `Go migration bundle synchronized (${sourceFiles.length} files)`);
|