-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcommand_new.go
90 lines (71 loc) · 1.64 KB
/
command_new.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"errors"
"flag"
"fmt"
"os"
"path"
"strings"
"text/template"
"time"
migrate "github.com/rubenv/sql-migrate"
"github.com/spf13/viper"
)
var templateContent = `
-- +migrate Up
-- +migrate Down
`
var tpl *template.Template
func init() {
tpl = template.Must(template.New("new_migration").Parse(templateContent))
}
type NewCommand struct {
}
func (c *NewCommand) Help() string {
helpText := `
Usage: evedbtool new [options] name
Create a new a database migration.
Options:
name The name of the migration
`
return strings.TrimSpace(helpText)
}
func (c *NewCommand) Synopsis() string {
return "Create a new migration"
}
func (c *NewCommand) Run(args []string) int {
cmdFlags := flag.NewFlagSet("new", flag.ContinueOnError)
cmdFlags.Usage = func() { ui.Output(c.Help()) }
migrate.SetTable("migrations")
if len(args) < 1 {
err := errors.New("A name for the migration is needed")
ui.Error(err.Error())
return 1
}
if err := cmdFlags.Parse(args); err != nil {
return 1
}
if err := CreateMigration(cmdFlags.Arg(0)); err != nil {
ui.Error(err.Error())
return 1
}
return 0
}
func CreateMigration(name string) error {
dir := viper.GetString("migrations-dir")
if _, err := os.Stat(dir); os.IsNotExist(err) {
return err
}
fileName := fmt.Sprintf("%s-%s.sql", time.Now().Format("20060102150405"), strings.TrimSpace(name))
pathName := path.Join(dir, fileName)
f, err := os.Create(pathName)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
if err := tpl.Execute(f, nil); err != nil {
return err
}
ui.Output(fmt.Sprintf("Created migration %s", pathName))
return nil
}