context.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package ctx
  2. import (
  3. "errors"
  4. "path/filepath"
  5. "git.i2edu.net/i2/go-zero/tools/goctl/rpc/execx"
  6. )
  7. var errModuleCheck = errors.New("the work directory must be found in the go mod or the $GOPATH")
  8. // ProjectContext is a structure for the project,
  9. // which contains WorkDir, Name, Path and Dir
  10. type ProjectContext struct {
  11. WorkDir string
  12. // Name is the root name of the project
  13. // eg: go-zero、greet
  14. Name string
  15. // Path identifies which module a project belongs to, which is module value if it's a go mod project,
  16. // or else it is the root name of the project, eg: git.i2edu.net/i2/go-zero、greet
  17. Path string
  18. // Dir is the path of the project, eg: /Users/keson/goland/go/go-zero、/Users/keson/go/src/greet
  19. Dir string
  20. }
  21. // Prepare checks the project which module belongs to,and returns the path and module.
  22. // workDir parameter is the directory of the source of generating code,
  23. // where can be found the project path and the project module,
  24. func Prepare(workDir string) (*ProjectContext, error) {
  25. ctx, err := background(workDir)
  26. if err == nil {
  27. return ctx, nil
  28. }
  29. name := filepath.Base(workDir)
  30. _, err = execx.Run("go mod init "+name, workDir)
  31. if err != nil {
  32. return nil, err
  33. }
  34. return background(workDir)
  35. }
  36. func background(workDir string) (*ProjectContext, error) {
  37. isGoMod, err := IsGoMod(workDir)
  38. if err != nil {
  39. return nil, err
  40. }
  41. if isGoMod {
  42. return projectFromGoMod(workDir)
  43. }
  44. return projectFromGoPath(workDir)
  45. }