path.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 pkgSep = "/"
  11. func JoinPackages(pkgs ...string) string {
  12. return strings.Join(pkgs, pkgSep)
  13. }
  14. func MkdirIfNotExist(dir string) error {
  15. if len(dir) == 0 {
  16. return nil
  17. }
  18. if _, err := os.Stat(dir); os.IsNotExist(err) {
  19. return os.MkdirAll(dir, os.ModePerm)
  20. }
  21. return nil
  22. }
  23. func PathFromGoSrc() (string, error) {
  24. dir, err := os.Getwd()
  25. if err != nil {
  26. return "", err
  27. }
  28. gopath := os.Getenv("GOPATH")
  29. parent := path.Join(gopath, "src", vars.ProjectName)
  30. pos := strings.Index(dir, parent)
  31. if pos < 0 {
  32. return "", fmt.Errorf("%s is not in GOPATH", dir)
  33. }
  34. // skip slash
  35. return dir[len(parent)+1:], nil
  36. }
  37. func GetParentPackage(dir string) (string, error) {
  38. absDir, err := filepath.Abs(dir)
  39. if err != nil {
  40. return "", err
  41. }
  42. pos := strings.Index(absDir, vars.ProjectName)
  43. if pos < 0 {
  44. return "", fmt.Errorf("error dir:[%s],please make sure that your project is in the %s directory", vars.ProjectName, dir)
  45. }
  46. return absDir[pos:], nil
  47. }