cli.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package cli
  2. import (
  3. "errors"
  4. "fmt"
  5. "path/filepath"
  6. "github.com/tal-tech/go-zero/tools/goctl/rpc/execx"
  7. "github.com/tal-tech/go-zero/tools/goctl/rpc/generator"
  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. 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 := generator.NewDefaultRpcGenerator()
  24. return g.Generate(src, out, protoImportPath)
  25. }
  26. // RpcNew is to generate rpc greet service, this greet service can speed
  27. // up your understanding of the zrpc service structure
  28. func RpcNew(c *cli.Context) error {
  29. name := c.Args().First()
  30. ext := filepath.Ext(name)
  31. if len(ext) > 0 {
  32. return fmt.Errorf("unexpected ext: %s", ext)
  33. }
  34. protoName := name + ".proto"
  35. filename := filepath.Join(".", name, protoName)
  36. src, err := filepath.Abs(filename)
  37. if err != nil {
  38. return err
  39. }
  40. err = generator.ProtoTmpl(src)
  41. if err != nil {
  42. return err
  43. }
  44. workDir := filepath.Dir(src)
  45. _, err = execx.Run("go mod init "+name, workDir)
  46. if err != nil {
  47. return err
  48. }
  49. g := generator.NewDefaultRpcGenerator()
  50. return g.Generate(src, filepath.Dir(src), nil)
  51. }
  52. func RpcTemplate(c *cli.Context) error {
  53. protoFile := c.String("o")
  54. if len(protoFile) == 0 {
  55. return errors.New("missing -o")
  56. }
  57. return generator.ProtoTmpl(protoFile)
  58. }