path.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 = absDir[len(tempPath)+1:]
  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. }