diff --git a/README.md b/README.md index 44372b0..7506c5c 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ dbmate drop # drop the database dbmate migrate # run any pending migrations dbmate rollback # roll back the most recent migration dbmate down # alias for rollback -dbmate status # show the status of all migrations +dbmate status # show the status of all migrations (supports --exit-code and --quiet) dbmate dump # write the database schema.sql file dbmate wait # wait for the database server to become available ``` diff --git a/main.go b/main.go index 34151a2..d8bc1e8 100644 --- a/main.go +++ b/main.go @@ -17,9 +17,10 @@ func main() { app := NewApp() err := app.Run(os.Args) + if err != nil { _, _ = fmt.Fprintf(os.Stderr, "Error: %s\n", err) - os.Exit(1) + os.Exit(2) } } @@ -105,8 +106,33 @@ func NewApp() *cli.App { { Name: "status", Usage: "List applied and pending migrations", + Flags: []cli.Flag{ + cli.BoolFlag{ + Name: "exit-code", + Usage: "return 1 if there are pending migrations", + }, + cli.BoolFlag{ + Name: "quiet", + Usage: "don't output any text (implies --exit-code)", + }, + }, Action: action(func(db *dbmate.DB, c *cli.Context) error { - return db.Status() + setExitCode := c.Bool("exit-code") + quiet := c.Bool("quiet") + if quiet { + setExitCode = true + } + + pending, err := db.Status(quiet) + if err != nil { + return err + } + + if pending > 0 && setExitCode { + return cli.NewExitError("", 1) + } + + return nil }), }, { diff --git a/pkg/dbmate/db.go b/pkg/dbmate/db.go index 83f8220..e899cc0 100644 --- a/pkg/dbmate/db.go +++ b/pkg/dbmate/db.go @@ -492,26 +492,33 @@ func checkMigrationsStatus(db *DB) ([]statusResult, error) { } // Status shows the status of all migrations -func (db *DB) Status() error { +func (db *DB) Status(quiet bool) (int, error) { results, err := checkMigrationsStatus(db) if err != nil { - return err + return -1, err } var totalApplied int + var line string for _, res := range results { if res.applied { - fmt.Println("[X]", res.filename) + line = fmt.Sprintf("[X] %s", res.filename) totalApplied++ } else { - fmt.Println("[ ]", res.filename) + line = fmt.Sprintf("[ ] %s", res.filename) + } + if !quiet { + fmt.Println(line) } } - fmt.Println() - fmt.Printf("Applied: %d\n", totalApplied) - fmt.Printf("Pending: %d\n", len(results)-totalApplied) + totalPending := len(results) - totalApplied + if !quiet { + fmt.Println() + fmt.Printf("Applied: %d\n", totalApplied) + fmt.Printf("Pending: %d\n", totalPending) + } - return nil + return totalPending, nil }