#!/usr/bin/env node import { pathToFileURL } from "node:url"; import { resolve } from "node:path"; import { ConfigError, loadDbConfig } from "./config.js"; import { Db } from "./db.js"; import { AppError, toSafeError } from "./errors.js"; import { listMigrations, runMigrations } from "./migrate.js"; /** * Point d'entree des migrations : `node dist/cli.js --dir `. * * Le conteneur de migration n'a besoin d'aucun secret lisible a la main : * les variables sont resolues par Docker depuis .env au lancement. * * Codes de sortie : * 0 tout est applique, ou rien a faire * 1 erreur (connexion, SQL, migration) OU derive detectee * 2 configuration incomplete */ interface Options { dir: string; dryRun: boolean; check: boolean; help: boolean; } const USAGE = `Utilisation : cohaise-migrate --dir [--dry-run] [--check] --dir Dossier contenant les fichiers NNN_nom.sql (obligatoire) --dry-run Analyse sans ecrire en base --check Echoue s'il reste une migration a appliquer --help Cette aide`; const parseArgs = (argv: string[]): Options => { const options: Options = { dir: "", dryRun: false, check: false, help: false }; for (let index = 0; index < argv.length; index += 1) { const arg = argv[index]; if (arg === undefined) continue; if (arg === "--dry-run") options.dryRun = true; else if (arg === "--check") options.check = true; else if (arg === "--help" || arg === "-h") options.help = true; else if (arg === "--dir") { options.dir = argv[index + 1] ?? ""; index += 1; } else if (arg.startsWith("--dir=")) { options.dir = arg.slice("--dir=".length); } else { throw AppError.badRequest(`Argument inconnu : ${arg}`, { argument: arg }); } } return options; }; const main = async (argv: string[]): Promise => { let options: Options; try { options = parseArgs(argv); } catch (error) { const safe = toSafeError(error); console.error(` ${safe.message}\n\n${USAGE}`); return 2; } if (options.help) { console.log(USAGE); return 0; } if (!options.dir) { console.error(` --dir est obligatoire\n\n${USAGE}`); return 2; } let config; try { config = loadDbConfig(); } catch (error) { if (error instanceof ConfigError) { console.error(` Configuration invalide :\n - ${error.issues.join("\n - ")}`); return 2; } throw error; } const dir = resolve(options.dir); const db = new Db(config); try { const migrations = await listMigrations(dir); if (migrations.length === 0) { console.log(` Aucune migration trouvee dans ${dir}`); return 0; } const result = await runMigrations(db, dir, { dryRun: options.dryRun }); const prefix = options.dryRun ? "[dry-run] " : ""; console.log( `${prefix}${migrations.length} migration(s) · ${result.applied.length} appliquee(s) · ` + `${result.skipped.length} deja en place · ${result.drifted.length} derivee(s)`, ); for (const version of result.applied) console.log(` + ${version}`); for (const drift of result.drifted) { console.error(` ! ${drift.version} modifiee depuis son execution (checksum attendu ${drift.recorded.slice(0, 12)}…, trouve ${drift.current.slice(0, 12)}…)`); } if (result.drifted.length > 0) return 1; if (options.check && result.applied.length > 0) return 1; return 0; } catch (error) { const safe = toSafeError(error); console.error(` Echec : ${safe.code} — ${safe.message}`); if (error instanceof AppError && error.status >= 500 && error.message.includes("migree")) { console.error(" Appliquez d'abord les migrations : cohaise-migrate --dir "); } return 1; } finally { await db.close().catch(() => undefined); } }; const isDirectRun = process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href; if (isDirectRun) { main(process.argv.slice(2)).then( (code) => process.exit(code), (error) => { console.error(` Erreur inattendue : ${error instanceof Error ? error.message : String(error)}`); process.exit(1); }, ); } export { main, parseArgs };