Validates a whole JSON file (course keys, meeting numbers, values, dates) and upserts meetings, courses, class sessions, deadlines and readings in one transaction, matched on their natural identity. Prints a created, updated and unchanged summary; --dry-run only validates. Ships a small example fixture with made-up data.
59 lines
1.9 KiB
Go
59 lines
1.9 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: "Validate the file without writing", 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)
|
|
}
|
|
if dry, _ := in.Flag("dry-run"); dry == "true" {
|
|
out.Success(fmt.Sprintf("%s is valid: %d meetings, %d courses, %d class sessions, %d deadlines, %d readings", path,
|
|
len(file.Meetings), len(file.Courses), len(file.ClassSessions), len(file.Deadlines), len(file.Readings)))
|
|
return nil
|
|
}
|
|
return withDB(ctx, func(db *gorm.DB) error {
|
|
sum, err := classes.Seed(ctx, db, file)
|
|
if err != nil {
|
|
return fmt.Errorf("bm:seed: nothing was written: %w", err)
|
|
}
|
|
out.Table([]string{"kind", "created", "updated", "unchanged"}, sum.Rows())
|
|
out.Success("bm:seed: " + path + " applied")
|
|
return nil
|
|
})
|
|
},
|
|
}
|
|
}
|