@@ -4,15 +4,17 @@ import (
4
4
"bytes"
5
5
"context"
6
6
"fmt"
7
- "time "
7
+ "path/filepath "
8
8
9
+ "github.com/ohkrab/krab/krabenv"
9
10
"github.com/ohkrab/krab/krabhcl"
10
11
"github.com/spf13/afero"
11
12
)
12
13
13
14
// CmdGenMigration generates migation file.
14
15
type CmdGenMigration struct {
15
16
FS afero.Afero
17
+ VersionGenerator
16
18
}
17
19
18
20
// ResponseGenMigration json
@@ -21,6 +23,18 @@ type ResponseGenMigration struct {
21
23
Ref string `json:"ref"`
22
24
}
23
25
26
+ func (c * CmdGenMigration ) Arguments () * Arguments {
27
+ return & Arguments {
28
+ Args : []* Argument {
29
+ {
30
+ Name : "name" ,
31
+ Type : "string" ,
32
+ Description : "Migration name" ,
33
+ },
34
+ },
35
+ }
36
+ }
37
+
24
38
func (c * CmdGenMigration ) Addr () krabhcl.Addr { return krabhcl .NullAddr }
25
39
26
40
func (c * CmdGenMigration ) Name () []string {
@@ -30,18 +44,32 @@ func (c *CmdGenMigration) Name() []string {
30
44
func (c * CmdGenMigration ) HttpMethod () string { return "" }
31
45
32
46
func (c * CmdGenMigration ) Do (ctx context.Context , o CmdOpts ) (interface {}, error ) {
33
-
34
- return c .run (ctx )
47
+ err := c .Arguments ().Validate (o .Inputs )
48
+ if err != nil {
49
+ return nil , err
50
+ }
51
+ return c .run (ctx , o .Inputs )
35
52
}
36
53
37
- func (c * CmdGenMigration ) run (ctx context.Context ) (ResponseGenMigration , error ) {
54
+ func (c * CmdGenMigration ) run (ctx context.Context , inputs Inputs ) (ResponseGenMigration , error ) {
38
55
result := ResponseGenMigration {}
39
- buf := bytes.Buffer {}
40
56
41
- ref := "create_animals"
57
+ dir , err := krabenv .ConfigDir ()
58
+ if err != nil {
59
+ return result , err
60
+ }
61
+ dir = filepath .Join (dir , "db" , "migrations" )
62
+ err = c .FS .MkdirAll (dir , 0755 )
63
+ if err != nil {
64
+ return result , err
65
+ }
66
+
67
+ version := c .VersionGenerator .Next ()
68
+ ref := inputs ["name" ].(string )
42
69
result .Ref = fmt .Sprint ("migration." , ref )
43
- version := time . Now (). UTC (). Format ( "20060102_150405" ) // YYYYMMDD_HHMMSS
70
+ result . Path = filepath . Join ( dir , fmt . Sprint ( version , "_" , ref , krabenv . Ext ()))
44
71
72
+ buf := bytes.Buffer {}
45
73
buf .WriteString (`migration "` )
46
74
buf .WriteString (ref )
47
75
buf .WriteString (`" {` )
@@ -61,7 +89,7 @@ func (c *CmdGenMigration) run(ctx context.Context) (ResponseGenMigration, error)
61
89
buf .WriteString (`}` )
62
90
buf .WriteString ("\n " )
63
91
64
- c .FS .WriteFile ("/tmp/migrate.krab.hcl" , buf .Bytes (), 0644 )
92
+ c .FS .WriteFile (result . Path , buf .Bytes (), 0644 )
65
93
66
94
return result , nil
67
95
}
0 commit comments