import path from "path" ; import execa from "execa" ; import fs from "fs-extra" ; import os from "os" ; import FlanCommand from "../FlanCommand" ; import { createExecaCommand , checkDumpNameForTag } from "../utils" ; export default class Save extends FlanCommand { static description = "save current database to dump" ; static examples = [ "$ flan save myDB" ] ; static flags = { ... FlanCommand . flags , } ; static args = [ { name : "output" , required : true , description : "name of output file" , } , ] ; async run ( ) { await this . runHook ( "beforeSave" ) ; const { args } = this . parse ( Save ) ; const { output } = args ; this . log ( `output file name: ${ output }` ) ; if ( checkDumpNameForTag ( output ) ) { await this . dumpWithRepo ( { output } ) ; } else { await this . dump ( path . resolve ( this . localConfig . saveDir , output ) ) ; } await this . runHook ( "afterSave" ) ; } async dumpWithRepo ( { output } ) { this . log ( "doing repo save" ) ; const git = createExecaCommand ( "git" , { cwd : this . localConfig . repoDir , } ) ; try { await git ( [ "checkout" , "master" ] ) ; } catch ( error ) { await git ( [ "checkout" , "-b" , "master" ] ) ; } this . log ( "checked out master" ) ; await git ( [ "update-ref" , "-d" , "HEAD" ] ) ; await git ( [ "reset" , "--hard" ] ) ; this . log ( "cleaned repo" ) ; await this . dump ( path . resolve ( this . localConfig . repoDir , output ) ) ; this . log ( "saved new file" ) ; await git ( [ "add" , output ] ) ; await git ( [ "commit" , "-a" , "-m" , `saved... ${ output }` ] ) ; this . log ( "git commit done" ) ; await git ( [ "tag" , "-a" , "-f" , "-m" , output , output ] ) ; this . log ( "git tag done" ) ; } async dump ( dir ) { if ( await fs . pathExists ( path . resolve ( dir , "./toc.dat" ) ) ) { await fs . remove ( path . resolve ( dir ) ) ; } const pgArgs = [ `--jobs=${ Math . floor ( os . cpus ( ) . length / 2 ) }` , "--compress=9" , "--format=directory" , ... this . getPgConnectionArgs ( ) , `--file=${ dir }` , ] ; console . time ( "pg_dump" ) ; await execa ( "pg_dump" , pgArgs ) ; console . timeEnd ( "pg_dump" ) ; } }