context.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package ctx
  2. import (
  3. "errors"
  4. "path/filepath"
  5. "github.com/tal-tech/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. type ProjectContext struct {
  9. WorkDir string
  10. // Name is the root name of the project
  11. // eg: go-zero、greet
  12. Name string
  13. // Path identifies which module a project belongs to, which is module value if it's a go mod project,
  14. // or else it is the root name of the project, eg: github.com/tal-tech/go-zero、greet
  15. Path string
  16. // Dir is the path of the project, eg: /Users/keson/goland/go/go-zero、/Users/keson/go/src/greet
  17. Dir string
  18. }
  19. // Prepare checks the project which module belongs to,and returns the path and module.
  20. // workDir parameter is the directory of the source of generating code,
  21. // where can be found the project path and the project module,
  22. func Prepare(workDir string) (*ProjectContext, error) {
  23. ctx, err := background(workDir)
  24. if err == nil {
  25. return ctx, nil
  26. }
  27. name := filepath.Base(workDir)
  28. _, err = execx.Run("go mod init "+name, workDir)
  29. if err != nil {
  30. return nil, err
  31. }
  32. return background(workDir)
  33. }
  34. func background(workDir string) (*ProjectContext, error) {
  35. isGoMod, err := IsGoMod(workDir)
  36. if err != nil {
  37. return nil, err
  38. }
  39. if isGoMod {
  40. return projectFromGoMod(workDir)
  41. }
  42. return projectFromGoPath(workDir)
  43. }