@socketsecurity/cli-with-sentry 1.17.0 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +5 -5
  3. package/dist/.config/tsconfig.dts.tsbuildinfo +1 -1
  4. package/dist/cli.js +426 -257
  5. package/dist/cli.js.map +1 -1
  6. package/dist/constants.js +4 -4
  7. package/dist/constants.js.map +1 -1
  8. package/dist/types/commands/fix/generated-socket-facts.d.mts +3 -2
  9. package/dist/types/commands/manifest/build-root-config.d.mts +18 -1
  10. package/dist/types/commands/manifest/generate-recursive-manifests.d.mts +3 -1
  11. package/dist/types/commands/manifest/run-manifest-facts.d.mts +4 -0
  12. package/dist/types/commands/manifest/scripts/build-tool.d.mts +0 -4
  13. package/dist/types/commands/manifest/setup-manifest-config.d.mts +9 -1
  14. package/dist/types/constants.d.mts +1 -1
  15. package/dist/types/utils/coana.d.mts +0 -2
  16. package/dist/types/utils/socket-json.d.mts +38 -0
  17. package/dist/utils.js +201 -29
  18. package/dist/utils.js.map +1 -1
  19. package/package.json +1 -3
  20. package/dist/manifest-scripts/dotnet-tool/Microsoft.Build.Locator.dll +0 -0
  21. package/dist/manifest-scripts/dotnet-tool/socket-facts-dotnet.deps.json +0 -42
  22. package/dist/manifest-scripts/dotnet-tool/socket-facts-dotnet.dll +0 -0
  23. package/dist/manifest-scripts/dotnet-tool/socket-facts-dotnet.dll.config +0 -623
  24. package/dist/manifest-scripts/dotnet-tool/socket-facts-dotnet.runtimeconfig.json +0 -15
  25. package/dist/manifest-scripts/maven-extension/coana-maven-extension.jar +0 -0
  26. package/dist/manifest-scripts/socket-facts.init.gradle +0 -832
  27. package/dist/manifest-scripts/socket-facts.plugin.scala +0 -1018
  28. package/dist/manifest-scripts/socket-workspaces.init.gradle +0 -123
  29. package/dist/manifest-scripts/socket-workspaces.plugin.scala +0 -147
  30. package/dist/types/commands/manifest/scripts/assemble.d.mts +0 -14
  31. package/dist/types/commands/manifest/scripts/exclude-paths-glob.d.mts +0 -8
  32. package/dist/types/commands/manifest/scripts/facts.d.mts +0 -111
  33. package/dist/types/commands/manifest/scripts/records.d.mts +0 -124
  34. package/dist/types/commands/manifest/scripts/resolution-report-gradle.d.mts +0 -10
  35. package/dist/types/commands/manifest/scripts/resolution-report-ivy.d.mts +0 -6
  36. package/dist/types/commands/manifest/scripts/resolution-report-maven.d.mts +0 -7
  37. package/dist/types/commands/manifest/scripts/resolution-report-nuget.d.mts +0 -6
  38. package/dist/types/commands/manifest/scripts/resolution-report-render.d.mts +0 -63
  39. package/dist/types/commands/manifest/scripts/resolution-report.d.mts +0 -28
  40. package/dist/types/commands/manifest/scripts/run.d.mts +0 -67
  41. package/dist/types/commands/manifest/scripts/sidecar.d.mts +0 -60
  42. package/dist/types/commands/manifest/scripts/test/assemble-records.d.mts +0 -1
@@ -1,832 +0,0 @@
1
- // Invoke via:
2
- // ./gradlew --init-script socket-facts.init.gradle socketFacts
3
-
4
- import java.util.Collections
5
-
6
- // Emits a flat line-protocol RECORDS file (NOT the final .socket.facts.json, and NOT to stdout). The
7
- // TS assembler (utils/src/manifest-scripts/assemble.ts) reads the records and owns all SBOM
8
- // construction — graph merge and per-subproject classpaths. This script only RESOLVES and emits
9
- // raw facts. See records.ts for the record grammar.
10
-
11
- // `Project.findProperty` only exists since Gradle 2.13; fall back to hasProperty/property for older Gradle.
12
- gradle.ext.socketProp = { proj, name -> proj.hasProperty(name) ? proj.property(name) : null }
13
-
14
- // `-Psocket.excludePaths` → PRE-COMPILED, comma-joined, anchored regex pattern sources, used only
15
- // to skip whole excluded subprojects (source-file-level exclusion is left to the reachability
16
- // analysis). The CLI compiles the user-facing globs in exclude-paths-glob.mts (the single glob
17
- // implementation, tested in CI); this script only Pattern.compile()s what it receives.
18
- gradle.ext.socketExcludeMatchersCache = null
19
- gradle.ext.socketExcludeMatchers = {
20
- if (gradle.ext.socketExcludeMatchersCache != null) return gradle.ext.socketExcludeMatchersCache
21
- def raw = gradle.socketProp.call(gradle.rootProject, 'socket.excludePaths')?.toString()
22
- def patterns = []
23
- if (raw != null && !raw.trim().isEmpty()) {
24
- raw.split(',').each { r ->
25
- def p = r.trim()
26
- if (!p.isEmpty()) {
27
- // A pattern that doesn't compile is dropped, never thrown: the CLI emits a
28
- // dialect-portable subset, so this only guards against a broken transport.
29
- try { patterns << java.util.regex.Pattern.compile(p) }
30
- catch (java.util.regex.PatternSyntaxException ignored) { }
31
- }
32
- }
33
- }
34
- gradle.ext.socketExcludeMatchersCache = patterns
35
- patterns
36
- }
37
- gradle.ext.socketIsExcluded = { String rel ->
38
- def c = (rel == null ? '' : rel).replace('\\', '/')
39
- while (c.startsWith('./')) { c = c.substring(2) }
40
- while (c.startsWith('/')) { c = c.substring(1) }
41
- while (c.endsWith('/')) { c = c.substring(0, c.length() - 1) }
42
- if (c.isEmpty()) { return false }
43
- gradle.ext.socketExcludeMatchers.call().any { p -> p.matcher(c).matches() }
44
- }
45
- // `-Psocket.excludeBase` (the scan root; the root project's dir by default) anchors `--exclude-paths`:
46
- // a project relocated outside the build root still matches, one outside the scan root never does.
47
- gradle.ext.socketExcludeBaseCache = null
48
- gradle.ext.socketIsExcludedDir = { java.io.File dir ->
49
- if (gradle.ext.socketExcludeMatchers.call().isEmpty()) { return false }
50
- if (gradle.ext.socketExcludeBaseCache == null) {
51
- def base = gradle.socketProp.call(gradle.rootProject, 'socket.excludeBase')?.toString()
52
- gradle.ext.socketExcludeBaseCache = (base ? new java.io.File(base) : gradle.rootProject.projectDir).canonicalFile.toPath()
53
- }
54
- def path = dir.canonicalFile.toPath()
55
- // On another Windows drive than the scan root, so outside it.
56
- if (path.root != gradle.ext.socketExcludeBaseCache.root) { return false }
57
- def rel = gradle.ext.socketExcludeBaseCache.relativize(path).toString().replace(File.separator, '/')
58
- !(rel == '..' || rel.startsWith('../')) && gradle.ext.socketIsExcluded.call(rel.isEmpty() ? '.' : rel)
59
- }
60
-
61
- // Synchronized collections so --parallel-enabled builds don't race; lives on gradle.ext so every
62
- // collector and the root aggregator share one instance.
63
- gradle.ext.socketFactsState = [
64
- nodes : Collections.synchronizedMap([:]),
65
- directIds : Collections.synchronizedSet([] as Set),
66
- // `detail` is the build tool's failure message verbatim; Coana classifies the failure KIND from it.
67
- failures : Collections.synchronizedList([]),
68
- // Whole configs whose resolution threw (vs a single unresolved dep in `failures`).
69
- unscannable : Collections.synchronizedList([]),
70
- scannedConfigs : Collections.synchronizedSet([] as Set),
71
- // Only populated with `-Psocket.withFiles=true`: reading `artifact.file` downloads the artifact.
72
- paths : Collections.synchronizedMap([:]),
73
- perSub : Collections.synchronizedMap([:]),
74
- projectsInfo : Collections.synchronizedList([]),
75
- // Project path -> the module's real artifact extension (e.g. jar), so an intra-project dep that
76
- // resolves without selecting a published artifact still gets its true coordinate, not ext-less.
77
- projectArtifactExt : Collections.synchronizedMap([:]),
78
- // Project path -> "group:name", to tell this build's projects from an included build's.
79
- projectGaByPath : Collections.synchronizedMap([:]),
80
- // Project path -> "group:name:version", the coordinate a failed project dependency is reported by.
81
- projectGavByPath : Collections.synchronizedMap([:]),
82
- ]
83
-
84
- // Capture every project's identity before collectors run so they can recognize intra-project deps
85
- // without an ordering dependency on other subprojects.
86
- gradle.projectsEvaluated { g ->
87
- def rootPath = g.rootProject.projectDir.toPath()
88
- // '/'-normalized so values are stable across OSes and portable to another machine.
89
- def rel = { java.io.File f ->
90
- def r = rootPath.relativize(f.toPath()).toString().replace(File.separator, '/')
91
- r.isEmpty() ? '.' : r
92
- }
93
- g.rootProject.allprojects.each { p ->
94
- // The module's real artifact extension (jar for java; '' for a project that builds no archive,
95
- // e.g. a pure aggregator). Used to stamp intra-project deps that resolve without an artifact.
96
- def artExt = ''
97
- try {
98
- def jt = p.tasks.findByName('jar')
99
- if (jt != null) {
100
- artExt = 'jar'
101
- try { def e = jt.archiveExtension.getOrNull(); if (e) artExt = e } catch (Exception ig1) {
102
- try { def e = jt.extension; if (e) artExt = e } catch (Exception ig2) {}
103
- }
104
- }
105
- } catch (Exception ignore) {}
106
- g.socketFactsState.projectArtifactExt[p.path] = artExt
107
- g.socketFactsState.projectGaByPath[p.path] = "${p.group ?: ''}:${p.name}".toString()
108
- g.socketFactsState.projectGavByPath[p.path] = "${p.group ?: ''}:${p.name}:${p.version ?: ''}".toString()
109
- // A wholly excluded subproject emits no project record and its configs are never resolved (see the
110
- // collector). The project maps above stay populated so a KEPT project depending on it
111
- // still recognizes it as a first-party module, and its paths are kept so it is analysed with its code.
112
- def excluded = g.ext.socketIsExcludedDir.call(p.projectDir)
113
- // Guarded: projects without the java `sourceSets` convention (pure aggregators) contribute empty
114
- // lists rather than failing. Kotlin and Android code lives outside it (see below).
115
- // ALL source sets are emitted (not just main/test) so custom ones (integrationTest,
116
- // functionalTest, ...) reach the analysis; source-file-level exclusion is coana's job.
117
- // `classesDirs` (Gradle 4+) falls back to the legacy single `classesDir` on older Gradle.
118
- def sources = [] as Set
119
- def targets = [] as Set
120
- try {
121
- if (p.hasProperty('sourceSets')) {
122
- p.sourceSets.each { ss ->
123
- if (ss != null) {
124
- ss.allSource.srcDirs.each { d -> sources << d.absolutePath }
125
- try {
126
- ss.output.classesDirs.each { d -> targets << d.absolutePath }
127
- } catch (Exception e1) {
128
- try { targets << ss.output.classesDir.absolutePath } catch (Exception ignore) {}
129
- }
130
- }
131
- }
132
- }
133
- } catch (Exception ignore) {}
134
- // Kotlin compilations for the JVM (kotlin-jvm, KMP `jvm()`, Android): Kotlin source sets, shared
135
- // ones like commonMain included, are not java source sets. Untyped: KGP is not on this classpath.
136
- def kotlin = p.extensions.findByName('kotlin')
137
- if (kotlin != null) {
138
- try {
139
- (kotlin.hasProperty('targets') ? kotlin.targets : [kotlin.target]).each { t ->
140
- try {
141
- if (t.platformType.name() in ['jvm', 'androidJvm']) {
142
- t.compilations.each { c ->
143
- c.allKotlinSourceSets.each { ks ->
144
- sources.addAll(ks.kotlin.srcDirs*.absolutePath)
145
- sources.addAll(ks.resources.srcDirs*.absolutePath)
146
- }
147
- targets.addAll(c.output.classesDirs*.absolutePath)
148
- }
149
- }
150
- } catch (Exception ignore) {}
151
- }
152
- } catch (Exception ignore) {}
153
- }
154
- // AGP keeps its source sets in the `android` extension and leaves the java ones empty.
155
- def android = p.extensions.findByName('android')
156
- if (android != null) {
157
- try {
158
- android.sourceSets.each { ss ->
159
- try {
160
- sources.addAll(ss.java.srcDirs*.absolutePath)
161
- sources.addAll(ss.resources.srcDirs*.absolutePath)
162
- // Last: older AGP has no `kotlin`.
163
- sources.addAll(ss.kotlin.srcDirs*.absolutePath)
164
- } catch (Exception ignore) {}
165
- }
166
- } catch (Exception ignore) {}
167
- // Class dirs come from the compile tasks: AGP's built-in Kotlin (AGP 9) leaves the Kotlin
168
- // compilations' classesDirs empty.
169
- def compileTypes = [JavaCompile]
170
- if (kotlin != null) {
171
- try {
172
- compileTypes << Class.forName('org.jetbrains.kotlin.gradle.tasks.KotlinCompileTool', false, kotlin.getClass().classLoader)
173
- } catch (Throwable ignore) {}
174
- }
175
- compileTypes.each { type ->
176
- try {
177
- p.tasks.withType(type).each { t ->
178
- try {
179
- targets << t.destinationDirectory.get().asFile.absolutePath
180
- } catch (Exception e1) {
181
- try { targets << t.destinationDir.absolutePath } catch (Exception ignore) {}
182
- }
183
- }
184
- } catch (Exception ignore) {}
185
- }
186
- }
187
- // `buildFile` is the configured script, absent on disk for a project configured from the root or
188
- // a convention plugin. Still emitted: a direct dependency's mark must name its subproject.
189
- def buildFiles = []
190
- try {
191
- def bf = p.buildFile
192
- if (bf != null) buildFiles << rel(bf)
193
- } catch (Exception ignore) {}
194
- g.socketFactsState.projectsInfo.add([
195
- path : p.path,
196
- group : (p.group ?: '').toString(),
197
- name : p.name,
198
- version: (p.version ?: '').toString(),
199
- dir : rel(p.projectDir),
200
- sources: (sources as List).sort(),
201
- targets: (targets as List).sort(),
202
- buildFiles: buildFiles,
203
- excluded: excluded,
204
- ])
205
- }
206
- }
207
-
208
- allprojects { project ->
209
- def collectTask = project.tasks.create('socketFactsCollect') {
210
- description = "Resolves ${project.path}'s configurations into the build-wide Socket facts accumulator"
211
- // Dependency resolution depends on state Gradle's up-to-date tracking can't represent reliably.
212
- outputs.upToDateWhen { false }
213
-
214
- doLast {
215
- def state = gradle.socketFactsState
216
- // Skip resolving a wholly excluded subproject: `--exclude-paths` covering its dir means we don't
217
- // resolve for it at all (matches the project-record skip in projectsEvaluated).
218
- if (gradle.ext.socketIsExcludedDir.call(project.projectDir)) {
219
- return
220
- }
221
- // Per-RESOLUTION-ROOT accumulators, LOCAL to this collector: one (subproject, configuration)
222
- // classpath resolved into its own coordinate-keyed tree. Reassigned per config below (the
223
- // visit/upsertNode closures capture them); `failures`/`scannedConfigs` stay shared.
224
- def nodes = [:]
225
- def directIds = [] as Set
226
- def configName = ''
227
- // "group:name:version" -> path of the build project this config resolved it to.
228
- def projectByGav = [:]
229
- def failures = state.failures
230
- def scannedConfigs = state.scannedConfigs
231
- def projectArtifactExt = state.projectArtifactExt
232
- def paths = [:]
233
- // Ids of nodes whose requested artifact yielded no file.
234
- def unfetched = [] as Set
235
- def withFiles = gradle.socketProp.call(project, 'socket.withFiles')?.toString()?.toLowerCase() == 'true'
236
- // Optional `-Psocket.populateFilesFor=<file>` (newline-delimited GAVs): scope `--with-files`
237
- // materialization to those GAVs. This run walks EVERY resolvable config (not told the SBOM's
238
- // include/exclude), so without a scope it would force-download the build's entire dep universe.
239
- // Matched at GAV level to tolerate untrustworthy-ext SBOMs (lockfile / version catalog hardcode
240
- // ext=jar). Absent/empty/missing file -> materialize all. Parsed once under the state monitor.
241
- def populateFilesFor = gradle.socketProp.call(project, 'socket.populateFilesFor')?.toString()
242
- def populateGavs = null
243
- if (withFiles && populateFilesFor != null && !populateFilesFor.trim().isEmpty()) {
244
- synchronized (state) {
245
- if (!state.containsKey('populateGavs')) {
246
- def f = new File(populateFilesFor.trim())
247
- if (f.exists()) {
248
- def set = [] as Set
249
- f.eachLine { line -> def t = line.trim(); if (!t.isEmpty()) { set << t } }
250
- if (set.isEmpty()) {
251
- // Empty file is more likely a wiring slip than a deliberate "fetch nothing"; materialize all.
252
- state.populateGavs = null
253
- println "[socket-facts] WARN populateFilesFor file empty; materializing files for all resolved artifacts"
254
- } else {
255
- state.populateGavs = set
256
- println "[socket-facts] --with-files scoped to ${set.size()} SBOM artifact(s)"
257
- }
258
- } else {
259
- // Missing file is more likely a wiring bug than an intentional empty scope; materialize all.
260
- state.populateGavs = null
261
- println "[socket-facts] WARN populateFilesFor file not found; materializing files for all resolved artifacts"
262
- }
263
- }
264
- }
265
- populateGavs = state.populateGavs
266
- }
267
-
268
- // Full Maven coordinate (absent segments dropped) — each ext/classifier variant is its own
269
- // component; the id is the coordinate key reachability joins on (see mavenCoordinateKey).
270
- def coordId = { coord ->
271
- [coord.groupId, coord.artifactId, coord.ext, coord.classifier, coord.version].findAll { it }.join(':')
272
- }
273
-
274
- // A first-party module dep can resolve with no published artifact (classes-dir variant, or
275
- // variant-ambiguous moduleArtifacts), leaving it ext-less. Stamp the module's real artifact
276
- // extension so it keeps a full, stable coordinate instead of an ext-less one.
277
- def effExt = { String projPath, String ext ->
278
- if ((ext == null || ext.isEmpty()) && projPath != null) {
279
- projectArtifactExt[projPath] ?: ''
280
- } else {
281
- ext ?: ''
282
- }
283
- }
284
-
285
- // A node is created once; its prod flag accumulates (OR) across the configs that reach it.
286
- def upsertNode = { Map coord, boolean isProd, String projPath ->
287
- def id = coordId(coord)
288
- synchronized (nodes) {
289
- def node = nodes[id]
290
- if (node == null) {
291
- node = [coord: coord, children: [] as Set, prod: false, project: projPath]
292
- nodes[id] = node
293
- }
294
- if (isProd) {
295
- node.prod = true
296
- }
297
- }
298
- id
299
- }
300
-
301
- def causeMessages = { problem ->
302
- def out = []
303
- def t = problem
304
- int guard = 0
305
- while (t != null && guard++ < 12) { out << t.message; t = t.cause }
306
- out
307
- }
308
-
309
- // The deepest cause's full message: the TS report classifies it, so nothing is categorized here.
310
- def rawDetail = { problem ->
311
- def messages = causeMessages(problem).findAll { it }
312
- return (messages ? messages[-1] : 'unknown resolution failure').toString().trim()
313
- }
314
-
315
- def recordFailure = { String coord, String detail ->
316
- failures << [coord: coord, detail: detail, config: configName, project: project.path]
317
- }
318
-
319
- // Walk a resolved dependency and its transitive closure. We never touch `artifact.file` here —
320
- // that forces Gradle to download the file (catastrophic on builds declaring distribution
321
- // archives as deps); `artifact.extension`/`artifact.classifier` read already-resolved metadata.
322
- // Intra-project deps (project(':lib')) ARE emitted and recursed, so an external the consumer
323
- // pins/forces to a different version THROUGH the edge is captured (firstLevelModuleDependencies
324
- // lists only declared deps, so a project dep's transitives are reachable only via the edge).
325
- def visit
326
- visit = { dep, boolean isProd, Map cache ->
327
- if (cache.containsKey(dep)) {
328
- return cache[dep]
329
- }
330
- // Pre-populate the cache to break cycles before we recurse.
331
- def producedIds = [] as Set
332
- cache[dep] = producedIds
333
-
334
- // `moduleArtifacts` forces ARTIFACT-level variant selection, which can throw on a
335
- // variant-ambiguous dep even when the dependency GRAPH resolves fine. Guard per-dep: on
336
- // failure keep walking so one ambiguous artifact can't sink the config.
337
- def gav = "${dep.moduleGroup ?: ''}:${dep.moduleName}:${dep.moduleVersion ?: ''}".toString()
338
- def shouldMaterialize = withFiles && (populateGavs == null || populateGavs.contains(gav))
339
- def projPath = projectByGav[gav]
340
- def artifacts
341
- def artifactsError = null
342
- try {
343
- artifacts = dep.moduleArtifacts
344
- } catch (Exception e) {
345
- artifacts = [] as Set
346
- artifactsError = e
347
- }
348
- if (artifactsError != null && projPath == null) {
349
- // No artifact was selected, so there is no coordinate to emit: report the module and
350
- // bubble its children up (below), as for a skipped first-party module.
351
- recordFailure(gav, rawDetail(artifactsError))
352
- } else if (artifacts.isEmpty()) {
353
- def ext = effExt(projPath, '')
354
- // Skip a no-artifact first-party module (aggregator / build root): it builds no archive, so
355
- // it's fully described by `projects` and is never a real artifact dependency.
356
- if (!(ext.isEmpty() && projPath != null)) {
357
- producedIds << upsertNode([
358
- groupId : dep.moduleGroup ?: '',
359
- artifactId: dep.moduleName,
360
- version : dep.moduleVersion ?: '',
361
- classifier: '',
362
- ext : ext,
363
- ], isProd, projPath)
364
- }
365
- } else {
366
- artifacts.each { a ->
367
- // Directory variants (java-classes-directory etc.) carry no extension; for a first-party
368
- // module fall back to its real artifact ext (never artifact.type, a Gradle variant attr).
369
- def ext = effExt(projPath, a.extension)
370
- // Skip a no-artifact first-party module (see the empty-artifacts branch above).
371
- if (ext.isEmpty() && projPath != null) return
372
- def aid = upsertNode([
373
- groupId : dep.moduleGroup ?: '',
374
- artifactId: dep.moduleName,
375
- version : dep.moduleVersion ?: '',
376
- classifier: a.classifier ?: '',
377
- ext : ext,
378
- ], isProd, projPath)
379
- producedIds << aid
380
- // `a.file` downloads the artifact if not already cached, so scoping avoids fetching
381
- // artifacts the SBOM doesn't reference. Per-artifact try/catch: a single download can
382
- // fail without the whole config being unresolvable.
383
- if (shouldMaterialize) {
384
- try {
385
- def path = a.file.absolutePath
386
- synchronized (paths) {
387
- def set = paths[aid]
388
- if (set == null) { set = [] as Set; paths[aid] = set }
389
- set << path
390
- }
391
- } catch (Exception e) {
392
- println "[socket-facts] could not materialize ${aid}: ${rawDetail(e).readLines().find()}"
393
- // A requested artifact that yields no file is a failure: without one, the dependency
394
- // would read as resolved with nothing to analyse.
395
- if (projPath == null) {
396
- recordFailure(gav, rawDetail(e))
397
- unfetched << aid
398
- }
399
- }
400
- }
401
- }
402
- }
403
-
404
- def childIds = [] as Set
405
- dep.children.each { child ->
406
- childIds.addAll(visit(child, isProd, cache))
407
- }
408
- // A skipped no-artifact first-party module, or a module whose artifacts could not be
409
- // selected, produced no node, so bubble its resolved children up to the parent (return
410
- // childIds); otherwise the module's transitives would be attached to nothing.
411
- if (producedIds.isEmpty()) {
412
- cache[dep] = childIds
413
- return childIds
414
- }
415
- synchronized (nodes) {
416
- producedIds.each { pid ->
417
- // Drop self-edges: a project that depends on its own output (test → main) can resolve
418
- // to the same coordinate as its root, which would otherwise emit a node listing itself.
419
- nodes[pid].children.addAll(childIds.findAll { it != pid })
420
- }
421
- }
422
- producedIds
423
- }
424
-
425
- def isTestConfig = { String name -> name.toLowerCase().contains('test') }
426
- // Matches real compile/runtime classpaths (modern `*Classpath`, legacy `compile`/`runtime`),
427
- // NOT a loose substring that would wrongly promote war-plugin `providedCompile`/`providedRuntime`
428
- // (provided deps are dev). Sets the informational `dev` flag only — never gates analysis.
429
- def isClasspathConfig = { String name ->
430
- def n = name.toLowerCase()
431
- n.contains('classpath') || n == 'compile' || n == 'runtime'
432
- }
433
-
434
- // Config-name glob to a case-SENSITIVE regex (matching is documented as case-sensitive).
435
- // Supports `*`, `?`, and `[...]` character classes: enumerations (`[cC]`), ranges (`[a-z]`),
436
- // and `[!..]`/`[^..]` negation. A malformed glob falls back to a literal match, never throws.
437
- def globToRegex = { String glob ->
438
- def sb = new StringBuilder()
439
- int i = 0
440
- int n = glob.length()
441
- while (i < n) {
442
- def ch = glob[i]
443
- if (ch == '*') { sb << '.*'; i++ }
444
- else if (ch == '?') { sb << '.'; i++ }
445
- else if (ch == '[') {
446
- int j = glob.indexOf(']', i + 1)
447
- // Treat as a class only with a non-empty body; else a literal `[`.
448
- if (j <= i + 1) { sb << '\\['; i++ }
449
- else {
450
- def body = glob.substring(i + 1, j)
451
- boolean neg = body.startsWith('!')
452
- if (neg) { body = body.substring(1) }
453
- // Only literal chars and `-` ranges are meaningful; neutralize regex-class tricks.
454
- body = body.replace('\\', '\\\\').replace('[', '\\[').replace('&', '\\&')
455
- sb << '[' << (neg ? '^' : '') << body << ']'
456
- i = j + 1
457
- }
458
- }
459
- else if ('.\\^$|+(){}]'.contains(ch)) { sb << '\\' << ch; i++ }
460
- else { sb << ch; i++ }
461
- }
462
- try {
463
- java.util.regex.Pattern.compile(sb.toString())
464
- } catch (java.util.regex.PatternSyntaxException e) {
465
- java.util.regex.Pattern.compile(java.util.regex.Pattern.quote(glob))
466
- }
467
- }
468
-
469
- // `-Psocket.includeConfigs`/`-Psocket.excludeConfigs`: comma-separated config-name globs. A
470
- // config is walked when it matches some include (or there are none) AND matches no exclude.
471
- def parsePatterns = { String s ->
472
- def out = []
473
- if (s != null && !s.trim().isEmpty()) {
474
- s.split(',').each { raw ->
475
- def p = raw.trim()
476
- if (!p.isEmpty()) out << globToRegex(p)
477
- }
478
- }
479
- out
480
- }
481
- def includePatterns = parsePatterns(gradle.socketProp.call(project, 'socket.includeConfigs')?.toString())
482
- def excludePatterns = parsePatterns(gradle.socketProp.call(project, 'socket.excludeConfigs')?.toString())
483
-
484
- // Don't filter by canBeConsumed: Gradle defaults both role flags to true, so a plain resolvable
485
- // config is also consumable, and excluding consumable configs would drop legitimate custom ones.
486
- // `isCanBeResolved` only exists since Gradle 3.3; older Gradle has no split (all resolvable).
487
- def isResolvable = { c -> c.metaClass.respondsTo(c, 'isCanBeResolved') ? c.canBeResolved : true }
488
- def targetConfigs = project.configurations.findAll {
489
- if (!isResolvable(it)) return false
490
- def name = it.name
491
- if (excludePatterns.any { p -> p.matcher(name).matches() }) return false
492
- if (!includePatterns.isEmpty() && !includePatterns.any { p -> p.matcher(name).matches() }) return false
493
- return true
494
- }
495
-
496
- // A failed edge is reported by the selector Gradle ATTEMPTED (after forces and substitutions).
497
- // A project of this build is named by its own coordinate, as its resolved node would be.
498
- def selectorCoord = { sel ->
499
- if (sel instanceof org.gradle.api.artifacts.component.ModuleComponentSelector) {
500
- return "${sel.group}:${sel.module}${sel.version ? ':' + sel.version : ''}".toString()
501
- }
502
- if (sel instanceof org.gradle.api.artifacts.component.ProjectComponentSelector) {
503
- def build = sel.metaClass.respondsTo(sel, 'getBuildPath') ? sel.buildPath :
504
- sel.metaClass.respondsTo(sel, 'getBuildName') ? sel.buildName : ':'
505
- def gav = build == ':' ? state.projectGavByPath[sel.projectPath] : null
506
- if (gav != null) {
507
- return gav
508
- }
509
- }
510
- sel.displayName.toString()
511
- }
512
-
513
- // Gradle verifies only artifact-set reads, never the walk's `ResolvedArtifact.file`, and fails
514
- // them with every fatal failure so far; only STRICT throws, from 6.2, with the root build's metadata.
515
- def rootBuild = gradle
516
- while (rootBuild.parent != null) {
517
- rootBuild = rootBuild.parent
518
- }
519
- def startParameter = gradle.startParameter
520
- def verifyArtifacts = withFiles &&
521
- new File(rootBuild.rootProject.rootDir, 'gradle/verification-metadata.xml').isFile() &&
522
- startParameter.metaClass.respondsTo(startParameter, 'getDependencyVerificationMode') &&
523
- startParameter.dependencyVerificationMode.toString() == 'STRICT'
524
- def gavOf = { Map c -> "${c.groupId}:${c.artifactId}:${c.version}".toString() }
525
- def verificationMessage = { Throwable e ->
526
- causeMessages(e).find { it?.startsWith('Dependency verification failed') }
527
- }
528
- // Old Gradle splits a module into one ResolvedDependency per target configuration, of which only
529
- // some carry its artifacts: an artifact-less one is the same component, so fold it into them.
530
- def foldArtifactless = {
531
- if (!nodes.values().any { n -> !n.coord.ext && n.project == null }) {
532
- return
533
- }
534
- def withExt = [:]
535
- nodes.each { id, n ->
536
- if (n.coord.ext) {
537
- withExt.get(gavOf(n.coord), []) << id
538
- }
539
- }
540
- def folds = [:]
541
- nodes.each { id, n ->
542
- def siblings = (!n.coord.ext && n.project == null) ? withExt[gavOf(n.coord)] : null
543
- if (siblings) {
544
- folds[id] = siblings
545
- }
546
- }
547
- if (folds.isEmpty()) {
548
- return
549
- }
550
- def replaced = { Collection ids -> ids.collectMany { c -> folds[c] ?: [c] } }
551
- folds.each { id, siblings ->
552
- def folded = nodes.remove(id)
553
- siblings.each { sid ->
554
- nodes[sid].children.addAll(replaced(folded.children).findAll { it != sid })
555
- if (folded.prod) {
556
- nodes[sid].prod = true
557
- }
558
- }
559
- }
560
- nodes.each { nid, n ->
561
- if (n.children.any { folds.containsKey(it) }) {
562
- def children = replaced(n.children).findAll { it != nid }
563
- n.children.clear()
564
- n.children.addAll(children)
565
- }
566
- }
567
- def direct = replaced(directIds)
568
- directIds.clear()
569
- directIds.addAll(direct)
570
- }
571
-
572
- // Drops the files of this config's artifacts that failed verification and reports them.
573
- def checkVerification = { cfg ->
574
- def external = paths.keySet().findAll { id -> nodes[id].project == null }
575
- if (external.isEmpty()) {
576
- return
577
- }
578
- def fetched = external.collect { id -> gavOf(nodes[id].coord) } as Set
579
- def message = null
580
- try {
581
- cfg.incoming.artifactView {
582
- lenient(true)
583
- componentFilter { id ->
584
- id instanceof org.gradle.api.artifacts.component.ModuleComponentIdentifier &&
585
- fetched.contains("${id.group}:${id.module}:${id.version}".toString())
586
- }
587
- }.artifacts.each { it.file }
588
- } catch (Exception e) {
589
- message = verificationMessage(e)
590
- if (message == null) {
591
- // Any other failure concerns files the walk already read without it.
592
- println "[socket-facts] could not check artifact verification for ${cfg.name}: ${rawDetail(e).readLines().find()}"
593
- }
594
- }
595
- if (message == null) {
596
- return
597
- }
598
- // Each failed artifact is named by its identifier's display name, "<file> (<group>:<module>:<version>)",
599
- // whose file part is `<name>-<version>[-<classifier>].<ext>` rather than the cached file's own name.
600
- def artifactRef = /(\S+) \(([^\s():]+):([^\s():]+):([^\s()]+)\)/
601
- def lines = message.readLines()
602
- def header = lines ? lines[0] : ''
603
- // The verbose report (the Socket CLI sets org.gradle.dependency.verification.console=verbose) gives
604
- // each artifact's problems: "On artifact <ref> in repository '<repo>': <problem>", or "On artifact
605
- // <ref> multiple problems reported:" followed by one "in repository '<repo>': <problem>" line each.
606
- def failed = []
607
- def current = null
608
- lines.each { raw ->
609
- def line = raw.trim().replaceFirst(/^- /, '')
610
- def m = line =~ ('^On artifact ' + artifactRef + ' (.*)$')
611
- if (m.matches()) {
612
- current = [gav: "${m.group(2)}:${m.group(3)}:${m.group(4)}".toString(), file: m.group(1), problems: []]
613
- failed << current
614
- if (m.group(5) != 'multiple problems reported:') {
615
- current.problems << m.group(5)
616
- }
617
- } else if (current != null && line.startsWith("in repository '")) {
618
- current.problems << line
619
- } else {
620
- current = null
621
- }
622
- }
623
- failed.each { f ->
624
- f.detail = ([header] + f.problems.collect { "On artifact ${f.file} (${f.gav}) ${it}" }).join('\n')
625
- }
626
- if (failed.isEmpty()) {
627
- // The summary report names only the artifacts.
628
- (message =~ artifactRef).each { m ->
629
- failed << [gav: "${m[2]}:${m[3]}:${m[4]}".toString(), file: m[1], detail: message]
630
- }
631
- }
632
- def markUnfetched = { Collection ids ->
633
- ids.each { id ->
634
- paths.remove(id)
635
- unfetched << id
636
- }
637
- }
638
- if (failed.isEmpty()) {
639
- // No artifact can be told apart: the walked graph stands, without any of its external files.
640
- state.unscannable << [config: cfg.name, detail: message, project: project.path]
641
- markUnfetched(external)
642
- return
643
- }
644
- failed.each { f ->
645
- def ids = external.findAll { id -> gavOf(nodes[id].coord) == f.gav }
646
- // A failed metadata file (pom, module) names none of the module's artifacts: all are suspect.
647
- // A failed artifact this config did not fetch leaves it untouched.
648
- def hit = (f.file.endsWith('.pom') || f.file.endsWith('.module')) ? ids : ids.findAll { id ->
649
- def c = nodes[id].coord
650
- def named = "${c.artifactId}-${c.version}${c.classifier ? '-' + c.classifier : ''}${c.ext ? '.' + c.ext : ''}"
651
- f.file == named.toString() || paths[id]?.any { p -> f.file == new File(p).name }
652
- }
653
- if (!hit.isEmpty()) {
654
- recordFailure(f.gav, f.detail)
655
- markUnfetched(hit)
656
- }
657
- }
658
- }
659
-
660
- targetConfigs.each { cfg ->
661
- // Recorded even if it resolves nothing or throws — Coana surfaces the full scanned set.
662
- scannedConfigs.add(cfg.name)
663
- // Informational only (OR-accumulated across configs); never gates analysis, so this name
664
- // heuristic can only mis-bucket a dep in prod/dev views, never drop it.
665
- def isProd = isClasspathConfig(cfg.name) && !isTestConfig(cfg.name)
666
- // Fresh tree for THIS resolution root — captured by visit/upsertNode, so no union with siblings.
667
- nodes = [:]
668
- directIds = [] as Set
669
- configName = cfg.name
670
- paths = [:]
671
- unfetched = [] as Set
672
- projectByGav = [:]
673
- // Per-config try/catch: AGP-style configs can fail variant ambiguity from an init-script
674
- // context lacking the consumer attributes AGP sets internally.
675
- def walked = false
676
- try {
677
- def lenient = cfg.resolvedConfiguration.lenientConfiguration
678
- // The resolution graph names a project dependency by project path; within one graph a
679
- // module resolves to a single component, so its GAV identifies that project here.
680
- cfg.incoming.resolutionResult.allComponents.each { comp ->
681
- def cid = comp.id
682
- def mv = comp.moduleVersion
683
- if (cid instanceof org.gradle.api.artifacts.component.ProjectComponentIdentifier && mv != null &&
684
- state.projectGaByPath[cid.projectPath] == "${mv.group ?: ''}:${mv.name}".toString()) {
685
- projectByGav["${mv.group ?: ''}:${mv.name}:${mv.version ?: ''}".toString()] = cid.projectPath
686
- }
687
- }
688
- def cache = [:]
689
- // No-arg getter only since Gradle 3.3; older Gradle has just the Spec-taking overload.
690
- def firstLevel
691
- try {
692
- firstLevel = lenient.firstLevelModuleDependencies
693
- } catch (MissingPropertyException e) {
694
- firstLevel = lenient.getFirstLevelModuleDependencies({ true } as org.gradle.api.specs.Spec)
695
- }
696
- firstLevel.each { dep ->
697
- directIds.addAll(visit(dep, isProd, cache))
698
- }
699
- foldArtifactless()
700
- // Unresolved deps drive the root aggregator's abort/warn decision but are NOT emitted as
701
- // nodes — their selector-only coordinates would surface as half-formed phantom artifacts.
702
- // hasError() covers every unresolved dependency, project ones included.
703
- if (cfg.resolvedConfiguration.hasError()) {
704
- def reported = [] as Set
705
- cfg.incoming.resolutionResult.allDependencies.each { d ->
706
- if (d instanceof org.gradle.api.artifacts.result.UnresolvedDependencyResult) {
707
- def coord = selectorCoord(d.attempted ?: d.requested)
708
- if (reported.add(coord)) {
709
- recordFailure(coord, rawDetail(d.failure))
710
- }
711
- }
712
- }
713
- }
714
- if (verifyArtifacts) {
715
- checkVerification(cfg)
716
- }
717
- walked = true
718
- } catch (Exception e) {
719
- // A config-LEVEL resolution failure (a resolutionStrategy/beforeResolve rule that throws,
720
- // an artifact-transform failure, a broken repository, ...) rather than a per-dep failure.
721
- // Record it instead of swallowing; the build still exits cleanly and the TS layer surfaces it.
722
- state.unscannable << [config: cfg.name, detail: rawDetail(e), project: project.path]
723
- }
724
- // Stash this resolution root's tree; the key only has to be unique per root. Skip empty
725
- // configs, which contribute nothing, and a partial walk, which can orphan components.
726
- if (walked && !nodes.isEmpty()) {
727
- synchronized (state.perSub) {
728
- state.perSub["${project.path}::${cfg.name}".toString()] =
729
- [nodes: nodes, direct: directIds, paths: paths, unfetched: unfetched, projectPath: project.path, config: cfg.name, prod: isProd]
730
- }
731
- }
732
- }
733
- }
734
- }
735
- }
736
-
737
- rootProject { rp ->
738
- // Hoist property reads to configuration time: the configuration cache forbids `Task.project` from
739
- // task actions. The Socket CLI disables the cache for this run, but hoisting is cheap insurance.
740
- def recordsFileOverride = gradle.socketProp.call(rp, 'socket.recordsFile')?.toString()
741
- def defaultRecordsFile = new File(rp.projectDir, '.socket.facts.records.tsv').absolutePath
742
- def buildRootPath = rp.projectDir.absolutePath
743
- // `sources`/`targets` are --with-files-only; a plain run emits only the graph fields.
744
- def withFilesProjects = gradle.socketProp.call(rp, 'socket.withFiles')?.toString()?.toLowerCase() == 'true'
745
-
746
- rp.tasks.create('socketFacts') {
747
- group = 'socket'
748
- description = 'Emits Socket facts records for the entire build'
749
- outputs.upToDateWhen { false }
750
-
751
- doLast {
752
- def state = gradle.socketFactsState
753
-
754
- // Backslash-escape so a value can never break line/field framing (see records.ts unescape).
755
- def esc = { v ->
756
- (v == null ? '' : v.toString())
757
- .replace('\\', '\\\\').replace('\t', '\\t').replace('\n', '\\n').replace('\r', '\\r')
758
- }
759
- def lines = []
760
- def rec = { List fields -> lines << fields.collect { esc(it) }.join('\t') }
761
-
762
- rec(['meta', 'gradle', gradle.gradleVersion, System.getProperty('java.version')])
763
- rec(['buildRoot', buildRootPath])
764
-
765
- // One `project` record per build module (sources/targets only with --with-files).
766
- def projectsInfo
767
- synchronized (state.projectsInfo) { projectsInfo = new ArrayList(state.projectsInfo) }
768
- projectsInfo.each { pi ->
769
- if (pi.excluded) {
770
- if (withFilesProjects) rec(['excludedProject', pi.path])
771
- } else {
772
- rec(['project', pi.path, pi.group ?: '', pi.name, pi.version ?: '', pi.dir])
773
- pi.buildFiles.each { f -> rec(['projectBuild', pi.path, f]) }
774
- }
775
- if (withFilesProjects) {
776
- pi.sources.each { s -> rec(['projectSrc', pi.path, s]) }
777
- pi.targets.each { t -> rec(['projectTgt', pi.path, t]) }
778
- }
779
- }
780
-
781
- // One resolution root per (subproject, configuration); the TS assembler merges them by
782
- // coordinate and derives each subproject's classpath from its roots.
783
- def perSub
784
- synchronized (state.perSub) { perSub = new LinkedHashMap(state.perSub) }
785
- int rootIdx = 0
786
- perSub.each { rootKey, tree ->
787
- def rootId = (rootIdx++).toString()
788
- rec(['root', rootId, tree.projectPath, tree.config, tree.prod ? '1' : '0'])
789
- tree.nodes.each { coordId, node ->
790
- def c = node.coord
791
- rec(['node', rootId, coordId, c.groupId ?: '', c.artifactId ?: '', c.version ?: '', c.ext ?: '',
792
- c.classifier ?: '', tree.direct.contains(coordId) ? '1' : '0', node.project ?: ''])
793
- node.children.each { childId -> rec(['edge', rootId, coordId, childId]) }
794
- def fs = tree.paths[coordId]
795
- if (fs) { (fs as List).sort().each { p -> rec(['file', rootId, coordId, p]) } }
796
- if (tree.unfetched.contains(coordId)) rec(['unfetched', rootId, coordId])
797
- }
798
- }
799
-
800
- // Scanned configs + raw failures (Coana owns the abort/warn policy and report rendering).
801
- def scanned
802
- synchronized (state.scannedConfigs) { scanned = (state.scannedConfigs as List).sort() }
803
- scanned.each { name -> rec(['scanned', name]) }
804
- def failures
805
- synchronized (state.failures) { failures = new ArrayList(state.failures) }
806
- failures.each { f -> rec(['failure', f.coord, f.detail, f.config, f.project]) }
807
- def unscannable
808
- synchronized (state.unscannable) { unscannable = new ArrayList(state.unscannable) }
809
- unscannable.each { u -> rec(['unscannable', u.config, u.detail, u.project]) }
810
-
811
- def outFile = new File(recordsFileOverride ?: defaultRecordsFile)
812
- outFile.parentFile?.mkdirs()
813
- // Explicit UTF-8: the TS reader reads UTF-8, but `File.text =` would encode
814
- // with the JVM default charset (Cp1252 / US-ASCII on Windows or a non-UTF-8
815
- // locale on JDK <=17), corrupting non-ASCII paths and failure messages.
816
- outFile.withWriter('UTF-8') { it.write(lines.join('\n') + '\n') }
817
- println "Socket facts records written to: ${outFile.absolutePath}"
818
- }
819
- }
820
- }
821
-
822
- gradle.projectsEvaluated { g ->
823
- def aggregator = g.rootProject.tasks.findByName('socketFacts')
824
- if (aggregator) {
825
- g.rootProject.allprojects.each { p ->
826
- def collector = p.tasks.findByName('socketFactsCollect')
827
- if (collector) {
828
- aggregator.dependsOn(collector)
829
- }
830
- }
831
- }
832
- }