Skip to content
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

solve the problem of duplicate comments and blank lines #5232

Merged

Conversation

youngzil
Copy link
Contributor

@youngzil youngzil commented Sep 19, 2024

  1. solve the problem of duplicate comments and blank lines
  2. reduce the data growth of the item table
  3. in the same case, the size of ItemChangeSets can be reduced
  4. when revoke configuration, if there is only one comment or blank line, it will not be deleted.

What's the purpose of this PR

XXXXX

Which issue(s) this PR fixes:

Fixes #5000

Brief changelog

XXXXX

Follow this checklist to help us incorporate your contribution quickly and easily:

  • Read the Contributing Guide before making this pull request.
  • Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
  • Write necessary unit tests to verify the code.
  • Run mvn clean test to make sure this pull request doesn't break anything.
  • Update the CHANGES log.

Summary by CodeRabbit

  • New Features

    • Enhanced handling of comment and blank items for improved processing efficiency.
    • Streamlined logic for managing deleted items, ensuring only valid entries are processed.
    • Added functionality to address duplicate comments and blank lines in the Apollo system.
  • Bug Fixes

    • Resolved issues related to duplicate comments and blank lines in configuration management.
  • Refactor

    • Simplified code structure for better maintainability and clarity in various methods related to item management.

1. solve the problem of duplicate comments and blank lines
2. reduce the data growth of the item table
3. in the same case, the size of ItemChangeSets can be reduced
4. when revoke configuration, if there is only one comment or blank line, it will not be deleted.
@dosubot dosubot bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Sep 19, 2024
Copy link
Contributor

coderabbitai bot commented Sep 19, 2024

Walkthrough

The changes primarily involve enhancing the handling of comment and blank items in the PropertyResolver class, improving the logic for deleted items in the ItemService class, and updating the changelog to document a new feature. The modifications streamline the processing of items, eliminate reliance on outdated structures, and ensure that only valid items are considered during operations. Overall, the updates focus on improving code clarity, efficiency, and correctness in item management.

Changes

File Change Summary
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/txtresolver/PropertyResolver.java Enhanced handling of comment and blank items; replaced old line number map with lists; refactored methods for clarity and efficiency.
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/ItemService.java Improved logic for handling deleted items by filtering out items with empty keys and simplifying item addition to changeSets.
CHANGES.md Added a new entry documenting a fix for duplicate comments and blank lines in version 2.4.0, maintaining the overall structure of the changelog.

Assessment against linked issues

Objective Addressed Explanation
Ensure no automatic addition of duplicate comments after undoing changes (#5000)

🐰 In the meadow, changes bloom,
Comments tidy, no more gloom.
Items handled with great care,
No duplicates lurking, everywhere!
Code now dances, clear and bright,
A hop of joy, all feels just right! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 904ab87 and 84180a2.

📒 Files selected for processing (1)
  • CHANGES.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGES.md

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

@youngzil
Copy link
Contributor Author

// TODO
code:com.ctrip.framework.apollo.portal.service.ItemService#revokeItem
Remaining issues:
When revoking a configuration, the number of configuration lines will be reset, which will cause confusion between the number of comments and configuration lines. This cannot be solved at present.

@youngzil
Copy link
Contributor Author

youngzil commented Sep 20, 2024

Using the test case in #5000, there is another problem
### Add a question about revoke configuration

  1. The initial configuration is as follows

image

  1. The second step only deletes the fourth line, and the comment on the third line is still retained.
  2. But when I revoke the configuration, I find that the comment on the third line is also deleted.

image

  1. The reasons why this happens are as follows:
    L218:oldKeyMapItem contains a comment or a blank line
    L241:The comment or blank line in oldKeyMapItem will be deleted.

So I removed this comment or blank line in #5232

https://github.com/apolloconfig/apollo/blob/31e6486791de3ad60f059f34957b343839aa5ebb/apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/ItemService.java#L218C1-L219C1

oldKeyMapItem.forEach((key, value) -> changeSets.addDeleteItem(oldKeyMapItem.get(key)));

Copy link
Member

@nobodyiam nobodyiam left a comment

Choose a reason for hiding this comment

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

  1. Please update the CHANGES.md
  2. I tested the new patch but find the line num is wrong after revoking the configurations
    the original configuration
    image
    after line 4 is deleted
    image
    after the configuration is revoked
    image

1. add CHANGES.md
2. PropertyResolver code style format
3. Revoke configurations cause the line num to be disordered
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: 4

🧹 Outside diff range and nitpick comments (3)
CHANGES.md (1)

11-11: LGTM! Consider adding more detail to the changelog entry.

The addition to the changelog accurately reflects the main objective of the PR and is consistent with the existing format. Well done!

To provide more context for users, consider expanding the changelog entry slightly. For example:

-* [Fix: The problem of duplicate comments and blank lines](https://github.com/apolloconfig/apollo/pull/5232)
+* [Fix: Resolve issues with duplicate comments and blank lines in configuration management](https://github.com/apolloconfig/apollo/pull/5232)

This gives users a clearer idea of where the fix applies without needing to click through to the PR.

apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/txtresolver/PropertyResolver.java (1)

200-200: Maintain consistency in string utility methods

At line 200~, Strings.nullToEmpty(line).trim().isEmpty() from Guava's Strings class is used. However, since StringUtils from com.ctrip.framework.apollo.core.utils.StringUtils is already imported (line 24~), consider using StringUtils for consistency and to reduce external dependencies. If StringUtils provides a method like StringUtils.isEmpty(line), it can replace the current implementation for a unified approach.

apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/ItemService.java (1)

234-235: Enhance readability by reordering the equality check

In the condition 0 == deletedItemDto.getLineNum(), consider switching the order to deletedItemDto.getLineNum() == 0 for better readability and consistency with common coding conventions.

-int newLineNum = 0 == deletedItemDto.getLineNum() ? lineNum.get() : deletedItemDto.getLineNum();
+int newLineNum = deletedItemDto.getLineNum() == 0 ? lineNum.get() : deletedItemDto.getLineNum();
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1c7dcf8 and 859bbdb.

📒 Files selected for processing (3)
  • CHANGES.md (1 hunks)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/txtresolver/PropertyResolver.java (9 hunks)
  • apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/ItemService.java (2 hunks)
🔇 Additional comments (5)
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/txtresolver/PropertyResolver.java (2)

83-88: Verify the correct mapping of comment and blank items

The current logic in handling comment and blank lines assumes a direct correspondence between the new items and the baseCommentItems/baseBlankItems lists by using remove(0). If there are additions or deletions of comments or blank lines, this might lead to mismatches or incorrect deletions.

Consider reviewing and testing cases where comments or blank lines are added, removed, or modified to ensure the resolve method correctly handles these scenarios. Adding unit tests for these cases will help validate the method's behavior.

Also applies to: 93-98


108-108: Ensure method signature changes are reflected across the codebase

The method deleteCommentAndBlankItem has been updated to accept List<ItemDTO> parameters instead of Map<Integer, ItemDTO>. Ensure that any calls to this method elsewhere in the codebase have been updated to match the new signature to prevent any NoSuchMethodError or MethodNotFoundException at runtime.

Run the following script to find usages of deleteCommentAndBlankItem:

#!/bin/bash
# Description: Find all usages of deleteCommentAndBlankItem to verify method signature compatibility.

# Search for method calls to deleteCommentAndBlankItem
rg --type java --pcre2 'deleteCommentAndBlankItem\s*\('
apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/ItemService.java (3)

53-53: Import statement is necessary

The import of java.util.stream.Collectors is required for the stream operations used in the code.


224-226: Properly filtering and mapping deleted items

The code correctly filters out items with empty keys and collects deleted items into a map, ensuring that only relevant items are processed.


242-242: Proper deletion of remaining items

The code correctly adds the remaining items in oldKeyMapItem to changeSets as delete items, ensuring that obsolete entries are removed.

Comment on lines 180 to 181
} else if (!newValue.equals(oldItem.getValue()) || lineCounter != oldItem.getLineNum()) {
changeSets.addUpdateItem(buildNormalItem(oldItem.getId(), namespaceId, newKey, newValue, oldItem.getComment(), lineCounter));
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Prevent potential NullPointerException when comparing string values

In the handleNormalLine method, the condition on line 180~ compares newValue and oldItem.getValue():

} else if (!newValue.equals(oldItem.getValue()) || lineCounter != oldItem.getLineNum()) {

If oldItem.getValue() is null, this could result in a NullPointerException. To safely handle possible null values, use StringUtils.equals(newValue, oldItem.getValue()), which handles null comparisons gracefully.

Apply this diff to prevent the potential exception:

-} else if (!newValue.equals(oldItem.getValue()) || lineCounter != oldItem.getLineNum()) {
+} else if (!StringUtils.equals(newValue, oldItem.getValue()) || lineCounter != oldItem.getLineNum()) {

value, oldItem.getComment(), lineNum.get()));
int newLineNum = 0 == deletedItemDto.getLineNum() ? lineNum.get() : deletedItemDto.getLineNum();
changeSets.addCreateItem(buildNormalItem(0L, namespaceId, key, value, deletedItemDto.getComment(), newLineNum));
} else if (!oldItem.getValue().equals(value) || lineNum.get() != oldItem.getLineNum()) {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use Objects.equals to prevent potential NullPointerException

If oldItem.getValue() or value could be null, using !oldItem.getValue().equals(value) may cause a NullPointerException. Consider using !Objects.equals(oldItem.getValue(), value) to safely compare values.

Ensure you have imported java.util.Objects.

+import java.util.Objects;

 ...

} else if (
-    !oldItem.getValue().equals(value) || lineNum.get() != oldItem.getLineNum()) {
+    !Objects.equals(oldItem.getValue(), value) || lineNum.get() != oldItem.getLineNum()) {

Committable suggestion was skipped due to low confidence.

Comment on lines +220 to +221
//remove comment and blank item map.
oldKeyMapItem.remove("");
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

Consider filtering out blank keys during map creation

Instead of removing entries with blank keys after creating oldKeyMapItem, consider filtering out items with blank keys when constructing the map. This can improve code clarity and prevent unnecessary entries from being processed.

You can modify the map creation as follows:

-import java.util.HashMap;
+import java.util.HashMap;
+import java.util.stream.Collectors;

 Map<String, ItemDTO> oldKeyMapItem = BeanUtils.mapByKey("key", baseItems);
-//remove comment and blank item map.
-oldKeyMapItem.remove("");
+oldKeyMapItem = oldKeyMapItem.entrySet().stream()
+    .filter(entry -> !StringUtils.isEmpty(entry.getKey()))
+    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Committable suggestion was skipped due to low confidence.

@youngzil
Copy link
Contributor Author

// TODO code:com.ctrip.framework.apollo.portal.service.ItemService#revokeItem Remaining issues: When revoking a configuration, the number of configuration lines will be reset, which will cause confusion between the number of comments and configuration lines. This cannot be solved at present.

I mentioned this problem in my reply above, but I don't have a good solution to solve it completely.

I submitted some small optimizations for this problem. With a small number of changes, the line num can be kept correct as much as possible.
But this code cannot solve the situation where a lot of comments and blank lines are added before undoing.
It also cannot solve the situation where the number of lines of comments changes a lot.
So this is not a complete solution

The code is as follows:
https://github.com/youngzil/apollo/blob/859bbdbf00934e6f308c8685bee616c106b42ebe/apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/ItemService.java#L233C6-L238C8

1. solve the problem of duplicate comments and blank lines
2. reduce the data growth of the item table
3. in the same case, the size of ItemChangeSets can be reduced
4. when revoke configuration, if there is only one comment or blank line, it will not be deleted.
1. add CHANGES.md
2. PropertyResolver code style format
3. Revoke configurations cause the line num to be disordered
Copy link
Member

@nobodyiam nobodyiam left a comment

Choose a reason for hiding this comment

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

LGTM

@dosubot dosubot bot added the lgtm This PR has been approved by a maintainer label Oct 1, 2024
@nobodyiam nobodyiam merged commit a1c7c96 into apolloconfig:master Oct 1, 2024
7 of 8 checks passed
@github-actions github-actions bot locked and limited conversation to collaborators Oct 1, 2024
@youngzil youngzil deleted the feature/comment_and_blank_repeat branch October 2, 2024 09:46
@nobodyiam nobodyiam added this to the 2.4.0 milestone Oct 6, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Text配置修改,含有注释的情况下,撤销修改导致后续存在自动添加重复注释
2 participants