cli.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package cli
  2. import (
  3. "errors"
  4. "fmt"
  5. "path/filepath"
  6. "github.com/tal-tech/go-zero/tools/goctl/rpc/generator"
  7. "github.com/tal-tech/go-zero/tools/goctl/util"
  8. "github.com/urfave/cli"
  9. )
  10. // RPC is to generate rpc service code from a proto file by specifying a proto file using flag src,
  11. // you can specify a target folder for code generation, when the proto file has import, you can specify
  12. // the import search directory through the proto_path command, for specific usage, please refer to protoc -h
  13. func RPC(c *cli.Context) error {
  14. src := c.String("src")
  15. out := c.String("dir")
  16. style := c.String("style")
  17. protoImportPath := c.StringSlice("proto_path")
  18. goOptions := c.StringSlice("go_opt")
  19. home := c.String("home")
  20. if len(home) > 0 {
  21. util.RegisterGoctlHome(home)
  22. }
  23. if len(src) == 0 {
  24. return errors.New("missing -src")
  25. }
  26. if len(out) == 0 {
  27. return errors.New("missing -dir")
  28. }
  29. g, err := generator.NewDefaultRPCGenerator(style)
  30. if err != nil {
  31. return err
  32. }
  33. return g.Generate(src, out, protoImportPath, goOptions...)
  34. }
  35. // RPCNew is to generate rpc greet service, this greet service can speed
  36. // up your understanding of the zrpc service structure
  37. func RPCNew(c *cli.Context) error {
  38. rpcname := c.Args().First()
  39. ext := filepath.Ext(rpcname)
  40. if len(ext) > 0 {
  41. return fmt.Errorf("unexpected ext: %s", ext)
  42. }
  43. style := c.String("style")
  44. home := c.String("home")
  45. if len(home) > 0 {
  46. util.RegisterGoctlHome(home)
  47. }
  48. protoName := rpcname + ".proto"
  49. filename := filepath.Join(".", rpcname, protoName)
  50. src, err := filepath.Abs(filename)
  51. if err != nil {
  52. return err
  53. }
  54. err = generator.ProtoTmpl(src)
  55. if err != nil {
  56. return err
  57. }
  58. g, err := generator.NewDefaultRPCGenerator(style)
  59. if err != nil {
  60. return err
  61. }
  62. return g.Generate(src, filepath.Dir(src), nil)
  63. }
  64. // RPCTemplate is the entry for generate rpc template
  65. func RPCTemplate(c *cli.Context) error {
  66. protoFile := c.String("o")
  67. home := c.String("home")
  68. if len(home) > 0 {
  69. util.RegisterGoctlHome(home)
  70. }
  71. if len(protoFile) == 0 {
  72. return errors.New("missing -o")
  73. }
  74. return generator.ProtoTmpl(protoFile)
  75. }