Repository navigation
Expand file tree
/
Copy pathparse-gradle-lock.go
More file actions
206 lines (167 loc) · 6.14 KB
/
Copy pathparse-gradle-lock.go
File metadata and controls
206 lines (167 loc) · 6.14 KB
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
package java
import (
"bufio"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/DataDog/datadog-sbom-generator/internal/cachedregexp"
"github.com/DataDog/datadog-sbom-generator/pkg/extractor"
"github.com/DataDog/datadog-sbom-generator/pkg/models"
)
func isGradleLockFileDepLine(line string) bool {
ret := strings.HasPrefix(line, gradleLockFileCommentPrefix) ||
strings.HasPrefix(line, gradleLockFileEmptyPrefix)
return !ret
}
func parseToGradlePackageDetail(line string) (extractor.PackageDetails, error) {
parts := strings.SplitN(line, ":", 3)
if len(parts) < 3 {
return extractor.PackageDetails{}, fmt.Errorf("invalid line in gradle lockfile: %s", line)
}
var scopes []string
group, artifact := parts[0], parts[1]
version, scopesStr, found := strings.Cut(parts[2], "=")
if found {
scopes = strings.Split(scopesStr, ",")
}
return extractor.PackageDetails{
Name: fmt.Sprintf("%s:%s", group, artifact),
Version: version,
PackageManager: gradlePackageManager,
DepGroups: scopes,
Ecosystem: models.EcosystemMaven,
}, nil
}
func (e GradleLockExtractor) ShouldExtract(path string) bool {
base := filepath.Base(path)
for _, lockfile := range []string{models.GradleBuildScriptFilePath.String(), models.GradleFilePath.String()} {
if lockfile == base {
return true
}
}
return false
}
func (e GradleLockExtractor) IsOfficiallySupported() bool {
return gradleOfficiallySupported
}
func (e GradleLockExtractor) PackageManager() models.PackageManager {
return gradlePackageManager
}
func (e GradleLockExtractor) Extract(f extractor.DepFile, context extractor.ScanContext) ([]extractor.PackageDetails, error) {
pkgs := make([]extractor.PackageDetails, 0)
scanner := bufio.NewScanner(f)
lineNumber := 0
for scanner.Scan() {
lineNumber++
lockLine := strings.TrimSpace(scanner.Text())
if !isGradleLockFileDepLine(lockLine) {
continue
}
pkg, err := parseToGradlePackageDetail(lockLine)
if err != nil {
continue
}
pkg.BlockLocation = models.FilePosition{
Line: models.Position{Start: lineNumber, End: lineNumber},
Column: models.Position{Start: 1, End: len(scanner.Text()) + 1},
Filename: f.Path(),
}
pkg.LocationRole = models.LocationRoleLockfile
pkgs = append(pkgs, pkg)
}
if err := scanner.Err(); err != nil {
return []extractor.PackageDetails{}, fmt.Errorf("failed to read: %w", err)
}
return pkgs, nil
}
// GetArtifact implements extractor.ArtifactExtractor.
// It looks for a build.gradle or build.gradle.kts file in the same directory
// as the lockfile, reads it to extract:
// - the top-level group assignment (group:projectDir → artifact Name for findArtifact matching)
// - project(':...') references → ProjectDeps for cross-subproject dependency edges
//
// If no build file is found, nil is returned.
func (e GradleLockExtractor) GetArtifact(f extractor.DepFile, ctx extractor.ScanContext) (*models.ScannedArtifact, error) {
for _, name := range []string{buildGradleFilename, buildGradleKtsFilename} {
buildFile, err := f.Open(name)
if err != nil {
continue
}
content, err := io.ReadAll(buildFile)
buildFilePath := buildFile.Path()
_ = buildFile.Close()
if err != nil {
return &models.ScannedArtifact{ArtifactDetail: models.ArtifactDetail{Filename: buildFilePath}}, err
}
artifact := &models.ScannedArtifact{
ArtifactDetail: models.ArtifactDetail{
Filename: buildFilePath,
Ecosystem: models.EcosystemMaven,
},
}
// Set artifact.Name = "group:projectName" so findArtifact can match this
// subproject when it appears as a dependency in another module's lockfile.
projectDir := filepath.Dir(f.Path())
group, projectName := resolveGradleArtifactName(ctx, projectDir, content)
if group != "" {
artifact.Name = group + ":" + projectName
}
// Extract project(':submodule') references to build inter-module dep edges.
if ctx.RootDir != "" {
artifact.ProjectDeps = extractGradleProjectDeps(content, ctx.RootDir)
}
return artifact, nil
}
return nil, nil
}
// extractTopLevelGroup extracts the value of a top-level `group = "..."` or
// `group = '...'` assignment from Gradle build file content.
// It ignores dependency kwargs like `group: 'x'` or method calls like `group("x")`.
func extractTopLevelGroup(content []byte) string {
groupRegex := cachedregexp.MustCompile(`(?m)^[\t ]*group\s*=\s*['"]([^'"]+)['"]`)
if m := groupRegex.FindSubmatch(content); m != nil {
return string(m[1])
}
return ""
}
// extractGradleProjectDeps parses project(':submodule') and project(':sub:module')
// references from Gradle build file content and returns ArtifactDetail entries
// whose Filename points to the corresponding build.gradle (or build.gradle.kts)
// under rootDir. Refs that cannot be resolved to an existing file are skipped.
func extractGradleProjectDeps(content []byte, rootDir string) []models.ArtifactDetail {
projectRegex := cachedregexp.MustCompile(`project\(['"]([^'"]+)['"]\)`)
matches := projectRegex.FindAllSubmatch(content, -1)
var deps []models.ArtifactDetail
seen := make(map[string]struct{})
for _, m := range matches {
ref := string(m[1]) // e.g. ":communication" or ":dd-java-agent:agent-tooling"
// Convert Gradle project path to filesystem path: strip leading ':', replace ':' with '/'.
subPath := strings.ReplaceAll(strings.TrimPrefix(ref, ":"), ":", string(filepath.Separator))
for _, buildFileName := range []string{buildGradleFilename, buildGradleKtsFilename} {
depPath := filepath.Join(rootDir, subPath, buildFileName)
if _, err := os.Stat(depPath); err != nil {
continue
}
if _, dup := seen[depPath]; dup {
break
}
seen[depPath] = struct{}{}
deps = append(deps, models.ArtifactDetail{Filename: depPath})
break
}
}
return deps
}
var _ extractor.ArtifactExtractor = GradleLockExtractor{}
var GradleExtractor = GradleLockExtractor{
extractor.WithMatcher{Matchers: []extractor.Matcher{&BuildGradleMatcher{}}},
}
func ParseGradleLock(pathToLockfile string) ([]extractor.PackageDetails, error) {
return extractor.ExtractFromFile(pathToLockfile, GradleExtractor)
}
//nolint:gochecknoinits
func init() {
extractor.RegisterExtractor(models.GradleFilePath, GradleExtractor)
}