context.go 1.5 KB

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