|
| 1 | +/* |
| 2 | + * Copyright (C) 2025 The ORT Project Authors (see <https://github.com/oss-review-toolkit/ort/blob/main/NOTICE>) |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + * |
| 16 | + * SPDX-License-Identifier: Apache-2.0 |
| 17 | + * License-Filename: LICENSE |
| 18 | + */ |
| 19 | + |
| 20 | +package org.ossreviewtoolkit.plugins.packagemanagers.maven |
| 21 | + |
| 22 | +import java.io.File |
| 23 | +import java.io.PrintStream |
| 24 | +import java.util.concurrent.atomic.AtomicReference |
| 25 | + |
| 26 | +import org.apache.logging.log4j.kotlin.logger |
| 27 | +import org.apache.maven.AbstractMavenLifecycleParticipant |
| 28 | +import org.apache.maven.cli.MavenCli |
| 29 | +import org.apache.maven.execution.MavenSession |
| 30 | +import org.apache.maven.project.MavenProject |
| 31 | + |
| 32 | +import org.codehaus.plexus.DefaultPlexusContainer |
| 33 | +import org.codehaus.plexus.PlexusContainer |
| 34 | +import org.codehaus.plexus.classworlds.ClassWorld |
| 35 | +import org.codehaus.plexus.logging.BaseLoggerManager |
| 36 | + |
| 37 | +import org.eclipse.aether.graph.DependencyNode |
| 38 | + |
| 39 | +import org.ossreviewtoolkit.analyzer.AbstractPackageManagerFactory |
| 40 | +import org.ossreviewtoolkit.analyzer.PackageManager |
| 41 | +import org.ossreviewtoolkit.analyzer.PackageManagerResult |
| 42 | +import org.ossreviewtoolkit.analyzer.ProjectResults |
| 43 | +import org.ossreviewtoolkit.model.DependencyGraph |
| 44 | +import org.ossreviewtoolkit.model.ProjectAnalyzerResult |
| 45 | +import org.ossreviewtoolkit.model.config.AnalyzerConfiguration |
| 46 | +import org.ossreviewtoolkit.model.config.RepositoryConfiguration |
| 47 | +import org.ossreviewtoolkit.model.utils.DependencyGraphBuilder |
| 48 | +import org.ossreviewtoolkit.plugins.packagemanagers.maven.utils.DependencyTreeLogger |
| 49 | +import org.ossreviewtoolkit.plugins.packagemanagers.maven.utils.LocalProjectWorkspaceReader |
| 50 | +import org.ossreviewtoolkit.plugins.packagemanagers.maven.utils.MavenDependencyHandler |
| 51 | +import org.ossreviewtoolkit.plugins.packagemanagers.maven.utils.MavenLogger |
| 52 | +import org.ossreviewtoolkit.plugins.packagemanagers.maven.utils.MavenSupport |
| 53 | +import org.ossreviewtoolkit.plugins.packagemanagers.maven.utils.identifier |
| 54 | +import org.ossreviewtoolkit.plugins.packagemanagers.maven.utils.internalId |
| 55 | +import org.ossreviewtoolkit.plugins.packagemanagers.maven.utils.isTychoProject |
| 56 | +import org.ossreviewtoolkit.plugins.packagemanagers.maven.utils.parseDependencyTree |
| 57 | +import org.ossreviewtoolkit.plugins.packagemanagers.maven.utils.toOrtProject |
| 58 | +import org.ossreviewtoolkit.utils.ort.createOrtTempFile |
| 59 | + |
| 60 | +/** |
| 61 | + * A package manager implementation supporting Maven projects using [Tycho](https://github.com/eclipse-tycho/tycho). |
| 62 | + */ |
| 63 | +class Tycho( |
| 64 | + name: String, |
| 65 | + analysisRoot: File, |
| 66 | + analyzerConfig: AnalyzerConfiguration, |
| 67 | + repoConfig: RepositoryConfiguration |
| 68 | +) : PackageManager(name, "Tycho", analysisRoot, analyzerConfig, repoConfig) { |
| 69 | + class Factory : AbstractPackageManagerFactory<Tycho>("Tycho") { |
| 70 | + override val globsForDefinitionFiles = listOf("pom.xml") |
| 71 | + |
| 72 | + override fun create( |
| 73 | + analysisRoot: File, |
| 74 | + analyzerConfig: AnalyzerConfiguration, |
| 75 | + repoConfig: RepositoryConfiguration |
| 76 | + ) = Tycho(type, analysisRoot, analyzerConfig, repoConfig) |
| 77 | + } |
| 78 | + |
| 79 | + /** |
| 80 | + * The builder to generate the dependency graph. This could actually be a local variable, but it is also needed |
| 81 | + * to construct the final [PackageManagerResult]. |
| 82 | + */ |
| 83 | + private lateinit var graphBuilder: DependencyGraphBuilder<DependencyNode> |
| 84 | + |
| 85 | + override fun mapDefinitionFiles(definitionFiles: List<File>): List<File> = definitionFiles.filter(::isTychoProject) |
| 86 | + |
| 87 | + override fun resolveDependencies(definitionFile: File, labels: Map<String, String>): List<ProjectAnalyzerResult> { |
| 88 | + logger.info { "Resolving Tycho dependencies for $definitionFile." } |
| 89 | + |
| 90 | + val collector = TychoProjectsCollector() |
| 91 | + val (_, buildLog) = runBuild(collector, definitionFile.parentFile) |
| 92 | + // TODO: Create issues for a failed build and projects for which dependencies could not be resolved. |
| 93 | + |
| 94 | + val resolvedProjects = createMavenSupport(collector).use { mavenSupport -> |
| 95 | + val dependencyHandler = |
| 96 | + MavenDependencyHandler(managerName, projectType, mavenSupport, collector.mavenProjects, false) |
| 97 | + |
| 98 | + graphBuilder = DependencyGraphBuilder(dependencyHandler) |
| 99 | + |
| 100 | + buildLog.inputStream().use { stream -> |
| 101 | + parseDependencyTree(stream, collector.mavenProjects.values).map { projectNode -> |
| 102 | + val project = collector.mavenProjects.getValue(projectNode.artifact.identifier()) |
| 103 | + processProjectDependencies(graphBuilder, project, projectNode.children) |
| 104 | + project |
| 105 | + }.toList() |
| 106 | + } |
| 107 | + } |
| 108 | + |
| 109 | + buildLog.delete() |
| 110 | + |
| 111 | + return resolvedProjects.map { mavenProject -> |
| 112 | + val projectId = mavenProject.identifier(projectType) |
| 113 | + val project = mavenProject.toOrtProject( |
| 114 | + projectId, |
| 115 | + mavenProject.file, |
| 116 | + mavenProject.file.parentFile, |
| 117 | + graphBuilder.scopesFor(projectId) |
| 118 | + ) |
| 119 | + ProjectAnalyzerResult(project, emptySet()) |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + override fun createPackageManagerResult(projectResults: ProjectResults): PackageManagerResult = |
| 124 | + PackageManagerResult(projectResults, graphBuilder.build(), graphBuilder.packages()) |
| 125 | + |
| 126 | + /** |
| 127 | + * Create the [MavenCli] instance to trigger a build on the analyzed project. Register the given [collector], so |
| 128 | + * that it is invoked during the build. Also install a specific logger that forwards the output of the dependency |
| 129 | + * tree plugin to the given [outputStream]. |
| 130 | + */ |
| 131 | + private fun createMavenCli(collector: TychoProjectsCollector, outputStream: PrintStream): MavenCli = |
| 132 | + object : MavenCli(ClassWorld("plexus.core", javaClass.classLoader)) { |
| 133 | + override fun customizeContainer(container: PlexusContainer) { |
| 134 | + container.addComponent( |
| 135 | + collector, |
| 136 | + AbstractMavenLifecycleParticipant::class.java, |
| 137 | + "TychoProjectsCollector" |
| 138 | + ) |
| 139 | + |
| 140 | + (container as? DefaultPlexusContainer)?.loggerManager = object : BaseLoggerManager() { |
| 141 | + override fun createLogger(name: String): org.codehaus.plexus.logging.Logger = |
| 142 | + if (DEPENDENCY_TREE_LOGGER == name) { |
| 143 | + DependencyTreeLogger(outputStream) |
| 144 | + } else { |
| 145 | + MavenLogger(logger.delegate.level) |
| 146 | + } |
| 147 | + } |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + /** |
| 152 | + * Run a Maven build on the Tycho project in [projectRoot] utilizing the given [collector]. Return a pair with |
| 153 | + * the exit code of the Maven project and a [File] that contains the output generated during the build. |
| 154 | + */ |
| 155 | + private fun runBuild(collector: TychoProjectsCollector, projectRoot: File): Pair<Int, File> { |
| 156 | + // The Maven CLI seems to change the context class loader. This has side effects on ORT's plugin mechanism. |
| 157 | + // To prevent this, store the class loader and restore it at the end of this function. |
| 158 | + val tccl = Thread.currentThread().contextClassLoader |
| 159 | + |
| 160 | + try { |
| 161 | + val buildLog = createOrtTempFile() |
| 162 | + |
| 163 | + val exitCode = PrintStream(buildLog.outputStream()).use { out -> |
| 164 | + val cli = createMavenCli(collector, out) |
| 165 | + |
| 166 | + // With the current CLI API, there does not seem to be another way to set the build root folder than |
| 167 | + // using a system property. |
| 168 | + System.setProperty(MavenCli.MULTIMODULE_PROJECT_DIRECTORY, projectRoot.absolutePath) |
| 169 | + |
| 170 | + cli.doMain( |
| 171 | + // The "package" goal is required; otherwise the Tycho extension is not activated. |
| 172 | + arrayOf("package", "dependency:tree", "-DoutputType=json"), |
| 173 | + projectRoot.path, |
| 174 | + null, |
| 175 | + null |
| 176 | + ).also { logger.info { "Tycho analysis completed. Exit code: $it." } } |
| 177 | + } |
| 178 | + |
| 179 | + return exitCode to buildLog |
| 180 | + } finally { |
| 181 | + Thread.currentThread().contextClassLoader = tccl |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + /** |
| 186 | + * Create a [MavenSupport] instance to be used for resolving the packages found during the Maven build. Obtain |
| 187 | + * the local projects from the given [collector] |
| 188 | + */ |
| 189 | + private fun createMavenSupport(collector: TychoProjectsCollector): MavenSupport { |
| 190 | + val localProjects = collector.mavenProjects |
| 191 | + val resolveFunc: (String) -> File? = { projectId -> localProjects[projectId]?.file } |
| 192 | + |
| 193 | + return MavenSupport(LocalProjectWorkspaceReader(resolveFunc)) |
| 194 | + } |
| 195 | + |
| 196 | + /** |
| 197 | + * Process the [dependencies] of the given [project] by adding them to the [graphBuilder]. |
| 198 | + */ |
| 199 | + private fun processProjectDependencies( |
| 200 | + graphBuilder: DependencyGraphBuilder<DependencyNode>, |
| 201 | + project: MavenProject, |
| 202 | + dependencies: Collection<DependencyNode> |
| 203 | + ) { |
| 204 | + val projectId = project.identifier(projectType) |
| 205 | + |
| 206 | + dependencies.forEach { node -> |
| 207 | + graphBuilder.addDependency(DependencyGraph.qualifyScope(projectId, node.dependency.scope), node) |
| 208 | + } |
| 209 | + } |
| 210 | +} |
| 211 | + |
| 212 | +/** The name of the logger used by the Maven dependency tree plugin. */ |
| 213 | +private const val DEPENDENCY_TREE_LOGGER = "org.apache.maven.plugins.dependency.tree.TreeMojo" |
| 214 | + |
| 215 | +/** |
| 216 | + * An internal helper class that gets registered as a Maven lifecycle participant to obtain all [MavenProject]s |
| 217 | + * encountered during the build. |
| 218 | + */ |
| 219 | +internal class TychoProjectsCollector : AbstractMavenLifecycleParticipant() { |
| 220 | + /** |
| 221 | + * Stores the projects that have been found during the Maven build. To be on the safe side with regard to |
| 222 | + * possible threading issues, use an [AtomicReference] to ensure safe publication. |
| 223 | + */ |
| 224 | + private val projects = AtomicReference<Map<String, MavenProject>>(emptyMap()) |
| 225 | + |
| 226 | + /** |
| 227 | + * Return the projects that have been found during the Maven build. |
| 228 | + */ |
| 229 | + val mavenProjects: Map<String, MavenProject> |
| 230 | + get() = projects.get() |
| 231 | + |
| 232 | + override fun afterSessionEnd(session: MavenSession) { |
| 233 | + val builtProjects = session.projects.associateBy(MavenProject::internalId) |
| 234 | + projects.set(builtProjects) |
| 235 | + |
| 236 | + logger.info { "Found ${builtProjects.size} projects during build." } |
| 237 | + } |
| 238 | +} |
0 commit comments