aboutsummaryrefslogtreecommitdiff
path: root/generate/migration/migration.go
blob: 37515bfa867a031c36e226a8e5d44b79c314a739 (plain)
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
package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os/exec"
	"path"
	"strings"
	"time"
)

const (
	dateFormat     = "20060102150405"
	migrationsPath = "server/store/migrations"
)

var (
	contents = []byte(`-- +migrate Up


-- +migrate Down`)
)

func main() {
	flag.Usage = func() {
		fmt.Println("Usage: migration <migration name>")
	}
	flag.Parse()
	if len(flag.Args()) != 1 {
		flag.Usage()
	}
	name := fmt.Sprintf("%s_%s.sql", time.Now().UTC().Format(dateFormat), flag.Arg(0))
	gitRoot, err := exec.Command("git", "rev-parse", "--show-toplevel").Output()
	if err != nil {
		log.Fatal(err)
	}
	root := strings.TrimSpace(string(gitRoot))
	ents, err := ioutil.ReadDir(path.Join(root, migrationsPath))
	if err != nil {
		log.Fatal(err)
	}
	for _, e := range ents {
		if e.IsDir() {
			filename := path.Join(migrationsPath, e.Name(), name)
			fmt.Printf("Wrote empty migration file: %s\n", filename)
			if err := ioutil.WriteFile(filename, contents, 0644); err != nil {
				log.Fatal(err)
			}
		}
	}
}