You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.6 KiB
Go

package cmd
import (
"fmt"
"os"
6 years ago
"github.com/xie1xiao1jun/public/tools"
6 years ago
"github.com/xie1xiao1jun/gorm-tools/data/config"
6 years ago
"github.com/xie1xiao1jun/gorm-tools/data/view/gtools"
6 years ago
"github.com/spf13/cobra"
"gopkg.in/go-playground/validator.v9"
)
var mysqlInfo config.MysqlDbInfo
var outDir string
var singular_table bool
var rootCmd = &cobra.Command{
Use: "main",
Short: "gorm mysql reflect tools",
Long: `base on gorm tools for mysql database to golang struct`,
Run: func(cmd *cobra.Command, args []string) {
6 years ago
gtools.Execute()
//开始做事情
},
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}
func init() {
cobra.OnInitialize(initConfig)
6 years ago
rootCmd.PersistentFlags().StringVarP(&mysqlInfo.Host, "host", "H", "", "数据库地址.(注意-H为大写)")
rootCmd.MarkFlagRequired("host")
rootCmd.PersistentFlags().StringVarP(&mysqlInfo.Username, "user", "u", "", "用户名.")
rootCmd.MarkFlagRequired("user")
rootCmd.PersistentFlags().StringVarP(&mysqlInfo.Password, "password", "p", "", "密码.")
rootCmd.MarkFlagRequired("password")
rootCmd.PersistentFlags().StringVarP(&mysqlInfo.Database, "database", "d", "", "数据库名")
rootCmd.MarkFlagRequired("database")
rootCmd.PersistentFlags().StringVarP(&outDir, "outdir", "o", "", "输出目录")
rootCmd.MarkFlagRequired("outdir")
rootCmd.PersistentFlags().StringVarP(&singular_table, "singular", "s", "", "是否禁用表名复数")
rootCmd.MarkFlagRequired("singular")
rootCmd.Flags().IntVar(&mysqlInfo.Port, "port", 3306, "端口号")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
6 years ago
MergeMysqlDbInfo()
validate := validator.New()
6 years ago
err := validate.Struct(config.GetMysqlDbInfo())
if err != nil {
6 years ago
fmt.Println("Can't read cmd: using -h, --help) to get more imfo")
fmt.Println("error info: ", err, err)
os.Exit(1)
} else {
6 years ago
fmt.Println("using config info:")
6 years ago
fmt.Println(tools.GetJsonStr(config.GetMysqlDbInfo()))
}
}
6 years ago
//合并
func MergeMysqlDbInfo() {
var tmp = config.GetMysqlDbInfo()
if len(mysqlInfo.Database) > 0 {
tmp.Database = mysqlInfo.Database
}
if len(mysqlInfo.Host) > 0 {
tmp.Host = mysqlInfo.Host
}
if len(mysqlInfo.Password) > 0 {
tmp.Password = mysqlInfo.Password
}
if mysqlInfo.Port != 3306 {
tmp.Port = mysqlInfo.Port
}
if len(mysqlInfo.Username) > 0 {
tmp.Username = mysqlInfo.Username
}
config.SetMysqlDbInfo(&tmp)
config.SetOutDir(outDir)
config.SetSingularTable(singular_table)
6 years ago
}