ctx.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package ctx
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "runtime"
  6. "strings"
  7. "github.com/tal-tech/go-zero/core/logx"
  8. "github.com/tal-tech/go-zero/tools/goctl/util"
  9. "github.com/tal-tech/go-zero/tools/goctl/util/console"
  10. "github.com/tal-tech/go-zero/tools/goctl/util/project"
  11. "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
  12. "github.com/urfave/cli"
  13. )
  14. const (
  15. flagSrc = "src"
  16. flagDir = "dir"
  17. flagService = "service"
  18. flagIdea = "idea"
  19. )
  20. type RpcContext struct {
  21. ProjectPath string
  22. ProjectName stringx.String
  23. ServiceName stringx.String
  24. CurrentPath string
  25. Module string
  26. ProtoFileSrc string
  27. ProtoSource string
  28. TargetDir string
  29. console.Console
  30. }
  31. func MustCreateRpcContext(protoSrc, targetDir, serviceName string, idea bool) *RpcContext {
  32. log := console.NewConsole(idea)
  33. info, err := project.Prepare(targetDir, true)
  34. log.Must(err)
  35. if stringx.From(protoSrc).IsEmptyOrSpace() {
  36. log.Fatalln("expected proto source, but nothing found")
  37. }
  38. srcFp, err := filepath.Abs(protoSrc)
  39. log.Must(err)
  40. if !util.FileExists(srcFp) {
  41. log.Fatalln("%s is not exists", srcFp)
  42. }
  43. current := filepath.Dir(srcFp)
  44. if stringx.From(targetDir).IsEmptyOrSpace() {
  45. targetDir = current
  46. }
  47. targetDirFp, err := filepath.Abs(targetDir)
  48. log.Must(err)
  49. if stringx.From(serviceName).IsEmptyOrSpace() {
  50. serviceName = getServiceFromRpcStructure(targetDirFp)
  51. }
  52. serviceNameString := stringx.From(serviceName)
  53. if serviceNameString.IsEmptyOrSpace() {
  54. log.Fatalln("service name is not found")
  55. }
  56. return &RpcContext{
  57. ProjectPath: info.Path,
  58. ProjectName: stringx.From(info.Name),
  59. ServiceName: serviceNameString,
  60. CurrentPath: current,
  61. Module: info.GoMod.Module,
  62. ProtoFileSrc: srcFp,
  63. ProtoSource: filepath.Base(srcFp),
  64. TargetDir: targetDirFp,
  65. Console: log,
  66. }
  67. }
  68. func MustCreateRpcContextFromCli(ctx *cli.Context) *RpcContext {
  69. os := runtime.GOOS
  70. switch os {
  71. case "darwin", "linux", "windows":
  72. default:
  73. logx.Must(fmt.Errorf("unexpected os: %s", os))
  74. }
  75. protoSrc := ctx.String(flagSrc)
  76. targetDir := ctx.String(flagDir)
  77. serviceName := ctx.String(flagService)
  78. idea := ctx.Bool(flagIdea)
  79. return MustCreateRpcContext(protoSrc, targetDir, serviceName, idea)
  80. }
  81. func getServiceFromRpcStructure(targetDir string) string {
  82. targetDir = filepath.Clean(targetDir)
  83. suffix := filepath.Join("cmd", "rpc")
  84. return filepath.Base(strings.TrimSuffix(targetDir, suffix))
  85. }