Ctrl K
ComunidadGuías…

packages/desktop/script/migration.ts

Rama dev · réplica de lectura del repositorio original.

Archivo original ↗Preguntar a KiBot
#!/usr/bin/env bun
// Renders the drizzle-kit output under src/main/storage/migration into migration.gen.ts so the
// main bundle and Bun tests import plain TypeScript instead of reading SQL files at runtime.
//
//   bun run migration --name <change>   generate a migration from schema.ts, then render
//   bun run migration                   render only
//   bun run migration --check           fail when the rendered registry is stale

import { $ } from "bun"
import path from "node:path"
import { parseArgs } from "node:util"

const root = path.resolve(import.meta.dirname, "..")

const directory = path.join(root, "src/main/storage/migration")

const output = path.join(root, "src/main/storage/migration.gen.ts")

const args = parseArgs({
  args: process.argv.slice(2),
  options: {
    check: { type: "boolean" },
    name: { type: "string" },
  },
})

if (args.values.name) await $`bun drizzle-kit generate --name ${args.values.name}`.cwd(root)

const rendered = await render()

if (!args.values.check) {
  await Bun.write(output, rendered)
  process.exit(0)
}

if ((await Bun.file(output).text()) !== rendered) {
  throw new Error("Desktop storage migrations are stale. Run `bun run migration` from packages/desktop.")
}

async function render() {
  const ids = (await Array.fromAsync(new Bun.Glob("*/migration.sql").scan({ cwd: directory })))
    .map((file) => path.dirname(file))
    .sort()

  const migrations = await Promise.all(
    ids.map(async (id) => ({
      id,
      // Normalize so a CRLF checkout renders the same registry as an LF one.
      statements: (await Bun.file(path.join(directory, id, "migration.sql")).text())
        .replaceAll("\r\n", "\n")
        .split("--> statement-breakpoint")
        .map((statement) => statement.trim())
        .filter((statement) => statement.length > 0),
    })),
  )

  const source = `// Generated by script/migration.ts from src/main/storage/migration. Do not edit.

export const migrations = ${JSON.stringify(migrations, null, 2)}
`

  const prettier = await import("prettier")

  return prettier.format(source, { parser: "typescript", semi: false, printWidth: 120 })
}