forked from eaigner/hood
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.go
287 lines (256 loc) · 6.26 KB
/
cmd.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"os"
"os/exec"
"path"
"strconv"
"strings"
"text/template"
"time"
)
var (
dbDir string
migrationsDir string
configFile string
schemaFile string
environment string
keyPath string
driver string
source string
command string
workingDir string
testMode bool
migrationTemplate = template.Must(template.New("migration").Parse(_migrationTemplate))
)
func init() {
flag.StringVar(&dbDir, "db-dir", "db", "Sets the db directory.")
flag.StringVar(&migrationsDir, "migrations-dir", "db/migrations", "Sets the migrations directory")
flag.StringVar(&configFile, "conf", "db/config.json", "Sets the path to the config.json file")
flag.StringVar(&schemaFile, "schema", "db/schema.go", "Sets the generated schema file path")
flag.StringVar(&environment, "env", "development", "Sets the environment")
flag.StringVar(&keyPath, "key-path", "", `Sets the key path of the driver and source fields relative to the environment field in the config.json. For example, if the driver and source fields were located at <environment>:{"postgres":{"hood":{"driver": ... }}} the key path would be "postgres.hood"`)
flag.StringVar(&driver, "driver", "", "Sets the driver. If the driver and source fields are set, the config.json will be ignored.")
flag.StringVar(&source, "source", "", "Sets the source. If the driver and source fields are set, the config.json will be ignored.")
flag.BoolVar(&testMode, "test", false, "If set to true, just the configuration is printed without running a command.")
flag.Parse()
// Get driver and source from config, if flags were not set
if driver == "" || source == "" {
// Read file
wd, err := os.Getwd()
if err != nil {
panic(err)
}
f, err := os.Open(path.Join(wd, configFile))
if err != nil {
panic(err)
}
defer f.Close()
// Parse JSON
var v map[string]interface{}
err = json.NewDecoder(f).Decode(&v)
if err != nil {
panic(err)
}
// Append environment to key path
fqKeyPath := environment
if len(keyPath) > 0 {
fqKeyPath += "." + keyPath
}
// Get driver and source fields
root := v
for _, key := range strings.Split(fqKeyPath, ".") {
if node, ok := root[key].(map[string]interface{}); ok {
root = node
}
}
if node, ok := root["driver"].(string); ok {
driver = node
}
if node, ok := root["source"].(string); ok {
source = node
}
}
// Set driver and source
if driver == "" {
panic("driver not set")
}
if source == "" {
panic("source not set")
}
// Get working dir
wd, err := os.Getwd()
if err != nil {
panic(err)
}
workingDir = wd
command = flag.Arg(0)
}
func main() {
// Only print config in test mode
if testMode {
fmt.Printf("db-dir:\t\t'%s'\n", dbDir)
fmt.Printf("migrations-dir:\t'%s'\n", migrationsDir)
fmt.Printf("conf:\t\t'%s'\n", configFile)
fmt.Printf("schema:\t\t'%s'\n", schemaFile)
fmt.Printf("env:\t\t'%s'\n", environment)
fmt.Printf("key-path:\t'%s'\n", keyPath)
fmt.Printf("driver:\t\t'%s'\n", driver)
fmt.Printf("source:\t\t'%s'\n", source)
return
}
// Run command
switch command {
case "create:config":
cmdCreateConfig()
case "create:migration":
cmdCreateMigration(flag.Arg(1))
case "db:migrate":
cmdMigrate()
case "db:rollback":
cmdRollback()
case "db:reset":
cmdReset()
default:
log.Println("invalid command")
}
}
func cmdCreateConfig() {
err := ioutil.WriteFile(path.Join(workingDir, configFile), []byte(confTmpl), 0666)
if err != nil {
panic(err)
}
log.Printf("created db configuration '%s'", configFile)
}
func cmdCreateMigration(name string) {
if name == "" {
panic("invalid migration name")
}
// Write template
ts := time.Now().Unix()
file := path.Join(workingDir, migrationsDir, fmt.Sprintf("%d_%s.go", ts, name))
f, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
panic(err)
}
defer f.Close()
err = migrationTemplate.Execute(f, &struct {
Timestamp int64
Name string
}{
Timestamp: ts,
Name: name,
})
if err != nil {
panic(err)
}
// Write init.go file
file = path.Join(workingDir, migrationsDir, "init.go")
err = ioutil.WriteFile(file, []byte(initTmpl), 0644)
if err != nil {
panic(err)
}
log.Printf("created migration '%s'", file)
}
var initTmpl = `package main
type M struct{}
func main() {}
`
var confTmpl = `{
"development": {
"driver": "",
"source": ""
},
"production": {
"driver": "",
"source": ""
},
"test": {
"driver": "",
"source": ""
}
}`
func cmdMigrate() {
runMigrations(math.MaxInt32)
}
func cmdRollback() {
runMigrations(-1)
}
func cmdReset() {
runMigrations(math.MinInt32)
}
func runMigrations(steps int32) {
// Read the migrations dir
info, err := ioutil.ReadDir(path.Join(workingDir, migrationsDir))
if err != nil {
panic(nil)
}
// Create a temp dir to copy the migrations to
tmpDir, err := ioutil.TempDir("", "hood-migration-")
if err != nil {
panic(err)
}
defer os.RemoveAll(tmpDir)
// Copy all migrations
files := []string{}
for _, file := range info {
// Skip the init file
if file.Name() == "init.go" {
continue
}
// Copy
dstFile := path.Join(tmpDir, file.Name())
_, err = copyFile(
dstFile,
path.Join(workingDir, migrationsDir, file.Name()),
)
if err != nil {
panic(err)
}
files = append(files, dstFile)
}
// Copy the runner template
main := path.Join(tmpDir, "runner.go")
err = ioutil.WriteFile(main, []byte(_runnerTemplate), 0666)
if err != nil {
panic(err)
}
files = append(files, main)
// Adjust schema path
if !path.IsAbs(schemaFile) {
schemaFile = path.Join(workingDir, schemaFile)
}
// Invoke runner
cmd := exec.Command("go", "run")
cmd.Args = append(cmd.Args, files...)
cmd.Args = append(cmd.Args,
"-driver", strconv.Quote(driver),
"-source", strconv.Quote(source),
"-schema", strconv.Quote(schemaFile),
"-steps", fmt.Sprintf("%d", steps),
)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err = cmd.Run(); err != nil {
panic(err)
}
}
func copyFile(dst, src string) (int64, error) {
sf, err := os.Open(src)
if err != nil {
return 0, err
}
defer sf.Close()
df, err := os.Create(dst)
if err != nil {
return 0, err
}
defer df.Close()
return io.Copy(df, sf)
}