gomod.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package ctx
  2. import (
  3. "errors"
  4. "os"
  5. "path/filepath"
  6. "github.com/tal-tech/go-zero/core/jsonx"
  7. "github.com/tal-tech/go-zero/tools/goctl/rpc/execx"
  8. "github.com/tal-tech/go-zero/tools/goctl/util"
  9. )
  10. // Module contains the relative data of go module,
  11. // which is the result of the command go list
  12. type Module struct {
  13. Path string
  14. Main bool
  15. Dir string
  16. GoMod string
  17. GoVersion string
  18. }
  19. // projectFromGoMod is used to find the go module and project file path
  20. // the workDir flag specifies which folder we need to detect based on
  21. // only valid for go mod project
  22. func projectFromGoMod(workDir string) (*ProjectContext, error) {
  23. if len(workDir) == 0 {
  24. return nil, errors.New("the work directory is not found")
  25. }
  26. if _, err := os.Stat(workDir); err != nil {
  27. return nil, err
  28. }
  29. workDir, err := util.ReadLink(workDir)
  30. if err != nil {
  31. return nil, err
  32. }
  33. data, err := execx.Run("go list -json -m", workDir)
  34. if err != nil {
  35. return nil, err
  36. }
  37. var m Module
  38. err = jsonx.Unmarshal([]byte(data), &m)
  39. if err != nil {
  40. return nil, err
  41. }
  42. var ret ProjectContext
  43. ret.WorkDir = workDir
  44. ret.Name = filepath.Base(m.Dir)
  45. dir, err := util.ReadLink(m.Dir)
  46. if err != nil {
  47. return nil, err
  48. }
  49. ret.Dir = dir
  50. ret.Path = m.Path
  51. return &ret, nil
  52. }