cli.go 1.8 KB

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