From 4d83590344f9daa28304766453c4556f9693ad50 Mon Sep 17 00:00:00 2001 From: Frank Viernau Date: Fri, 11 Oct 2024 09:00:02 +0200 Subject: [PATCH] refactor(pnpm): Make `Pnpm` separate from `Npm` Stop inheriting from `Npm` and rely entirely on the output of `pnpm` commands to figure out the necessary information. For example, do not re-construct the dependency from the file structure within `node_modles`, but rely on `pnpm list` instead. This reduces complexity and makes the implementation easy to understand, maintain or change. From the diff of the expected result files it becomes aparent that this change contains the following fixes: 1. htmlparser2 now dependends on domutils 1.7.0 instead of 1.5.1, which is inline with the dependency tree output by `pnpm list --depth 1000` 2. The cyclic reference from the workspace root project to itself is now included. Also note that it good to drop the `--shamefully-hoist` command line option, because it is not needed and its use is discouraged. Omiting it may also reduce the amount of warnings. Signed-off-by: Frank Viernau --- .../project-with-lockfile-expected-output.yml | 32 ++++- .../pnpm/workspaces-expected-output.yml | 8 ++ .../node/src/main/kotlin/Npm.kt | 2 +- .../node/src/main/kotlin/pnpm/ModuleInfo.kt | 48 ++++++++ .../node/src/main/kotlin/pnpm/Pnpm.kt | 112 ++++++++++++++++-- .../main/kotlin/pnpm/PnpmDependencyHandler.kt | 81 +++++++++++++ 6 files changed, 270 insertions(+), 13 deletions(-) create mode 100644 plugins/package-managers/node/src/main/kotlin/pnpm/ModuleInfo.kt create mode 100644 plugins/package-managers/node/src/main/kotlin/pnpm/PnpmDependencyHandler.kt diff --git a/plugins/package-managers/node/src/funTest/assets/projects/synthetic/pnpm/project-with-lockfile-expected-output.yml b/plugins/package-managers/node/src/funTest/assets/projects/synthetic/pnpm/project-with-lockfile-expected-output.yml index 133b94678ad6d..d97bcea77306c 100644 --- a/plugins/package-managers/node/src/funTest/assets/projects/synthetic/pnpm/project-with-lockfile-expected-output.yml +++ b/plugins/package-managers/node/src/funTest/assets/projects/synthetic/pnpm/project-with-lockfile-expected-output.yml @@ -47,7 +47,7 @@ project: - id: "NPM::domhandler:2.4.2" dependencies: - id: "NPM::domelementtype:1.3.1" - - id: "NPM::domutils:1.5.1" + - id: "NPM::domutils:1.7.0" dependencies: - id: "NPM::dom-serializer:0.1.1" dependencies: @@ -477,6 +477,36 @@ packages: url: "https://github.com/FB55/domutils.git" revision: "7d4bd16cd36ffce62362ef91616806ea27e30d95" path: "" +- id: "NPM::domutils:1.7.0" + purl: "pkg:npm/domutils@1.7.0" + authors: + - "Felix Boehm" + declared_licenses: + - "BSD-2-Clause" + declared_licenses_processed: + spdx_expression: "BSD-2-Clause" + description: "utilities for working with htmlparser2's dom" + homepage_url: "https://github.com/FB55/domutils#readme" + binary_artifact: + url: "" + hash: + value: "" + algorithm: "" + source_artifact: + url: "https://registry.npmjs.org/domutils/-/domutils-1.7.0.tgz" + hash: + value: "56ea341e834e06e6748af7a1cb25da67ea9f8c2a" + algorithm: "SHA-1" + vcs: + type: "Git" + url: "git://github.com/FB55/domutils.git" + revision: "34f193ca17d11a98d9310b1965efe5f73d32d79f" + path: "" + vcs_processed: + type: "Git" + url: "https://github.com/FB55/domutils.git" + revision: "34f193ca17d11a98d9310b1965efe5f73d32d79f" + path: "" - id: "NPM::eachr:3.3.0" purl: "pkg:npm/eachr@3.3.0" authors: diff --git a/plugins/package-managers/node/src/funTest/assets/projects/synthetic/pnpm/workspaces-expected-output.yml b/plugins/package-managers/node/src/funTest/assets/projects/synthetic/pnpm/workspaces-expected-output.yml index 61a42437989aa..fc08e23003218 100644 --- a/plugins/package-managers/node/src/funTest/assets/projects/synthetic/pnpm/workspaces-expected-output.yml +++ b/plugins/package-managers/node/src/funTest/assets/projects/synthetic/pnpm/workspaces-expected-output.yml @@ -89,6 +89,14 @@ analyzer: - id: "NPM::json-stable-stringify:1.0.1" dependencies: - id: "NPM::jsonify:0.0.0" + - id: "PNPM::pnpm-workspaces:1.0.1" + linkage: "PROJECT_DYNAMIC" + dependencies: + - id: "NPM::json-stable-stringify:1.0.1" + dependencies: + - id: "NPM::jsonify:0.0.0" + - id: "PNPM::pnpm-workspaces:1.0.1" + linkage: "PROJECT_DYNAMIC" - id: "PNPM::testing-pnpm-package-a:1.0.2" definition_file_path: "plugins/package-managers/node/src/funTest/assets/projects/synthetic/pnpm/workspaces/src/packages/package-a/package.json" authors: diff --git a/plugins/package-managers/node/src/main/kotlin/Npm.kt b/plugins/package-managers/node/src/main/kotlin/Npm.kt index 112571e8edb89..908d4512e91ae 100644 --- a/plugins/package-managers/node/src/main/kotlin/Npm.kt +++ b/plugins/package-managers/node/src/main/kotlin/Npm.kt @@ -603,7 +603,7 @@ internal fun parsePackage( return module } -private fun parseProject(packageJsonFile: File, analysisRoot: File, managerName: String): Project { +internal fun parseProject(packageJsonFile: File, analysisRoot: File, managerName: String): Project { Npm.logger.debug { "Parsing project info from '$packageJsonFile'." } val packageJson = parsePackageJson(packageJsonFile) diff --git a/plugins/package-managers/node/src/main/kotlin/pnpm/ModuleInfo.kt b/plugins/package-managers/node/src/main/kotlin/pnpm/ModuleInfo.kt new file mode 100644 index 0000000000000..ba9354be0a048 --- /dev/null +++ b/plugins/package-managers/node/src/main/kotlin/pnpm/ModuleInfo.kt @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2024 The ORT Project Authors (see ) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * License-Filename: LICENSE + */ + +package org.ossreviewtoolkit.plugins.packagemanagers.node.pnpm + +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +private val JSON = Json { ignoreUnknownKeys = true } + +internal fun parsePnpmList(json: String): List = JSON.decodeFromString(json) + +@Serializable +internal data class ModuleInfo( + val name: String, + val version: String, + val path: String, + val private: Boolean, + val dependencies: Map = emptyMap(), + val devDependencies: Map = emptyMap(), + val optionalDependencies: Map = emptyMap() +) { + @Serializable + data class Dependency( + val from: String, + val version: String, + val resolved: String? = null, + val path: String, + val dependencies: Map = emptyMap(), + val optionalDependencies: Map = emptyMap() + ) +} diff --git a/plugins/package-managers/node/src/main/kotlin/pnpm/Pnpm.kt b/plugins/package-managers/node/src/main/kotlin/pnpm/Pnpm.kt index 40d735ce9b81b..15d534dbf2ee7 100644 --- a/plugins/package-managers/node/src/main/kotlin/pnpm/Pnpm.kt +++ b/plugins/package-managers/node/src/main/kotlin/pnpm/Pnpm.kt @@ -1,5 +1,5 @@ /* - * Copyright (C) 2019 The ORT Project Authors (see ) + * Copyright (C) 2024 The ORT Project Authors (see ) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,15 +20,24 @@ package org.ossreviewtoolkit.plugins.packagemanagers.node.pnpm import java.io.File +import org.apache.logging.log4j.kotlin.logger import org.ossreviewtoolkit.analyzer.AbstractPackageManagerFactory +import org.ossreviewtoolkit.analyzer.PackageManager +import org.ossreviewtoolkit.analyzer.PackageManagerResult +import org.ossreviewtoolkit.model.DependencyGraph +import org.ossreviewtoolkit.model.ProjectAnalyzerResult import org.ossreviewtoolkit.model.config.AnalyzerConfiguration import org.ossreviewtoolkit.model.config.RepositoryConfiguration -import org.ossreviewtoolkit.plugins.packagemanagers.node.Npm +import org.ossreviewtoolkit.model.utils.DependencyGraphBuilder +import org.ossreviewtoolkit.plugins.packagemanagers.node.PackageJson +import org.ossreviewtoolkit.plugins.packagemanagers.node.parsePackageJson +import org.ossreviewtoolkit.plugins.packagemanagers.node.parseProject import org.ossreviewtoolkit.plugins.packagemanagers.node.utils.NodePackageManager import org.ossreviewtoolkit.plugins.packagemanagers.node.utils.NpmDetection +import org.ossreviewtoolkit.utils.common.CommandLineTool import org.ossreviewtoolkit.utils.common.Os -import org.ossreviewtoolkit.utils.common.realFile +import org.ossreviewtoolkit.utils.common.stashDirectories import org.semver4j.RangesList import org.semver4j.RangesListFactory @@ -41,7 +50,7 @@ class Pnpm( analysisRoot: File, analyzerConfig: AnalyzerConfiguration, repoConfig: RepositoryConfiguration -) : Npm(name, analysisRoot, analyzerConfig, repoConfig) { +) : PackageManager(name, analysisRoot, analyzerConfig, repoConfig), CommandLineTool { class Factory : AbstractPackageManagerFactory("PNPM") { override val globsForDefinitionFiles = listOf("package.json", "pnpm-lock.yaml") @@ -52,30 +61,80 @@ class Pnpm( ) = Pnpm(type, analysisRoot, analyzerConfig, repoConfig) } - override fun hasLockfile(projectDir: File) = NodePackageManager.PNPM.hasLockfile(projectDir) + private val handler = PnpmDependencyHandler(this) + private val graphBuilder by lazy { DependencyGraphBuilder(handler) } + private val packageDetailsCache = mutableMapOf() - override fun File.isWorkspaceDir() = realFile() in findWorkspaceSubmodules(analysisRoot) + override fun resolveDependencies(definitionFile: File, labels: Map): List = + stashDirectories(definitionFile.resolveSibling("node_modules")).use { + resolveDependencies(definitionFile) + } - override fun loadWorkspaceSubmodules(moduleDir: File): Set { - val process = run(moduleDir, "list", "--recursive", "--depth=-1", "--parseable") + private fun resolveDependencies(definitionFile: File): List { + val workingDir = definitionFile.parentFile + installDependencies(workingDir) - return process.stdout.lines().filter { it.isNotEmpty() }.mapTo(mutableSetOf()) { File(it) } + val workspaceModuleDirs = getWorkspaceModuleDirs(workingDir) + handler.setWorkspaceModuleDirs(workspaceModuleDirs) + + val moduleInfosForScope = Scope.entries.associateWith { scope -> listModules(workingDir, scope) } + + return workspaceModuleDirs.map { projectDir -> + val project = parseProject(projectDir.resolve("package.json"), analysisRoot, managerName) + + val scopeNames = Scope.entries.mapTo(mutableSetOf()) { scope -> + val scopeName = scope.toString() + val qualifiedScopeName = DependencyGraph.qualifyScope(project, scope.toString()) + val moduleInfo = moduleInfosForScope.getValue(scope).single { it.path == projectDir.absolutePath } + + moduleInfo.getScopeDependencies(scope).forEach { dependency -> + graphBuilder.addDependency(qualifiedScopeName, dependency) + } + + scopeName + } + + ProjectAnalyzerResult( + project = project.copy(scopeNames = scopeNames), + packages = emptySet(), + issues = emptyList() + ) + } } override fun command(workingDir: File?) = if (Os.isWindows) "pnpm.cmd" else "pnpm" + private fun getWorkspaceModuleDirs(workingDir: File): Set { + val json = run(workingDir, "list", "--json", "--only-projects", "--recursive").stdout + + return parsePnpmList(json).mapTo(mutableSetOf()) { File(it.path) } + } + + private fun listModules(workingDir: File, scope: Scope): List { + val scopeOption = when (scope) { + Scope.DEPENDENCIES -> "--prod" + Scope.DEV_DEPENDENCIES -> "--dev" + } + + val json = run(workingDir, "list", "--json", "--recursive", "--depth", "10000", scopeOption).stdout + + return parsePnpmList(json) + } + + override fun createPackageManagerResult(projectResults: Map>) = + PackageManagerResult(projectResults, graphBuilder.build(), graphBuilder.packages()) + override fun getVersionRequirement(): RangesList = RangesListFactory.create("5.* - 9.*") override fun mapDefinitionFiles(definitionFiles: List) = NpmDetection(definitionFiles).filterApplicable(NodePackageManager.PNPM) - override fun runInstall(workingDir: File) = + private fun installDependencies(workingDir: File) = run( "install", "--ignore-pnpmfile", "--ignore-scripts", "--frozen-lockfile", // Use the existing lockfile instead of updating an outdated one. - "--shamefully-hoist", // Build a similar node_modules structure as NPM and Yarn does. workingDir = workingDir ) @@ -83,4 +142,35 @@ class Pnpm( // We do not actually depend on any features specific to a PNPM version, but we still want to stick to a // fixed major version to be sure to get consistent results. checkVersion() + + internal fun getRemotePackageDetails(workingDir: File, packageName: String): PackageJson? { + packageDetailsCache[packageName]?.let { return it } + + return runCatching { + val process = run(workingDir, "info", "--json", packageName) + + parsePackageJson(process.stdout) + }.onFailure { e -> + logger.warn { "Error getting details for $packageName in directory $workingDir: ${e.message.orEmpty()}" } + }.getOrNull()?.also { + packageDetailsCache[packageName] = it + } + } } + +private enum class Scope(val descriptor: String) { + DEPENDENCIES("dependencies"), + DEV_DEPENDENCIES("devDependencies"); + + override fun toString(): String = descriptor +} + +private fun ModuleInfo.getScopeDependencies(scope: Scope) = + when (scope) { + Scope.DEPENDENCIES -> buildList { + addAll(dependencies.values) + addAll(optionalDependencies.values) + } + + Scope.DEV_DEPENDENCIES -> devDependencies.values.toList() + } diff --git a/plugins/package-managers/node/src/main/kotlin/pnpm/PnpmDependencyHandler.kt b/plugins/package-managers/node/src/main/kotlin/pnpm/PnpmDependencyHandler.kt new file mode 100644 index 0000000000000..3c80132c4977c --- /dev/null +++ b/plugins/package-managers/node/src/main/kotlin/pnpm/PnpmDependencyHandler.kt @@ -0,0 +1,81 @@ +/* + * Copyright (C) 2024 The ORT Project Authors (see ) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * License-Filename: LICENSE + */ + +package org.ossreviewtoolkit.plugins.packagemanagers.node.pnpm + +import java.io.File + +import org.ossreviewtoolkit.model.Identifier +import org.ossreviewtoolkit.model.Issue +import org.ossreviewtoolkit.model.Package +import org.ossreviewtoolkit.model.PackageLinkage +import org.ossreviewtoolkit.model.utils.DependencyHandler +import org.ossreviewtoolkit.plugins.packagemanagers.node.PackageJson +import org.ossreviewtoolkit.plugins.packagemanagers.node.parsePackage +import org.ossreviewtoolkit.plugins.packagemanagers.node.parsePackageJson +import org.ossreviewtoolkit.plugins.packagemanagers.node.pnpm.ModuleInfo.Dependency +import org.ossreviewtoolkit.utils.common.realFile + +internal class PnpmDependencyHandler(private val pnpm: Pnpm) : DependencyHandler { + private val workspaceModuleDirs = mutableSetOf() + private val packageJsonCache = mutableMapOf() + + private fun Dependency.isProject() = File(path).realFile().absoluteFile in workspaceModuleDirs + + fun setWorkspaceModuleDirs(dirs: Collection) { + workspaceModuleDirs.apply { + clear() + addAll(dirs) + } + } + + override fun identifierFor(dependency: Dependency): Identifier { + val type = pnpm.managerName.takeIf { dependency.isProject() } ?: "NPM" + val namespace = dependency.from.substringBeforeLast("/", "") + val name = dependency.from.substringAfterLast("/") + val version = if (dependency.isProject()) { + readPackageJson(dependency.packageJsonFile).version.orEmpty() + } else { + dependency.version.takeUnless { it.startsWith("link:") || it.startsWith("file:") }.orEmpty() + } + + return Identifier(type, namespace, name, version) + } + + override fun dependenciesFor(dependency: Dependency): List = + (dependency.dependencies + dependency.optionalDependencies).values.toList() + + override fun linkageFor(dependency: Dependency): PackageLinkage = + PackageLinkage.DYNAMIC.takeUnless { dependency.isProject() } ?: PackageLinkage.PROJECT_DYNAMIC + + override fun createPackage(dependency: Dependency, issues: MutableCollection): Package? = + dependency.takeUnless { it.isProject() }?.let { + parsePackage( + workingDir = it.workingDir, + packageJsonFile = it.packageJsonFile, + getRemotePackageDetails = pnpm::getRemotePackageDetails + ) + } + + private fun readPackageJson(packageJsonFile: File): PackageJson = + packageJsonCache.getOrPut(packageJsonFile.realFile()) { parsePackageJson(packageJsonFile) } +} + +private val Dependency.workingDir: File get() = File(path) +private val Dependency.packageJsonFile: File get() = File(path, "package.json")