Skip to content

Conversation

@gaosaroma
Copy link
Collaborator

@gaosaroma gaosaroma commented May 14, 2025

根据基座插件打出的 bom 瘦身及瘦身优化:

  1. 瘦身优化:
    a. 配置优化:如果模块配置的 parent 是基座 starter,且模块 sofa-ark-maven-plugin 中配置了 baseDependencyParentIdentity 标识,那么就会根据该 starter 做瘦身:将瘦身所有基座中有的依赖(GroupId 和 artifactId 相同即可);
    b. 日志优化:打印瘦身了但基座中没有的依赖;打印瘦身了但基座里不同版本的依赖。
    c. 构建防御:如果配置了 buildFailWhenExcludeDiffBaseDependency = true 且瘦身了基座中没有或基座有不同版本的依赖,那么直接构建失败
  2. 根据基座插件打出的 bom 瘦身:
    当模块配置的 parent 是基座 starter、且模块 sofa-ark-maven-plugin 中配置了 baseDependencyParentIdentity 标识、且模块正在 dependencyManagement 中引入了基座插件打出的 plugin-bom (打 plugin-bom 的方式见 Feat build plugin bom koupleless/runtime#244 ),那么瘦身时,将一同瘦身该 bom 中 dependencyManagement 中声明的依赖。如:
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.alipay.lipengtestsingle</groupId>
                <artifactId>lipengtestsingle-plugin-bom</artifactId>
                <version>0.0.1</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
        </dependencies>
    </dependencyManagement>

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 14, 2025

Walkthrough

This change refactors the module slimming logic in the Maven plugin by renaming ModuleSlimStrategy to ModuleSlimExecutor, expanding artifact filtering to include base plugin dependencies, centralizing Maven artifact identity utilities, and updating related tests. It also updates the project version to 2.3.2-SNAPSHOT and removes an unused configuration flag.

Changes

File(s) Change Summary
pom.xml Updated <sofa.ark.version> from 2.3.1 to 2.3.2-SNAPSHOT.
.../MavenUtils.java Added utility methods for constructing Maven artifact and parent identities without and with version.
.../ModuleSlimConfig.java Removed the excludeSameBaseDependency field and its getter/setter.
.../ModuleSlimExecutor.java
(formerly ModuleSlimStrategy.java)
Renamed class, updated constructor, expanded artifact filtering to include base plugin dependencies, centralized identity logic via MavenUtils, improved error reporting, and refactored configuration and helper methods.
.../RepackageMojo.java Injected ProjectBuilder component, updated Javadoc for baseDependencyParentIdentity, and replaced usage of ModuleSlimStrategy with ModuleSlimExecutor.
.../utils/ParseUtils.java Added a method to retrieve boolean configuration values from both Properties and YAML sources with a default fallback.
.../ModuleSlimExecutorTest.java
(formerly ModuleSlimStrategyTest.java)
Renamed test class, updated all usages to ModuleSlimExecutor, adjusted constructor calls and method signatures, added test for base plugin BOM filtering, and enhanced mocking for Maven project models.
.../RepackageMojoTest.java Changed imports of ExcludeConfig and ExcludeConfigResponse from ModuleSlimStrategy to ModuleSlimExecutor; no test logic changes.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MavenPlugin (RepackageMojo)
    participant ModuleSlimExecutor
    participant MavenUtils
    participant ProjectBuilder
    participant RepositorySystem

    User->>MavenPlugin: Run plugin goal
    MavenPlugin->>ModuleSlimExecutor: Instantiate with project, config, ProjectBuilder, RepositorySystem, etc.
    ModuleSlimExecutor->>MavenUtils: Retrieve artifact/parent identities
    ModuleSlimExecutor->>ProjectBuilder: Resolve POM models for base plugins
    ModuleSlimExecutor->>RepositorySystem: (If needed) Resolve artifacts
    ModuleSlimExecutor->>MavenPlugin: Return slimmed artifacts
Loading

Possibly related PRs

  • sofastack/sofa-ark#1070: Refactors and renames ModuleSlimStrategy to ModuleSlimExecutor and updates artifact filtering logic, closely related as both PRs modify the same class and exclusion/error handling logic.
  • sofastack/sofa-ark#1017: Adds and later removes the excludeSameBaseDependency field and related logic in module slimming, overlapping with the configuration and artifact filtering changes in this PR.
  • sofastack/sofa-ark#1019: Improves artifact identity handling in module slimming logic, which is further refactored and centralized in this PR.

Suggested labels

cla:yes, size/L

Suggested reviewers

  • lvjing2

Poem

In the garden where Maven hops,
A rabbit refactors, never stops.
Slimming modules, filtering with care,
New executors and tests everywhere!
With snapshot dreams and identities neat,
This code hop makes the build more fleet.
🐇✨

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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.

Copy link
Contributor

@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

🔭 Outside diff range comments (1)
sofa-ark-parent/support/ark-maven-plugin/src/main/java/com/alipay/sofa/ark/boot/mojo/ModuleSlimExecutor.java (1)

95-105: ⚠️ Potential issue

Constructor allows null collaborators that are later dereferenced

repositorySystem and projectBuilder are optional in the tests, but they are required at runtime (see resolvePomAsOriginalModel).
Passing null will lead to a NullPointerException during real execution or during certain test paths that do not stub the method.

Add Objects.requireNonNull checks (or fall-back strategies) so incorrect wiring fails fast and clearly.

 this.repositorySystem = repositorySystem;
 this.projectBuilder = projectBuilder;
+Objects.requireNonNull(this.repositorySystem,  "repositorySystem must not be null");
+Objects.requireNonNull(this.projectBuilder,    "projectBuilder must not be null");
🧹 Nitpick comments (4)
sofa-ark-parent/support/ark-maven-plugin/src/main/java/com/alipay/sofa/ark/boot/mojo/MavenUtils.java (1)

170-181: Add null–safety (and reuse existing helpers) in the new GA/GAV helpers**

All newly-added helpers blindly dereference artifact / parent, which is consistent with older methods in the class, but it propagates NPEs outward and forces every caller to guard against null.
Because these helpers will be called from slimming code that processes partially-resolved models, an occasional null is realistic (e.g., optional‐scope artifacts, failed model resolution).

Consider a defensive implementation that returns null or an empty string when the input is null, or use Objects.requireNonNull() so the failure is explicit.
Additionally, note that getArtifactIdentityWithoutVersion(Artifact) already returns “GA[:classifier]:type”, so the GA helpers could delegate to it to avoid duplication.

-    public static String getGAIdentity(Artifact artifact) {
-        return artifact.getGroupId() + STRING_COLON + artifact.getArtifactId();
-    }
+    public static String getGAIdentity(Artifact artifact) {
+        if (artifact == null) {
+            return null;
+        }
+        return artifact.getGroupId() + STRING_COLON + artifact.getArtifactId();
+    }
sofa-ark-parent/support/ark-maven-plugin/src/main/java/com/alipay/sofa/ark/boot/mojo/ModuleSlimExecutor.java (2)

151-159: Minor optimisation: avoid building large interim sets twice

dependencyIdentities is recomputed for every call to getSameArtifactsInBasePlugin, yet it only depends on the resolved BOM models.
Moving this calculation to getBasePluginModel() (and caching the result) would avoid repeated stream traversals when multiple modules are processed.


188-223: Version-mismatch check may still throw NPEs

baseDependencyIdentityWithoutVersion.get(identity) can return null (e.g., shrink-wrapped list mismatch) causing getDependencyIdentity(null) to NPE when logging.
Guard the call or log the raw identity to keep the build from crashing while still surfacing the error.

sofa-ark-parent/support/ark-maven-plugin/src/test/java/com/alipay/sofa/ark/boot/mojo/ModuleSlimExecutorTest.java (1)

150-159: Mocked BOM dependencies lack type/scope – diverges from real data

mockBasePluginBomModel constructs Dependency instances without setting type or scope.
In production, these fields will be "jar"/"" or inherit from the parent POM, influencing the filtering logic that checks getType() and getScope().
Consider populating them to avoid false positives/negatives in tests.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2bd49a5 and 4e80774.

📒 Files selected for processing (8)
  • pom.xml (1 hunks)
  • sofa-ark-parent/support/ark-maven-plugin/src/main/java/com/alipay/sofa/ark/boot/mojo/MavenUtils.java (2 hunks)
  • sofa-ark-parent/support/ark-maven-plugin/src/main/java/com/alipay/sofa/ark/boot/mojo/ModuleSlimConfig.java (0 hunks)
  • sofa-ark-parent/support/ark-maven-plugin/src/main/java/com/alipay/sofa/ark/boot/mojo/ModuleSlimExecutor.java (12 hunks)
  • sofa-ark-parent/support/ark-maven-plugin/src/main/java/com/alipay/sofa/ark/boot/mojo/RepackageMojo.java (4 hunks)
  • sofa-ark-parent/support/ark-maven-plugin/src/main/java/com/alipay/sofa/ark/boot/mojo/utils/ParseUtils.java (1 hunks)
  • sofa-ark-parent/support/ark-maven-plugin/src/test/java/com/alipay/sofa/ark/boot/mojo/ModuleSlimExecutorTest.java (17 hunks)
  • sofa-ark-parent/support/ark-maven-plugin/src/test/java/com/alipay/sofa/ark/boot/mojo/RepackageMojoTest.java (1 hunks)
💤 Files with no reviewable changes (1)
  • sofa-ark-parent/support/ark-maven-plugin/src/main/java/com/alipay/sofa/ark/boot/mojo/ModuleSlimConfig.java
🧰 Additional context used
🧬 Code Graph Analysis (1)
sofa-ark-parent/support/ark-maven-plugin/src/test/java/com/alipay/sofa/ark/boot/mojo/RepackageMojoTest.java (1)
sofa-ark-parent/support/ark-maven-plugin/src/main/java/com/alipay/sofa/ark/boot/mojo/ModuleSlimExecutor.java (3)
  • ModuleSlimExecutor (75-906)
  • ExcludeConfig (803-904)
  • ExcludeConfigResponse (780-801)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build
  • GitHub Check: build
  • GitHub Check: sca
🔇 Additional comments (7)
pom.xml (1)

17-17: Version updated to development snapshot

The version property <sofa.ark.version> has been updated from 2.3.1 to 2.3.2-SNAPSHOT, indicating the beginning of development for the next release that will include the new dependency slimming feature.

sofa-ark-parent/support/ark-maven-plugin/src/test/java/com/alipay/sofa/ark/boot/mojo/RepackageMojoTest.java (1)

19-20: Import paths updated to reflect class rename

The imports have been updated to reference the renamed class ModuleSlimExecutor instead of the previous ModuleSlimStrategy. This change aligns the test with the core refactoring where the slimming logic was restructured and enhanced.

sofa-ark-parent/support/ark-maven-plugin/src/main/java/com/alipay/sofa/ark/boot/mojo/utils/ParseUtils.java (1)

75-85: Well-designed utility method for combined configuration sources

This new method enhances configuration handling by checking for boolean values in both Properties and YAML sources, prioritizing Properties if the value exists in both. This centralizes configuration logic and reduces duplicate code, supporting the broader refactoring of the plugin's slimming capabilities.

The method follows good practices:

  1. Checks both configuration sources
  2. Uses clear variable names
  3. Provides appropriate fallback to default values
  4. Properly handles type conversion
sofa-ark-parent/support/ark-maven-plugin/src/main/java/com/alipay/sofa/ark/boot/mojo/RepackageMojo.java (3)

100-102: Added ProjectBuilder component for enhanced POM processing

The ProjectBuilder component has been injected, providing capabilities to properly resolve and build complete Maven project models. This allows the plugin to better analyze dependencies and their relationships when implementing the slimming logic.


324-324: Expanded base dependency identity format support

The Javadoc now indicates that baseDependencyParentIdentity can be specified in two formats:

  1. ${groupId}:${artifactId}:${version} (original format)
  2. ${groupId}:${artifactId} (new simplified format)

This change provides more flexibility when specifying the base plugin for dependency filtering.


562-566: Core slimming logic refactored and enhanced

The core dependency slimming implementation now:

  1. Uses the renamed ModuleSlimExecutor (previously ModuleSlimStrategy)
  2. Includes the new projectBuilder parameter for enhanced POM resolution
  3. Maintains the same interface for retrieving slimmed artifacts

This refactoring enables the improved dependency filtering based on the base plugin's BOM, which is the main feature of this PR.

sofa-ark-parent/support/ark-maven-plugin/src/test/java/com/alipay/sofa/ark/boot/mojo/ModuleSlimExecutorTest.java (1)

83-91: Tests mask NPE risk by passing null infrastructure objects

The new constructor parameters (RepositorySystem, ProjectBuilder) are passed as null, yet ModuleSlimExecutor dereferences them when resolving POMs.
The tests succeed only because the relevant code paths are stubbed with doReturn.
Add minimal mocks (or use Mockito.RETURNS_DEEP_STUBS) so the tests exercise the real code and fail if future changes access these collaborators unexpectedly.

Comment on lines +130 to +141
protected Model resolvePomAsOriginalModel(String groupId, String artifactId, String version) {
try {
Artifact artifact = repositorySystem
.createProjectArtifact(groupId, artifactId, version);
return projectBuilder.build(artifact, project.getProjectBuildingRequest()).getProject()
.getOriginalModel();
} catch (ProjectBuildingException e) {
log.warn("resolve pom as project error: with " + groupId + ":" + artifactId + ":"
+ version);
return null;
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

project.getProjectBuildingRequest() does not exist – compilation will fail

MavenProject has no getProjectBuildingRequest() method in any Maven 3.x API.
The current code therefore does not compile.
You either need the ProjectBuildingRequest that is available from the MavenSession, or you must build one manually.

-            Artifact artifact = repositorySystem
-                .createProjectArtifact(groupId, artifactId, version);
-            return projectBuilder.build(artifact, project.getProjectBuildingRequest()).getProject()
-                .getOriginalModel();
+            Artifact artifact = repositorySystem.createProjectArtifact(groupId, artifactId, version);
+
+            // Acquire a ProjectBuildingRequest (e.g. injected from Mojo or built here)
+            ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest();
+            buildingRequest.setRepositorySession(project.getProjectBuildingRequest().getRepositorySession());
+            buildingRequest.setRemoteRepositories(project.getRemoteArtifactRepositories());
+
+            return projectBuilder.build(artifact, buildingRequest)
+                                 .getProject()
+                                 .getOriginalModel();

You will also need to pass a valid ProjectBuildingRequest (or a MavenSession) into ModuleSlimExecutor, and update callers/tests accordingly.

Committable suggestion skipped: line range outside the PR's diff.

@codecov
Copy link

codecov bot commented May 14, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 77.86%. Comparing base (2bd49a5) to head (87cfb58).
Report is 1 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master    #1074      +/-   ##
============================================
+ Coverage     77.72%   77.86%   +0.13%     
  Complexity      910      910              
============================================
  Files           175      175              
  Lines          7376     7376              
  Branches       1082     1082              
============================================
+ Hits           5733     5743      +10     
+ Misses         1093     1082      -11     
- Partials        550      551       +1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@gaosaroma gaosaroma requested a review from yuanyuancin May 14, 2025 06:44
Copy link
Collaborator

@yuanyuancin yuanyuancin left a comment

Choose a reason for hiding this comment

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

LGTM

@gaosaroma gaosaroma merged commit 146d64e into sofastack:master May 14, 2025
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants