63 lines
2.6 KiB
JavaScript
63 lines
2.6 KiB
JavaScript
import { Command } from "commander";
|
|
import path from "path";
|
|
import fs from "fs";
|
|
import chalk from "chalk";
|
|
import grabDBDir from "../utils/grab-db-dir";
|
|
import { AppData } from "../data/app-data";
|
|
import { dumpDatabase } from "../utils/mariadb-dump-restore";
|
|
import { writeExportArchive } from "../utils/export-archive";
|
|
import trimExports from "../utils/trim-exports";
|
|
function defaultExportFileName(dbName, format) {
|
|
return `${dbName}-${Date.now()}.${format}`;
|
|
}
|
|
export default function () {
|
|
return new Command("export")
|
|
.description("Export database SQL dump + schema.ts into a portable archive")
|
|
.option("-o, --output <path>", "Output archive path (.tar.gz or .zip). Defaults to db exports dir")
|
|
.option("-f, --format <format>", "Archive format when --output is omitted: tar.gz | zip", "tar.gz")
|
|
.action(async (opts) => {
|
|
console.log(`Exporting database ...`);
|
|
const config = global.CONFIG;
|
|
const { db_dir, export_dir } = grabDBDir({ config });
|
|
if (!fs.existsSync(export_dir)) {
|
|
fs.mkdirSync(export_dir, { recursive: true });
|
|
}
|
|
const schemaPath = path.join(db_dir, AppData.DbSchemaFileName);
|
|
if (!fs.existsSync(schemaPath)) {
|
|
console.error(chalk.red(`Schema file not found: ${schemaPath}`));
|
|
process.exit(1);
|
|
}
|
|
const formatRaw = String(opts.format || "tar.gz").toLowerCase();
|
|
const format = formatRaw === "zip" ? "zip" : "tar.gz";
|
|
let outPath;
|
|
if (opts.output) {
|
|
outPath = path.resolve(opts.output);
|
|
const parent = path.dirname(outPath);
|
|
if (!fs.existsSync(parent)) {
|
|
fs.mkdirSync(parent, { recursive: true });
|
|
}
|
|
}
|
|
else {
|
|
outPath = path.join(export_dir, defaultExportFileName(config.db_name, format));
|
|
}
|
|
try {
|
|
const sql = await dumpDatabase(config);
|
|
const schemaTs = fs.readFileSync(schemaPath, "utf-8");
|
|
await writeExportArchive({
|
|
contents: { sql, schemaTs },
|
|
outPath,
|
|
});
|
|
if (path.dirname(outPath) === export_dir) {
|
|
trimExports({ config });
|
|
}
|
|
console.log(`${chalk.bold(chalk.green(`DB Export Success!`))} → ${outPath}`);
|
|
console.log(chalk.dim(`Contains: dump.sql + ${AppData.DbSchemaFileName}`));
|
|
process.exit(0);
|
|
}
|
|
catch (error) {
|
|
console.error(chalk.red(`Export ERROR => ${error.message}`));
|
|
process.exit(1);
|
|
}
|
|
});
|
|
}
|