Skip to content

Commit

Permalink
Update migration generator to v2 migrations
Browse files Browse the repository at this point in the history
* update migration generator to v2 migrations
* use %w verb
  • Loading branch information
Neur0toxine authored May 13, 2022
1 parent 27aee62 commit 8c5a614
Showing 1 changed file with 23 additions and 17 deletions.
40 changes: 23 additions & 17 deletions core/db/migration_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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...
},
Expand All @@ -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
Expand All @@ -46,38 +52,38 @@ 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
}

defer file.Close()

if _, err := file.WriteString(migrationData); err != nil {
if err := tpl.Execute(file, migrationData); err != nil {
return err
}

Expand Down

0 comments on commit 8c5a614

Please sign in to comment.