-
Notifications
You must be signed in to change notification settings - Fork 0
/
gomod.go
130 lines (118 loc) Β· 2.45 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// Copyright 2011-2018 visualfc <visualfc@gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gomod
import (
"encoding/json"
"os/exec"
"path/filepath"
"strings"
)
func LooupModList(dir string) *ModuleList {
data := ListModuleJson(dir)
if data == nil {
return nil
}
ms := parseModuleJson(data)
ms.Dir = dir
return &ms
}
func LookupModFile(dir string) string {
command := exec.Command("go", "env", "GOMOD")
command.Dir = dir
data, err := command.Output()
if err != nil {
return ""
}
return strings.TrimSpace(string(data))
}
func ListModuleJson(dir string) []byte {
command := exec.Command("go", "list", "-m", "-json", "all")
command.Dir = dir
data, err := command.Output()
if err != nil {
return nil
}
return data
}
type ModuleList struct {
Dir string
Module Module
Require []*Module
}
func makePath(path, dir string, addin string) string {
dir = filepath.ToSlash(dir)
pos := strings.Index(dir, "mod/"+path+"@")
if pos == -1 {
return path
}
return filepath.Join(dir[pos:], addin)
}
type Package struct {
Dir string
ImportPath string
Name string
Module *Module
}
func (m *ModuleList) LookupModule(pkgname string) (require *Module, path string, dir string) {
for _, r := range m.Require {
if strings.HasPrefix(pkgname, r.Path) {
addin := pkgname[len(r.Path):]
if r.Replace != nil {
path = makePath(r.Replace.Path, r.Dir, addin)
} else {
path = makePath(r.Path, r.Dir, addin)
}
return r, path, filepath.Join(r.Dir, addin)
}
}
c := exec.Command("go", "list", "-json", "-e", pkgname)
c.Dir = m.Dir
data, err := c.Output()
if err == nil {
var p Package
err = json.Unmarshal(data, &p)
if err == nil {
add := &Module{Path: p.ImportPath, Dir: p.Dir}
m.Require = append(m.Require, add)
return add, p.ImportPath, p.Dir
}
}
return nil, "", ""
}
type Module struct {
Path string
Version string
Time string
Dir string
Main bool
Replace *Module
}
func parseModuleJson(data []byte) ModuleList {
var ms ModuleList
var index int
var tag int
for i, v := range data {
switch v {
case '{':
if tag == 0 {
index = i
}
tag++
case '}':
tag--
if tag == 0 {
var m Module
err := json.Unmarshal(data[index:i+1], &m)
if err == nil {
if m.Main {
ms.Module = m
} else {
ms.Require = append(ms.Require, &m)
}
}
}
}
}
return ms
}