github.com/yoogoc/kratos-scaffold@v0.0.0-20240402032722-a538b3c18955/project_generator/cmd.go (about) 1 package project_generator 2 3 import ( 4 "bytes" 5 "fmt" 6 "os" 7 "path" 8 "strings" 9 "text/template" 10 11 "github.com/yoogoc/kratos-scaffold/pkg/util" 12 ) 13 14 func genCmd(name string, appPath string, isSubMono, isBff bool) error { 15 // mkdir cmd/server. gen main.go, wire.go, wire_gen.go 16 mainPath := path.Join(appPath, "cmd") 17 if err := os.MkdirAll(mainPath, 0o700); err != nil { 18 return err 19 } 20 appPkgPath := name 21 serviceName := strings.ReplaceAll(name, "/", ".") 22 if isSubMono { 23 appPkgPath = path.Join(util.ModName(), "app", name) 24 serviceName = strings.ReplaceAll(path.Join(util.ModName(), name), "/", ".") 25 } 26 cmdTmpl := CmdTmpl{ 27 AppPkgPath: appPkgPath, 28 ServiceName: serviceName, 29 OutPath: mainPath, 30 IsBff: isBff, 31 } 32 if err := cmdTmpl.Generate(); err != nil { 33 return err 34 } 35 return nil 36 } 37 38 type CmdTmpl struct { 39 AppPkgPath string 40 ServiceName string 41 OutPath string 42 IsBff bool 43 } 44 45 func (ct CmdTmpl) Generate() error { 46 fmt.Println("generate cmd/server/main.go ...") 47 mainBuf := new(bytes.Buffer) 48 tmpl, err := template.New("mainTmpl").Parse(cmdMainTmpl) 49 if err != nil { 50 return err 51 } 52 if err := tmpl.Execute(mainBuf, ct); err != nil { 53 return err 54 } 55 if err := util.WhiteGo(path.Join(ct.OutPath, "main.go"), mainBuf.Bytes()); err != nil { 56 return err 57 } 58 59 fmt.Println("generate cmd/server/server.go ...") 60 serverBuf := new(bytes.Buffer) 61 serverTmpl, err := template.New("serverTmpl").Parse(cmdServerTmpl) 62 if err != nil { 63 return err 64 } 65 if err := serverTmpl.Execute(serverBuf, ct); err != nil { 66 return err 67 } 68 if err := util.WhiteGo(path.Join(ct.OutPath, "server.go"), serverBuf.Bytes()); err != nil { 69 return err 70 } 71 72 if !ct.IsBff { 73 fmt.Println("generate cmd/server/migration.go ...") 74 migrationBuf := new(bytes.Buffer) 75 migrationTmpl, err := template.New("migrationTmpl").Parse(cmdMigrationTmpl) 76 if err != nil { 77 return err 78 } 79 if err := migrationTmpl.Execute(migrationBuf, ct); err != nil { 80 return err 81 } 82 if err := util.WhiteGo(path.Join(ct.OutPath, "migration.go"), migrationBuf.Bytes()); err != nil { 83 return err 84 } 85 } 86 87 fmt.Println("generate cmd/server/wire.go ...") 88 wireBuf := new(bytes.Buffer) 89 wireTmpl, err := template.New("wireTmpl").Parse(cmdWireTmpl) 90 if err != nil { 91 return err 92 } 93 if err := wireTmpl.Execute(wireBuf, ct); err != nil { 94 return err 95 } 96 if err := util.WhiteGo(path.Join(ct.OutPath, "wire.go"), wireBuf.Bytes()); err != nil { 97 return err 98 } 99 100 fmt.Println("skip wire generate") 101 102 return nil 103 }