forked from zeromicro/go-zero
/
gomod.go
103 lines (89 loc) · 2.16 KB
/
gomod.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package ctx
import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/sanhuanshisanshao/go-zero/tools/goctl/rpc/execx"
"github.com/sanhuanshisanshao/go-zero/tools/goctl/util/pathx"
)
const goModuleWithoutGoFiles = "command-line-arguments"
var errInvalidGoMod = errors.New("invalid go module")
// Module contains the relative data of go module,
// which is the result of the command go list
type Module struct {
Path string
Main bool
Dir string
GoMod string
GoVersion string
}
func (m *Module) validate() error {
if m.Path == goModuleWithoutGoFiles || m.Dir == "" {
return errInvalidGoMod
}
return nil
}
// projectFromGoMod is used to find the go module and project file path
// the workDir flag specifies which folder we need to detect based on
// only valid for go mod project
func projectFromGoMod(workDir string) (*ProjectContext, error) {
if len(workDir) == 0 {
return nil, errors.New("the work directory is not found")
}
if _, err := os.Stat(workDir); err != nil {
return nil, err
}
workDir, err := pathx.ReadLink(workDir)
if err != nil {
return nil, err
}
m, err := getRealModule(workDir, execx.Run)
if err != nil {
return nil, err
}
if err := m.validate(); err != nil {
return nil, err
}
var ret ProjectContext
ret.WorkDir = workDir
ret.Name = filepath.Base(m.Dir)
dir, err := pathx.ReadLink(m.Dir)
if err != nil {
return nil, err
}
ret.Dir = dir
ret.Path = m.Path
return &ret, nil
}
func getRealModule(workDir string, execRun execx.RunFunc) (*Module, error) {
data, err := execRun("go list -json -m", workDir)
if err != nil {
return nil, err
}
modules, err := decodePackages(strings.NewReader(data))
if err != nil {
return nil, err
}
for _, m := range modules {
if strings.HasPrefix(workDir, m.Dir) {
return &m, nil
}
}
return nil, errors.New("no matched module")
}
func decodePackages(rc io.Reader) ([]Module, error) {
var modules []Module
decoder := json.NewDecoder(rc)
for decoder.More() {
var m Module
if err := decoder.Decode(&m); err != nil {
return nil, fmt.Errorf("invalid module: %v", err)
}
modules = append(modules, m)
}
return modules, nil
}