This commit is contained in:
xxjwxc
2020-02-29 00:19:25 +08:00
parent 73c399165e
commit ce3904575d
11 changed files with 132 additions and 80 deletions

View File

@@ -22,7 +22,6 @@ var foreignKey bool
var funcKey bool var funcKey bool
var ui bool var ui bool
var urlTag string var urlTag string
var tableList string
var outFileName string var outFileName string
var rootCmd = &cobra.Command{ var rootCmd = &cobra.Command{
@@ -75,9 +74,6 @@ func init() {
rootCmd.PersistentFlags().StringVarP(&urlTag, "url", "l", "", "url标签(json,url)") rootCmd.PersistentFlags().StringVarP(&urlTag, "url", "l", "", "url标签(json,url)")
rootCmd.MarkFlagRequired("url tag") rootCmd.MarkFlagRequired("url tag")
rootCmd.PersistentFlags().StringVarP(&tableList, "tablelist", "t", "", "目标table列表以','隔开")
rootCmd.MarkFlagRequired("table list")
rootCmd.Flags().StringVar(&outFileName, "outfilename", "", "输出文件名,默认以数据库名称命名") rootCmd.Flags().StringVar(&outFileName, "outfilename", "", "输出文件名,默认以数据库名称命名")
rootCmd.Flags().IntVar(&mysqlInfo.Port, "port", 3306, "端口号") rootCmd.Flags().IntVar(&mysqlInfo.Port, "port", 3306, "端口号")
@@ -119,13 +115,6 @@ func MergeMysqlDbInfo() {
if len(urlTag) > 0 { if len(urlTag) > 0 {
config.SetURLTag(urlTag) config.SetURLTag(urlTag)
} }
if len(tableList) > 0 {
m := make(map[string]struct{})
for _, v := range strings.Split(tableList, ",") {
m[v] = struct{}{}
}
config.SetTableList(m)
}
if len(outFileName) > 0 { if len(outFileName) > 0 {
if !strings.HasSuffix(outFileName, ".go") { if !strings.HasSuffix(outFileName, ".go") {
outFileName += ".go" outFileName += ".go"

View File

@@ -9,21 +9,20 @@ import (
// Config custom config struct // Config custom config struct
type Config struct { type Config struct {
CfgBase `yaml:"base"` CfgBase `yaml:"base"`
MySQLInfo MysqlDbInfo `yaml:"mysql_info"` MySQLInfo MysqlDbInfo `yaml:"mysql_info"`
OutDir string `yaml:"out_dir"` OutDir string `yaml:"out_dir"`
URLTag string `yaml:"url_tag"` // url tag URLTag string `yaml:"url_tag"` // url tag
Language string `yaml:"language"` // language Language string `yaml:"language"` // language
DbTag string `yaml:"db_tag"` // 数据库标签gormt,db DbTag string `yaml:"db_tag"` // 数据库标签gormt,db
Simple bool `yaml:"simple"` Simple bool `yaml:"simple"`
IsWEBTag bool `yaml:"is_web_tag"` IsWEBTag bool `yaml:"is_web_tag"`
SingularTable bool `yaml:"singular_table"` SingularTable bool `yaml:"singular_table"`
IsForeignKey bool `yaml:"is_foreign_key"` IsForeignKey bool `yaml:"is_foreign_key"`
IsOutSQL bool `yaml:"is_out_sql"` IsOutSQL bool `yaml:"is_out_sql"`
IsOutFunc bool `yaml:"is_out_func"` IsOutFunc bool `yaml:"is_out_func"`
IsGUI bool `yaml:"is_gui"` // IsGUI bool `yaml:"is_gui"` //
IsTableName bool `yaml:"is_table_name"` IsTableName bool `yaml:"is_table_name"`
TableList map[string]struct{} `yaml:"-"` OutFileName string `yaml:"-"`
OutFileName string `yaml:"-"`
} }
// MysqlDbInfo mysql database information. mysql 数据库信息 // MysqlDbInfo mysql database information. mysql 数据库信息
@@ -145,14 +144,6 @@ func SetIsTableName(b bool) {
_map.IsTableName = b _map.IsTableName = b
} }
func SetTableList(m map[string]struct{}) {
_map.TableList = m
}
func GetTableList() map[string]struct{} {
return _map.TableList
}
func SetOutFileName(f string) { func SetOutFileName(f string) {
_map.OutFileName = f _map.OutFileName = f
} }

View File

@@ -3,6 +3,8 @@ package config
import ( import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"os"
"path"
"github.com/xxjwxc/public/dev" "github.com/xxjwxc/public/dev"
"github.com/xxjwxc/public/tools" "github.com/xxjwxc/public/tools"
@@ -18,33 +20,65 @@ type CfgBase struct {
IsDev bool `json:"is_dev" yaml:"is_dev"` // Is it a development version?是否是开发版本 IsDev bool `json:"is_dev" yaml:"is_dev"` // Is it a development version?是否是开发版本
} }
var _map = Config{} var _map = Config{
CfgBase: CfgBase{
IsDev: false,
},
MySQLInfo: MysqlDbInfo{
Host: "127.0.0.1",
Port: 3306,
Username: "root",
Password: "root",
Database: "test",
},
OutDir: "./model",
URLTag: "json",
Language: "中 文",
DbTag: "gorm",
Simple: false,
IsWEBTag: false,
SingularTable: true,
IsForeignKey: true,
IsOutSQL: false,
IsOutFunc: true,
IsGUI: false,
}
var configPath string
func init() { func init() {
configPath = path.Join(tools.GetModelPath(), "config.yml")
onInit() onInit()
dev.OnSetDev(_map.IsDev) dev.OnSetDev(_map.IsDev)
} }
func onInit() { func onInit() {
path := tools.GetModelPath() err := InitFile(configPath)
err := InitFile(path + "/config.yml")
if err != nil { if err != nil {
fmt.Println("InitFile: ", err.Error()) fmt.Println("Load config file error: ", err.Error())
return return
} }
} }
// InitFile default value from file . // InitFile default value from file .
func InitFile(filename string) error { func InitFile(filename string) error {
if _, e := os.Stat(filename); e != nil {
fmt.Println("init default config file: ", filename)
if err := SaveToFile(); err == nil {
fmt.Println("done,please restart.")
} else {
fmt.Println("shit,fail", err)
}
os.Exit(0)
}
bs, err := ioutil.ReadFile(filename) bs, err := ioutil.ReadFile(filename)
if err != nil { if err != nil {
return err return err
} }
if err := yaml.Unmarshal(bs, &_map); err != nil { if err := yaml.Unmarshal(bs, &_map); err != nil {
fmt.Println("read toml error: ", err.Error()) fmt.Println("read config file error: ", err.Error())
return err return err
} }
return nil return nil
} }
@@ -72,9 +106,8 @@ func SaveToFile() error {
if err != nil { if err != nil {
return err return err
} }
tools.WriteFile(tools.GetModelPath()+"/config.yml", []string{ tools.WriteFile(configPath, []string{
string(d), string(d),
}, true) }, true)
return nil return nil
} }

View File

@@ -4,12 +4,14 @@ import (
"fmt" "fmt"
"log" "log"
"strconv" "strconv"
"strings"
"github.com/xxjwxc/public/tools" "github.com/xxjwxc/public/tools"
"github.com/xxjwxc/gormt/data/config" "github.com/xxjwxc/gormt/data/config"
"github.com/jroimartin/gocui" "github.com/jroimartin/gocui"
"github.com/xxjwxc/public/myclipboard"
"github.com/xxjwxc/public/mycui" "github.com/xxjwxc/public/mycui"
) )
@@ -77,7 +79,7 @@ func mainLayout(g *gocui.Gui) error {
// } // }
} }
if v, err := g.SetView(_viewDefine, division(maxX, uiPart[0]), 1, maxX-1, maxY-1); err != nil { if v, err := g.SetView(_viewDefine, division(maxX, uiPart[0]), 1, maxX-1, maxY-3); err != nil {
if err != gocui.ErrUnknownView { if err != gocui.ErrUnknownView {
return err return err
} }
@@ -103,6 +105,11 @@ func nemuLayOut(g *gocui.Gui) {
AddHandler(gocui.KeyArrowUp, menuDlg.prevButton).AddHandler(gocui.KeyArrowDown, menuDlg.nextButton). AddHandler(gocui.KeyArrowUp, menuDlg.prevButton).AddHandler(gocui.KeyArrowDown, menuDlg.nextButton).
AddHandler(gocui.KeyEnter, enterSet).AddHandler(gocui.MouseLeft, enterSet)) AddHandler(gocui.KeyEnter, enterSet).AddHandler(gocui.MouseLeft, enterSet))
maxX, maxY := g.Size() // division(maxY, uiPart[1])
clipboardBtn = mycui.NewButton(g, _clipboardBtn, SLocalize(_clipboardBtn), division(maxX, uiPart[0])+2, maxY-3, 5).
AddHandler(gocui.KeyEnter, enterClipboard).AddHandler(gocui.MouseLeft, enterClipboard)
clipboardBtn.Draw()
menuDlg.Draw() menuDlg.Draw()
menuFocusButton(g) menuFocusButton(g)
} }
@@ -163,6 +170,24 @@ func addlog(g *gocui.Gui, str string) error {
return err return err
} }
func enterClipboard(g *gocui.Gui, v *gocui.View) error {
myclipboard.Set(copyInfo)
maxX, _ := g.Size()
modal := mycui.NewModal(g, division(maxX, uiPart[0])+5, 10, division(maxX, uiPart[0])+35).
SetTextColor(gocui.ColorRed).SetText("copy success \n 已 复 制 到 剪 切 板 ")
modal.Mouse = true
// modal.SetBgColor(gocui.ColorRed)
_handle := func(g *gocui.Gui, v *gocui.View) error {
modal.Close()
return nil
}
modal.AddButton("ok", "OK", gocui.KeyEnter, _handle).AddHandler(gocui.MouseLeft, _handle)
modal.Draw()
return nil
}
func enterRun(g *gocui.Gui, v *gocui.View) error { func enterRun(g *gocui.Gui, v *gocui.View) error {
setlog(g, "run .... ing") setlog(g, "run .... ing")
generate(g, v) generate(g, v)
@@ -244,12 +269,14 @@ func buttonSave(g *gocui.Gui, v *gocui.View) error {
port, err := strconv.Atoi(mp["db_port"]) port, err := strconv.Atoi(mp["db_port"])
if err != nil { if err != nil {
modal := mycui.NewModal(g, division(maxX, uiPart[0])+5, 10, division(maxX, uiPart[0])+35).SetTextColor(gocui.ColorRed).SetText("port error") modal := mycui.NewModal(g, division(maxX, uiPart[0])+5, 10, division(maxX, uiPart[0])+35).SetTextColor(gocui.ColorRed).SetText("port error")
// modal.SetBgColor(gocui.ColorRed)
modal.AddButton("ok", "OK", gocui.KeyEnter, func(g *gocui.Gui, v *gocui.View) error { _handle := func(g *gocui.Gui, v *gocui.View) error {
modal.Close() modal.Close()
form.SetCurrentItem(form.GetCurrentItem()) form.SetCurrentItem(form.GetCurrentItem())
return nil return nil
}) }
// modal.SetBgColor(gocui.ColorRed)
modal.AddButton("ok", "OK", gocui.KeyEnter, _handle).AddHandler(gocui.MouseLeft, _handle)
modal.Draw() modal.Draw()
return nil return nil
@@ -276,11 +303,12 @@ func buttonSave(g *gocui.Gui, v *gocui.View) error {
config.SaveToFile() config.SaveToFile()
modal := mycui.NewModal(g, division(maxX, uiPart[0])+5, 10, division(maxX, uiPart[0])+35).SetText("save success") modal := mycui.NewModal(g, division(maxX, uiPart[0])+5, 10, division(maxX, uiPart[0])+35).SetText("save success")
modal.AddButton("ok", "OK", gocui.KeyEnter, func(g *gocui.Gui, v *gocui.View) error { _handle := func(g *gocui.Gui, v *gocui.View) error {
modal.Close() modal.Close()
buttonCancel(g, v) buttonCancel(g, v)
return nil return nil
}) }
modal.AddButton("ok", "OK", gocui.KeyEnter, _handle).AddHandler(gocui.MouseLeft, _handle)
modal.Draw() modal.Draw()
return nil return nil
@@ -309,10 +337,11 @@ func showStruct(g *gocui.Gui, v *gocui.View) error {
l = "" l = ""
} }
var out []string var out, out1 []string
for _, v := range gPkg.Structs { for _, v := range gPkg.Structs {
if v.Name == l { if v.Name == l {
out = v.GeneratesColor() out = v.GeneratesColor()
out1 = v.Generates()
break break
} }
} }
@@ -321,6 +350,9 @@ func showStruct(g *gocui.Gui, v *gocui.View) error {
for _, v := range out { for _, v := range out {
addlog(g, v) addlog(g, v)
} }
copyInfo = strings.Join(out1, "\n")
return nil return nil
} }

View File

@@ -6,15 +6,16 @@ import (
) )
const ( const (
_menuDefine = "menu" _menuDefine = "menu"
_listDefine = "list" _listDefine = "list"
_viewDefine = "view" _viewDefine = "view"
_run = "run" _run = "run"
_set = "set" _set = "set"
_clipboardBtn = "clipboardBtn"
) )
var ( var (
uiPart = []float32{4, 3} // x,y 对应列表 uiPart = []float32{4, 5} // x,y 对应列表
mainViewArr = []string{_menuDefine, _listDefine, _viewDefine} // 主菜单列表 mainViewArr = []string{_menuDefine, _listDefine, _viewDefine} // 主菜单列表
mainIndex = 0 mainIndex = 0
@@ -33,6 +34,9 @@ type listDetails struct {
btnList []*mycui.Button btnList []*mycui.Button
} }
var clipboardBtn *mycui.Button
var copyInfo string
var menuDlg *menuDetails var menuDlg *menuDetails
var form *mycui.Form var form *mycui.Form
var gPkg genstruct.GenPackage var gPkg genstruct.GenPackage

View File

@@ -47,6 +47,9 @@ func addChinese() error {
}, &i18n.Message{ }, &i18n.Message{
ID: "set", ID: "set",
Other: "设 置 🛠 ", Other: "设 置 🛠 ",
}, &i18n.Message{
ID: "clipboardBtn",
Other: "复 制 到 剪 切 板 ",
}, &i18n.Message{ }, &i18n.Message{
ID: "out_dir", ID: "out_dir",
Other: " 输 出 目 录 :", Other: " 输 出 目 录 :",
@@ -138,6 +141,9 @@ func addEnglish() error {
}, &i18n.Message{ }, &i18n.Message{
ID: "set", ID: "set",
Other: "Set 🛠 ", Other: "Set 🛠 ",
}, &i18n.Message{
ID: "clipboardBtn",
Other: "Copy to clipboard",
}, &i18n.Message{ }, &i18n.Message{
ID: "out_dir", ID: "out_dir",
Other: "out dir:", Other: "out dir:",

View File

@@ -10,8 +10,6 @@ var EImportsHead = map[string]string{
// TypeMysqlDicMp Accurate matching type.精确匹配类型 // TypeMysqlDicMp Accurate matching type.精确匹配类型
var TypeMysqlDicMp = map[string]string{ var TypeMysqlDicMp = map[string]string{
"tinyint": "int8",
"tinyint unsigned": "uint8",
"smallint": "int16", "smallint": "int16",
"smallint unsigned": "uint16", "smallint unsigned": "uint16",
"int": "int", "int": "int",
@@ -24,6 +22,7 @@ var TypeMysqlDicMp = map[string]string{
"datetime": "time.Time", "datetime": "time.Time",
"bit(1)": "int8", "bit(1)": "int8",
"tinyint": "int8", "tinyint": "int8",
"tinyint unsigned": "uint8",
"tinyint(1)": "int8", "tinyint(1)": "int8",
"tinyint(1) unsigned": "int8", "tinyint(1) unsigned": "int8",
"json": "string", "json": "string",

View File

@@ -181,8 +181,12 @@ func (s *GenStruct) GeneratesColor() []string {
} }
p.Add("\033[32;1m " + s.Notes + " \033[0m") p.Add("\033[32;1m " + s.Notes + " \033[0m")
p.Add("\033[34;1m type \033[0m", s.Name, "\033[34;1m struct \033[0m {") p.Add("\033[34;1m type \033[0m", s.Name, "\033[34;1m struct \033[0m {")
mp := make(map[string]bool, len(s.Em))
for _, v := range s.Em { for _, v := range s.Em {
p.Add(" \t\t" + v.GenerateColor()) if !mp[v.Name] {
mp[v.Name] = true
p.Add(" \t\t" + v.GenerateColor())
}
} }
p.Add(" }") p.Add(" }")
@@ -231,12 +235,8 @@ func (p *GenPackage) Generate() string {
for _, v1 := range v.Generates() { for _, v1 := range v.Generates() {
pa.Add(v1) pa.Add(v1)
} }
}
// -----------end
// add table name func if config.GetIsTableName() { // add table name func
if config.GetIsTableName() {
for _, v := range p.Structs {
for _, v1 := range v.GenerateTableName() { for _, v1 := range v.GenerateTableName() {
pa.Add(v1) pa.Add(v1)
} }

View File

@@ -60,18 +60,18 @@ func (m *mysqlModel) GetPkgName() string {
func getPackageInfo(orm *mysqldb.MySqlDB, info *model.DBInfo) { func getPackageInfo(orm *mysqldb.MySqlDB, info *model.DBInfo) {
tabls := getTables(orm) // get table and notes tabls := getTables(orm) // get table and notes
if m := config.GetTableList(); len(m) > 0 { // if m := config.GetTableList(); len(m) > 0 {
// 制定了表之后 // // 制定了表之后
newTabls := make(map[string]string) // newTabls := make(map[string]string)
for t := range m { // for t := range m {
if notes, ok := tabls[t]; ok { // if notes, ok := tabls[t]; ok {
newTabls[t] = notes // newTabls[t] = notes
} else { // } else {
fmt.Printf("table: %s not found in db\n", t) // fmt.Printf("table: %s not found in db\n", t)
} // }
} // }
tabls = newTabls // tabls = newTabls
} // }
for tabName, notes := range tabls { for tabName, notes := range tabls {
var tab model.TabInfo var tab model.TabInfo
tab.Name = tabName tab.Name = tabName

View File

@@ -29,11 +29,8 @@ func Generate(info DBInfo) (out []GenOutInfo, m _Model) {
// struct // struct
var stt GenOutInfo var stt GenOutInfo
stt.FileCtx = m.generate() stt.FileCtx = m.generate()
if fn := config.GetOutFileName(); fn != "" { stt.FileName = info.DbName + ".go"
stt.FileName = fn
} else {
stt.FileName = info.DbName + ".go"
}
out = append(out, stt) out = append(out, stt)
// ------end // ------end

1
go.sum
View File

@@ -12,6 +12,7 @@ github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRF
github.com/ant0ine/go-json-rest v3.3.2+incompatible/go.mod h1:q6aCt0GfU6LhpBsnZ/2U+mwe+0XB5WStbmwyoPfc+sk= github.com/ant0ine/go-json-rest v3.3.2+incompatible/go.mod h1:q6aCt0GfU6LhpBsnZ/2U+mwe+0XB5WStbmwyoPfc+sk=
github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ=
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
github.com/atotto/clipboard v0.1.2 h1:YZCtFu5Ie8qX2VmVTBnrqLSiU9XOWwqNRmdT3gIQzbY=
github.com/atotto/clipboard v0.1.2/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/atotto/clipboard v0.1.2/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/axgle/mahonia v0.0.0-20180208002826-3358181d7394 h1:OYA+5W64v3OgClL+IrOD63t4i/RW7RqrAVl9LTZ9UqQ= github.com/axgle/mahonia v0.0.0-20180208002826-3358181d7394 h1:OYA+5W64v3OgClL+IrOD63t4i/RW7RqrAVl9LTZ9UqQ=
github.com/axgle/mahonia v0.0.0-20180208002826-3358181d7394/go.mod h1:Q8n74mJTIgjX4RBBcHnJ05h//6/k6foqmgE45jTQtxg= github.com/axgle/mahonia v0.0.0-20180208002826-3358181d7394/go.mod h1:Q8n74mJTIgjX4RBBcHnJ05h//6/k6foqmgE45jTQtxg=