gopath.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package ctx
  2. import (
  3. "errors"
  4. "go/build"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "github.com/tal-tech/go-zero/tools/goctl/util"
  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. buildContext := build.Default
  21. goPath := buildContext.GOPATH
  22. goSrc := filepath.Join(goPath, "src")
  23. if !util.FileExists(goSrc) {
  24. return nil, moduleCheckErr
  25. }
  26. wd, err := filepath.Abs(workDir)
  27. if err != nil {
  28. return nil, err
  29. }
  30. if !strings.HasPrefix(wd, goSrc) {
  31. return nil, moduleCheckErr
  32. }
  33. projectName := strings.TrimPrefix(wd, goSrc+string(filepath.Separator))
  34. return &ProjectContext{
  35. WorkDir: workDir,
  36. Name: projectName,
  37. Path: projectName,
  38. Dir: filepath.Join(goSrc, projectName),
  39. }, nil
  40. }