/
pom.go
351 lines (305 loc) · 9.05 KB
/
pom.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
package pom
import (
"encoding/xml"
"fmt"
"golang.org/x/xerrors"
"io"
"maps"
"reflect"
"strings"
"github.com/samber/lo"
"github.com/aquasecurity/go-dep-parser/pkg/types"
"github.com/aquasecurity/go-dep-parser/pkg/utils"
)
type pom struct {
filePath string
content *pomXML
}
func (p *pom) inherit(result analysisResult) {
// Merge properties
p.content.Properties = utils.MergeMaps(result.properties, p.content.Properties)
art := p.artifact().Inherit(result.artifact)
p.content.GroupId = art.GroupID
p.content.ArtifactId = art.ArtifactID
p.content.Licenses = art.ToPOMLicenses()
if isProperty(art.Version.String()) {
p.content.Version = evaluateVariable(art.Version.String(), p.content.Properties, nil)
} else {
p.content.Version = art.Version.String()
}
}
func (p pom) properties() properties {
props := p.content.Properties
return utils.MergeMaps(props, p.projectProperties())
}
func (p pom) projectProperties() map[string]string {
val := reflect.ValueOf(p.content).Elem()
props := p.listProperties(val)
// "version" and "groupId" elements could be inherited from parent.
// https://maven.apache.org/pom.html#inheritance
props["groupId"] = p.content.GroupId
props["version"] = p.content.Version
// https://maven.apache.org/pom.html#properties
projectProperties := map[string]string{}
for k, v := range props {
if strings.HasPrefix(k, "project.") {
continue
}
// e.g. ${project.groupId}
key := fmt.Sprintf("project.%s", k)
projectProperties[key] = v
// It is deprecated, but still available.
// e.g. ${groupId}
projectProperties[k] = v
}
return projectProperties
}
func (p pom) listProperties(val reflect.Value) map[string]string {
props := map[string]string{}
for i := 0; i < val.NumField(); i++ {
f := val.Type().Field(i)
tag, ok := f.Tag.Lookup("xml")
if !ok || strings.Contains(tag, ",") {
// e.g. ",chardata"
continue
}
switch f.Type.Kind() {
case reflect.Slice:
continue
case reflect.Map:
m := val.Field(i)
for _, e := range m.MapKeys() {
v := m.MapIndex(e)
props[e.String()] = v.String()
}
case reflect.Struct:
nestedProps := p.listProperties(val.Field(i))
for k, v := range nestedProps {
key := fmt.Sprintf("%s.%s", tag, k)
props[key] = v
}
default:
props[tag] = val.Field(i).String()
}
}
return props
}
func (p pom) artifact() artifact {
return newArtifact(p.content.GroupId, p.content.ArtifactId, p.content.Version, p.licenses(), p.content.Properties)
}
func (p pom) licenses() []string {
return lo.FilterMap(p.content.Licenses.License, func(lic pomLicense, _ int) (string, bool) {
return lic.Name, lic.Name != ""
})
}
func (p pom) repositories() []string {
var urls []string
for _, rep := range p.content.Repositories.Repository {
if rep.Releases.Enabled != "false" {
urls = append(urls, rep.URL)
}
}
return urls
}
type pomXML struct {
Parent pomParent `xml:"parent"`
GroupId string `xml:"groupId"`
ArtifactId string `xml:"artifactId"`
Version string `xml:"version"`
Licenses pomLicenses `xml:"licenses"`
Modules struct {
Text string `xml:",chardata"`
Module []string `xml:"module"`
} `xml:"modules"`
Properties properties `xml:"properties"`
DependencyManagement struct {
Text string `xml:",chardata"`
Dependencies pomDependencies `xml:"dependencies"`
} `xml:"dependencyManagement"`
Dependencies pomDependencies `xml:"dependencies"`
Repositories struct {
Text string `xml:",chardata"`
Repository []struct {
Text string `xml:",chardata"`
ID string `xml:"id"`
Name string `xml:"name"`
URL string `xml:"url"`
Releases struct {
Text string `xml:",chardata"`
Enabled string `xml:"enabled"`
} `xml:"releases"`
Snapshots struct {
Text string `xml:",chardata"`
Enabled string `xml:"enabled"`
} `xml:"snapshots"`
} `xml:"repository"`
} `xml:"repositories"`
}
type pomParent struct {
GroupId string `xml:"groupId"`
ArtifactId string `xml:"artifactId"`
Version string `xml:"version"`
RelativePath string `xml:"relativePath"`
}
type pomLicenses struct {
Text string `xml:",chardata"`
License []pomLicense `xml:"license"`
}
type pomLicense struct {
Name string `xml:"name"`
}
type pomDependencies struct {
Text string `xml:",chardata"`
Dependency []pomDependency `xml:"dependency"`
}
type pomDependency struct {
Text string `xml:",chardata"`
GroupID string `xml:"groupId"`
ArtifactID string `xml:"artifactId"`
Version string `xml:"version"`
Scope string `xml:"scope"`
Optional bool `xml:"optional"`
Exclusions pomExclusions `xml:"exclusions"`
StartLine int
EndLine int
}
type pomExclusions struct {
Text string `xml:",chardata"`
Exclusion []pomExclusion `xml:"exclusion"`
}
// ref. https://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html
type pomExclusion struct {
GroupID string `xml:"groupId"`
ArtifactID string `xml:"artifactId"`
}
func (d pomDependency) Name() string {
return fmt.Sprintf("%s:%s", d.GroupID, d.ArtifactID)
}
// Resolve evaluates variables in the dependency and inherit some fields from dependencyManagement to the dependency.
func (d pomDependency) Resolve(props map[string]string, depManagement, rootDepManagement []pomDependency) pomDependency {
// Evaluate variables
dep := pomDependency{
Text: d.Text,
GroupID: evaluateVariable(d.GroupID, props, nil),
ArtifactID: evaluateVariable(d.ArtifactID, props, nil),
Version: evaluateVariable(d.Version, props, nil),
Scope: evaluateVariable(d.Scope, props, nil),
Optional: d.Optional,
Exclusions: d.Exclusions,
StartLine: d.StartLine,
EndLine: d.EndLine,
}
// If this dependency is managed in the root POM,
// we need to overwrite fields according to the managed dependency.
if managed, found := findDep(d.Name(), rootDepManagement); found { // dependencyManagement from the root POM
if managed.Version != "" {
dep.Version = evaluateVariable(managed.Version, props, nil)
}
if managed.Scope != "" {
dep.Scope = evaluateVariable(managed.Scope, props, nil)
}
if managed.Optional {
dep.Optional = managed.Optional
}
if len(managed.Exclusions.Exclusion) != 0 {
dep.Exclusions = managed.Exclusions
}
return dep
}
// Inherit version, scope and optional from dependencyManagement if empty
if managed, found := findDep(d.Name(), depManagement); found { // dependencyManagement from parent
if dep.Version == "" {
dep.Version = evaluateVariable(managed.Version, props, nil)
}
if dep.Scope == "" {
dep.Scope = evaluateVariable(managed.Scope, props, nil)
}
// TODO: need to check the behavior
if !dep.Optional {
dep.Optional = managed.Optional
}
if len(dep.Exclusions.Exclusion) == 0 {
dep.Exclusions = managed.Exclusions
}
}
return dep
}
// ToArtifact converts dependency to artifact.
// It should be called after calling Resolve() so that variables can be evaluated.
func (d pomDependency) ToArtifact(opts analysisOptions) artifact {
// To avoid shadow adding exclusions to top pom's,
// we need to initialize a new map for each new artifact
// See `exclusions in child` test for more information
exclusions := map[string]struct{}{}
if opts.exclusions != nil {
exclusions = maps.Clone(opts.exclusions)
}
for _, e := range d.Exclusions.Exclusion {
exclusions[fmt.Sprintf("%s:%s", e.GroupID, e.ArtifactID)] = struct{}{}
}
var locations types.Locations
if opts.lineNumber {
locations = types.Locations{
{
StartLine: d.StartLine,
EndLine: d.EndLine,
},
}
}
return artifact{
GroupID: d.GroupID,
ArtifactID: d.ArtifactID,
Version: newVersion(d.Version),
Exclusions: exclusions,
Locations: locations,
}
}
type properties map[string]string
type property struct {
XMLName xml.Name
Value string `xml:",chardata"`
}
func (props *properties) UnmarshalXML(d *xml.Decoder, _ xml.StartElement) error {
*props = properties{}
for {
var p property
err := d.Decode(&p)
if err == io.EOF {
break
} else if err != nil {
return xerrors.Errorf("XML decode error: %w", err)
}
(*props)[p.XMLName.Local] = p.Value
}
return nil
}
func (deps *pomDependencies) UnmarshalXML(d *xml.Decoder, _ xml.StartElement) error {
for {
token, err := d.Token()
if err == io.EOF {
break
} else if err != nil {
return xerrors.Errorf("XML decode error: %w", err)
}
switch t := token.(type) {
case xml.StartElement:
if t.Name.Local == "dependency" {
var dep pomDependency
dep.StartLine, _ = d.InputPos() // <dependency> tag starts
// Decode the <dependency> element
err = d.DecodeElement(&dep, &t)
if err != nil {
return xerrors.Errorf("Error decoding dependency: %w")
}
dep.EndLine, _ = d.InputPos() // <dependency> tag ends
deps.Dependency = append(deps.Dependency, dep)
}
}
}
return nil
}
func findDep(name string, depManagement []pomDependency) (pomDependency, bool) {
return lo.Find(depManagement, func(item pomDependency) bool {
return item.Name() == name
})
}