package main import ( "context" "fmt" "github.com/spf13/cobra" "log" "os" "strconv" ) func SetupDatabaseConnection(cmd *cobra.Command, args []string) { dbPort, _ := strconv.Atoi(os.Getenv("DB_PORT")) db := NewDatabase(os.Getenv("DB_HOST"), dbPort) err := db.Connect(os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_NAME")) if err != nil { log.Printf("Failed to connect to the database: %s", err) os.Exit(1) } cmd.SetContext(context.WithValue(cmd.Context(), "db", db)) } var cli = &cobra.Command{ Use: "cobble", Short: "Cobble is a simple SQL migration utility.", } var up = &cobra.Command{ Use: "up", Short: "Applies migrations", PreRun: SetupDatabaseConnection, Run: func(cmd *cobra.Command, args []string) { db := cmd.Context().Value("db").(DB) migrationRoot := args[0] migrationGraph, _ := NewMigrationGraphFromDirectory(migrationRoot) migrationHistory, _ := migrationGraph.GetLinearHistory() for _, migration := range migrationHistory { log.Printf("%s", migration.Name) if err := migration.Apply(db); err != nil { os.Exit(1) } } }, } var inspect = &cobra.Command{ Use: "inspect", Short: "Prints the nth migration in the history", Run: func(cmd *cobra.Command, args []string) { migrationRoot := args[0] migrationIndex, _ := strconv.Atoi(args[1]) migrationGraph, _ := NewMigrationGraphFromDirectory(migrationRoot) migrationHistory, _ := migrationGraph.GetLinearHistory() migration := migrationHistory[migrationIndex] sql, _ := migration.Sql() fmt.Printf("%s:\n%s", migration.Name, sql) }, } func main() { cli.AddCommand(up) cli.AddCommand(inspect) if err := cli.Execute(); err != nil { log.Fatal(err) os.Exit(1) } }