Merge branch 'master' of https://github.com/LLLLancelot/gormt into LLLLancelot-master

master
xxjwxc 5 years ago
commit d7c76feba6

@ -38,6 +38,7 @@ is_out_func : true # Whether to output function
is_url_tag : true # Whether to mark web or not
is_foreign_key : true # Whether to mark foreign key or not
is_gui : false # Whether to operate on gui
is_table_name : false # Whether to out GetTableName function
mysql_info :
host : "127.0.0.1"

@ -42,6 +42,7 @@ is_out_func : true # 是否输出 快捷函数
is_url_tag : true # 是否打web标记
is_foreign_key : true # 是否导出外键关联
is_gui : false # 是否ui模式显示
is_table_name : false # 是否直接生成表名函数
mysql_info:
host : 127.0.0.1
port : 3306

@ -11,6 +11,7 @@ is_out_func : true # 是否输出 快捷函数
is_url_tag : true # 是否打web标记
is_foreign_key : true # 是否导出外键关联
is_gui : false # 是否ui模式显示
is_table_name : false # 是否直接生成表名函数
mysql_info:
host : 127.0.0.1
port : 3306

@ -3,6 +3,7 @@ package cmd
import (
"fmt"
"os"
"strings"
"github.com/xxjwxc/public/tools"
@ -21,6 +22,8 @@ var foreignKey bool
var funcKey bool
var ui bool
var urlTag string
var tableList string
var outFileName string
var rootCmd = &cobra.Command{
Use: "main",
@ -72,6 +75,11 @@ func init() {
rootCmd.PersistentFlags().StringVarP(&urlTag, "url", "l", "", "url标签(json,url)")
rootCmd.MarkFlagRequired("url tag")
rootCmd.PersistentFlags().StringVarP(&tableList, "tablelist", "t", "", "目标table列表以','隔开")
rootCmd.MarkFlagRequired("table list")
rootCmd.Flags().StringVar(&outFileName, "outfilename", "", "输出文件名,默认以数据库名称命名")
rootCmd.Flags().IntVar(&mysqlInfo.Port, "port", 3306, "端口号")
}
@ -111,6 +119,19 @@ func MergeMysqlDbInfo() {
if len(urlTag) > 0 {
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 !strings.HasSuffix(outFileName, ".go") {
outFileName += ".go"
}
config.SetOutFileName(outFileName)
}
config.SetMysqlDbInfo(&tmp)

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

@ -3,8 +3,6 @@ package config
import (
"fmt"
"io/ioutil"
"os"
"path"
"github.com/xxjwxc/public/dev"
"github.com/xxjwxc/public/tools"
@ -20,65 +18,33 @@ type CfgBase struct {
IsDev bool `json:"is_dev" yaml:"is_dev"` // Is it a development version?是否是开发版本
}
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
var _map = Config{}
func init() {
configPath = path.Join(tools.GetModelPath(), "config.yml")
onInit()
dev.OnSetDev(_map.IsDev)
}
func onInit() {
err := InitFile(configPath)
path := tools.GetModelPath()
err := InitFile(path + "/config.yml")
if err != nil {
fmt.Println("Load config file error: ", err.Error())
fmt.Println("InitFile: ", err.Error())
return
}
}
// InitFile default value from file .
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)
if err != nil {
return err
}
if err := yaml.Unmarshal(bs, &_map); err != nil {
fmt.Println("read config file error: ", err.Error())
fmt.Println("read toml error: ", err.Error())
return err
}
return nil
}
@ -106,8 +72,9 @@ func SaveToFile() error {
if err != nil {
return err
}
tools.WriteFile(configPath, []string{
tools.WriteFile(tools.GetModelPath()+"/config.yml", []string{
string(d),
}, true)
return nil
}

@ -4,14 +4,12 @@ import (
"fmt"
"log"
"strconv"
"strings"
"github.com/xxjwxc/public/tools"
"github.com/xxjwxc/gormt/data/config"
"github.com/jroimartin/gocui"
"github.com/xxjwxc/public/myclipboard"
"github.com/xxjwxc/public/mycui"
)
@ -79,7 +77,7 @@ func mainLayout(g *gocui.Gui) error {
// }
}
if v, err := g.SetView(_viewDefine, division(maxX, uiPart[0]), 1, maxX-1, maxY-3); err != nil {
if v, err := g.SetView(_viewDefine, division(maxX, uiPart[0]), 1, maxX-1, maxY-1); err != nil {
if err != gocui.ErrUnknownView {
return err
}
@ -105,11 +103,6 @@ func nemuLayOut(g *gocui.Gui) {
AddHandler(gocui.KeyArrowUp, menuDlg.prevButton).AddHandler(gocui.KeyArrowDown, menuDlg.nextButton).
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()
menuFocusButton(g)
}
@ -170,24 +163,6 @@ func addlog(g *gocui.Gui, str string) error {
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 {
setlog(g, "run .... ing")
generate(g, v)
@ -230,6 +205,8 @@ func enterSet(g *gocui.Gui, v *gocui.View) error {
AddOptions(SLocalize("true"), SLocalize("false")).SetSelected(SLocalize(tools.AsString(config.GetIsForeignKey())))
form.AddSelect("is_gui", SLocalize("is_gui"), formPart[0], formPart[2]).
AddOptions(SLocalize("true"), SLocalize("false")).SetSelected(SLocalize(tools.AsString(config.GetIsGUI())))
form.AddSelect("is_table_name", SLocalize("is_table_name"), formPart[0], formPart[2]).
AddOptions(SLocalize("true"), SLocalize("false")).SetSelected(SLocalize(tools.AsString(config.GetIsTableName())))
form.AddSelect("url_tag", SLocalize("url_tag"), formPart[0], formPart[2]).
AddOptions("json", "url").SetSelected(tools.AsString(config.GetURLTag()))
form.AddSelect("db_tag", SLocalize("db_tag"), formPart[0], formPart[2]).
@ -267,14 +244,12 @@ func buttonSave(g *gocui.Gui, v *gocui.View) error {
port, err := strconv.Atoi(mp["db_port"])
if err != nil {
modal := mycui.NewModal(g, division(maxX, uiPart[0])+5, 10, division(maxX, uiPart[0])+35).SetTextColor(gocui.ColorRed).SetText("port error")
_handle := func(g *gocui.Gui, v *gocui.View) error {
// modal.SetBgColor(gocui.ColorRed)
modal.AddButton("ok", "OK", gocui.KeyEnter, func(g *gocui.Gui, v *gocui.View) error {
modal.Close()
form.SetCurrentItem(form.GetCurrentItem())
return nil
}
// modal.SetBgColor(gocui.ColorRed)
modal.AddButton("ok", "OK", gocui.KeyEnter, _handle).AddHandler(gocui.MouseLeft, _handle)
})
modal.Draw()
return nil
@ -294,18 +269,18 @@ func buttonSave(g *gocui.Gui, v *gocui.View) error {
config.SetIsOutFunc(getBool(mp["is_out_func"]))
config.SetForeignKey(getBool(mp["is_foreign_key"]))
config.SetIsGUI(getBool(mp["is_gui"]))
config.SetIsTableName(getBool(mp["is_table_name"]))
config.SetURLTag(mp["url_tag"])
config.SetDBTag(mp["db_tag"])
config.SetLG(mp["language"])
config.SaveToFile()
modal := mycui.NewModal(g, division(maxX, uiPart[0])+5, 10, division(maxX, uiPart[0])+35).SetText("save success")
_handle := func(g *gocui.Gui, v *gocui.View) error {
modal.AddButton("ok", "OK", gocui.KeyEnter, func(g *gocui.Gui, v *gocui.View) error {
modal.Close()
buttonCancel(g, v)
return nil
}
modal.AddButton("ok", "OK", gocui.KeyEnter, _handle).AddHandler(gocui.MouseLeft, _handle)
})
modal.Draw()
return nil
@ -334,11 +309,10 @@ func showStruct(g *gocui.Gui, v *gocui.View) error {
l = ""
}
var out, out1 []string
var out []string
for _, v := range gPkg.Structs {
if v.Name == l {
out = v.GeneratesColor()
out1 = v.Generates()
break
}
}
@ -347,9 +321,6 @@ func showStruct(g *gocui.Gui, v *gocui.View) error {
for _, v := range out {
addlog(g, v)
}
copyInfo = strings.Join(out1, "\n")
return nil
}

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

@ -47,9 +47,6 @@ func addChinese() error {
}, &i18n.Message{
ID: "set",
Other: "设 置 🛠 ",
}, &i18n.Message{
ID: "clipboardBtn",
Other: "复 制 到 剪 切 板 ",
}, &i18n.Message{
ID: "out_dir",
Other: " 输 出 目 录 :",
@ -89,6 +86,9 @@ func addChinese() error {
}, &i18n.Message{
ID: "is_gui",
Other: " 界 面 模 式 :",
}, &i18n.Message{
ID: "is_table_name",
Other: " 生 成 表 名 :",
}, &i18n.Message{
ID: "url_tag",
Other: " web 标 签:",
@ -138,9 +138,6 @@ func addEnglish() error {
}, &i18n.Message{
ID: "set",
Other: "Set 🛠 ",
}, &i18n.Message{
ID: "clipboardBtn",
Other: "Copy to clipboard",
}, &i18n.Message{
ID: "out_dir",
Other: "out dir:",
@ -180,6 +177,9 @@ func addEnglish() error {
}, &i18n.Message{
ID: "is_gui",
Other: "is show gui:",
}, &i18n.Message{
ID: "is_table_name",
Other: "is table name:",
}, &i18n.Message{
ID: "url_tag",
Other: "url tag:",

@ -10,8 +10,14 @@ var EImportsHead = map[string]string{
// TypeMysqlDicMp Accurate matching type.精确匹配类型
var TypeMysqlDicMp = map[string]string{
"tinyint": "int8",
"tinyint unsigned": "uint8",
"smallint": "int16",
"smallint unsigned": "uint16",
"int": "int",
"int unsigned": "uint",
"bigint": "int64",
"bigint unsigned": "uint64",
"varchar": "string",
"char": "string",
"date": "time.Time",
@ -34,7 +40,7 @@ var TypeMysqlDicMp = map[string]string{
// TypeMysqlMatchMp Fuzzy Matching Types.模糊匹配类型
var TypeMysqlMatchMp = map[string]string{
`^(tinyint)[(]\d+[)]`: "int8",
`^(smallint)[(]\d+[)]`: "int8",
`^(smallint)[(]\d+[)]`: "int16",
`^(int)[(]\d+[)]`: "int",
`^(bigint)[(]\d+[)]`: "int64",
`^(char)[(]\d+[)]`: "string",
@ -45,4 +51,5 @@ var TypeMysqlMatchMp = map[string]string{
`^(mediumint)[(]\d+[)]`: "string",
`^(double)[(]\d+,\d+[)]`: "float64",
`^(float)[(]\d+,\d+[)]`: "float64",
`^(datetime)[(]\d+[)]`: "time.Time",
}

@ -1,6 +1,12 @@
package genfunc
const (
genTnf = `
// TableName get sql table name.获取数据库表名
func (m *{{.StructName}}) TableName() string {
return "{{.TableName}}"
}
`
genBase = `
package {{.PackageName}}
import (

@ -1,5 +1,10 @@
package genfunc
// GetGenTableNameTemp get gen base template str
func GetGenTableNameTemp() string {
return genTnf
}
// GetGenBaseTemp get gen base template str
func GetGenBaseTemp() string {
return genBase

@ -1,13 +1,16 @@
package genstruct
import (
"bytes"
"fmt"
"sort"
"strings"
"text/template"
"github.com/xxjwxc/gormt/data/config"
"github.com/xxjwxc/gormt/data/view/cnf"
"github.com/xxjwxc/gormt/data/view/generate"
"github.com/xxjwxc/gormt/data/view/genfunc"
)
// SetName Setting element name.设置元素名字
@ -96,6 +99,11 @@ func (s *GenStruct) SetCreatTableStr(sql string) {
s.SQLBuildStr = sql
}
// SetTableName Setting the name of struct.设置struct名字
func (s *GenStruct) SetTableName(name string) {
s.TableName = name
}
// SetStructName Setting the name of struct.设置struct名字
func (s *GenStruct) SetStructName(name string) {
s.Name = name
@ -125,6 +133,21 @@ func (s *GenStruct) AddElement(e ...GenElement) {
s.Em = append(s.Em, e...)
}
func (s *GenStruct) GenerateTableName() []string {
tmpl, err := template.New("gen_tnf").Parse(genfunc.GetGenTableNameTemp())
if err != nil {
panic(err)
}
var data struct {
TableName string
StructName string
}
data.TableName, data.StructName = s.TableName, s.Name
var buf bytes.Buffer
tmpl.Execute(&buf, data)
return []string{buf.String()}
}
// Generates Get the result data.获取结果数据
func (s *GenStruct) Generates() []string {
var p generate.PrintAtom
@ -158,12 +181,8 @@ func (s *GenStruct) GeneratesColor() []string {
}
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 {")
mp := make(map[string]bool, len(s.Em))
for _, v := range s.Em {
if !mp[v.Name] {
mp[v.Name] = true
p.Add(" \t\t" + v.GenerateColor())
}
p.Add(" \t\t" + v.GenerateColor())
}
p.Add(" }")
@ -215,6 +234,16 @@ func (p *GenPackage) Generate() string {
}
// -----------end
// add table name func
if config.GetIsTableName() {
for _, v := range p.Structs {
for _, v1 := range v.GenerateTableName() {
pa.Add(v1)
}
}
}
// -----------end
// add func
for _, v := range p.FuncStrList {
pa.Add(v)

@ -11,6 +11,7 @@ type GenElement struct {
// GenStruct struct of IStruct .结构体
type GenStruct struct {
SQLBuildStr string // Create SQL statements.创建sql语句
TableName string // table_name.表名
Name string // name.名字
Notes string // notes.注释
Em []GenElement // em.元素组合

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

@ -29,7 +29,11 @@ func Generate(info DBInfo) (out []GenOutInfo, m _Model) {
// struct
var stt GenOutInfo
stt.FileCtx = m.generate()
stt.FileName = info.DbName + ".go"
if fn := config.GetOutFileName(); fn != "" {
stt.FileName = fn
} else {
stt.FileName = info.DbName + ".go"
}
out = append(out, stt)
// ------end
@ -48,6 +52,7 @@ func (m *_Model) GetPackage() genstruct.GenPackage {
pkg.SetPackage(m.info.PackageName) //package name
for _, tab := range m.info.TabList {
var sct genstruct.GenStruct
sct.SetTableName(tab.Name)
sct.SetStructName(getCamelName(tab.Name)) // Big hump.大驼峰
sct.SetNotes(tab.Notes)
sct.AddElement(m.genTableElement(tab.Em)...) // build element.构造元素

@ -12,7 +12,6 @@ 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/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/atotto/clipboard v0.1.2 h1:YZCtFu5Ie8qX2VmVTBnrqLSiU9XOWwqNRmdT3gIQzbY=
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/go.mod h1:Q8n74mJTIgjX4RBBcHnJ05h//6/k6foqmgE45jTQtxg=

Loading…
Cancel
Save