cli.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. if len(src) == 0 {
  18. return errors.New("missing -src")
  19. }
  20. if len(out) == 0 {
  21. return errors.New("missing -dir")
  22. }
  23. g, err := generator.NewDefaultRpcGenerator(style)
  24. if err != nil {
  25. return err
  26. }
  27. return g.Generate(src, out, protoImportPath)
  28. }
  29. // RpcNew is to generate rpc greet service, this greet service can speed
  30. // up your understanding of the zrpc service structure
  31. func RpcNew(c *cli.Context) error {
  32. rpcname := c.Args().First()
  33. ext := filepath.Ext(rpcname)
  34. if len(ext) > 0 {
  35. return fmt.Errorf("unexpected ext: %s", ext)
  36. }
  37. style := c.String("style")
  38. protoName := rpcname + ".proto"
  39. filename := filepath.Join(".", rpcname, protoName)
  40. src, err := filepath.Abs(filename)
  41. if err != nil {
  42. return err
  43. }
  44. err = generator.ProtoTmpl(src)
  45. if err != nil {
  46. return err
  47. }
  48. g, err := generator.NewDefaultRpcGenerator(style)
  49. if err != nil {
  50. return err
  51. }
  52. return g.Generate(src, filepath.Dir(src), nil)
  53. }
  54. func RpcTemplate(c *cli.Context) error {
  55. protoFile := c.String("o")
  56. if len(protoFile) == 0 {
  57. return errors.New("missing -o")
  58. }
  59. return generator.ProtoTmpl(protoFile)
  60. }