Skip to content

🐛 Increase Gradle compatibility#142

Merged
jmle merged 1 commit intokonveyor:mainfrom
jmle:MTA-5945
Aug 25, 2025
Merged

🐛 Increase Gradle compatibility#142
jmle merged 1 commit intokonveyor:mainfrom
jmle:MTA-5945

Conversation

@jmle
Copy link
Copy Markdown
Collaborator

@jmle jmle commented Aug 20, 2025

https://issues.redhat.com/browse/MTA-5907

Summary by CodeRabbit

  • New Features
    • Added a task to download all project source archives into a single consolidated directory with duplicate-safe handling.
  • Refactor
    • Unified source retrieval across projects for consistency and performance.
    • Enhanced resilience with non-failing error handling and clearer, per-project logging.
    • Streamlined output to a single download location instead of per-configuration copies.
  • Chores
    • Updated the container image to include the Gradle script required for the new source download capability.

Signed-off-by: Juan Manuel Leflet Estrada <jleflete@redhat.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Aug 20, 2025

Walkthrough

Adds a new Gradle script (build-v9.gradle) and wires it into the Docker image. Both the existing build.gradle and the new script implement a konveyorDownloadSources task that aggregates source artifacts across projects/configurations and copies them into a single build directory.

Changes

Cohort / File(s) Summary
Container integration
Dockerfile
Copies gradle/build-v9.gradle into the image at /usr/local/etc/task-v9.gradle.
Gradle v9 script (new)
gradle/build-v9.gradle
New script aggregates source artifacts at configuration time across projects (compileClasspath, runtimeClasspath, implementation, api), resolves sources classifiers via detached configurations with lenient, non-transitive views, stores in a shared list, and defines konveyorDownloadSources to copy them into build/downloaded-sources.
Gradle task refactor (existing)
gradle/build.gradle
Refactors konveyorDownloadSources to aggregate modules project-wide from selected resolvable configurations, resolve sources artifacts via detached configurations, and copy all found sources into a single build/download directory with improved logging and error handling.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Dev as Developer
  participant Gradle as Gradle
  participant Proj as All Projects
  participant Cfg as Target Configs (compileClasspath/runtimeClasspath/implementation/api)
  participant Repo as Repositories
  participant Task as konveyorDownloadSources

  Dev->>Gradle: run konveyorDownloadSources
  Gradle->>Proj: iterate projects
  Proj->>Cfg: collect resolvable configurations
  loop For each module (group:name:version)
    Cfg->>Gradle: create detached config (classifier=sources)
    Gradle->>Repo: resolve sources (lenient, non-transitive)
    Repo-->>Gradle: source jars/files (if available)
    Gradle->>Task: add resolved files to aggregate list
  end
  alt any sources found
    Task->>Task: copy to build/download(/downloaded-sources)
  else none found
    Task->>Task: log no sources available
  end
Loading
sequenceDiagram
  %% Variant: build-v9.gradle emphasizes config-time aggregation
  participant Gradle as Gradle (Config Time)
  participant Proj as All Projects
  participant Repo as Repositories
  participant Store as allProjectSourceFiles
  participant Task as konveyorDownloadSources

  Gradle->>Proj: scan target configs
  Proj->>Repo: resolve module sources via detached configs
  Repo-->>Store: append resolved source files (lenient)
  Note over Store,Task: At execution time
  Task->>Store: read aggregated files
  Task->>Task: copy to build/downloaded-sources
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I thump my paw—new scripts arrive!
Two trails to jars where sources thrive.
In burrows deep, I stash each find,
One basket now, all neatly lined.
Docker packs my carrot cache tight—
Hop, copy, build—we’re set for night. 🥕✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@jmle jmle changed the title Increase Gradle compatibility 🐛 Increase Gradle compatibility Aug 20, 2025
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (6)
gradle/build-v9.gradle (4)

21-41: Avoid re-resolving identical modules across multiple configurations (reduce duplicate work).

The same module can be present in multiple target configs (compileClasspath, runtimeClasspath, etc.). You dedupe within a config via unique(), but you still re-resolve across configs/projects. Maintain a global Set of seen module coordinates to prevent redundant detachedConfiguration resolutions.

Apply these diffs to introduce de-duplication:

@@
-// Collect all source files at configuration time
-def allProjectSourceFiles = []
+// Collect all source files at configuration time
+def allProjectSourceFiles = []
+// Track seen modules across all projects/configurations (group:name:version)
+def seenModules = new LinkedHashSet<String>()
@@
-            // Extract module identifiers for source resolution
+            // Extract module identifiers for source resolution
             def moduleIds = artifactResults.collect { artifactResult ->
                 def componentId = artifactResult.id.componentIdentifier
                 if (componentId instanceof ModuleComponentIdentifier) {
-                    return [
-                        group: componentId.group,
-                        name: componentId.module,
-                        version: componentId.version
-                    ]
+                    return [
+                        group: componentId.group,
+                        name: componentId.module,
+                        version: componentId.version
+                    ]
                 }
                 return null
             }.findAll { it != null }.unique()
@@
-            if (!moduleIds.isEmpty()) {
+            if (!moduleIds.isEmpty()) {
                 // Create source dependencies
-                def sourceDependencies = moduleIds.collect { moduleId ->
-                    proj.dependencies.create(
-                        "${moduleId.group}:${moduleId.name}:${moduleId.version}:sources"
-                    )
-                }
+                def sourceDependencies = moduleIds.collectMany { moduleId ->
+                    def coord = "${moduleId.group}:${moduleId.name}:${moduleId.version}"
+                    if (!seenModules.add(coord)) {
+                        return [] // already processed elsewhere
+                    }
+                    return [proj.dependencies.create("${coord}:sources")]
+                }

79-100: Make the task configuration-cache and up-to-date friendly (use task registration and proper inputs/outputs).

Currently, resolution and aggregation happen at configuration time, and the task captures a mutable list without declared inputs/outputs. Prefer tasks.register with typed task (Copy) and wire a Provider as input, with outputs to layout.buildDirectory. This improves configuration cache compatibility and up-to-date checks.

Consider refactoring the task as:

-task konveyorDownloadSources {
-    // Store the collected files as task input
-    def sourceFiles = allProjectSourceFiles
-
-    doLast {
-        // Copy all found source files
-        if (!sourceFiles.isEmpty()) {
-            def downloadDir = new File(project.layout.buildDirectory.get().asFile, "downloaded-sources")
-            downloadDir.mkdirs()
-
-            copy {
-                from sourceFiles
-                into downloadDir
-                duplicatesStrategy = DuplicatesStrategy.EXCLUDE
-            }
-
-            println "Downloaded ${sourceFiles.size()} source files to ${downloadDir}"
-        } else {
-            println "No source files found to download"
-        }
-    }
-}
+def collectedSources = project.layout.files({ allProjectSourceFiles })
+tasks.register('konveyorDownloadSources', Copy) {
+    from(collectedSources)
+    into(project.layout.buildDirectory.dir("downloaded-sources"))
+    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
+    // Optional: declare inputs/outputs explicitly for older Gradle
+    inputs.files(collectedSources)
+    outputs.dir(project.layout.buildDirectory.dir("downloaded-sources"))
+    doFirst {
+        if (collectedSources.asFileTree.isEmpty()) {
+            logger.lifecycle("No source files found to download")
+            // Copy does nothing when from is empty; keep behavior consistent.
+        } else {
+            logger.lifecycle("Downloading ${collectedSources.asFileTree.files.size()} source files ...")
+        }
+    }
+    doLast {
+        if (!collectedSources.asFileTree.isEmpty()) {
+            logger.lifecycle("Downloaded ${collectedSources.asFileTree.files.size()} source files to ${destinationDir ?: 'build/downloaded-sources'}")
+        }
+    }
+}

Note: This keeps collection at configuration time as you intended, but makes the copying task cacheable and incremental. If desired, the resolution itself can also be moved behind Providers to execute later.


64-70: Prefer Gradle logger over println for better build UX and CC safety.

Switch to logger.lifecycle/info/warn across the script. This produces consistent structured output and plays nicer with tooling.

Example:

-println "Found ${sourceFiles.size()} source files for ${proj.name}:${configName}"
+logger.lifecycle("Found ${sourceFiles.size()} source files for ${proj.name}:${configName}")

Apply similarly to other println statements.


86-96: Output directory name differs from Gradle 4–8 script (may confuse downstream tooling).

This script writes to build/downloaded-sources, while gradle/build.gradle writes to build/download. If any consumer expects a consistent path, this divergence can break flows.

Do we want both scripts to agree on the same target directory? If yes, align one to the other. For example, to match this script from the 4–8 script:

-            def downloadDir = new File(buildDir, "download")
+            def downloadDir = new File(buildDir, "downloaded-sources")

Or change this v9 script to “download” to match legacy behavior. Please confirm the expected path for downstream steps.

gradle/build.gradle (2)

71-76: Align output directory name with the v9 script (avoid divergent paths).

This script writes to build/download, while gradle/build-v9.gradle writes to build/downloaded-sources. For consistency and simpler downstream handling, use the same name in both.

Apply this diff if you prefer the v9 naming:

-            def downloadDir = new File(buildDir, "download")
+            def downloadDir = new File(buildDir, "downloaded-sources")

Alternatively, change the v9 file to “download” and keep this as-is. Please confirm the expected path.


74-78: Use enum for duplicatesStrategy for parity with v9 and static typing.

Small consistency/readability improvement.

-                duplicatesStrategy = "exclude"
+                duplicatesStrategy = DuplicatesStrategy.EXCLUDE

Note: org.gradle.api.file.DuplicatesStrategy is implicitly imported in Gradle scripts.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between fa57c2b and 7758e16.

📒 Files selected for processing (3)
  • Dockerfile (1 hunks)
  • gradle/build-v9.gradle (1 hunks)
  • gradle/build.gradle (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: e2e / e2e-api-integration-tests
  • GitHub Check: e2e / e2e-ui-integration-tests
🔇 Additional comments (3)
Dockerfile (1)

42-42: Ensure the correct Gradle init-script is selected at runtime

You’re now copying both
/usr/local/etc/task.gradle
/usr/local/etc/task-v9.gradle

into the image, but there’s no code in this repo that ever references or chooses between them. Without version‐detection logic in your launcher (e.g. jdtls.py or another wrapper), projects running on Gradle 8.14+ will still pick up the old task.gradle script.

Please verify (or implement) in your startup wrapper that you:

• Detect the Gradle version (for example, by parsing gradle --version)
• Conditionally invoke /usr/local/etc/task-v9.gradle when the version is ≥ 8.14, falling back to /usr/local/etc/task.gradle otherwise

This will ensure the new build-v9 script is actually used for newer Gradle versions.

gradle/build.gradle (2)

27-35: Heads-up: resolvedConfiguration API is deprecated in Gradle 8 and removed in 9.

This script is explicitly for Gradle 4–8, so usage is acceptable. Just ensure callers won’t apply this script on Gradle 9+, since it will fail there. The new v9 script covers 8.14+.

Confirm the runtime selects this script only for Gradle < 8.14 and uses build-v9.gradle for >= 8.14. If desired, I can provide a version-detection snippet to choose the correct script at runtime.


9-20: Nice narrowing to resolvable configurations.

Filtering with canBeResolved avoids accidental resolution of configurations like implementation/api when not resolvable. Good defensive practice across multi-plugin projects.

Comment thread gradle/build-v9.gradle
Comment on lines +30 to +36
def moduleIds = artifactResults.collect { artifactResult ->
def componentId = artifactResult.id.componentIdentifier
if (componentId instanceof ModuleComponentIdentifier) {
return [
group: componentId.group,
name: componentId.module,
version: componentId.version
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix missing import for ModuleComponentIdentifier (will fail at configuration time).

Gradle scripts don’t implicitly import org.gradle.api.artifacts.component.*. Referencing ModuleComponentIdentifier without an import will trigger “unable to resolve class ModuleComponentIdentifier” during configuration.

Apply this diff to add the import:

@@
 /**
  * Configuration cache compatible sources download task - compatible with Gradle 8.14+
  * All project iteration happens at configuration time
  */
 
+import org.gradle.api.artifacts.component.ModuleComponentIdentifier
+
 // Collect all source files at configuration time
 def allProjectSourceFiles = []
🤖 Prompt for AI Agents
In gradle/build-v9.gradle around lines 30 to 36, the script references
ModuleComponentIdentifier but lacks the required import which causes a
configuration-time "unable to resolve class ModuleComponentIdentifier" error;
add the import statement for
org.gradle.api.artifacts.component.ModuleComponentIdentifier near the top of the
file (with other imports) so the ModuleComponentIdentifier type resolves, then
re-run configuration to verify the error is gone.

jmle added a commit to konveyor/analyzer-lsp that referenced this pull request Aug 25, 2025
https://issues.redhat.com/browse/MTA-5907

Requires:
- konveyor/java-analyzer-bundle#142

Fixes:
- #878

Bundle PR: 142

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- New Features
  - Gradle 9 support when resolving source JARs.
  - Automatic detection of the Gradle wrapper and Gradle version.
- Automatic JAVA_HOME selection based on detected Gradle version and
per-run resolution.

- Bug Fixes
  - Exclude Gradle “constraint” entries from dependency results.
  - More robust Gradle dependency parsing and version extraction.
- Context-aware Gradle execution with per-invocation environment and
clearer errors when Java home or wrapper are unavailable.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Juan Manuel Leflet Estrada <jleflete@redhat.com>
@jmle jmle merged commit 69eff90 into konveyor:main Aug 25, 2025
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants