diff --git a/migrate.go b/migrate.go index 34ce205..d4b24d2 100644 --- a/migrate.go +++ b/migrate.go @@ -238,7 +238,7 @@ func getLatestMigration(db *sql.DB) (file string, createdAt int64) { // writeMigrationSourceFile create the source file based on MIGRATION_MAIN_TPL func writeMigrationSourceFile(dir, source, driver, connStr string, latestTime int64, latestName string, task string) { - os.Chdir(dir) + changeDir(dir) if f, err := os.OpenFile(source, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0666); err != nil { ColorLog("[ERRO] Could not create file: %s\n", err) os.Exit(2) @@ -258,7 +258,7 @@ func writeMigrationSourceFile(dir, source, driver, connStr string, latestTime in // buildMigrationBinary changes directory to database/migrations folder and go-build the source func buildMigrationBinary(dir, binary string) { - os.Chdir(dir) + changeDir(dir) cmd := exec.Command("go", "build", "-o", binary) if out, err := cmd.CombinedOutput(); err != nil { ColorLog("[ERRO] Could not build migration binary: %s\n", err) @@ -271,7 +271,7 @@ func buildMigrationBinary(dir, binary string) { // runMigrationBinary runs the migration program who does the actual work func runMigrationBinary(dir, binary string) { - os.Chdir(dir) + changeDir(dir) cmd := exec.Command("./" + binary) if out, err := cmd.CombinedOutput(); err != nil { formatShellOutput(string(out)) @@ -284,6 +284,15 @@ func runMigrationBinary(dir, binary string) { } } +// changeDir changes working directory to dir. +// It exits the system when encouter an error +func changeDir(dir string) { + if err := os.Chdir(dir); err != nil { + ColorLog("[ERRO] Could not find migration directory: %s\n", err) + os.Exit(2) + } +} + // removeTempFile removes a file in dir func removeTempFile(dir, file string) { os.Chdir(dir)