cli.go 1.9 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. if len(src) == 0 {
  18. return errors.New("missing -src")
  19. }
  20. if len(out) == 0 {
  21. return errors.New("missing -dir")
  22. }
  23. namingStyle, valid := generator.IsNamingValid(style)
  24. if !valid {
  25. return fmt.Errorf("unexpected naming style %s", style)
  26. }
  27. g := generator.NewDefaultRpcGenerator(namingStyle)
  28. return g.Generate(src, out, protoImportPath)
  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. name := c.Args().First()
  34. ext := filepath.Ext(name)
  35. if len(ext) > 0 {
  36. return fmt.Errorf("unexpected ext: %s", ext)
  37. }
  38. style := c.String("style")
  39. namingStyle, valid := generator.IsNamingValid(style)
  40. if !valid {
  41. return fmt.Errorf("expected naming style [lower|camel|snake], but found %s", style)
  42. }
  43. protoName := name + ".proto"
  44. filename := filepath.Join(".", name, protoName)
  45. src, err := filepath.Abs(filename)
  46. if err != nil {
  47. return err
  48. }
  49. err = generator.ProtoTmpl(src)
  50. if err != nil {
  51. return err
  52. }
  53. g := generator.NewDefaultRpcGenerator(namingStyle)
  54. return g.Generate(src, filepath.Dir(src), nil)
  55. }
  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. }