ctx.go 2.3 KB

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