From 8c5a614c932977e45d3effe4a163e1fc0a70059e Mon Sep 17 00:00:00 2001 From: Neur0toxine Date: Fri, 13 May 2022 13:31:21 +0300 Subject: [PATCH] Update migration generator to v2 migrations * update migration generator to v2 migrations * use %w verb --- core/db/migration_generator.go | 40 +++++++++++++++++++--------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/core/db/migration_generator.go b/core/db/migration_generator.go index 8d6d20a..b078ad0 100644 --- a/core/db/migration_generator.go +++ b/core/db/migration_generator.go @@ -5,21 +5,21 @@ import ( "os" "path" "strconv" - "strings" + "text/template" "time" ) -var migrationTemplate = `package $package +var migrationTemplate = `package {{.Package}} import ( "github.com/jinzhu/gorm" - "github.com/retailcrm/mg-transport-core/core" + "github.com/retailcrm/mg-transport-core/v2/core/db" "gopkg.in/gormigrate.v1" ) func init() { - core.Migrations().Add(&gormigrate.Migration{ - ID: "$version", + db.Migrations().Add(&gormigrate.Migration{ + ID: "{{.Version}}", Migrate: func(db *gorm.DB) error { // Write your migration code here... }, @@ -30,6 +30,12 @@ func init() { } ` +// MigrationData contains base variables for the new migration. +type MigrationData struct { + Package string + Version string +} + // NewMigrationCommand struct. type NewMigrationCommand struct { Directory string `short:"d" long:"directory" default:"./migrations" description:"Directory where migration will be created"` // nolint:lll @@ -46,30 +52,30 @@ func (x *NewMigrationCommand) FileExists(filename string) bool { // Execute migration generator command. func (x *NewMigrationCommand) Execute(args []string) error { - version := strconv.FormatInt(time.Now().Unix(), 10) + tpl, err := template.New("migration").Parse(migrationTemplate) + if err != nil { + return fmt.Errorf("fatal: cannot parse base migration template: %w", err) + } + directory := path.Clean(x.Directory) - packageName := "migrations" + migrationData := MigrationData{ + Package: "migrations", + Version: strconv.FormatInt(time.Now().Unix(), 10), + } if _, err := os.Stat(directory); os.IsNotExist(err) { return fmt.Errorf("err: specified directory doesn't exist") } if base := path.Base(directory); base != "/" && base != "." { - packageName = base + migrationData.Package = base } - filePath := path.Join(directory, version+"_app.go") + filePath := path.Join(directory, migrationData.Version+"_app.go") if x.FileExists(filePath) { return fmt.Errorf("\"%s\" already exists or it's a directory", filePath) } - migrationData := strings.Replace( - strings.Replace(migrationTemplate, "$version", version, 1), - "$package", - packageName, - 1, - ) - file, err := os.Create(filePath) if err != nil { return err @@ -77,7 +83,7 @@ func (x *NewMigrationCommand) Execute(args []string) error { defer file.Close() - if _, err := file.WriteString(migrationData); err != nil { + if err := tpl.Execute(file, migrationData); err != nil { return err }