Files
sm-bm-plugin/console/seed.go

67 lines
2.4 KiB
Go

// Code generated by summer make. DO NOT EDIT.
package console
import (
"context"
"fmt"
"os"
"git.golem15.com/golem15/summercms/modules/bonfire"
"git.golem15.com/jakub/sm-bm-plugin/classes"
"gorm.io/gorm"
)
// SeedCommand returns the bm:seed console command. withDB runs the
// command's work with the application's database; the plugin supplies it.
func SeedCommand(withDB func(ctx context.Context, fn func(*gorm.DB) error) error) bonfire.Command {
return bonfire.Command{
Name: "bm:seed",
Description: "Upsert meetings, courses, class sessions, deadlines and readings from a JSON file",
Args: []bonfire.Arg{{Name: "file", Description: "Path of the seed JSON file", Required: true}},
Flags: []bonfire.Flag{
{Name: "dry-run", Description: "Show what the seed would change, then roll it back", Bare: true},
{Name: "prune", Description: "Delete courses of the file's semesters, and sessions and readings of its courses, that the file does not list", Bare: true},
},
Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
path, _ := in.Argument("file")
if path == "" {
return fmt.Errorf("bm:seed: a file is required")
}
fh, err := os.Open(path)
if err != nil {
return fmt.Errorf("bm:seed: %w", err)
}
defer fh.Close()
file, err := classes.ParseSeed(fh)
if err != nil {
return err
}
if err := file.Validate(); err != nil {
return fmt.Errorf("bm:seed: %s is not valid, nothing was written:\n%w", path, err)
}
dry, _ := in.Flag("dry-run")
prune, _ := in.Flag("prune")
opts := classes.SeedOptions{DryRun: dry == "true", Prune: prune == "true"}
out.Printf("%s is valid: %d meetings, %d courses, %d class sessions, %d deadlines, %d readings\n", path,
len(file.Meetings), len(file.Courses), len(file.ClassSessions), len(file.Deadlines), len(file.Readings))
return withDB(ctx, func(db *gorm.DB) error {
sum, err := classes.SeedWith(ctx, db, file, opts)
if err != nil {
return fmt.Errorf("bm:seed: nothing was written: %w", err)
}
out.Table([]string{"kind", "created", "updated", "unchanged", "deleted"}, sum.Rows())
for _, r := range sum.Removed {
out.Printf("deleted: %s\n", r)
}
if opts.DryRun {
out.Success("bm:seed: dry run of " + path + ", nothing was written")
return nil
}
out.Success("bm:seed: " + path + " applied")
return nil
})
},
}
}