2020-10-11 08:02:17 +00:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"path"
|
|
|
|
|
|
|
|
"github.com/c9s/goose"
|
2020-10-23 06:28:07 +00:00
|
|
|
"github.com/sirupsen/logrus"
|
2020-10-11 08:02:17 +00:00
|
|
|
"github.com/spf13/cobra"
|
|
|
|
"github.com/spf13/viper"
|
2020-10-20 03:46:44 +00:00
|
|
|
|
|
|
|
"github.com/c9s/bbgo/pkg/bbgo"
|
2020-10-11 08:02:17 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
MigrateCmd.Flags().Bool("no-update", false, "update source repository")
|
|
|
|
RootCmd.AddCommand(MigrateCmd)
|
|
|
|
}
|
|
|
|
|
|
|
|
var MigrateCmd = &cobra.Command{
|
|
|
|
Use: "migrate",
|
|
|
|
Short: "run database migration",
|
|
|
|
SilenceUsage: true,
|
|
|
|
Args: cobra.MinimumNArgs(1),
|
|
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
|
|
ctx := context.Background()
|
|
|
|
|
|
|
|
noUpdate, err := cmd.Flags().GetBool("no-update")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
mysqlURL := viper.GetString("mysql-url")
|
|
|
|
mysqlURL = fmt.Sprintf("%s?parseTime=true", mysqlURL)
|
|
|
|
db, err := goose.OpenDBWithDriver("mysql", mysqlURL)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2020-10-20 03:46:44 +00:00
|
|
|
dotDir := bbgo.HomeDir()
|
|
|
|
sourceDir := bbgo.SourceDir()
|
2020-10-11 08:02:17 +00:00
|
|
|
migrationDir := path.Join(sourceDir, "migrations")
|
|
|
|
|
2020-10-23 06:28:07 +00:00
|
|
|
logrus.Infof("creating dir: %s", dotDir)
|
2020-10-11 08:02:17 +00:00
|
|
|
if err := os.Mkdir(dotDir, 0777); err != nil {
|
|
|
|
// return err
|
|
|
|
}
|
|
|
|
|
2020-10-23 06:28:07 +00:00
|
|
|
logrus.Infof("checking %s", sourceDir)
|
2020-10-11 08:02:17 +00:00
|
|
|
_, err = os.Stat(sourceDir)
|
|
|
|
if err != nil {
|
2020-10-23 06:28:07 +00:00
|
|
|
logrus.Infof("cloning bbgo source into %s ...", sourceDir)
|
2020-10-11 08:02:17 +00:00
|
|
|
cmd := exec.CommandContext(ctx, "git", "clone", "https://github.com/c9s/bbgo", sourceDir)
|
|
|
|
if err := cmd.Run(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
} else if !noUpdate {
|
2020-10-23 06:28:07 +00:00
|
|
|
logrus.Infof("updating: %s ...", sourceDir)
|
2020-10-11 08:02:17 +00:00
|
|
|
cmd := exec.CommandContext(ctx, "git", "--work-tree", sourceDir, "pull")
|
|
|
|
if err := cmd.Run(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-23 06:28:07 +00:00
|
|
|
logrus.Infof("using migration file dir: %s", migrationDir)
|
2020-10-11 08:02:17 +00:00
|
|
|
|
|
|
|
command := args[0]
|
|
|
|
if err := goose.Run(command, db, migrationDir); err != nil {
|
2020-10-23 06:28:07 +00:00
|
|
|
logrus.Fatalf("goose run: %v", err)
|
2020-10-11 08:02:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
defer db.Close()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
},
|
|
|
|
}
|