refactor: use flags instead of positionals, reorganize cli init
All checks were successful
/ sast (push) Successful in 43s
/ tests (push) Successful in 45s
/ build (push) Successful in 47s

This commit is contained in:
Marc 2024-07-13 23:44:04 -04:00
parent 1720855a2d
commit 2b54cbb95b
Signed by: marc
GPG key ID: 048E042F22B5DC79

View file

@ -23,12 +23,13 @@ func SetupDatabaseConnection(cmd *cobra.Command, args []string) {
cmd.SetContext(context.WithValue(cmd.Context(), "db", db))
}
var cli = &cobra.Command{
func NewCli() *cobra.Command {
cli := &cobra.Command{
Use: "cobble",
Short: "Cobble is a simple SQL migration utility.",
}
}
var up = &cobra.Command{
up := &cobra.Command{
Use: "up",
Short: "Applies migrations",
PreRun: SetupDatabaseConnection,
@ -44,14 +45,14 @@ var up = &cobra.Command{
}
}
},
}
}
var inspect = &cobra.Command{
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])
migrationRoot, _ := cmd.Flags().GetString("root")
migrationIndex, _ := cmd.Flags().GetInt("index")
migrationGraph, _ := NewMigrationGraphFromDirectory(migrationRoot)
migrationHistory, _ := migrationGraph.GetLinearHistory()
@ -59,13 +60,20 @@ var inspect = &cobra.Command{
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 {
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)
os.Exit(1)
}