cli.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. rpcname := c.Args().First()
  15. ext := filepath.Ext(rpcname)
  16. if len(ext) > 0 {
  17. return fmt.Errorf("unexpected ext: %s", ext)
  18. }
  19. style := c.String("style")
  20. home := c.String("home")
  21. remote := c.String("remote")
  22. branch := c.String("branch")
  23. if len(remote) > 0 {
  24. repo, _ := util.CloneIntoGitHome(remote, branch)
  25. if len(repo) > 0 {
  26. home = repo
  27. }
  28. }
  29. if len(home) > 0 {
  30. pathx.RegisterGoctlHome(home)
  31. }
  32. protoName := rpcname + ".proto"
  33. filename := filepath.Join(".", rpcname, protoName)
  34. src, err := filepath.Abs(filename)
  35. if err != nil {
  36. return err
  37. }
  38. err = generator.ProtoTmpl(src)
  39. if err != nil {
  40. return err
  41. }
  42. var ctx generator.ZRpcContext
  43. ctx.Src = src
  44. ctx.GoOutput = filepath.Dir(src)
  45. ctx.GrpcOutput = filepath.Dir(src)
  46. ctx.IsGooglePlugin = true
  47. ctx.Output = filepath.Dir(src)
  48. 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))
  49. g := generator.NewGenerator(style)
  50. return g.Generate(&ctx)
  51. }
  52. // RPCTemplate is the entry for generate rpc template
  53. func RPCTemplate(c *cli.Context) error {
  54. protoFile := c.String("o")
  55. home := c.String("home")
  56. remote := c.String("remote")
  57. branch := c.String("branch")
  58. if len(remote) > 0 {
  59. repo, _ := util.CloneIntoGitHome(remote, branch)
  60. if len(repo) > 0 {
  61. home = repo
  62. }
  63. }
  64. if len(home) > 0 {
  65. pathx.RegisterGoctlHome(home)
  66. }
  67. if len(protoFile) == 0 {
  68. return errors.New("missing -o")
  69. }
  70. return generator.ProtoTmpl(protoFile)
  71. }