path.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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. func JoinPackages(pkgs ...string) string {
  15. return strings.Join(pkgs, pkgSep)
  16. }
  17. func MkdirIfNotExist(dir string) error {
  18. if len(dir) == 0 {
  19. return nil
  20. }
  21. if _, err := os.Stat(dir); os.IsNotExist(err) {
  22. return os.MkdirAll(dir, os.ModePerm)
  23. }
  24. return nil
  25. }
  26. func PathFromGoSrc() (string, error) {
  27. dir, err := os.Getwd()
  28. if err != nil {
  29. return "", err
  30. }
  31. gopath := os.Getenv("GOPATH")
  32. parent := path.Join(gopath, "src", vars.ProjectName)
  33. pos := strings.Index(dir, parent)
  34. if pos < 0 {
  35. return "", fmt.Errorf("%s is not in GOPATH", dir)
  36. }
  37. // skip slash
  38. return dir[len(parent)+1:], nil
  39. }
  40. func FindGoModPath(dir string) (string, bool) {
  41. absDir, err := filepath.Abs(dir)
  42. if err != nil {
  43. return "", false
  44. }
  45. absDir = strings.ReplaceAll(absDir, `\`, `/`)
  46. var rootPath string
  47. var tempPath = absDir
  48. var hasGoMod = false
  49. for {
  50. if FileExists(filepath.Join(tempPath, goModeIdentifier)) {
  51. tempPath = filepath.Dir(tempPath)
  52. rootPath = strings.TrimPrefix(absDir[len(tempPath):], "/")
  53. hasGoMod = true
  54. break
  55. }
  56. if tempPath == filepath.Dir(tempPath) {
  57. break
  58. }
  59. tempPath = filepath.Dir(tempPath)
  60. if tempPath == string(filepath.Separator) {
  61. break
  62. }
  63. }
  64. if hasGoMod {
  65. return rootPath, true
  66. }
  67. return "", false
  68. }
  69. func FindProjectPath(loc string) (string, bool) {
  70. var dir string
  71. if strings.IndexByte(loc, '/') == 0 {
  72. dir = loc
  73. } else {
  74. wd, err := os.Getwd()
  75. if err != nil {
  76. return "", false
  77. }
  78. dir = filepath.Join(wd, loc)
  79. }
  80. for {
  81. if FileExists(filepath.Join(dir, goModeIdentifier)) {
  82. return dir, true
  83. }
  84. dir = filepath.Dir(dir)
  85. if dir == "/" {
  86. break
  87. }
  88. }
  89. return "", false
  90. }