/
gopath.go
57 lines (48 loc) · 1.18 KB
/
gopath.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
package ctx
import (
"errors"
"go/build"
"os"
"path/filepath"
"strings"
"github.com/wuntsong-org/goctlwt/util/pathx"
)
// projectFromGoPath is used to find the main module and project file path
// the workDir flag specifies which folder we need to detect based on
// only valid for go mod project
func projectFromGoPath(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
}
buildContext := build.Default
goPath := buildContext.GOPATH
goPath, err = pathx.ReadLink(goPath)
if err != nil {
return nil, err
}
goSrc := filepath.Join(goPath, "src")
if !pathx.FileExists(goSrc) {
return nil, errModuleCheck
}
wd, err := filepath.Abs(workDir)
if err != nil {
return nil, err
}
if !strings.HasPrefix(wd, goSrc) {
return nil, errModuleCheck
}
projectName := strings.TrimPrefix(wd, goSrc+string(filepath.Separator))
return &ProjectContext{
WorkDir: workDir,
Name: projectName,
Path: projectName,
Dir: filepath.Join(goSrc, projectName),
}, nil
}