gomod.go 1.0 KB

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