path.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. package util
  2. import (
  3. "fmt"
  4. "os"
  5. "path"
  6. "path/filepath"
  7. "strings"
  8. "github.com/tal-tech/go-zero/tools/goctl/vars"
  9. )
  10. const (
  11. pkgSep = "/"
  12. goModeIdentifier = "go.mod"
  13. )
  14. // JoinPackages calls strings.Join and returns
  15. func JoinPackages(pkgs ...string) string {
  16. return strings.Join(pkgs, pkgSep)
  17. }
  18. // MkdirIfNotExist makes directories if the input path is not exists
  19. func MkdirIfNotExist(dir string) error {
  20. if len(dir) == 0 {
  21. return nil
  22. }
  23. if _, err := os.Stat(dir); os.IsNotExist(err) {
  24. return os.MkdirAll(dir, os.ModePerm)
  25. }
  26. return nil
  27. }
  28. // PathFromGoSrc returns the path without slash where has been trim the prefix $GOPATH
  29. func PathFromGoSrc() (string, error) {
  30. dir, err := os.Getwd()
  31. if err != nil {
  32. return "", err
  33. }
  34. gopath := os.Getenv("GOPATH")
  35. parent := path.Join(gopath, "src", vars.ProjectName)
  36. pos := strings.Index(dir, parent)
  37. if pos < 0 {
  38. return "", fmt.Errorf("%s is not in GOPATH", dir)
  39. }
  40. // skip slash
  41. return dir[len(parent)+1:], nil
  42. }
  43. // FindGoModPath returns the path in project where has file go.mod, it maybe return empty string if
  44. // there is no go.mod file in project
  45. func FindGoModPath(dir string) (string, bool) {
  46. absDir, err := filepath.Abs(dir)
  47. if err != nil {
  48. return "", false
  49. }
  50. absDir = strings.ReplaceAll(absDir, `\`, `/`)
  51. var rootPath string
  52. tempPath := absDir
  53. hasGoMod := false
  54. for {
  55. if FileExists(filepath.Join(tempPath, goModeIdentifier)) {
  56. rootPath = strings.TrimPrefix(absDir[len(tempPath):], "/")
  57. hasGoMod = true
  58. break
  59. }
  60. if tempPath == filepath.Dir(tempPath) {
  61. break
  62. }
  63. tempPath = filepath.Dir(tempPath)
  64. if tempPath == string(filepath.Separator) {
  65. break
  66. }
  67. }
  68. if hasGoMod {
  69. return rootPath, true
  70. }
  71. return "", false
  72. }
  73. // FindProjectPath returns the parent directory where has file go.mod in project
  74. func FindProjectPath(loc string) (string, bool) {
  75. var dir string
  76. if strings.IndexByte(loc, '/') == 0 {
  77. dir = loc
  78. } else {
  79. wd, err := os.Getwd()
  80. if err != nil {
  81. return "", false
  82. }
  83. dir = filepath.Join(wd, loc)
  84. }
  85. for {
  86. if FileExists(filepath.Join(dir, goModeIdentifier)) {
  87. return dir, true
  88. }
  89. dir = filepath.Dir(dir)
  90. if dir == "/" {
  91. break
  92. }
  93. }
  94. return "", false
  95. }