73 lines
3.0 KiB
JavaScript
73 lines
3.0 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 { dumpDatabase } from "../utils/mariadb-dump-restore";
|
|
import { writeExportArchive } from "../utils/export-archive";
|
|
import trimExports from "../utils/trim-exports";
|
|
import { resolveDataFile, supportedDataFileNames, } from "../utils/resolve-and-load-data-file";
|
|
import { AppData } from "../data/app-data";
|
|
function defaultExportFileName(dbName, format) {
|
|
return `${dbName}-${Date.now()}.${format}`;
|
|
}
|
|
export default function () {
|
|
return new Command("export")
|
|
.description("Export database SQL dump + schema 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 schemaResolved = (global.SCHEMA_FILE_PATH &&
|
|
fs.existsSync(global.SCHEMA_FILE_PATH) && {
|
|
path: global.SCHEMA_FILE_PATH,
|
|
basename: path.basename(global.SCHEMA_FILE_PATH),
|
|
}) ||
|
|
resolveDataFile(db_dir, AppData.DbSchemaFileName);
|
|
if (!schemaResolved) {
|
|
console.error(chalk.red(`Schema file not found in \`${db_dir}\` (${supportedDataFileNames(AppData.DbSchemaFileName)})`));
|
|
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 schema = fs.readFileSync(schemaResolved.path, "utf-8");
|
|
await writeExportArchive({
|
|
contents: {
|
|
sql,
|
|
schema,
|
|
schemaFileName: schemaResolved.basename,
|
|
},
|
|
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 + ${schemaResolved.basename}`));
|
|
process.exit(0);
|
|
}
|
|
catch (error) {
|
|
console.error(chalk.red(`Export ERROR => ${error.message}`));
|
|
process.exit(1);
|
|
}
|
|
});
|
|
}
|