cli.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package cli
  2. import (
  3. "errors"
  4. "fmt"
  5. "path/filepath"
  6. "github.com/urfave/cli"
  7. "github.com/zeromicro/go-zero/tools/goctl/rpc/generator"
  8. "github.com/zeromicro/go-zero/tools/goctl/util"
  9. "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
  10. )
  11. // RPCNew is to generate rpc greet service, this greet service can speed
  12. // up your understanding of the zrpc service structure
  13. func RPCNew(c *cli.Context) error {
  14. if c.NArg() == 0 {
  15. cli.ShowCommandHelpAndExit(c, "new", 1)
  16. }
  17. rpcname := c.Args().First()
  18. ext := filepath.Ext(rpcname)
  19. if len(ext) > 0 {
  20. return fmt.Errorf("unexpected ext: %s", ext)
  21. }
  22. style := c.String("style")
  23. home := c.String("home")
  24. remote := c.String("remote")
  25. branch := c.String("branch")
  26. verbose := c.Bool("verbose")
  27. if len(remote) > 0 {
  28. repo, _ := util.CloneIntoGitHome(remote, branch)
  29. if len(repo) > 0 {
  30. home = repo
  31. }
  32. }
  33. if len(home) > 0 {
  34. pathx.RegisterGoctlHome(home)
  35. }
  36. protoName := rpcname + ".proto"
  37. filename := filepath.Join(".", rpcname, protoName)
  38. src, err := filepath.Abs(filename)
  39. if err != nil {
  40. return err
  41. }
  42. err = generator.ProtoTmpl(src)
  43. if err != nil {
  44. return err
  45. }
  46. var ctx generator.ZRpcContext
  47. ctx.Src = src
  48. ctx.GoOutput = filepath.Dir(src)
  49. ctx.GrpcOutput = filepath.Dir(src)
  50. ctx.IsGooglePlugin = true
  51. ctx.Output = filepath.Dir(src)
  52. ctx.ProtocCmd = fmt.Sprintf("protoc -I=%s %s --go_out=%s --go-grpc_out=%s", filepath.Dir(src), filepath.Base(src), filepath.Dir(src), filepath.Dir(src))
  53. g := generator.NewGenerator(style, verbose)
  54. return g.Generate(&ctx)
  55. }
  56. // RPCTemplate is the entry for generate rpc template
  57. func RPCTemplate(c *cli.Context) error {
  58. if c.NumFlags() == 0 {
  59. cli.ShowCommandHelpAndExit(c, "template", 1)
  60. }
  61. protoFile := c.String("o")
  62. home := c.String("home")
  63. remote := c.String("remote")
  64. branch := c.String("branch")
  65. if len(remote) > 0 {
  66. repo, _ := util.CloneIntoGitHome(remote, branch)
  67. if len(repo) > 0 {
  68. home = repo
  69. }
  70. }
  71. if len(home) > 0 {
  72. pathx.RegisterGoctlHome(home)
  73. }
  74. if len(protoFile) == 0 {
  75. return errors.New("missing -o")
  76. }
  77. return generator.ProtoTmpl(protoFile)
  78. }