-
Notifications
You must be signed in to change notification settings - Fork 91
Get the direct dependencies while checking for promotion #952
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
yezhu6
wants to merge
2
commits into
main
Choose a base branch
from
yezhu/get-direct-deps
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,10 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT license. | ||
|
|
||
| import * as fs from 'fs'; | ||
| import * as path from 'path'; | ||
| import * as semver from 'semver'; | ||
| import { Uri } from 'vscode'; | ||
| import { Jdtls } from "../java/jdtls"; | ||
| import { NodeKind, type INodeData } from "../java/nodeData"; | ||
| import { type DependencyCheckItem, type UpgradeIssue, type PackageDescription, UpgradeReason } from "./type"; | ||
|
|
@@ -145,7 +148,7 @@ async function getDependencyIssues(dependencies: PackageDescription[]): Promise< | |
|
|
||
| async function getProjectIssues(projectNode: INodeData): Promise<UpgradeIssue[]> { | ||
| const issues: UpgradeIssue[] = []; | ||
| const dependencies = await getAllDependencies(projectNode); | ||
| const dependencies = await getDirectDependencies(projectNode); | ||
| issues.push(...await getCVEIssues(dependencies)); | ||
| issues.push(...getJavaIssues(projectNode)); | ||
| issues.push(...await getDependencyIssues(dependencies)); | ||
|
|
@@ -175,30 +178,181 @@ async function getWorkspaceIssues(workspaceFolderUri: string): Promise<UpgradeIs | |
| return workspaceIssues; | ||
| } | ||
|
|
||
| async function getAllDependencies(projectNode: INodeData): Promise<PackageDescription[]> { | ||
| const MAVEN_CONTAINER_PATH = "org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER"; | ||
| const GRADLE_CONTAINER_PATH = "org.eclipse.buildship.core.gradleclasspathcontainer"; | ||
|
|
||
| /** | ||
| * Parse direct dependencies from pom.xml file. | ||
| * Also checks parent pom.xml for multi-module projects. | ||
| */ | ||
| function parseDirectDependenciesFromPom(pomPath: string): Set<string> { | ||
| const directDeps = new Set<string>(); | ||
| try { | ||
| const pomContent = fs.readFileSync(pomPath, 'utf-8'); | ||
|
|
||
| // Extract dependencies from <dependencies> section (not inside <dependencyManagement>) | ||
| // First, remove dependencyManagement sections to avoid including managed deps | ||
| const withoutDepMgmt = pomContent.replace(/<dependencyManagement>[\s\S]*?<\/dependencyManagement>/g, ''); | ||
|
|
||
| // Match <dependency> blocks and extract groupId and artifactId | ||
| const dependencyRegex = /<dependency>\s*<groupId>([^<]+)<\/groupId>\s*<artifactId>([^<]+)<\/artifactId>/g; | ||
| let match; | ||
| while ((match = dependencyRegex.exec(withoutDepMgmt)) !== null) { | ||
| const groupId = match[1].trim(); | ||
| const artifactId = match[2].trim(); | ||
| // Skip property references like ${project.groupId} | ||
| if (!groupId.includes('${') && !artifactId.includes('${')) { | ||
| directDeps.add(`${groupId}:${artifactId}`); | ||
| } | ||
| } | ||
|
|
||
| // Check for parent pom in multi-module projects | ||
| const parentPomPath = path.join(path.dirname(pomPath), '..', 'pom.xml'); | ||
| if (fs.existsSync(parentPomPath)) { | ||
| const parentDeps = parseDirectDependenciesFromPom(parentPomPath); | ||
| parentDeps.forEach(dep => directDeps.add(dep)); | ||
| } | ||
| } catch { | ||
| // If we can't read the pom, return empty set | ||
| } | ||
| return directDeps; | ||
| } | ||
|
|
||
| /** | ||
| * Parse direct dependencies from build.gradle or build.gradle.kts file | ||
| */ | ||
| function parseDirectDependenciesFromGradle(gradlePath: string): Set<string> { | ||
| const directDeps = new Set<string>(); | ||
| try { | ||
| const gradleContent = fs.readFileSync(gradlePath, 'utf-8'); | ||
|
|
||
| // Match common dependency configurations: | ||
| // implementation 'group:artifact:version' | ||
| // implementation "group:artifact:version" | ||
| // api 'group:artifact:version' | ||
| // compileOnly, runtimeOnly, testImplementation, etc. | ||
| const shortFormRegex = /(?:implementation|api|compile|compileOnly|runtimeOnly|testImplementation|testCompileOnly|testRuntimeOnly)\s*\(?['"]([^:'"]+):([^:'"]+)(?::[^'"]*)?['"]\)?/g; | ||
| let match; | ||
| while ((match = shortFormRegex.exec(gradleContent)) !== null) { | ||
| const groupId = match[1].trim(); | ||
| const artifactId = match[2].trim(); | ||
| if (!groupId.includes('$') && !artifactId.includes('$')) { | ||
| directDeps.add(`${groupId}:${artifactId}`); | ||
| } | ||
| } | ||
|
|
||
| // Match map notation: implementation group: 'x', name: 'y', version: 'z' | ||
| const mapFormRegex = /(?:implementation|api|compile|compileOnly|runtimeOnly|testImplementation|testCompileOnly|testRuntimeOnly)\s*\(?group:\s*['"]([^'"]+)['"]\s*,\s*name:\s*['"]([^'"]+)['"]/g; | ||
| while ((match = mapFormRegex.exec(gradleContent)) !== null) { | ||
| const groupId = match[1].trim(); | ||
| const artifactId = match[2].trim(); | ||
| if (!groupId.includes('$') && !artifactId.includes('$')) { | ||
| directDeps.add(`${groupId}:${artifactId}`); | ||
| } | ||
| } | ||
| } catch { | ||
| // If we can't read the gradle file, return empty set | ||
| } | ||
| return directDeps; | ||
| } | ||
|
|
||
| /** | ||
| * Find the build file (pom.xml or build.gradle) for a project | ||
| */ | ||
| function findBuildFile(projectUri: string | undefined): { path: string; type: 'maven' | 'gradle' } | null { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. you can use "glob" to find the pom.xml files, remember to exclude certain folders to improve performance. you can find the usage of glob in vscode-java-upgrade. |
||
| if (!projectUri) { | ||
| return null; | ||
| } | ||
| try { | ||
| const projectPath = Uri.parse(projectUri).fsPath; | ||
|
|
||
| // Check for Maven | ||
| const pomPath = path.join(projectPath, 'pom.xml'); | ||
| if (fs.existsSync(pomPath)) { | ||
| return { path: pomPath, type: 'maven' }; | ||
| } | ||
|
|
||
| // Check for Gradle Kotlin DSL | ||
| const gradleKtsPath = path.join(projectPath, 'build.gradle.kts'); | ||
| if (fs.existsSync(gradleKtsPath)) { | ||
| return { path: gradleKtsPath, type: 'gradle' }; | ||
| } | ||
|
|
||
| // Check for Gradle Groovy DSL | ||
| const gradlePath = path.join(projectPath, 'build.gradle'); | ||
| if (fs.existsSync(gradlePath)) { | ||
| return { path: gradlePath, type: 'gradle' }; | ||
| } | ||
| } catch { | ||
| // Ignore errors | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| /** | ||
| * Parse direct dependencies from build file (Maven or Gradle) | ||
| */ | ||
| function parseDirectDependencies(buildFile: { path: string; type: 'maven' | 'gradle' }): Set<string> { | ||
| if (buildFile.type === 'maven') { | ||
| return parseDirectDependenciesFromPom(buildFile.path); | ||
| } else { | ||
| return parseDirectDependenciesFromGradle(buildFile.path); | ||
| } | ||
| } | ||
|
|
||
| async function getDirectDependencies(projectNode: INodeData): Promise<PackageDescription[]> { | ||
| const projectStructureData = await Jdtls.getPackageData({ kind: NodeKind.Project, projectUri: projectNode.uri }); | ||
| const packageContainers = projectStructureData.filter(x => x.kind === NodeKind.Container); | ||
| // Only include Maven or Gradle containers (not JRE or other containers) | ||
| const dependencyContainers = projectStructureData.filter(x => | ||
| x.kind === NodeKind.Container && | ||
| (x.path?.startsWith(MAVEN_CONTAINER_PATH) || x.path?.startsWith(GRADLE_CONTAINER_PATH)) | ||
| ); | ||
|
|
||
| // Get direct dependency identifiers from build file | ||
| const buildFile = findBuildFile(projectNode.uri); | ||
| const directDependencyIds = buildFile ? parseDirectDependencies(buildFile) : null; | ||
|
|
||
| const allPackages = await Promise.allSettled( | ||
| packageContainers.map(async (packageContainer) => { | ||
| dependencyContainers.map(async (packageContainer) => { | ||
| const packageNodes = await Jdtls.getPackageData({ | ||
| kind: NodeKind.Container, | ||
| projectUri: projectNode.uri, | ||
| path: packageContainer.path, | ||
| }); | ||
| return packageNodes.map(packageNodeToDescription).filter((x): x is PackageDescription => Boolean(x)); | ||
| return packageNodes | ||
| .map(packageNodeToDescription) | ||
| .filter((x): x is PackageDescription => Boolean(x)); | ||
| }) | ||
| ); | ||
|
|
||
| const fulfilled = allPackages.filter((x): x is PromiseFulfilledResult<PackageDescription[]> => x.status === "fulfilled"); | ||
| const failedPackageCount = allPackages.length - fulfilled.length; | ||
| if (failedPackageCount > 0) { | ||
| sendInfo("", { | ||
| operationName: "java.dependency.assessmentManager.getAllDependencies.rejected", | ||
| operationName: "java.dependency.assessmentManager.getDirectDependencies.rejected", | ||
| failedPackageCount: String(failedPackageCount), | ||
| }); | ||
| } | ||
| return fulfilled.map(x => x.value).flat(); | ||
|
|
||
| let dependencies = fulfilled.map(x => x.value).flat(); | ||
|
|
||
| // Filter to only direct dependencies if we have build file info | ||
| if (directDependencyIds && directDependencyIds.size > 0) { | ||
| dependencies = dependencies.filter(pkg => | ||
| directDependencyIds.has(`${pkg.groupId}:${pkg.artifactId}`) | ||
| ); | ||
| } | ||
|
|
||
| // Deduplicate by GAV coordinates | ||
| const seen = new Set<string>(); | ||
| return dependencies.filter(pkg => { | ||
| const key = `${pkg.groupId}:${pkg.artifactId}:${pkg.version}`; | ||
| if (seen.has(key)) { | ||
| return false; | ||
| } | ||
| seen.add(key); | ||
| return true; | ||
| }); | ||
| } | ||
|
|
||
| async function getCVEIssues(dependencies: PackageDescription[]): Promise<UpgradeIssue[]> { | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this may not be the fact. I think you can find all the pom.xml in this project first and then parse them one by one to find all the dependencies.