gopath.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package ctx
  2. import (
  3. "errors"
  4. "go/build"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
  9. )
  10. // projectFromGoPath is used to find the main module and project file path
  11. // the workDir flag specifies which folder we need to detect based on
  12. // only valid for go mod project
  13. func projectFromGoPath(workDir string) (*ProjectContext, error) {
  14. if len(workDir) == 0 {
  15. return nil, errors.New("the work directory is not found")
  16. }
  17. if _, err := os.Stat(workDir); err != nil {
  18. return nil, err
  19. }
  20. workDir, err := pathx.ReadLink(workDir)
  21. if err != nil {
  22. return nil, err
  23. }
  24. buildContext := build.Default
  25. goPath := buildContext.GOPATH
  26. goPath, err = pathx.ReadLink(goPath)
  27. if err != nil {
  28. return nil, err
  29. }
  30. goSrc := filepath.Join(goPath, "src")
  31. if !pathx.FileExists(goSrc) {
  32. return nil, errModuleCheck
  33. }
  34. wd, err := filepath.Abs(workDir)
  35. if err != nil {
  36. return nil, err
  37. }
  38. if !strings.HasPrefix(wd, goSrc) {
  39. return nil, errModuleCheck
  40. }
  41. projectName := strings.TrimPrefix(wd, goSrc+string(filepath.Separator))
  42. return &ProjectContext{
  43. WorkDir: workDir,
  44. Name: projectName,
  45. Path: projectName,
  46. Dir: filepath.Join(goSrc, projectName),
  47. }, nil
  48. }