context.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package ctx
  2. import (
  3. "errors"
  4. "path/filepath"
  5. "github.com/tal-tech/go-zero/tools/goctl/rpc/execx"
  6. )
  7. var moduleCheckErr = errors.New("the work directory must be found in the go mod or the $GOPATH")
  8. type (
  9. ProjectContext struct {
  10. WorkDir string
  11. // Name is the root name of the project
  12. // eg: go-zero、greet
  13. Name string
  14. // Path identifies which module a project belongs to, which is module value if it's a go mod project,
  15. // or else it is the root name of the project, eg: github.com/tal-tech/go-zero、greet
  16. Path string
  17. // Dir is the path of the project, eg: /Users/keson/goland/go/go-zero、/Users/keson/go/src/greet
  18. Dir string
  19. }
  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. }