From 649b1f2d561234d0226514d7af765a91ba04ba73 Mon Sep 17 00:00:00 2001 From: 2637309949 <“2637309949@qq.com”> Date: Thu, 1 Jul 2021 09:47:04 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0new=E5=91=BD=E4=BB=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/dolphin/main.go | 22 +- cmd/dolphin/schema/common.go | 304 ---------- cmd/dolphin/schema/schema.go | 521 ++++++++++++++---- cmd/dolphin/utils/clone.go | 90 --- cmd/dolphin/utils/files.go | 10 - cmd/dolphin/utils/utils.go | 120 +++- ...53\351\200\237\345\205\245\351\227\250.md" | 40 +- 7 files changed, 559 insertions(+), 548 deletions(-) delete mode 100644 cmd/dolphin/schema/common.go delete mode 100644 cmd/dolphin/utils/clone.go delete mode 100644 cmd/dolphin/utils/files.go diff --git a/cmd/dolphin/main.go b/cmd/dolphin/main.go index 8cf01976..853e69e6 100644 --- a/cmd/dolphin/main.go +++ b/cmd/dolphin/main.go @@ -26,7 +26,7 @@ import ( ) // InitViper defined -func InitViper(cmd *cobra.Command, args []string) { +func InitViper(cmd *cobra.Command, _ []string) { utils.SetFormatter(terminal.IsTerminal(unix.Stdout)) utils.SetLevel(cmd) viper.SetConfigName("app") @@ -88,14 +88,14 @@ var ( rootCmd = &cobra.Command{ Use: "dolphin", Short: "dol", - Long: `dolphin, a cli tools for generate golang code`, + Long: `dolphin, a code generation tool for golang`, PersistentPreRun: func(cmd *cobra.Command, args []string) { InitViper(cmd, args) }, } build = &cobra.Command{ Use: "build", - Short: "Build project from xml", + Short: "build from the configuration file", RunE: func(_ *cobra.Command, args []string) error { wd, err := os.Getwd() justOne := false @@ -128,7 +128,7 @@ var ( } clean = &cobra.Command{ Use: "clean", - Short: "Removing intermediate files", + Short: "remove temp file, such as *.go.new", RunE: func(*cobra.Command, []string) error { wd, err := os.Getwd() if err != nil { @@ -140,7 +140,7 @@ var ( } more = &cobra.Command{ Use: "more", - Short: "Add controller and table", + Short: "add controller and table", RunE: func(_ *cobra.Command, args []string) error { wd, err := os.Getwd() if err != nil { @@ -153,13 +153,18 @@ var ( }, } setup = &cobra.Command{ - Use: "init", - Short: "Initialize a empty project", + Use: "new", + Short: "new a empty project", RunE: func(_ *cobra.Command, args []string) error { wd, err := os.Getwd() if err != nil { return err } + if len(args) < 1 { + logrus.Warn("please provide the project name") + return nil + } + wd = path.Join(wd, args[0]) if files, _ := utils.WalkFileInDirWithSuffix(wd, ".xml"); len(files) == 0 { p := parser.NewTpl(path.Base(wd), path.Base(wd)) if err := p.Walk(wd); err != nil { @@ -172,8 +177,9 @@ var ( return err } } else { - logrus.Warn("It is not allowed to initialize a non-empty project") + logrus.Warn("it is not allowed to initialize a non-empty project") } + logrus.Infof("new project success, cd to %v dir and run `dolphin build`", args[0]) return nil }, } diff --git a/cmd/dolphin/schema/common.go b/cmd/dolphin/schema/common.go deleted file mode 100644 index 6e94b2e8..00000000 --- a/cmd/dolphin/schema/common.go +++ /dev/null @@ -1,304 +0,0 @@ -// Copyright (c) 2018-2020 Double All rights reserved. -// Use of this source code is governed by a MIT style -// license that can be found in the LICENSE file. - -package schema - -import ( - "fmt" - "html/template" - "strconv" - "strings" - "unicode" - - "github.com/thoas/go-funk" -) - -// Common struct -type Common struct { - Name string `validate:"required"` - Desc string `validate:"required"` - Path string -} - -// Import packages -func (c *Common) Import(pkgs ...string) template.HTML { - pkg := strings.Join(pkgs, ",") - if len(pkg) > 0 { - packages := strings.Split(pkg, ",") - for i, v := range packages { - packages[i] = fmt.Sprintf(` "%v"`, v) - } - tmpl := "import (\n%s\n)" - return c.Unescaped(fmt.Sprintf(tmpl, strings.Join(packages, "\n"))) - } - return c.Unescaped("") -} - -// Unescaped unescaped -func (c *Common) Unescaped(x string) template.HTML { - return template.HTML(x) -} - -// SQLInsertOne insert one -func (c *Common) SQLInsertOne(table Table, name string) string { - names := strings.Join(funk.Map(table.Columns, func(col *Column) string { - return fmt.Sprintf("`%v`", col.Name) - }).([]string), ",") - values := strings.Join(funk.Map(table.Columns, func(col *Column) string { - return fmt.Sprintf("?%v", col.Name) - }).([]string), ",") - return `insert into ` + name + ` - (` + names + `) - values - (` + values + `)` -} - -// SQLSelectOne select one -func (c *Common) SQLSelectOne(table Table, name string) string { - names := strings.Join(funk.Map(table.Columns, func(col *Column) string { - return fmt.Sprintf("`%v`", col.Name) - }).([]string), ",") - return `select ` + names + ` from ` + name + ` where id =?id` -} - -// SQLDelOne remove one -func (c *Common) SQLDelOne(table Table, name string) string { - return `delete from ` + name + ` where id =?id` -} - -// SQLSelectAll select one -func (c *Common) SQLSelectAll(table Table, name string) string { - names := strings.Join(funk.Map(table.Columns, func(col *Column) string { - return fmt.Sprintf("`%v`", col.Name) - }).([]string), ",") - return `select ` + names + ` from ` + name -} - -// SQLUpdateOne update one -func (c *Common) SQLUpdateOne(table Table, name string) string { - names := strings.Join(funk.Map(table.Columns, func(col *Column) string { - return fmt.Sprintf("`%v`=?%v", col.Name, col.Name) - }).([]string), ",") - return `update ` + name + ` set ` + names + ` - where id =?id` -} - -// ToUpper toUpper -func (c *Common) ToUpper(name string) string { - return strings.ToUpper(name) -} - -// ToTypeValue value -func (c *Common) ToTypeValue(t string, v string) template.HTML { - if strings.TrimSpace(v) == "" { - return c.Unescaped("") - } - switch t { - case "int": - i, e := strconv.ParseInt(v, 10, 64) - if e != nil { - panic(e) - } - return c.Unescaped(fmt.Sprintf("%v", i)) - case "string": - return c.Unescaped(fmt.Sprintf(`"%v"`, v)) - case "bool": - b, e := strconv.ParseBool(v) - if e != nil { - panic(e) - } - return c.Unescaped(fmt.Sprintf("%v", b)) - } - return c.Unescaped("") -} - -// ToUpperCase uppercase -func (c *Common) ToUpperCase(name string) string { - var newName string - var toupper bool - var initialisms = []string{ - "ACL", "API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", - "HTTPS", "ID", "IP", "JSON", "LHS", "QPS", "RAM", "RHS", "RPC", "SLA", - "SMTP", "SQL", "SSH", "TCP", "TLS", "TTL", "UDP", "UI", "UID", "UUID", - "URI", "URL", "UTF8", "VM", "XML", "XMPP", "XSRF", "XSS", - } - sms, ext := funk.FindString(initialisms, func(sms string) bool { - return strings.ToUpper(name) == sms - }) - if ext { - return sms - } - for i, r := range name { - if i == 0 { - if fmt.Sprintf("%c", r) != "$" { - newName = newName + strings.ToUpper(fmt.Sprintf("%c", r)) - } else { - toupper = true - } - } else if fmt.Sprintf("%c", r) == "_" { - toupper = true - } else { - if toupper { - newName = newName + strings.ToUpper(fmt.Sprintf("%c", r)) - toupper = false - } else { - newName = newName + fmt.Sprintf("%c", r) - } - } - } - return newName -} - -// Title first word -func (c *Common) Title(str string) string { - return strings.Title(strings.ToLower(str)) -} - -// LcFirst first word -func (c *Common) LcFirst(str string) string { - for i, v := range str { - return string(unicode.ToLower(v)) + str[i+1:] - } - return "" -} - -// UcFirst first word -func (c *Common) UcFirst(str string) string { - for i, v := range str { - return string(unicode.ToUpper(v)) + str[i+1:] - } - return "" -} - -// Contains defined -func (c *Common) Contains(args []string, s string) bool { - for _, v := range args { - if v == s { - return true - } - } - return false -} - -// FormatString defined -func (c *Common) FormatString(args []string, segm string) template.HTML { - strs := []string{} - for _, v := range args { - strs = append(strs, fmt.Sprintf(`"%v"`, v)) - } - return template.HTML(strings.Join(strs, segm)) -} - -// APIPrefix version path -func (c *Common) APIPrefix(v string) string { - if v == "" { - return "" - } - vf, err := strconv.ParseFloat(v, 64) - vi := int(vf) - if err != nil { - panic(err) - } - return fmt.Sprintf("/v%v", vi) -} - -// APIPath api path -func (c *Common) APIPath(ctrName, apiName, apiPath string) string { - if apiPath == "" { - return "/" + strings.ReplaceAll(ctrName, "_", "/") + "/" + apiName - } - return apiPath -} - -// ToTitle title -func (c *Common) ToTitle(title string) string { - return strings.Title(title) -} - -// Ref defined model name -func (c *Common) Ref(m string) string { - if strings.HasPrefix(m, "$") || strings.HasPrefix(m, "[]$") || strings.HasPrefix(m, "[]*$") { - if strings.HasPrefix(m, "[]$") { - return fmt.Sprintf("[]model.%v", c.ToUpperCase(strings.ReplaceAll(m, "[]$", ""))) - } else if strings.HasPrefix(m, "[]*$") { - return fmt.Sprintf("[]*model.%v", c.ToUpperCase(strings.ReplaceAll(m, "[]*$", ""))) - } - return fmt.Sprintf("model.%v", c.ToUpperCase(m)) - } - return m -} - -// TypeWithPointer defined model name -func (c *Common) TypeWithPointer(m string) string { - if strings.Contains(m, "*") { - return m - } - splites := strings.Split(m, "[]") - if len(splites) == 1 { - return fmt.Sprintf("%v%v", "*", m) - } - return fmt.Sprintf("%v%v%v", "[]", "*", splites[1]) -} - -// PRef defined model name -func (c *Common) PRef(m string) string { - if strings.HasPrefix(m, "$") { - return fmt.Sprintf("%v", c.ToUpperCase(strings.ReplaceAll(m, "$", ""))) - } - return m -} - -// SRef defined model name -func (c *Common) SRef(m string) string { - if strings.HasPrefix(m, "$") || strings.HasPrefix(m, "[]$") || strings.HasPrefix(m, "[]*$") { - if strings.HasPrefix(m, "[]$") { - return fmt.Sprintf("[]%v", c.ToUpperCase(strings.ReplaceAll(m, "[]$", ""))) - } else if strings.HasPrefix(m, "[]*$") { - return fmt.Sprintf("[]*%v", c.ToUpperCase(strings.ReplaceAll(m, "[]*$", ""))) - } - return fmt.Sprintf("%v", c.ToUpperCase(m)) - } - return m -} - -// ORef defined model name -func (c *Common) ORef(m string) string { - return strings.ReplaceAll(c.Ref(m), "[]", "") -} - -// ISArray defined isarray -func (c *Common) ISArray(m string) bool { - return strings.HasPrefix(m, "[]") -} - -// TableName defined table -func (c *Common) TableName(app string, table string) string { - return fmt.Sprintf("%v", table) -} - -// SplitExtends extends model,bean -func (c *Common) SplitExtends(parent string) []string { - return funk.Map(strings.Split(parent, ","), func(p string) string { - return strings.ReplaceAll(c.Ref(p), "model.", "") - }).([]string) -} - -// TableNameOfType defined -func (c *Common) TableNameOfType(t string) string { - return strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(t, "[]", ""), "$", ""), "model.", "") -} - -// AutoIncr defined -func (c *Common) AutoIncr(tables []*Table, tableName string) (fields []string) { - for i := range tables { - if tables[i].Name == tableName { - for c := range tables[i].Columns { - if strings.Contains(tables[i].Columns[c].Xorm, "pk") && !strings.Contains(tables[i].Columns[c].Xorm, "autoincr") { - fields = append(fields, tables[i].Columns[c].ToUpperCase(tables[i].Columns[c].Name)) - } - } - } - } - return fields -} diff --git a/cmd/dolphin/schema/schema.go b/cmd/dolphin/schema/schema.go index 26a05051..76daa747 100644 --- a/cmd/dolphin/schema/schema.go +++ b/cmd/dolphin/schema/schema.go @@ -4,121 +4,416 @@ package schema -// Success struct -type Success struct { - Common - Type string +import ( + "fmt" + "html/template" + "strconv" + "strings" + "unicode" + + "github.com/thoas/go-funk" +) + +type ( + // Common defined TODO + Common struct { + Name string `validate:"required"` + Desc string `validate:"required"` + Path string + } + // Success defined TODO + Success struct { + Common + Type string + } + // Failure defined TODO + Failure struct { + Common + Type string + } + // Return defined TODO + Return struct { + Common + Success *Success + Failure *Failure + } + // Param defined TODO + Param struct { + Common + Type string + Value string + } + // API defined TODO + API struct { + Common + Roles []string + Auth []string + Version string + Path string + Func string + Table string + Method string + Cache uint64 + Params []*Param + Return *Return + } + // Controller defined TODO + Controller struct { + Common + APIS []*API + Prefix string + } + + // Service defined TODO + Service struct { + Common + RPCS []*RPC + } + + // RPC defined TODO + RPC struct { + Common + Request *Request + Reply *Reply + } + + // Request defined TODO + Request struct { + Common + Type string + } + + // Reply defined TODO + Reply struct { + Common + Type string + } + + // Prop defined TODO + Prop struct { + Common + Type string + JSON string + Form string + Example string + } + + // Bean defined TODO + Bean struct { + Common + Packages string + Props []*Prop + Extends string + } + + // Column defined TODO + Column struct { + Common + Type string + Xorm string + JSON string + Form string + Example string + } + + // Table defined TODO + Table struct { + Common + Bind string + Packages string + Columns []*Column + Extends string + } + + // Application defined TODO + Application struct { + Common + PackageName string `validate:"required"` + Controllers []*Controller + Services []*Service + Beans []*Bean + Tables []*Table + } +) + +// Import packages +func (c *Common) Import(pkgs ...string) template.HTML { + pkg := strings.Join(pkgs, ",") + if len(pkg) > 0 { + packages := strings.Split(pkg, ",") + for i, v := range packages { + packages[i] = fmt.Sprintf(` "%v"`, v) + } + tmpl := "import (\n%s\n)" + return c.Unescaped(fmt.Sprintf(tmpl, strings.Join(packages, "\n"))) + } + return c.Unescaped("") +} + +// Unescaped unescaped +func (c *Common) Unescaped(x string) template.HTML { + return template.HTML(x) +} + +// SQLInsertOne insert one +func (c *Common) SQLInsertOne(table Table, name string) string { + names := strings.Join(funk.Map(table.Columns, func(col *Column) string { + return fmt.Sprintf("`%v`", col.Name) + }).([]string), ",") + values := strings.Join(funk.Map(table.Columns, func(col *Column) string { + return fmt.Sprintf("?%v", col.Name) + }).([]string), ",") + return `insert into ` + name + ` + (` + names + `) + values + (` + values + `)` +} + +// SQLSelectOne select one +func (c *Common) SQLSelectOne(table Table, name string) string { + names := strings.Join(funk.Map(table.Columns, func(col *Column) string { + return fmt.Sprintf("`%v`", col.Name) + }).([]string), ",") + return `select ` + names + ` from ` + name + ` where id =?id` +} + +// SQLDelOne remove one +func (c *Common) SQLDelOne(table Table, name string) string { + return `delete from ` + name + ` where id =?id` +} + +// SQLSelectAll select one +func (c *Common) SQLSelectAll(table Table, name string) string { + names := strings.Join(funk.Map(table.Columns, func(col *Column) string { + return fmt.Sprintf("`%v`", col.Name) + }).([]string), ",") + return `select ` + names + ` from ` + name +} + +// SQLUpdateOne update one +func (c *Common) SQLUpdateOne(table Table, name string) string { + names := strings.Join(funk.Map(table.Columns, func(col *Column) string { + return fmt.Sprintf("`%v`=?%v", col.Name, col.Name) + }).([]string), ",") + return `update ` + name + ` set ` + names + ` + where id =?id` +} + +// ToUpper toUpper +func (c *Common) ToUpper(name string) string { + return strings.ToUpper(name) +} + +// ToTypeValue value +func (c *Common) ToTypeValue(t string, v string) template.HTML { + if strings.TrimSpace(v) == "" { + return c.Unescaped("") + } + switch t { + case "int": + i, e := strconv.ParseInt(v, 10, 64) + if e != nil { + panic(e) + } + return c.Unescaped(fmt.Sprintf("%v", i)) + case "string": + return c.Unescaped(fmt.Sprintf(`"%v"`, v)) + case "bool": + b, e := strconv.ParseBool(v) + if e != nil { + panic(e) + } + return c.Unescaped(fmt.Sprintf("%v", b)) + } + return c.Unescaped("") +} + +// ToUpperCase uppercase +func (c *Common) ToUpperCase(name string) string { + var newName string + var toupper bool + var initialisms = []string{ + "ACL", "API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", + "HTTPS", "ID", "IP", "JSON", "LHS", "QPS", "RAM", "RHS", "RPC", "SLA", + "SMTP", "SQL", "SSH", "TCP", "TLS", "TTL", "UDP", "UI", "UID", "UUID", + "URI", "URL", "UTF8", "VM", "XML", "XMPP", "XSRF", "XSS", + } + sms, ext := funk.FindString(initialisms, func(sms string) bool { + return strings.ToUpper(name) == sms + }) + if ext { + return sms + } + for i, r := range name { + if i == 0 { + if fmt.Sprintf("%c", r) != "$" { + newName = newName + strings.ToUpper(fmt.Sprintf("%c", r)) + } else { + toupper = true + } + } else if fmt.Sprintf("%c", r) == "_" { + toupper = true + } else { + if toupper { + newName = newName + strings.ToUpper(fmt.Sprintf("%c", r)) + toupper = false + } else { + newName = newName + fmt.Sprintf("%c", r) + } + } + } + return newName +} + +// Title first word +func (c *Common) Title(str string) string { + return strings.Title(strings.ToLower(str)) +} + +// LcFirst first word +func (c *Common) LcFirst(str string) string { + for i, v := range str { + return string(unicode.ToLower(v)) + str[i+1:] + } + return "" +} + +// UcFirst first word +func (c *Common) UcFirst(str string) string { + for i, v := range str { + return string(unicode.ToUpper(v)) + str[i+1:] + } + return "" +} + +// Contains defined +func (c *Common) Contains(args []string, s string) bool { + for _, v := range args { + if v == s { + return true + } + } + return false +} + +// FormatString defined +func (c *Common) FormatString(args []string, segm string) template.HTML { + strs := []string{} + for _, v := range args { + strs = append(strs, fmt.Sprintf(`"%v"`, v)) + } + return template.HTML(strings.Join(strs, segm)) +} + +// APIPrefix version path +func (c *Common) APIPrefix(v string) string { + if v == "" { + return "" + } + vf, err := strconv.ParseFloat(v, 64) + vi := int(vf) + if err != nil { + panic(err) + } + return fmt.Sprintf("/v%v", vi) +} + +// APIPath api path +func (c *Common) APIPath(ctrName, apiName, apiPath string) string { + if apiPath == "" { + return "/" + strings.ReplaceAll(ctrName, "_", "/") + "/" + apiName + } + return apiPath +} + +// ToTitle title +func (c *Common) ToTitle(title string) string { + return strings.Title(title) +} + +// Ref defined model name +func (c *Common) Ref(m string) string { + if strings.HasPrefix(m, "$") || strings.HasPrefix(m, "[]$") || strings.HasPrefix(m, "[]*$") { + if strings.HasPrefix(m, "[]$") { + return fmt.Sprintf("[]model.%v", c.ToUpperCase(strings.ReplaceAll(m, "[]$", ""))) + } else if strings.HasPrefix(m, "[]*$") { + return fmt.Sprintf("[]*model.%v", c.ToUpperCase(strings.ReplaceAll(m, "[]*$", ""))) + } + return fmt.Sprintf("model.%v", c.ToUpperCase(m)) + } + return m +} + +// TypeWithPointer defined model name +func (c *Common) TypeWithPointer(m string) string { + if strings.Contains(m, "*") { + return m + } + splites := strings.Split(m, "[]") + if len(splites) == 1 { + return fmt.Sprintf("%v%v", "*", m) + } + return fmt.Sprintf("%v%v%v", "[]", "*", splites[1]) +} + +// PRef defined model name +func (c *Common) PRef(m string) string { + if strings.HasPrefix(m, "$") { + return fmt.Sprintf("%v", c.ToUpperCase(strings.ReplaceAll(m, "$", ""))) + } + return m +} + +// SRef defined model name +func (c *Common) SRef(m string) string { + if strings.HasPrefix(m, "$") || strings.HasPrefix(m, "[]$") || strings.HasPrefix(m, "[]*$") { + if strings.HasPrefix(m, "[]$") { + return fmt.Sprintf("[]%v", c.ToUpperCase(strings.ReplaceAll(m, "[]$", ""))) + } else if strings.HasPrefix(m, "[]*$") { + return fmt.Sprintf("[]*%v", c.ToUpperCase(strings.ReplaceAll(m, "[]*$", ""))) + } + return fmt.Sprintf("%v", c.ToUpperCase(m)) + } + return m +} + +// ORef defined model name +func (c *Common) ORef(m string) string { + return strings.ReplaceAll(c.Ref(m), "[]", "") +} + +// ISArray defined isarray +func (c *Common) ISArray(m string) bool { + return strings.HasPrefix(m, "[]") +} + +// TableName defined table +func (c *Common) TableName(app string, table string) string { + return fmt.Sprintf("%v", table) +} + +// SplitExtends extends model,bean +func (c *Common) SplitExtends(parent string) []string { + return funk.Map(strings.Split(parent, ","), func(p string) string { + return strings.ReplaceAll(c.Ref(p), "model.", "") + }).([]string) } -// Failure struct -type Failure struct { - Common - Type string +// TableNameOfType defined +func (c *Common) TableNameOfType(t string) string { + return strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(t, "[]", ""), "$", ""), "model.", "") } -// Return struct -type Return struct { - Common - Success *Success - Failure *Failure -} - -// Param struct -type Param struct { - Common - Type string - Value string -} - -// API struct -type API struct { - Common - Roles []string - Auth []string - Version string - Path string - Func string - Table string - Method string - Cache uint64 - Params []*Param - Return *Return -} - -// Controller deifned -type Controller struct { - Common - APIS []*API - Prefix string -} - -// Service defined -type Service struct { - Common - RPCS []*RPC -} - -// RPC defined -type RPC struct { - Common - Request *Request - Reply *Reply -} - -// Request defined -type Request struct { - Common - Type string -} - -// Reply defined -type Reply struct { - Common - Type string -} - -// Prop struct -type Prop struct { - Common - Type string - JSON string - Form string - Example string -} - -// Bean struct -type Bean struct { - Common - Packages string - Props []*Prop - Extends string -} - -// Column struct -type Column struct { - Common - Type string - Xorm string - JSON string - Form string - Example string -} - -// Table struct -type Table struct { - Common - Bind string - Packages string - Columns []*Column - Extends string -} - -// Application struct -type Application struct { - Common - PackageName string `validate:"required"` - Controllers []*Controller - Services []*Service - Beans []*Bean - Tables []*Table +// AutoIncr defined +func (c *Common) AutoIncr(tables []*Table, tableName string) (fields []string) { + for i := range tables { + if tables[i].Name == tableName { + for c := range tables[i].Columns { + if strings.Contains(tables[i].Columns[c].Xorm, "pk") && !strings.Contains(tables[i].Columns[c].Xorm, "autoincr") { + fields = append(fields, tables[i].Columns[c].ToUpperCase(tables[i].Columns[c].Name)) + } + } + } + } + return fields } diff --git a/cmd/dolphin/utils/clone.go b/cmd/dolphin/utils/clone.go deleted file mode 100644 index 6b454f49..00000000 --- a/cmd/dolphin/utils/clone.go +++ /dev/null @@ -1,90 +0,0 @@ -package utils - -import ( - "reflect" - "time" -) - -// Interface defined -type Interface interface { - DeepCopy() interface{} -} - -// Copy defined -func Copy(src interface{}) interface{} { - if src == nil { - return nil - } - original := reflect.ValueOf(src) - cpy := reflect.New(original.Type()).Elem() - copyRecursive(original, cpy) - - return cpy.Interface() -} - -func copyRecursive(src, dst reflect.Value) { - if src.CanInterface() { - if copier, ok := src.Interface().(Interface); ok { - dst.Set(reflect.ValueOf(copier.DeepCopy())) - return - } - } - - switch src.Kind() { - case reflect.Ptr: - originalValue := src.Elem() - - if !originalValue.IsValid() { - return - } - dst.Set(reflect.New(originalValue.Type())) - copyRecursive(originalValue, dst.Elem()) - - case reflect.Interface: - if src.IsNil() { - return - } - originalValue := src.Elem() - copyValue := reflect.New(originalValue.Type()).Elem() - copyRecursive(originalValue, copyValue) - dst.Set(copyValue) - - case reflect.Struct: - t, ok := src.Interface().(time.Time) - if ok { - dst.Set(reflect.ValueOf(t)) - return - } - for i := 0; i < src.NumField(); i++ { - if src.Type().Field(i).PkgPath != "" { - continue - } - copyRecursive(src.Field(i), dst.Field(i)) - } - - case reflect.Slice: - if src.IsNil() { - return - } - dst.Set(reflect.MakeSlice(src.Type(), src.Len(), src.Cap())) - for i := 0; i < src.Len(); i++ { - copyRecursive(src.Index(i), dst.Index(i)) - } - - case reflect.Map: - if src.IsNil() { - return - } - dst.Set(reflect.MakeMap(src.Type())) - for _, key := range src.MapKeys() { - originalValue := src.MapIndex(key) - copyValue := reflect.New(originalValue.Type()).Elem() - copyRecursive(originalValue, copyValue) - copyKey := Copy(key.Interface()) - dst.SetMapIndex(reflect.ValueOf(copyKey), copyValue) - } - - default: - dst.Set(src) - } -} diff --git a/cmd/dolphin/utils/files.go b/cmd/dolphin/utils/files.go deleted file mode 100644 index dc1d560c..00000000 --- a/cmd/dolphin/utils/files.go +++ /dev/null @@ -1,10 +0,0 @@ -package utils - -import "path/filepath" - -// FileNameTrimSuffix defined -func FileNameTrimSuffix(fp string) string { - extension, filename := filepath.Ext(fp), filepath.Base(fp) - filename = filename[0 : len(filename)-len(extension)] - return filename -} diff --git a/cmd/dolphin/utils/utils.go b/cmd/dolphin/utils/utils.go index 8a610c15..57f5ac79 100644 --- a/cmd/dolphin/utils/utils.go +++ b/cmd/dolphin/utils/utils.go @@ -8,6 +8,7 @@ import ( "path/filepath" "reflect" "strings" + "time" "github.com/go-errors/errors" @@ -20,7 +21,92 @@ import ( var timeFormat = "2006/01/02 15:04:05" -// ISBlank defined +// DeepCopyInterface defined TODO +type DeepCopyInterface interface { + DeepCopy() interface{} +} + +// Copy defined TODO +func Copy(src interface{}) interface{} { + if src == nil { + return nil + } + original := reflect.ValueOf(src) + cpy := reflect.New(original.Type()).Elem() + copyRecursive(original, cpy) + + return cpy.Interface() +} + +// copyRecursive defined TODO +func copyRecursive(src, dst reflect.Value) { + if src.CanInterface() { + if copier, ok := src.Interface().(DeepCopyInterface); ok { + dst.Set(reflect.ValueOf(copier.DeepCopy())) + return + } + } + + switch src.Kind() { + case reflect.Ptr: + originalValue := src.Elem() + + if !originalValue.IsValid() { + return + } + dst.Set(reflect.New(originalValue.Type())) + copyRecursive(originalValue, dst.Elem()) + + case reflect.Interface: + if src.IsNil() { + return + } + originalValue := src.Elem() + copyValue := reflect.New(originalValue.Type()).Elem() + copyRecursive(originalValue, copyValue) + dst.Set(copyValue) + + case reflect.Struct: + t, ok := src.Interface().(time.Time) + if ok { + dst.Set(reflect.ValueOf(t)) + return + } + for i := 0; i < src.NumField(); i++ { + if src.Type().Field(i).PkgPath != "" { + continue + } + copyRecursive(src.Field(i), dst.Field(i)) + } + + case reflect.Slice: + if src.IsNil() { + return + } + dst.Set(reflect.MakeSlice(src.Type(), src.Len(), src.Cap())) + for i := 0; i < src.Len(); i++ { + copyRecursive(src.Index(i), dst.Index(i)) + } + + case reflect.Map: + if src.IsNil() { + return + } + dst.Set(reflect.MakeMap(src.Type())) + for _, key := range src.MapKeys() { + originalValue := src.MapIndex(key) + copyValue := reflect.New(originalValue.Type()).Elem() + copyRecursive(originalValue, copyValue) + copyKey := Copy(key.Interface()) + dst.SetMapIndex(reflect.ValueOf(copyKey), copyValue) + } + + default: + dst.Set(src) + } +} + +// ISBlank defined TODO func ISBlank(value reflect.Value) bool { switch value.Kind() { case reflect.String: @@ -39,7 +125,7 @@ func ISBlank(value reflect.Value) bool { return reflect.DeepEqual(value.Interface(), reflect.Zero(value.Type()).Interface()) } -// ViperSetDefault defined +// ViperSetDefault defined TODO func ViperSetDefault(key string, value interface{}, standby ...interface{}) { isBlank := ISBlank(reflect.ValueOf(value)) if isBlank { @@ -48,7 +134,7 @@ func ViperSetDefault(key string, value interface{}, standby ...interface{}) { viper.SetDefault(key, value) } -// WalkFileInDirWithSuffix defined +// WalkFileInDirWithSuffix defined TODO func WalkFileInDirWithSuffix(wd string, suffix string) ([]string, error) { var files []string if err := filepath.Walk(wd, func(path string, info os.FileInfo, err error) error { @@ -62,7 +148,7 @@ func WalkFileInDirWithSuffix(wd string, suffix string) ([]string, error) { return files, nil } -// SearchFileInDirWithSuffix defined +// SearchFileInDirWithSuffix defined TODO func SearchFileInDirWithSuffix(wd string, suffix string, cb func(string) bool) string { var file string filepath.Walk(wd, func(path string, info os.FileInfo, err error) error { @@ -78,7 +164,7 @@ func SearchFileInDirWithSuffix(wd string, suffix string, cb func(string) bool) s return file } -// RemoveFileWithSuffix defined +// RemoveFileWithSuffix defined TODO func RemoveFileWithSuffix(wd string, suffix string) { files, _ := WalkFileInDirWithSuffix(wd, suffix) funk.ForEach(files, func(file string) { @@ -86,7 +172,7 @@ func RemoveFileWithSuffix(wd string, suffix string) { }) } -// SetFormatter defined +// SetFormatter defined TODO func SetFormatter(isTerminal bool) { if !isTerminal { logrus.SetFormatter(&logrus.JSONFormatter{ @@ -100,14 +186,14 @@ func SetFormatter(isTerminal bool) { } } -// SetLevel defined +// SetLevel defined TODO func SetLevel(cmd *cobra.Command) { if verbose, _ := cmd.Flags().GetBool("verbose"); verbose { logrus.SetLevel(logrus.DebugLevel) } } -// OpenFile defiend +// OpenFile defiend TODO func OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) { if err := os.MkdirAll(path.Dir(name), os.ModePerm); err != nil { return nil, err @@ -115,7 +201,7 @@ func OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) { return os.OpenFile(name, flag, perm) } -// NetWorkStatus defined +// NetWorkStatus defined TODO func NetWorkStatus() bool { if err := exec.Command("ping", "baidu.com", "-c", "1", "-W", "5").Run(); err != nil { return false @@ -123,7 +209,7 @@ func NetWorkStatus() bool { return true } -// InstallPackages defined +// InstallPackages defined TODO func InstallPackages(pkgs ...string) error { for i := range pkgs { if err := exec.Command("go", "get", pkgs[i]).Run(); err != nil && err != exec.ErrNotFound { @@ -133,6 +219,7 @@ func InstallPackages(pkgs ...string) error { return nil } +// HasBin defined TODO func HasBin(bins ...string) bool { for i := range bins { if err := exec.Command(bins[i]).Run(); err == exec.ErrNotFound { @@ -142,7 +229,7 @@ func HasBin(bins ...string) bool { return true } -// EnsureLeft defined return left +// EnsureLeft defined TODO func EnsureLeft(left interface{}, err error) interface{} { if err != nil { panic(fmt.Errorf("%v", string(errors.Wrap(err, 3).Stack()))) @@ -150,7 +237,7 @@ func EnsureLeft(left interface{}, err error) interface{} { return left } -// EnsureRight defined return right +// EnsureRight defined TODO func EnsureRight(err error, right interface{}) interface{} { if err != nil { panic(fmt.Errorf("%v", string(errors.Wrap(err, 3).Stack()))) @@ -158,9 +245,16 @@ func EnsureRight(err error, right interface{}) interface{} { return right } -// Ensure defined +// Ensure defined TODO func Ensure(err error) { if err != nil { panic(fmt.Errorf("%v", string(errors.Wrap(err, 3).Stack()))) } } + +// FileNameTrimSuffix defined TODO +func FileNameTrimSuffix(fp string) string { + extension, filename := filepath.Ext(fp), filepath.Base(fp) + filename = filename[0 : len(filename)-len(extension)] + return filename +} diff --git "a/docs/\345\277\253\351\200\237\345\205\245\351\227\250.md" "b/docs/\345\277\253\351\200\237\345\205\245\351\227\250.md" index e1dd4a48..4ebb7a28 100644 --- "a/docs/\345\277\253\351\200\237\345\205\245\351\227\250.md" +++ "b/docs/\345\277\253\351\200\237\345\205\245\351\227\250.md" @@ -9,7 +9,7 @@ $ go get -u github.com/2637309949/dolphin/cmd/dolphin - 使用dolphin命令创建项目 ```sh -$ mkdir helloword && cd helloword && dolphin init && dolphin build && go run main.go +$ dolphin new hello && cd hello && dolphin build && go run main.go ``` 输出: @@ -18,11 +18,16 @@ time="2020/06/13 11:55:58" level=info msg="grpc listen on port:9081" time="2020/06/13 11:55:58" level=info msg="http listen on port:8082" ``` +-- 根据需要创建对应的xml, 也可以使用more指令一键生成table, controller + +```sh + dolphin more wechat_article +``` + ### 目录结构 > 准目录结构如下面所示, 这是简化且推荐的目录结构, 当需要使用dolphin管理大型项目时可以复用这个结构去创建更多的子项目. - ```sh . ├── app @@ -48,6 +53,12 @@ time="2020/06/13 11:55:58" level=info msg="http listen on port:8082" │ ├── article.auto.go │ └── article_info.auto.go ├── README.md + ├── rpc + │ ├── article.cli.go + │ ├── article.go + │ └── proto + │ ├── article.pb.go + │ └── article.proto ├── script │ ├── apis │ │ ├── article.js @@ -65,14 +76,23 @@ time="2020/06/13 11:55:58" level=info msg="http listen on port:8082" │ └── web │ ├── affirm.html │ └── login.html + ├── svc + │ ├── cache.go + │ ├── db.go + │ ├── http.go + │ └── svc.go ├── util │ └── common.go - └── xml - ├── application.xml - ├── bean - │ └── article_info.xml - ├── controller - │ └── article.xml - └── table - └── article.xml + ├── x_hello_test.go + ├── xml + │ ├── application.xml + │ ├── bean + │ │ └── article_info.xml + │ ├── controller + │ │ └── article.xml + │ ├── rpc + │ │ └── article.xml + │ └── table + │ └── article.xml + └── x_test.go ``` \ No newline at end of file