@socketsecurity/cli-with-sentry 1.17.1 → 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 +7 -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,1018 +0,0 @@
1
- package socket
2
-
3
- import sbt._
4
- import sbt.Keys._
5
-
6
- import scala.collection.mutable
7
-
8
- /**
9
- * Emits a flat line-protocol RECORDS file at the build root (NOT the final
10
- * `.socket.facts.json`, and NOT to stdout — sbt prints resolution noise to stdout
11
- * with no way to silence it). The TS assembler (utils/src/manifest-scripts/assemble.ts)
12
- * reads the records and owns all SBOM construction — graph merge and per-subproject
13
- * classpaths. This plugin only RESOLVES and emits raw facts. See records.ts for
14
- * the record grammar.
15
- *
16
- * Must compile on Scala 2.10/sbt 0.13 and Scala 2.12/sbt 1.x (compiled by the sbt
17
- * meta-build), hence string-named TaskKeys and reflection for version-specific
18
- * UpdateConfiguration / ResolveException / ConfigRef shapes.
19
- */
20
- object SocketFactsPlugin extends AutoPlugin {
21
- override def trigger = allRequirements
22
-
23
- object autoImport {
24
- val socketFacts =
25
- taskKey[Unit]("Emit Socket facts records for the whole build")
26
- }
27
- import autoImport._
28
-
29
- override def projectSettings: Seq[Setting[_]] = Seq(
30
- aggregate in socketFacts := false,
31
- socketFacts := {
32
- val st = state.value
33
- val buildRoot = (baseDirectory in ThisBuild).value
34
- val withFiles = boolProp("socket.withFiles")
35
- val populateScope: Option[Set[String]] = readPopulateScope()
36
-
37
- val extracted = Project.extract(st)
38
- val allRefs = extracted.structure.allProjectRefs
39
-
40
- // `-Dsocket.excludePaths` (scan-root-relative globs): a subproject whose dir is wholly excluded is
41
- // never resolved and emits no project record. Source-file-level exclusion is left to the analysis.
42
- val excludeMatchers = parseExcludeMatchers()
43
- val rootCanonPath = buildRoot.getCanonicalFile.toPath
44
- def relTo(base: java.nio.file.Path)(f: File): String = {
45
- val r = base.relativize(f.getCanonicalFile.toPath).toString.replace(java.io.File.separator, "/")
46
- if (r.isEmpty) "." else r
47
- }
48
- def relOf(f: File): String = relTo(rootCanonPath)(f)
49
- // `-Dsocket.excludeBase`: the directory `--exclude-paths` is relative to (the scan root; the
50
- // build root by default); a project outside it never matches.
51
- val excludeBase = sys.props.get("socket.excludeBase").filter(_.nonEmpty)
52
- .map(b => new File(b).getCanonicalFile.toPath).getOrElse(rootCanonPath)
53
- def isExcludedRef(ref: ProjectRef): Boolean = excludeMatchers.nonEmpty && {
54
- val dir = extracted.get(baseDirectory.in(ref))
55
- // Another Windows drive than the scan root is outside it.
56
- dir.getCanonicalFile.toPath.getRoot == excludeBase.getRoot && {
57
- val rel = relTo(excludeBase)(dir)
58
- rel != ".." && !rel.startsWith("../") && isExcludedPath(rel, excludeMatchers)
59
- }
60
- }
61
-
62
- // Prefer `updateFull` (coursier `update` returns empty callers); fall back to `update` (sbt 0.13).
63
- val hasUpdateFull =
64
- extracted.structure.settings.map(_.key.key).exists(_.label == "updateFull")
65
- val updateTaskName = if (hasUpdateFull) "updateFull" else "update"
66
-
67
- // One tree per resolution root (project, config); the TS assembler merges them path-sensitively.
68
- val perSub = mutable.LinkedHashMap.empty[String, RootTree]
69
- val failures = mutable.LinkedHashSet.empty[Failure]
70
- val unscannable = mutable.LinkedHashSet.empty[Unscannable]
71
- val scannedConfigs = mutable.LinkedHashSet.empty[String]
72
- val matcher = buildConfigMatcher()
73
-
74
- // Real artifact ext per build module, so an ext-less inter-project dep gets its true coordinate.
75
- val moduleExts = buildModuleExts(allRefs, extracted)
76
-
77
- // Every project: `update` also runs each upstream project's update, which would fail strictly.
78
- lazy val lenientState = extracted.append(allRefs.map(r => updateConfiguration.in(r) ~= (c => withMissingOk(c))), st)
79
- val pomsByCache = mutable.HashMap.empty[Option[File], PomPackaging]
80
-
81
- allRefs.foreach { ref =>
82
- if (!isExcludedRef(ref)) {
83
- // Built-in lm-coursier (sbt 1.3+) and the legacy sbt-coursier plugin name their caches differently.
84
- val legacyCoursierCache = extracted.getOpt(SettingKey[File]("coursierCache").in(ref))
85
- val csrCache = extracted.getOpt(SettingKey[File]("csrCacheDirectory").in(ref)).orElse(legacyCoursierCache)
86
- val poms = pomsByCache.getOrElseUpdate(csrCache, new PomPackaging(csrCache))
87
- // sbt 0.13 has no `useCoursier`: it resolves with Ivy unless the legacy plugin replaces it.
88
- val ivy = extracted.getOpt(SettingKey[Boolean]("useCoursier").in(ref)) match {
89
- case Some(useCoursier) => !useCoursier
90
- case None => legacyCoursierCache.isEmpty
91
- }
92
- val resolver = new Resolver(ivy, poms)
93
- runUpdateResilient(updateTaskName, ref, extracted, st, lenientState, matcher, failures, unscannable, resolver)
94
- .foreach { case (report, unresolved, ivyUnfetched, updateFailed) =>
95
- foldReport(report, unresolved, ref, extracted, matcher, scannedConfigs, withFiles, populateScope, moduleExts,
96
- resolver, ivyUnfetched, updateFailed, failures).foreach {
97
- case (rootKey, tree) => perSub(rootKey) = tree
98
- }
99
- }
100
- }
101
- }
102
-
103
- val moduleDirs: Map[String, (Seq[String], Seq[String])] =
104
- if (withFiles) buildModuleDirs(allRefs, extracted, st) else Map.empty
105
-
106
- // Where sbt recorded the project's own settings as defined (the root build.sbt for a subproject
107
- // defined there); positions outside the build are sbt defaults, plugins or our injected base.
108
- val buildFilesByRef: Map[ProjectRef, Seq[String]] =
109
- extracted.structure.settings
110
- .flatMap { setting =>
111
- (setting.key.scope.project, setting.pos) match {
112
- case (Select(ref: ProjectRef), pos: FilePosition) =>
113
- val f = new File(pos.path)
114
- if (f.isAbsolute && f.isFile && f.getCanonicalFile.toPath.startsWith(rootCanonPath)) Some(ref -> relOf(f))
115
- else None
116
- case _ => None
117
- }
118
- }
119
- .groupBy(_._1)
120
- .map { case (ref, pairs) => ref -> pairs.map(_._2) }
121
-
122
- val sb = new StringBuilder
123
- def rec(fields: String*): Unit = {
124
- sb.append(fields.map(esc).mkString("\t")); sb.append('\n')
125
- }
126
-
127
- rec("meta", "sbt", extracted.getOpt(sbtVersion).getOrElse(""), sys.props.getOrElse("java.version", ""))
128
- rec("buildRoot", rootCanonPath.toString)
129
-
130
- // One `project` record per build module (sources/targets only with --with-files). Excluded
131
- // subprojects get none (they were also skipped during resolution above), but keep their paths so
132
- // a kept project depending on one is analysed with its code.
133
- allRefs.foreach { ref =>
134
- val mid = rootIdOf(extracted, ref)
135
- val ver = if (mid.revision == null) "" else mid.revision
136
- if (isExcludedRef(ref)) {
137
- if (withFiles) rec("excludedProject", ref.project)
138
- } else {
139
- val baseDir = extracted.get(baseDirectory.in(ref))
140
- rec("project", ref.project, mid.organization, mid.name, ver, relOf(baseDir))
141
- (buildFilesByRef.getOrElse(ref, Nil) ++ baseBuildSbt(baseDir, rootCanonPath).map(relOf)).distinct.sorted
142
- .foreach(f => rec("projectBuild", ref.project, f))
143
- }
144
- if (withFiles) {
145
- moduleDirs.get(mid.organization + ":" + mid.name + ":" + ver).foreach {
146
- case (sources, targets) =>
147
- sources.foreach(s => rec("projectSrc", ref.project, s))
148
- targets.foreach(t => rec("projectTgt", ref.project, t))
149
- }
150
- }
151
- }
152
-
153
- // One resolution root per (subproject, configuration); the TS assembler merges them by
154
- // coordinate and derives each subproject's classpath from its roots.
155
- var rootIdx = 0
156
- perSub.foreach {
157
- case (_, tree) =>
158
- val rootId = rootIdx.toString
159
- rootIdx += 1
160
- rec("root", rootId, tree.projectKey, tree.config, if (tree.prod) "1" else "0")
161
- tree.nodes.foreach {
162
- case (coordId, node) =>
163
- val c = node.coord
164
- rec("node", rootId, coordId, c.org, c.name, c.version, c.ext, c.classifier, if (node.direct) "1" else "0",
165
- node.project)
166
- node.children.foreach(ch => rec("edge", rootId, coordId, ch))
167
- node.targets.foreach(p => rec("file", rootId, coordId, p))
168
- if (node.unfetched) rec("unfetched", rootId, coordId)
169
- }
170
- }
171
-
172
- // Scanned configs + raw failures (Coana owns the abort/warn policy and report rendering).
173
- scannedConfigs.toList.sorted.foreach(c => rec("scanned", c))
174
- failures.foreach(f => rec("failure", f.coord, f.detail, f.config, f.project))
175
- unscannable.foreach(u => rec("unscannable", "", u.detail, u.project))
176
-
177
- val recordsFile = sys.props.get("socket.recordsFile").filter(_.nonEmpty) match {
178
- case Some(p) => new File(p)
179
- case None => new File(buildRoot, ".socket.facts.records.tsv")
180
- }
181
- Option(recordsFile.getParentFile).foreach(_.mkdirs())
182
- IO.write(recordsFile, sb.toString)
183
- println("Socket facts records written to: " + recordsFile.getAbsolutePath)
184
- }
185
- )
186
-
187
- // ---- resolution ---------------------------------------------------------
188
-
189
- private def crossOf(extracted: Extracted, ref: ProjectRef): ModuleID => ModuleID =
190
- CrossVersion.apply(extracted.get(scalaVersion.in(ref)), extracted.get(scalaBinaryVersion.in(ref)))
191
-
192
- private def rootIdOf(extracted: Extracted, ref: ProjectRef): ModuleID =
193
- crossOf(extracted, ref)(extracted.get(projectID.in(ref)))
194
-
195
- // GAV -> a build module's real artifact extension (jar for a normal project). coursier reports an
196
- // inter-project dependency with no resolved artifact, so it would otherwise be ext-less and not
197
- // match how depscan ingests it (ext=jar); stamping the real ext keeps a full, matching coordinate.
198
- private def buildModuleExts(allRefs: Seq[ProjectRef], extracted: Extracted): Map[String, String] = {
199
- allRefs.map { ref =>
200
- val ext = extracted.getOpt(artifact.in(ref)).map(_.extension).filter(e => e != null && e.nonEmpty).getOrElse("jar")
201
- gavKey(rootIdOf(extracted, ref)) -> ext
202
- }.toMap
203
- }
204
-
205
- // Absolute source roots + compiled-output dirs per build module, keyed by GAV. --with-files only;
206
- // absolute because reachability locates an internal module's code on THIS machine (no registry jar).
207
- // ALL of the project's configurations are scanned (not just Compile/Test) so custom ones
208
- // (IntegrationTest, ...) reach the analysis; source-file-level exclusion is coana's job.
209
- private def buildModuleDirs(
210
- allRefs: Seq[ProjectRef],
211
- extracted: Extracted,
212
- state: State
213
- ): Map[String, (Seq[String], Seq[String])] = {
214
- allRefs.map { ref =>
215
- val mid = rootIdOf(extracted, ref)
216
- val ver = if (mid.revision == null) "" else mid.revision
217
- val configs: Seq[Configuration] =
218
- extracted.getOpt(thisProject.in(ref)).map(_.configurations).getOrElse(Seq(Compile, Test))
219
- val sources = (configs.flatMap(c => extracted.getOpt(sourceDirectories.in(ref).in(c)).getOrElse(Nil)) ++
220
- baseDirSources(ref, configs, extracted, state))
221
- .map(_.getAbsolutePath).distinct.sorted
222
- val targets = configs
223
- .flatMap(c => extracted.getOpt(classDirectory.in(ref).in(c)))
224
- .map(_.getAbsolutePath).distinct.sorted
225
- (mid.organization + ":" + mid.name + ":" + ver) -> ((sources, targets))
226
- }.toMap
227
- }
228
-
229
- // Sources sbt compiles from the base dir itself (`sourcesInBase`), as files: sbt includes them
230
- // non-recursively, and the base dir as a source root would be walked into nested subprojects.
231
- private def baseDirSources(
232
- ref: ProjectRef,
233
- configs: Seq[Configuration],
234
- extracted: Extracted,
235
- state: State
236
- ): Seq[File] = {
237
- val base = extracted.get(baseDirectory.in(ref)).getCanonicalFile
238
- // A configuration that only inherits the task (Runtime from Compile) would re-run the same walk.
239
- val definingScopes = configs.flatMap { c =>
240
- val key = unmanagedSources.in(ref).in(c)
241
- extracted.structure.data.definingScope(key.scope, key.key)
242
- }.distinct
243
- definingScopes.flatMap { scope =>
244
- Project.runTask(Def.ScopedKey(scope, unmanagedSources.key), state) match {
245
- case Some((_, sbt.Value(files))) =>
246
- files.groupBy(_.getAbsoluteFile.getParentFile).collect {
247
- case (dir, inDir) if dir.getCanonicalFile == base => inDir
248
- }.flatten
249
- case _ => Nil
250
- }
251
- }
252
- }
253
-
254
- // A failure naming no module is an artifact that could not be fetched, which only the lenient
255
- // report's missing artifacts reveal; with neither, the project is unscannable.
256
- private def runUpdateResilient(
257
- taskName: String,
258
- ref: ProjectRef,
259
- extracted: Extracted,
260
- state: State,
261
- lenient: => State,
262
- matcher: String => Boolean,
263
- failures: mutable.LinkedHashSet[Failure],
264
- unscannable: mutable.LinkedHashSet[Unscannable],
265
- resolver: Resolver
266
- ): Option[(UpdateReport, Set[String], IvyUnfetched, Boolean)] = {
267
- val key = TaskKey[UpdateReport](taskName)
268
-
269
- def runOn(st: State): Either[(Seq[ModuleID], String), UpdateReport] =
270
- Project.runTask(key.in(ref).scopedKey, st) match {
271
- case Some((_, sbt.Value(rep))) => Right(rep)
272
- case Some((_, sbt.Inc(inc))) => Left((extractFailedModules(inc), incompleteMessage(inc)))
273
- case _ => Left((Nil, s"$taskName did not run"))
274
- }
275
-
276
- runOn(state) match {
277
- case Right(rep) => Some((rep, Set.empty[String], Map.empty: IvyUnfetched, false))
278
- case Left((failed, detail)) =>
279
- val lenientRun = runOn(lenient).right.map { rep =>
280
- (rep, if (resolver.ivy) ivyUnfetchedOf(rep, extracted.get(target.in(ref))) else Map.empty: IvyUnfetched)
281
- }
282
- lenientRun match {
283
- case Right((rep, ivyUnfetched))
284
- if failed.isEmpty && ivyUnfetched.isEmpty &&
285
- !rep.configurations.exists(_.modules.exists(m => !m.evicted && resolver.missingOf(m).nonEmpty)) =>
286
- unscannable += Unscannable(detail, ref.project)
287
- None
288
- case Right((rep, ivyUnfetched)) =>
289
- val confsByGav = mutable.HashMap.empty[String, mutable.LinkedHashSet[String]]
290
- rep.configurations.foreach { cr =>
291
- cr.modules.foreach { r =>
292
- if (!r.evicted) confsByGav.getOrElseUpdate(gavKey(r.module), mutable.LinkedHashSet.empty[String]) += confName(cr)
293
- }
294
- }
295
- failed.foreach { m =>
296
- // Absent from the graph: no configuration. Present only in excluded ones: not reported.
297
- confsByGav.get(gavKey(m)) match {
298
- case None => failures += Failure(coordOf(m), detailFor(m, detail), "", ref.project)
299
- case Some(confs) => confs.filter(matcher).foreach(c => failures += Failure(coordOf(m), detailFor(m, detail), c, ref.project))
300
- }
301
- }
302
- Some((rep, failed.map(gavKey).toSet, ivyUnfetched, failed.isEmpty))
303
- case Left(_) =>
304
- // Even a lenient update failed: the whole project is unresolved, but the modules sbt
305
- // named are still reported.
306
- failed.foreach(m => failures += Failure(coordOf(m), detailFor(m, detail), "", ref.project))
307
- unscannable += Unscannable(detail, ref.project)
308
- None
309
- }
310
- }
311
- }
312
-
313
- // config -> "org:name:rev" -> artifacts Ivy failed to download.
314
- private type IvyUnfetched = Map[String, Map[String, Seq[IvyArtifact]]]
315
-
316
- private final case class IvyArtifact(ext: String, classifier: String, detail: String)
317
-
318
- // sbt 0.13's UpdateReport omits artifacts Ivy failed to download; Ivy's own report per configuration,
319
- // `<resolution cache>/reports/<organisation>-<module>-<conf>.xml`, keeps them.
320
- private def ivyUnfetchedOf(rep: UpdateReport, projectTarget: File): IvyUnfetched = {
321
- val descriptor = Option(rep.cachedDescriptor).filter(_.isFile)
322
- val bound = projectTarget.getCanonicalFile.toPath
323
- def reportsDirs(f: File): Stream[File] =
324
- Option(f.getParentFile).filter(_.getCanonicalFile.toPath.startsWith(bound)).toStream
325
- .flatMap(p => new File(p, "reports") #:: reportsDirs(p))
326
- (for {
327
- d <- descriptor.toSeq
328
- id <- ivyResolveId(d).toSeq
329
- cr <- rep.configurations
330
- conf = confName(cr)
331
- report <- reportsDirs(d).map(new File(_, id + "-" + conf + ".xml")).find(_.isFile).toSeq
332
- arts = ivyFailedArtifacts(report)
333
- if arts.nonEmpty
334
- } yield conf -> arts).toMap
335
- }
336
-
337
- private def parseXml(f: File): org.w3c.dom.Document = {
338
- // A POM may declare a DOCTYPE, so only what it could pull in from outside is refused.
339
- val dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance()
340
- dbf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true)
341
- dbf.setFeature("http://xml.org/sax/features/external-general-entities", false)
342
- dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false)
343
- dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false)
344
- dbf.setXIncludeAware(false)
345
- dbf.setExpandEntityReferences(false)
346
- dbf.newDocumentBuilder().parse(f)
347
- }
348
-
349
- // Child elements by local name; "*" for all.
350
- private def pomKids(e: org.w3c.dom.Element, name: String): Seq[org.w3c.dom.Element] = {
351
- val ns = e.getChildNodes
352
- (0 until ns.getLength).map(ns.item).collect {
353
- case c: org.w3c.dom.Element if name == "*" || c.getNodeName.split(':').last == name => c
354
- }
355
- }
356
-
357
- private def pomText(e: org.w3c.dom.Element, name: String): Option[String] =
358
- pomKids(e, name).headOption.map(_.getTextContent.trim).filter(_.nonEmpty)
359
-
360
- private def pomGroupId(e: org.w3c.dom.Element): String =
361
- pomText(e, "groupId").orElse(pomKids(e, "parent").headOption.flatMap(pomText(_, "groupId"))).getOrElse("")
362
-
363
- private val PropertyRef = "\\$\\{([^}]+)\\}".r
364
-
365
- // A POM after inheritance: its dependencies (groupId:artifactId -> declared scope, optional), its
366
- // managed scopes, the BOMs it imports, and its properties.
367
- private final case class PomModel(
368
- deps: Map[String, (String, Boolean)],
369
- managed: Map[String, String],
370
- imports: Seq[(String, String, String)],
371
- props: Map[String, String])
372
-
373
- private object PomModel {
374
- val empty = PomModel(Map.empty, Map.empty, Nil, Map.empty)
375
- }
376
-
377
- // Until nothing changes, as a property's value may refer to another.
378
- private def interpolate(s: String, props: Map[String, String]): String = {
379
- var cur = s
380
- var prev = ""
381
- var rounds = 0
382
- while (cur != prev && rounds < 16) {
383
- prev = cur
384
- cur = PropertyRef.replaceAllIn(cur, m => java.util.regex.Matcher.quoteReplacement(props.getOrElse(m.group(1), m.matched)))
385
- rounds += 1
386
- }
387
- cur
388
- }
389
-
390
- // Ivy's ResolveOptions.getDefaultResolveId: `<organisation>-<module>` of the resolved descriptor.
391
- private def ivyResolveId(descriptor: File): Option[String] =
392
- try {
393
- val info = parseXml(descriptor).getElementsByTagName("info")
394
- if (info.getLength == 0) None
395
- else {
396
- val e = info.item(0).asInstanceOf[org.w3c.dom.Element]
397
- Some(e.getAttribute("organisation") + "-" + e.getAttribute("module"))
398
- }
399
- } catch { case _: Exception => None }
400
-
401
- private def ivyFailedArtifacts(report: File): Map[String, Seq[IvyArtifact]] =
402
- try {
403
- val modules = parseXml(report).getElementsByTagName("module")
404
- val out = for {
405
- mi <- 0 until modules.getLength
406
- module = modules.item(mi).asInstanceOf[org.w3c.dom.Element]
407
- revisions = module.getElementsByTagName("revision")
408
- ri <- 0 until revisions.getLength
409
- revision = revisions.item(ri).asInstanceOf[org.w3c.dom.Element]
410
- if revision.getAttribute("evicted").isEmpty
411
- artifacts = revision.getElementsByTagName("artifact")
412
- ai <- 0 until artifacts.getLength
413
- a = artifacts.item(ai).asInstanceOf[org.w3c.dom.Element]
414
- if a.getAttribute("status") == "failed"
415
- } yield {
416
- val (org, name, rev) = (module.getAttribute("organisation"), module.getAttribute("name"), revision.getAttribute("name"))
417
- val classifier = a.getAttribute("extra-classifier")
418
- val file = a.getAttribute("name") + (if (classifier.isEmpty) "" else "-" + classifier) + "." + a.getAttribute("ext")
419
- // An absent artifact is "missing artifact" (empty under sbt 0.13's Ivy); one the resolver chain
420
- // failed itself has "null"; anything else is a transfer failure's message.
421
- val details = a.getAttribute("details")
422
- val cause =
423
- if (details.isEmpty || details == "missing artifact") "not found"
424
- else if (details == "null") "download failed"
425
- else "download failed (" + details + ")"
426
- (org + ":" + name + ":" + rev) -> IvyArtifact(a.getAttribute("ext"), classifier, cause + ": " + org + "#" + name + ";" + rev + "!" + file)
427
- }
428
- out.groupBy(_._1).map { case (gav, pairs) => gav -> pairs.map(_._2).distinct }
429
- } catch { case _: Exception => Map.empty }
430
-
431
- // UpdateConfiguration has `withMissingOk` on sbt 1.x; on 0.13 its only Boolean field is missingOk.
432
- private def withMissingOk[T](c: T): T = {
433
- val cls = c.getClass
434
- try cls.getMethod("withMissingOk", classOf[Boolean]).invoke(c, java.lang.Boolean.TRUE).asInstanceOf[T]
435
- catch {
436
- case _: NoSuchMethodException =>
437
- val copy = cls.getMethods.find(_.getName == "copy").get
438
- val args = copy.getParameterTypes.zipWithIndex.map { case (t, i) =>
439
- if (t == classOf[Boolean]) java.lang.Boolean.TRUE
440
- else cls.getMethod("copy$default$" + (i + 1)).invoke(c)
441
- }
442
- copy.invoke(c, args: _*).asInstanceOf[T]
443
- }
444
- }
445
-
446
- // One module's part of a batch resolve message, so records grow with the failure count, not its
447
- // square: Coursier writes an indented "Error downloading org:name:rev" block per module, Ivy a line.
448
- private def detailFor(m: ModuleID, batch: String): String = {
449
- val lines = batch.split("\n").toList
450
- val keys = Seq(coordOf(m), s"${orEmpty(m.organization)}#${orEmpty(m.name)};${orEmpty(m.revision)}")
451
- val start = lines.indexWhere(l => keys.exists(k => l.contains(k)))
452
- if (start < 0) lines.map(_.trim).find(_.nonEmpty).getOrElse(batch)
453
- else (lines(start) :: lines.drop(start + 1).takeWhile(l => l.startsWith(" ") || l.startsWith("\t"))).mkString("\n").trim
454
- }
455
-
456
- private def incompleteMessage(inc: sbt.Incomplete): String = {
457
- def first(i: sbt.Incomplete): Option[String] =
458
- i.directCause.flatMap(ex => Option(ex.getMessage)).orElse(i.causes.view.flatMap(first).headOption)
459
- first(inc).map(_.trim).filter(_.nonEmpty).getOrElse("unresolved dependency")
460
- }
461
-
462
- // Reflection: ResolveException's package and the `failed` accessor differ between sbt 0.13 and 1.x.
463
- private def extractFailedModules(inc: sbt.Incomplete): Seq[ModuleID] = {
464
- val out = mutable.ListBuffer.empty[ModuleID]
465
- def walk(i: sbt.Incomplete): Unit = {
466
- i.directCause.foreach { ex =>
467
- val cn = ex.getClass.getName
468
- if (cn == "sbt.ResolveException" || cn == "sbt.librarymanagement.ResolveException") {
469
- try {
470
- val m = ex.getClass.getMethod("failed")
471
- out ++= m.invoke(ex).asInstanceOf[Seq[ModuleID]]
472
- } catch { case _: Throwable => }
473
- }
474
- }
475
- i.causes.foreach(walk)
476
- }
477
- walk(inc)
478
- out.toList.distinct
479
- }
480
-
481
- // Fold one project's UpdateReport into one tree per configuration (rootKey -> tree), keyed by coordinate.
482
- private def foldReport(
483
- report: UpdateReport,
484
- unresolved: Set[String],
485
- ref: ProjectRef,
486
- extracted: Extracted,
487
- matcher: String => Boolean,
488
- scannedConfigs: mutable.LinkedHashSet[String],
489
- withFiles: Boolean,
490
- populateScope: Option[Set[String]],
491
- moduleExts: Map[String, String],
492
- resolver: Resolver,
493
- ivyUnfetched: IvyUnfetched,
494
- // sbt's own update failed on artifacts alone, so one it could not fetch is a failure even
495
- // without files.
496
- updateFailed: Boolean,
497
- failures: mutable.LinkedHashSet[Failure]
498
- ): mutable.LinkedHashMap[String, RootTree] = {
499
- val perRoot = mutable.LinkedHashMap.empty[String, RootTree]
500
- val rootKey = moduleKey(rootIdOf(extracted, ref))
501
-
502
- // Build modules come from the build structure instead: lm-coursier lists every inter-project
503
- // dependency in every configuration, and cross-versioning can merge distinct ones.
504
- def emittable(m: ModuleReport): Boolean =
505
- !m.evicted && !moduleExts.contains(gavKey(m.module)) && !unresolved.contains(gavKey(m.module))
506
-
507
- def confsOf(r: ProjectRef): Seq[Configuration] = extracted.getOpt(ivyConfigurations.in(r)).getOrElse(Nil)
508
- lazy val refByProject: Map[String, ProjectRef] = extracted.structure.allProjectRefs.map(r => r.project -> r).toMap
509
- // Whether build project `r` declares module `c` in one of `confs`. A declaration without a
510
- // configuration goes to Compile; the report names the module cross-versioned.
511
- def declares(r: ProjectRef, c: ModuleID, confs: Set[String]): Boolean = {
512
- val cross = crossOf(extracted, r)
513
- extracted.getOpt(libraryDependencies.in(r)).getOrElse(Nil).exists { d =>
514
- val masters = d.configurations.getOrElse("compile").split(';').flatMap(_.split("->").head.split(',')).map(_.trim)
515
- d.organization == c.organization && cross(d).name == c.name && masters.exists(m => m == "*" || confs(m))
516
- }
517
- }
518
- val buildDeps = extracted.get(buildDependencies)
519
-
520
- // Classpaths.interSort, recording the (project -> dependency project) edges it follows and the
521
- // configurations of each project it reaches.
522
- def interProjectEdges(conf: Configuration): (mutable.LinkedHashSet[(ProjectRef, ProjectRef)], Map[String, Set[String]]) = {
523
- val masterConfs = confsOf(ref).map(_.name)
524
- val visited = mutable.HashSet.empty[(ProjectRef, String)]
525
- val edges = mutable.LinkedHashSet.empty[(ProjectRef, ProjectRef)]
526
- def visit(p: ProjectRef, c: Configuration): Unit = {
527
- val applicable = Classpaths.allConfigs(c)
528
- applicable.foreach(ac => visited += (p -> ac.name))
529
- buildDeps.classpath.getOrElse(p, Nil).foreach { d =>
530
- val depConfs = confsOf(d.project)
531
- val mapping = Classpaths.mapped(d.configuration, masterConfs, depConfs.map(_.name), "compile", "*->compile")
532
- for {
533
- ac <- applicable
534
- depConfName <- mapping(ac.name)
535
- depConf <- depConfs.find(_.name == depConfName)
536
- } {
537
- edges += (p -> d.project)
538
- if (!visited((d.project, depConfName))) visit(d.project, depConf)
539
- }
540
- }
541
- }
542
- visit(ref, conf)
543
- (edges, visited.toSeq.groupBy(_._1.project).map { case (p, vs) => p -> vs.map(_._2).toSet })
544
- }
545
-
546
- def buildModuleCoord(r: ProjectRef): Coord = {
547
- val mid = rootIdOf(extracted, r)
548
- val ver = if (mid.revision == null) "" else mid.revision
549
- Coord(mid.organization, mid.name, ver, moduleExts.getOrElse(gavKey(mid), ""), "")
550
- }
551
-
552
- def inScope(m: ModuleID): Boolean = populateScope match {
553
- case None => true
554
- case Some(gavs) => gavs.contains(gavKey(m))
555
- }
556
-
557
- report.configurations.foreach { cr =>
558
- val cfg = confName(cr)
559
- if (matcher(cfg)) {
560
- scannedConfigs += cfg
561
- val prod = isProdConf(cfg) && !isTestConf(cfg)
562
- val nodes = mutable.LinkedHashMap.empty[String, Node]
563
- // org:name -> component ids (caller edges are module-level).
564
- val midToIds = mutable.HashMap.empty[String, mutable.LinkedHashSet[String]]
565
- var reachedConfs = Map.empty[String, Set[String]]
566
-
567
- confsOf(ref).find(_.name == cfg).foreach { conf =>
568
- // Keyed by project id, as projects need not have distinct coordinates.
569
- def buildModuleNode(r: ProjectRef): String = {
570
- midToIds.getOrElseUpdate(moduleKey(rootIdOf(extracted, r)), mutable.LinkedHashSet.empty[String]) += r.project
571
- nodes.getOrElseUpdate(r.project, {
572
- val node = new Node(buildModuleCoord(r))
573
- node.project = r.project
574
- node
575
- })
576
- r.project
577
- }
578
- val (edges, reached) = interProjectEdges(conf)
579
- reachedConfs = reached
580
- edges.foreach { case (p, d) =>
581
- val child = buildModuleNode(d)
582
- if (p == ref) nodes(child).direct = true
583
- else nodes(buildModuleNode(p)).children += child
584
- }
585
- }
586
-
587
- cr.modules.foreach { m =>
588
- if (emittable(m)) {
589
- val ids = midToIds.getOrElseUpdate(moduleKey(m.module), mutable.LinkedHashSet.empty[String])
590
- val ivyMissing =
591
- if (ivyUnfetched.isEmpty) Nil
592
- else ivyUnfetched.getOrElse(cfg, Map.empty[String, Seq[IvyArtifact]]).getOrElse(gavKey(m.module), Nil)
593
- val recordFiles = withFiles && inScope(m.module)
594
- variantsOf(m, resolver, ivyMissing).foreach { v =>
595
- val node = nodes.getOrElseUpdate(v.coord.id, new Node(v.coord))
596
- ids += v.coord.id
597
- if (recordFiles) v.file.foreach(f => node.targets += f.getAbsolutePath)
598
- v.unfetched.foreach { url =>
599
- if (recordFiles) node.unfetched = true
600
- if (recordFiles || updateFailed) failures += Failure(coordOf(m.module), url, cfg, ref.project)
601
- }
602
- }
603
- }
604
- }
605
-
606
- // Caller edges within this config: a root caller marks the child direct, any other becomes its parent.
607
- // Coursier resolves a Maven relocation's target in place of the relocating module, but reports
608
- // neither the relocating module nor who declared it, so that caller is missing from the report.
609
- // Its declarers are read off the build's own declarations and the POMs instead.
610
- val candidates = cr.modules.filter(emittable)
611
- // Drops self-edges (test → main resolving to the same coordinate), matching gradle.
612
- def link(parentIds: Iterable[String], childIds: Iterable[String]): Unit =
613
- parentIds.foreach(pid => childIds.foreach(cid => if (pid != cid) nodes(pid).children += cid))
614
- def declaredBy(p: String, c: ModuleID): Boolean =
615
- refByProject.get(p).exists(declares(_, c, reachedConfs.getOrElse(p, Set.empty)))
616
- candidates.foreach { m =>
617
- midToIds.get(moduleKey(m.module)).foreach { childIds =>
618
- // lm-coursier gives a declared caller its declared revision, not the resolved one, so
619
- // callers match by org:name (a configuration resolves one version per module).
620
- m.callers.foreach { c =>
621
- val callerKey = moduleKey(c.caller)
622
- if (callerKey == rootKey) childIds.foreach(cid => nodes(cid).direct = true)
623
- else midToIds.get(callerKey) match {
624
- case Some(parentIds) => link(parentIds, childIds)
625
- case None if !resolver.ivy && resolver.poms.relocates(c.caller, m) =>
626
- if (declaredBy(ref.project, c.caller)) childIds.foreach(cid => nodes(cid).direct = true)
627
- link(nodes.collect { case (nid, n) if n.project.nonEmpty && declaredBy(n.project, c.caller) => nid }, childIds)
628
- resolver.poms.declaringModules(c.caller, candidates).foreach(p => midToIds.get(moduleKey(p)).foreach(link(_, childIds)))
629
- case None =>
630
- }
631
- }
632
- }
633
- }
634
-
635
- if (nodes.nonEmpty) perRoot(ref.project + "::" + cfg) = new RootTree(ref.project, cfg, prod, nodes)
636
- }
637
- }
638
- perRoot
639
- }
640
-
641
- private def variantsOf(m: ModuleReport, resolver: Resolver, ivyMissing: Seq[IvyArtifact]): Seq[Variant] = {
642
- val mid = m.module
643
- // `mid.revision` is normally set for a resolved module, but normalize null (Coord.id calls
644
- // `.nonEmpty`, which NPEs on null) to match the other call sites (gavKey, module records).
645
- val ver = if (mid.revision == null) "" else mid.revision
646
- def coordFor(art: Artifact) = Coord(mid.organization, mid.name, ver, extOf(art), classifierOf(art))
647
- val fetched = Option(m.artifacts).toList.flatten.map { case (art, file) => Variant(coordFor(art), Option(file), None) }
648
- val missing = resolver.missingOf(m).map { art =>
649
- // The update report does not say why: a 401 or a timeout is as likely as an absent file.
650
- Variant(coordFor(art), None, Some("could not be fetched: " + art.url.map(_.toString).getOrElse(coordFor(art).id)))
651
- } ++ ivyMissing.map(a => Variant(Coord(mid.organization, mid.name, ver, a.ext, a.classifier), None, Some(a.detail)))
652
- if (fetched.isEmpty && missing.isEmpty)
653
- // No artifact expected (a pom-only module): leave it ext-less.
654
- Seq(Variant(Coord(mid.organization, mid.name, ver, "", ""), None, None))
655
- else fetched ++ missing
656
- }
657
-
658
- // Artifacts the resolver expected and did not fetch. Under Ivy they come from its resolution report
659
- // instead (see ivyUnfetchedOf).
660
- private final class Resolver(val ivy: Boolean, val poms: PomPackaging) {
661
- def missingOf(m: ModuleReport): List[Artifact] =
662
- if (ivy) Nil else Option(m.missingArtifacts).toList.flatten.filterNot(poms.isUnexpectedDefault)
663
- }
664
-
665
- // Coursier requests the default jar of every Maven module and skips it silently when absent unless
666
- // the POM declares a jar packaging. Only the module's own POM tells whether its artifact is a jar
667
- // (packaging defaults to jar, so a parent's never applies); an unreadable POM counts as one.
668
- private final class PomPackaging(csrCacheDir: Option[File]) {
669
- private val pomMemo = mutable.HashMap.empty[String, Option[org.w3c.dom.Element]]
670
-
671
- private def pom(url: String): Option[org.w3c.dom.Element] =
672
- pomMemo.getOrElseUpdate(url, coursierLocalFiles(url, csrCacheDir).find(_.isFile).flatMap { f =>
673
- try Some(parseXml(f).getDocumentElement)
674
- catch { case _: Exception => None }
675
- })
676
-
677
- // Maven repository layout.
678
- private def moduleDir(base: String, org: String, name: String): String =
679
- base + org.replace('.', '/') + "/" + name + "/"
680
-
681
- private def pomUrl(base: String, org: String, name: String, rev: String): String =
682
- moduleDir(base, org, name) + rev + "/" + name + "-" + rev + ".pom"
683
-
684
- // The repository root a module's artifacts were fetched from.
685
- private def repoBase(m: ModuleReport): Option[String] = {
686
- val mid = m.module
687
- val marker = moduleDir("/", mid.organization, mid.name) + orEmpty(mid.revision) + "/"
688
- val urls = Option(m.artifacts).toList.flatten.flatMap(_._1.url) ++
689
- Option(m.missingArtifacts).toList.flatten.flatMap(_.url)
690
- urls.map(_.toString).collectFirst { case u if u.contains(marker) => u.substring(0, u.indexOf(marker) + 1) }
691
- }
692
-
693
- private val modelMemo = mutable.HashMap.empty[String, PomModel]
694
-
695
- // Maven model inheritance and interpolation of a POM, as far as its dependencies' scopes need.
696
- private def model(base: String, org: String, name: String, rev: String, depth: Int): PomModel = {
697
- val url = pomUrl(base, org, name, rev)
698
- modelMemo.getOrElseUpdate(url, pom(url) match {
699
- case None => PomModel.empty
700
- case Some(e) =>
701
- val parent = pomKids(e, "parent").headOption
702
- val pm = parent match {
703
- case Some(p) if depth < 16 =>
704
- model(base, pomText(p, "groupId").getOrElse(""), pomText(p, "artifactId").getOrElse(""),
705
- pomText(p, "version").getOrElse(""), depth + 1)
706
- case _ => PomModel.empty
707
- }
708
- val groupId = pomGroupId(e)
709
- val artifactId = pomText(e, "artifactId").getOrElse("")
710
- val version = pomText(e, "version").orElse(parent.flatMap(pomText(_, "version"))).getOrElse("")
711
- val own = pomKids(e, "properties").flatMap(ps => pomKids(ps, "*")).map(p => p.getNodeName.split(':').last -> p.getTextContent.trim)
712
- val props = pm.props ++ own ++ Seq(
713
- "project.groupId" -> groupId, "pom.groupId" -> groupId, "groupId" -> groupId,
714
- "project.artifactId" -> artifactId, "pom.artifactId" -> artifactId, "artifactId" -> artifactId,
715
- "project.version" -> version, "pom.version" -> version, "version" -> version
716
- ) ++ parent.toSeq.flatMap { p =>
717
- Seq("project.parent.groupId" -> pomText(p, "groupId").getOrElse(""),
718
- "project.parent.version" -> pomText(p, "version").getOrElse(""))
719
- }
720
- def field(d: _root_.org.w3c.dom.Element, name: String) = interpolate(pomText(d, name).getOrElse(""), props)
721
- def ga(d: _root_.org.w3c.dom.Element) = field(d, "groupId") + ":" + field(d, "artifactId")
722
- val deps = pomKids(e, "dependencies").flatMap(ds => pomKids(ds, "dependency"))
723
- val managed = pomKids(e, "dependencyManagement").flatMap(pomKids(_, "dependencies")).flatMap(pomKids(_, "dependency"))
724
- val (imports, scoped) = managed.partition(d => field(d, "scope") == "import" && field(d, "type") == "pom")
725
- PomModel(
726
- pm.deps ++ deps.map(d => ga(d) -> ((field(d, "scope"), field(d, "optional") == "true"))),
727
- pm.managed ++ scoped.map(d => ga(d) -> field(d, "scope")),
728
- imports.map(d => (field(d, "groupId"), field(d, "artifactId"), field(d, "version"))) ++ pm.imports,
729
- props)
730
- })
731
- }
732
-
733
- private val managedMemo = mutable.HashMap.empty[String, Map[String, String]]
734
-
735
- // Managed scopes after BOM imports: the POM's own and inherited entries win, then the first import.
736
- private def managedScopes(base: String, org: String, name: String, rev: String, depth: Int): Map[String, String] =
737
- managedMemo.getOrElseUpdate(pomUrl(base, org, name, rev), {
738
- val m = model(base, org, name, rev, 0)
739
- m.imports.reverse.foldLeft(Map.empty[String, String]) { case (acc, (g, a, v)) =>
740
- if (depth < 16) acc ++ managedScopes(base, g, a, v, depth + 1) else acc
741
- } ++ m.managed
742
- })
743
-
744
- // org:name of the modules each relocating module's cached POMs relocate to.
745
- private val relocationsMemo = mutable.HashMap.empty[(String, String), Set[String]]
746
-
747
- // Whether `relocating` is a POM relocated to `target`'s module. The report gives the relocating
748
- // module its declared revision, which may be a range, so every cached version is tried; the
749
- // target may have resolved to another version than the relocation names.
750
- def relocates(relocating: ModuleID, target: ModuleReport): Boolean =
751
- repoBase(target).exists { base =>
752
- relocationsMemo.getOrElseUpdate((base, gavKey(relocating)), {
753
- val dir = moduleDir(base, relocating.organization, relocating.name)
754
- val versions = orEmpty(relocating.revision) +: coursierLocalFiles(dir, csrCacheDir)
755
- .flatMap(d => Option(d.listFiles).toSeq.flatten).filter(_.isDirectory).map(_.getName)
756
- versions.distinct.flatMap { v =>
757
- pom(pomUrl(base, relocating.organization, relocating.name, v)).toSeq.flatMap { e =>
758
- pomKids(e, "distributionManagement").flatMap(pomKids(_, "relocation")).headOption.map { r =>
759
- pomText(r, "groupId").getOrElse(pomGroupId(e)) + ":" +
760
- pomText(r, "artifactId").orElse(pomText(e, "artifactId")).getOrElse("")
761
- }
762
- }
763
- }.toSet
764
- })(moduleKey(target.module))
765
- }
766
-
767
- // The modules among `candidates` whose POM passes `declared` on to their dependents: compile or
768
- // runtime scope, declared or managed, and not optional.
769
- def declaringModules(declared: ModuleID, candidates: Seq[ModuleReport]): Seq[ModuleID] = {
770
- val key = moduleKey(declared)
771
- candidates.filter { p =>
772
- repoBase(p).exists { base =>
773
- val m = model(base, p.module.organization, p.module.name, orEmpty(p.module.revision), 0)
774
- m.deps.get(key).exists { case (scope, optional) =>
775
- val effective =
776
- if (scope.nonEmpty) scope
777
- else managedScopes(base, p.module.organization, p.module.name, orEmpty(p.module.revision), 0).getOrElse(key, "")
778
- Set("", "compile", "runtime")(effective) && !optional
779
- }
780
- }
781
- }.map(_.module)
782
- }
783
-
784
- def isUnexpectedDefault(a: Artifact): Boolean = {
785
- val ext = extOf(a)
786
- a.classifier.isEmpty && ext == "jar" && a.url.map(_.toString).exists { url =>
787
- url.endsWith("." + ext) &&
788
- pom(url.dropRight(ext.length) + "pom").exists(e => !JarPackagings(pomText(e, "packaging").getOrElse("jar")))
789
- }
790
- }
791
- }
792
-
793
- // coursier.maven.MavenAttributes.typeExtensions (2.1.24, which adds ejb): the packagings whose
794
- // artifact is a `.jar`. Any other packaging (pom, aar, war, ...) publishes its own artifact.
795
- private val JarPackagings = Set("eclipse-plugin", "maven-plugin", "hk2-jar", "orbit", "scala-jar", "jar", "bundle",
796
- "doc", "src", "test-jar", "ejb-client", "ejb")
797
-
798
- // coursier.paths.CachePath.localFile. A repository with credentials is cached under `user@host`,
799
- // and the update report does not carry the user.
800
- private def coursierLocalFiles(url: String, csrCacheDir: Option[File]): Seq[File] =
801
- if (url.startsWith("file:/"))
802
- try Seq(new File(new java.net.URI(url)))
803
- catch { case _: Exception => Nil }
804
- else {
805
- val i = url.indexOf(':')
806
- val protocol = if (i < 0) "" else url.substring(0, i)
807
- val rest = if (i < 0) "" else url.substring(i + 1).dropWhile(_ == '/')
808
- csrCacheDir.toSeq.flatMap { dir =>
809
- val protocolDir = new File(dir, coursierEscape(protocol))
810
- val host = coursierEscape(rest.takeWhile(_ != '/'))
811
- val path = coursierEscape(rest.dropWhile(_ != '/').drop(1))
812
- val withUser = Option(protocolDir.listFiles).toSeq.flatten.filter(_.getName.endsWith("%40" + host))
813
- (new File(protocolDir, host) +: withUser).map(new File(_, path))
814
- }
815
- }
816
-
817
- private def coursierEscape(s: String): String =
818
- s.flatMap { ch =>
819
- if (ch > 128 || " %$&+,:;=?@<>#".indexOf(ch) >= 0) "%" + "%02X".format(ch.toInt) else ch.toString
820
- }
821
-
822
- // ---- config selection ---------------------------------------------------
823
-
824
- // With no includes the default is ALL configurations (captures build/tooling deps).
825
- private def buildConfigMatcher(): String => Boolean = {
826
- def parse(prop: String): List[java.util.regex.Pattern] =
827
- sys.props.get(prop) match {
828
- case Some(s) if s.trim.nonEmpty =>
829
- s.split(",").map(_.trim).filter(_.nonEmpty).toList.map(globToRegex)
830
- case _ => Nil
831
- }
832
- val includes = parse("socket.includeConfigs")
833
- val excludes = parse("socket.excludeConfigs")
834
- (name: String) => {
835
- val included =
836
- if (includes.isEmpty) true
837
- else includes.exists(_.matcher(name).matches())
838
- included && !excludes.exists(_.matcher(name).matches())
839
- }
840
- }
841
-
842
- // Case-SENSITIVE (matching is documented as case-sensitive). Supports `*`, `?`, and `[...]`
843
- // character classes: enumerations (`[cC]`), ranges (`[a-z]`), and `[!..]`/`[^..]` negation. A
844
- // malformed glob falls back to a literal match, never throws.
845
- private def globToRegex(glob: String): java.util.regex.Pattern = {
846
- val sb = new StringBuilder
847
- var i = 0
848
- val n = glob.length
849
- while (i < n) {
850
- val c = glob.charAt(i)
851
- if (c == '*') { sb.append(".*"); i += 1 }
852
- else if (c == '?') { sb.append('.'); i += 1 }
853
- else if (c == '[') {
854
- val j = glob.indexOf(']', i + 1)
855
- // Treat as a class only with a non-empty body; else a literal `[`.
856
- if (j <= i + 1) { sb.append("\\["); i += 1 }
857
- else {
858
- var body = glob.substring(i + 1, j)
859
- val neg = body.startsWith("!")
860
- if (neg) body = body.substring(1)
861
- // Only literal chars and `-` ranges are meaningful; neutralize regex-class tricks.
862
- body = body.replace("\\", "\\\\").replace("[", "\\[").replace("&", "\\&")
863
- sb.append('[').append(if (neg) "^" else "").append(body).append(']')
864
- i = j + 1
865
- }
866
- } else if ("\\.^$|+(){}]".indexOf(c.toInt) >= 0) {
867
- sb.append('\\').append(c); i += 1
868
- } else { sb.append(c); i += 1 }
869
- }
870
- try java.util.regex.Pattern.compile(sb.toString)
871
- catch {
872
- case _: java.util.regex.PatternSyntaxException =>
873
- java.util.regex.Pattern.compile(java.util.regex.Pattern.quote(glob))
874
- }
875
- }
876
-
877
- // ConfigurationReport.configuration is a String on sbt 0.13, a ConfigRef on 1.x: read `.name` reflectively.
878
- private def confName(cr: ConfigurationReport): String = {
879
- val c: Any = cr.configuration
880
- try c.getClass.getMethod("name").invoke(c).toString
881
- catch { case _: Throwable => c.toString }
882
- }
883
-
884
- // `-Dsocket.excludePaths` → PRE-COMPILED, comma-joined, anchored regex pattern sources, used only
885
- // to skip whole excluded subprojects. The CLI compiles the user-facing globs in
886
- // exclude-paths-glob.mts (the single glob implementation, tested in CI); this plugin only
887
- // Pattern.compile()s what it receives.
888
- private def parseExcludeMatchers(): Seq[java.util.regex.Pattern] = {
889
- sys.props.get("socket.excludePaths").map(_.trim).filter(_.nonEmpty) match {
890
- case None => Nil
891
- case Some(raw) =>
892
- raw.split(",").toSeq.flatMap { r =>
893
- val p = r.trim
894
- // A pattern that doesn't compile is dropped, never thrown: the CLI emits a
895
- // dialect-portable subset, so this only guards against a broken transport.
896
- if (p.isEmpty) Nil
897
- else
898
- try Seq(java.util.regex.Pattern.compile(p))
899
- catch { case _: java.util.regex.PatternSyntaxException => Nil }
900
- }
901
- }
902
- }
903
-
904
- private def isExcludedPath(rel: String, patterns: Seq[java.util.regex.Pattern]): Boolean = {
905
- if (patterns.isEmpty) false
906
- else {
907
- var c = (if (rel == null) "" else rel).replace("\\", "/")
908
- while (c.startsWith("./")) c = c.substring(2)
909
- while (c.startsWith("/")) c = c.substring(1)
910
- while (c.endsWith("/")) c = c.substring(0, c.length - 1)
911
- if (c.isEmpty) false
912
- else patterns.exists(_.matcher(c).matches())
913
- }
914
- }
915
-
916
- private def isTestConf(name: String): Boolean = name.toLowerCase.contains("test")
917
-
918
- // Only feeds the informational `dev` flag, never gates analysis.
919
- private def isProdConf(name: String): Boolean = {
920
- val n = name.toLowerCase
921
- n == "compile" || n == "runtime"
922
- }
923
-
924
- // ---- misc helpers --------------------------------------------------------
925
-
926
- // sbt loads the `.sbt` files in a project's base directory into that project
927
- // (Load.configurationSources), so its build.sbt is the project's even when it sets nothing.
928
- private def baseBuildSbt(base: File, rootCanonPath: java.nio.file.Path): Option[File] =
929
- Some(new File(base, "build.sbt")).filter(f => f.isFile && f.getCanonicalFile.toPath.startsWith(rootCanonPath))
930
-
931
- private def boolProp(name: String): Boolean =
932
- java.lang.Boolean.parseBoolean(sys.props.getOrElse(name, "false"))
933
-
934
- private def readPopulateScope(): Option[Set[String]] = {
935
- sys.props.get("socket.populateFilesFor").map(_.trim).filter(_.nonEmpty) match {
936
- case None => None
937
- case Some(path) =>
938
- val f = new java.io.File(path)
939
- if (!f.exists) {
940
- println("[socket-facts] WARN populateFilesFor file not found; recording files for all resolved artifacts")
941
- None
942
- } else {
943
- val src = scala.io.Source.fromFile(f, "UTF-8")
944
- try {
945
- val set = src.getLines().map(_.trim).filter(_.nonEmpty).toSet
946
- if (set.isEmpty) {
947
- println("[socket-facts] WARN populateFilesFor file empty; recording files for all resolved artifacts")
948
- None
949
- } else {
950
- println("[socket-facts] --with-files scoped to " + set.size + " SBOM artifact(s)")
951
- Some(set)
952
- }
953
- } finally src.close()
954
- }
955
- }
956
- }
957
-
958
- private def orEmpty(v: String): String = if (v == null) "" else v
959
-
960
- private def moduleKey(m: ModuleID): String = orEmpty(m.organization) + ":" + orEmpty(m.name)
961
-
962
- private def gavKey(m: ModuleID): String = moduleKey(m) + ":" + orEmpty(m.revision)
963
-
964
- private def coordOf(m: ModuleID): String = {
965
- val rev = m.revision
966
- m.organization + ":" + m.name + (if (rev != null && rev.nonEmpty) ":" + rev else "")
967
- }
968
-
969
- private def extOf(a: Artifact): String = {
970
- val e = a.extension
971
- if (e == null || e.isEmpty) "jar" else e
972
- }
973
-
974
- private def classifierOf(a: Artifact): String =
975
- a.classifier.getOrElse("")
976
-
977
- // Backslash-escape so a value can never break line/field framing (see records.ts unescape).
978
- private def esc(v: String): String = {
979
- if (v == null) ""
980
- else v.replace("\\", "\\\\").replace("\t", "\\t").replace("\n", "\\n").replace("\r", "\\r")
981
- }
982
-
983
- // Empty `config`: the failure belongs to no configuration.
984
- private final case class Failure(coord: String, detail: String, config: String, project: String)
985
-
986
- private final case class Unscannable(detail: String, project: String)
987
-
988
- private final case class Coord(
989
- org: String,
990
- name: String,
991
- version: String,
992
- ext: String,
993
- classifier: String
994
- ) {
995
- val id: String = Seq(org, name, ext, classifier, version).filter(_.nonEmpty).mkString(":")
996
- }
997
-
998
- private final class Node(val coord: Coord) {
999
- val children = mutable.TreeSet.empty[String]
1000
- var direct = false
1001
- // Id of the build project this node is, when it is one.
1002
- var project = ""
1003
- // External artifact's resolved jar(s); --with-files only.
1004
- val targets = mutable.TreeSet.empty[String]
1005
- // An expected artifact was not fetched; --with-files only.
1006
- var unfetched = false
1007
- }
1008
-
1009
- // `unfetched`: why the expected artifact could not be fetched.
1010
- private final case class Variant(coord: Coord, file: Option[File], unfetched: Option[String])
1011
-
1012
- private final class RootTree(
1013
- val projectKey: String,
1014
- val config: String,
1015
- val prod: Boolean,
1016
- val nodes: mutable.LinkedHashMap[String, Node]
1017
- )
1018
- }