refactor: use flags instead of positionals, reorganize cli init
This commit is contained in:
parent
1720855a2d
commit
2b54cbb95b
1 changed files with 44 additions and 36 deletions
24
cobble.go
24
cobble.go
|
@ -23,12 +23,13 @@ func SetupDatabaseConnection(cmd *cobra.Command, args []string) {
|
||||||
cmd.SetContext(context.WithValue(cmd.Context(), "db", db))
|
cmd.SetContext(context.WithValue(cmd.Context(), "db", db))
|
||||||
}
|
}
|
||||||
|
|
||||||
var cli = &cobra.Command{
|
func NewCli() *cobra.Command {
|
||||||
|
cli := &cobra.Command{
|
||||||
Use: "cobble",
|
Use: "cobble",
|
||||||
Short: "Cobble is a simple SQL migration utility.",
|
Short: "Cobble is a simple SQL migration utility.",
|
||||||
}
|
}
|
||||||
|
|
||||||
var up = &cobra.Command{
|
up := &cobra.Command{
|
||||||
Use: "up",
|
Use: "up",
|
||||||
Short: "Applies migrations",
|
Short: "Applies migrations",
|
||||||
PreRun: SetupDatabaseConnection,
|
PreRun: SetupDatabaseConnection,
|
||||||
|
@ -46,12 +47,12 @@ var up = &cobra.Command{
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
var inspect = &cobra.Command{
|
inspect := &cobra.Command{
|
||||||
Use: "inspect",
|
Use: "inspect",
|
||||||
Short: "Prints the nth migration in the history",
|
Short: "Prints the nth migration in the history",
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
migrationRoot := args[0]
|
migrationRoot, _ := cmd.Flags().GetString("root")
|
||||||
migrationIndex, _ := strconv.Atoi(args[1])
|
migrationIndex, _ := cmd.Flags().GetInt("index")
|
||||||
|
|
||||||
migrationGraph, _ := NewMigrationGraphFromDirectory(migrationRoot)
|
migrationGraph, _ := NewMigrationGraphFromDirectory(migrationRoot)
|
||||||
migrationHistory, _ := migrationGraph.GetLinearHistory()
|
migrationHistory, _ := migrationGraph.GetLinearHistory()
|
||||||
|
@ -60,12 +61,19 @@ var inspect = &cobra.Command{
|
||||||
fmt.Printf("%s:\n%s", migration.Name, sql)
|
fmt.Printf("%s:\n%s", migration.Name, sql)
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
|
||||||
cli.AddCommand(up)
|
cli.AddCommand(up)
|
||||||
cli.AddCommand(inspect)
|
cli.AddCommand(inspect)
|
||||||
|
|
||||||
if err := cli.Execute(); err != nil {
|
cli.PersistentFlags().StringP("root", "r", "./migrations", "Root directory where migration files live.")
|
||||||
|
inspect.PersistentFlags().IntP("index", "i", 0, "Zero-based index of the migration to target.")
|
||||||
|
|
||||||
|
inspect.MarkFlagRequired("index")
|
||||||
|
|
||||||
|
return cli
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
if err := NewCli().Execute(); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue