Skip to content

Commit

Permalink
fix(OrtModelBuilder): Add an OrtDependency cache
Browse files Browse the repository at this point in the history
Only create one 'OrtDependency' for each 'ResolvedComponentResult'.
The 'ResolvedComponentResult' is immutable and therefore all
'OrtDependency' object derived from the same 'ResolvedComponentResult'
have the same content. Hence, we can reuse these objects to save memory
and computation time.

This PR is a refined version of the fix posted in the error description
of [1].

[1]: #9763

Signed-off-by: Jendrik Johannes <[email protected]>
  • Loading branch information
jjohannes authored and sschuberth committed Jan 23, 2025
1 parent 33b7a4f commit 7c63104
Showing 1 changed file with 14 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import org.gradle.api.artifacts.component.ProjectComponentIdentifier
import org.gradle.api.artifacts.component.ProjectComponentSelector
import org.gradle.api.artifacts.result.DependencyResult
import org.gradle.api.artifacts.result.ResolvedArtifactResult
import org.gradle.api.artifacts.result.ResolvedComponentResult
import org.gradle.api.artifacts.result.ResolvedDependencyResult
import org.gradle.api.artifacts.result.UnresolvedDependencyResult
import org.gradle.api.internal.GradleInternal
Expand All @@ -56,6 +57,9 @@ internal class OrtModelBuilder : ToolingModelBuilder {
private val warnings = mutableListOf<String>()
private val globalDependencySubtrees = mutableMapOf<String, List<OrtDependency>>()

// Only create one "OrtDependency" for each "ResolvedComponentResult".
private val ortDependencyCache = mutableMapOf<ResolvedComponentResult, OrtDependency>()

override fun canBuild(modelName: String): Boolean = modelName == OrtDependencyTreeModel::class.java.name

override fun buildAll(modelName: String, project: Project): OrtDependencyTreeModel {
Expand Down Expand Up @@ -165,6 +169,10 @@ internal class OrtModelBuilder : ToolingModelBuilder {
// Cut the graph on cyclic dependencies.
if (id in visited) return@mapNotNull null

if (selectedComponent in ortDependencyCache) {
return@mapNotNull ortDependencyCache[selectedComponent]
}

when (id) {
is ModuleComponentIdentifier -> {
val pomFile = if (selectedComponent is ResolvedComponentResultInternal) {
Expand Down Expand Up @@ -231,7 +239,9 @@ internal class OrtModelBuilder : ToolingModelBuilder {
)
},
localPath = null
)
).also {
ortDependencyCache[selectedComponent] = it
}
}

is ProjectComponentIdentifier -> {
Expand All @@ -250,7 +260,9 @@ internal class OrtModelBuilder : ToolingModelBuilder {
pomFile = null,
mavenModel = null,
localPath = id.projectPath
)
).also {
ortDependencyCache[selectedComponent] = it
}
}

else -> {
Expand Down

0 comments on commit 7c63104

Please sign in to comment.