path.go 991 B

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