path.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. rootPath = strings.TrimPrefix(absDir[len(tempPath):], "/")
  52. hasGoMod = true
  53. break
  54. }
  55. if tempPath == filepath.Dir(tempPath) {
  56. break
  57. }
  58. tempPath = filepath.Dir(tempPath)
  59. if tempPath == string(filepath.Separator) {
  60. break
  61. }
  62. }
  63. if hasGoMod {
  64. return rootPath, true
  65. }
  66. return "", false
  67. }
  68. func FindProjectPath(loc string) (string, bool) {
  69. var dir string
  70. if strings.IndexByte(loc, '/') == 0 {
  71. dir = loc
  72. } else {
  73. wd, err := os.Getwd()
  74. if err != nil {
  75. return "", false
  76. }
  77. dir = filepath.Join(wd, loc)
  78. }
  79. for {
  80. if FileExists(filepath.Join(dir, goModeIdentifier)) {
  81. return dir, true
  82. }
  83. dir = filepath.Dir(dir)
  84. if dir == "/" {
  85. break
  86. }
  87. }
  88. return "", false
  89. }