-
Notifications
You must be signed in to change notification settings - Fork 19
/
parser.go
168 lines (149 loc) · 5.13 KB
/
parser.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package depgraph
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"regexp"
"strings"
"github.com/sirupsen/logrus"
"github.com/Helcaraxan/gomod/lib/internal/util"
)
var depRE = regexp.MustCompile(`^([^@\s]+)@?([^@\s]+)? ([^@\s]+)@([^@\s]+)$`)
// GetDepGraph should be called from within a Go module. It will return the dependency
// graph for this module. The 'logger' parameter can be 'nil' which will result in no
// output or logging information to be provided.
func GetDepGraph(logger *logrus.Logger) (*DepGraph, error) {
if logger == nil {
logger = logrus.New()
logger.SetOutput(ioutil.Discard)
}
logger.Debug("Creating dependency graph.")
mainModule, modules, err := getSelectedModules(logger)
if err != nil {
return nil, err
}
graph := NewGraph(logger, mainModule)
logger.Debug("Retrieving dependency information via 'go mod graph'")
rawDeps, _, err := util.RunCommand(logger, "go", "mod", "graph")
if err != nil {
return nil, err
}
for _, depString := range strings.Split(strings.TrimSpace(string(rawDeps)), "\n") {
graph.logger.Debugf("Parsing dependency: %s", depString)
rawDep, ok := graph.parseDependency(depString, modules)
if !ok {
continue
}
if err = graph.addDependency(rawDep); err != nil {
return nil, err
}
}
for _, node := range graph.nodes.List() {
if node.Predecessors.Len() == 0 && node.Successors.Len() == 0 {
graph.removeNode(node.Name())
}
}
return graph, nil
}
func getSelectedModules(logger *logrus.Logger) (*Module, map[string]*Module, error) {
logger.Debug("Retrieving module information via 'go list'")
raw, _, err := util.RunCommand(logger, "go", "list", "-json", "-m", "all")
if err != nil {
return nil, nil, err
}
raw = bytes.ReplaceAll(bytes.TrimSpace(raw), []byte("\n}\n"), []byte("\n},\n"))
raw = append([]byte("[\n"), raw...)
raw = append(raw, []byte("\n]")...)
var moduleList []*Module
if err = json.Unmarshal(raw, &moduleList); err != nil {
return nil, nil, fmt.Errorf("Unable to retrieve information from 'go list': %v", err)
}
var main *Module
modules := map[string]*Module{}
for idx, module := range moduleList {
if module.Error != nil {
logger.Warnf("Unable to retrieve information for module %q: %s", module.Path, module.Error.Err)
}
if module.Main {
main = module
}
modules[module.Path] = moduleList[idx]
if module.Replace != nil {
modules[module.Replace.Path] = moduleList[idx]
}
}
if main == nil || len(main.Path) == 0 {
return nil, nil, errors.New("could not determine main module")
}
return main, modules, nil
}
func (g *DepGraph) addDependency(rawDependency *rawDependency) error {
beginNode, ok := g.Node(rawDependency.beginModule.Path)
if !ok {
if beginNode, ok = g.AddNode(rawDependency.beginModule); !ok {
return fmt.Errorf("could not create node based on %+v", beginNode.Module)
}
g.logger.Debugf("Created new node %q: %+v", rawDependency.beginModule.Path, beginNode)
}
endNode, ok := g.Node(rawDependency.endModule.Path)
if !ok {
if endNode, ok = g.AddNode(rawDependency.endModule); !ok {
return fmt.Errorf("could not create node based on %+v", beginNode.Module)
}
g.logger.Debugf("Created new node %q: %+v", rawDependency.endModule.Path, endNode)
}
if len(beginNode.SelectedVersion()) != 0 && beginNode.Module.Replace == nil && beginNode.SelectedVersion() != rawDependency.beginVersion {
g.logger.Warnf(
"Encountered unexpected version %q for dependency of %q on %q.",
rawDependency.beginVersion,
rawDependency.begineNodeName,
rawDependency.endNodeName,
)
}
beginNode.Successors.Add(&NodeReference{
Node: endNode,
VersionConstraint: rawDependency.endVersion,
})
endNode.Predecessors.Add(&NodeReference{
Node: beginNode,
VersionConstraint: rawDependency.endVersion,
})
g.logger.Debugf("Created new dependency from %q to %q with version %q.", beginNode.Name(), endNode.Name(), rawDependency.endVersion)
return nil
}
type rawDependency struct {
begineNodeName string
beginVersion string
beginModule *Module
endNodeName string
endVersion string
endModule *Module
}
func (g *DepGraph) parseDependency(depString string, modules map[string]*Module) (*rawDependency, bool) {
depContent := depRE.FindStringSubmatch(depString)
if len(depContent) == 0 {
g.logger.Warnf("Skipping ill-formed line in 'go mod graph' output: %s", depString)
return nil, false
}
beginNodeName, beginVersion := depContent[1], depContent[2]
endNodeName, endVersion := depContent[3], depContent[4]
beginModule := modules[beginNodeName]
endModule := modules[endNodeName]
if beginModule == nil || endModule == nil {
g.logger.Warnf("Encountered a dependency edge starting or ending at an unknown module %q -> %q.", beginNodeName, endNodeName)
return nil, false
} else if beginVersion != beginModule.Version {
g.logger.Debugf("Skipping edge from %q at %q to %q as we are not using that version.", beginNodeName, beginVersion, endNodeName)
return nil, false
}
return &rawDependency{
begineNodeName: beginNodeName,
beginVersion: beginVersion,
beginModule: beginModule,
endNodeName: endNodeName,
endVersion: endVersion,
endModule: endModule,
}, true
}