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