-
-
Notifications
You must be signed in to change notification settings - Fork 20
GH-865 Fix Illegal Stack and no space in /give command.
#865
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
Conversation
/give command./give command.
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.
Actionable comments posted: 4
🧹 Outside diff range and nitpick comments (6)
eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (1)
372-374: LGTM! Consider enhancing the description.The addition of the
dropOnFullInventoryconfiguration option aligns well with the PR objectives. It provides users with the ability to control the behavior of the/givecommand when a player's inventory is full.Consider enhancing the description to provide more context:
- @Description({ " ", "# Determines whether items should be dropped on the ground when the player's inventory is full" }) + @Description({ " ", "# Determines whether items should be dropped on the ground when the player's inventory is full during /give command execution" }) public boolean dropOnFullInventory = true;This minor change explicitly ties the configuration to the
/givecommand, making it clearer for users.eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/ENTranslation.java (1)
740-740: LGTM! Consider adding a placeholder for consistency.The new
giveNoSpacemessage is a good addition and aligns well with the PR objectives. It provides clear feedback when a player's inventory is full.For consistency with other messages in this class, consider adding a placeholder for potential customization. For example:
- public Notice giveNoSpace = Notice.chat("<red>✘ <dark_red>Not enough space in inventory!"); + public Notice giveNoSpace = Notice.chat("<red>✘ <dark_red>Not enough space in inventory! {ITEM}");This would allow for including the item name or any other relevant information in the message if needed in the future.
eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/PLTranslation.java (2)
755-756: LGTM! Consider adding placeholder for item name.The addition of the
giveNoSpacemessage is appropriate and aligns with the PR objectives. It provides clear feedback when a player's inventory is full.Consider adding a placeholder for the item name, e.g.,
{ITEM}. This would make the message more informative:- public Notice giveNoSpace = Notice.chat("<red>✘ <dark_red>Błąd: <red>Brak miejsca w ekwipunku!"); + public Notice giveNoSpace = Notice.chat("<red>✘ <dark_red>Błąd: <red>Brak miejsca w ekwipunku dla {ITEM}!");
Line range hint
1-756: Consider future refactoring for improved maintainabilityWhile the current change is appropriate and minimal, the overall file structure is quite complex. For future consideration:
- Consider splitting this large file into smaller, more focused files for each major section (e.g., chat, teleportation, inventory).
- Implement a more modular approach to loading translations, which could improve performance and make it easier to add new languages.
- Consider using a dedicated localization framework or library to manage translations more efficiently.
These suggestions are out of scope for the current PR but could be valuable for future maintenance and scalability of the plugin.
eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java (1)
116-136: Consider optimizing thehasSpacemethod for efficiencyCurrently, the
hasSpacemethod first checks for an empty slot and then iterates through the inventory to find stackable items. Depending on the typical state of player inventories, checking for stackable items first might be more efficient, as it avoids using additional slots when existing ones can be used.If optimizing for minimal slot usage is desired, you could adjust the order of the checks:
for (ItemStack contents : inventory.getContents()) { if (contents == null) { continue; } if (contents.isSimilar(itemStack) && contents.getMaxStackSize() > contents.getAmount()) { return true; } } return inventory.firstEmpty() != -1;However, if the current logic suits the game's inventory management strategy, no changes are necessary.
eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveCommand.java (1)
Line range hint
36-121: Consider refactoring to reduce code duplication amongexecutemethodsThe
executemethods share similar logic with variations in parameters. To improve maintainability and reduce duplication, consider refactoring common code into a helper method or implementing a more generic approach.Here's an example of how you might refactor the common logic into a helper method:
private void giveItemAndNotify(Viewer viewer, Player target, Material material, Integer amount, Enchantment enchantment, Integer level) { String formattedMaterial = MaterialUtil.format(material); if (amount == null) { amount = 1; } if (enchantment != null && level != null) { this.giveService.giveItem(target, material, amount, enchantment, level); } else { this.giveService.giveItem(target, material, amount); } NoticeBuilder noticeBuilder = this.noticeService.create() .placeholder("{ITEM}", formattedMaterial) .player(target.getUniqueId()); if (enchantment != null && level != null) { noticeBuilder .placeholder("{ENCHANTMENT}", enchantment.getKey().getKey()) .placeholder("{ENCHANTMENT_LEVEL}", String.valueOf(level)) .notice(translation -> translation.item().giveReceivedEnchantment()); } else { noticeBuilder.notice(translation -> translation.item().giveReceived()); } noticeBuilder.send(); if (!viewer.isSame(target)) { NoticeBuilder viewerNotice = this.noticeService.create() .placeholder("{ITEM}", formattedMaterial) .placeholder("{PLAYER}", target.getName()) .viewer(viewer); if (enchantment != null && level != null) { viewerNotice .placeholder("{ENCHANTMENT}", enchantment.getKey().getKey()) .placeholder("{ENCHANTMENT_LEVEL}", String.valueOf(level)) .notice(translation -> translation.item().giveGivenEnchantment()); } else { viewerNotice.notice(translation -> translation.item().giveGiven()); } viewerNotice.send(); } }You can then simplify your
executemethods by calling this helper method with appropriate parameters.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (6)
- eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (1 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveCommand.java (5 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java (1 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (1 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/ENTranslation.java (1 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/PLTranslation.java (1 hunks)
🧰 Additional context used
🔇 Additional comments (8)
eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (1)
384-384: LGTM: New method aligns with PR objectivesThe addition of the
giveNoSpace()method is a good implementation that addresses the PR objective of providing clearer feedback when there's no available space in the inventory. The method name is clear, its return type is consistent with other methods in this interface, and its placement is logical within the ItemSection.eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (1)
372-374: Summary: New configuration option successfully addresses PR objectiveThe addition of the
dropOnFullInventoryconfiguration option in theItemsclass successfully addresses one of the main objectives of the PR. It provides a way for users to control whether items should be dropped on the ground or not when a player's inventory is full during the execution of the/givecommand.This change is well-implemented, properly documented, and doesn't introduce any issues to the existing codebase. It enhances the flexibility of the plugin, allowing server administrators to customize the behavior according to their preferences.
To ensure that this configuration option is properly utilized in the
/givecommand implementation, please run the following verification script:This script will help confirm that the new configuration option is being used correctly in the implementation of the
/givecommand.✅ Verification successful
Verification Successful:
dropOnFullInventoryis Properly UtilizedThe
dropOnFullInventoryconfiguration option is correctly referenced inGiveService.java, ensuring that items are appropriately handled when a player's inventory is full during the/givecommand execution. No issues were detected regarding its implementation and usage within the relevant classes.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the usage of dropOnFullInventory configuration in GiveCommand or related classes # Search for references to dropOnFullInventory in relevant files rg --type java -g 'GiveCommand.java' -g 'GiveService.java' -g '*Give*.java' 'dropOnFullInventory'Length of output: 418
eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveCommand.java (6)
23-28: Good use ofGiveServiceto improve modularityRefactoring to use
GiveServicecentralizes the item-giving logic, enhancing modularity and maintainability of the code.
36-36: Delegation of item-giving toGiveServiceUsing
giveService.giveItem(player, material)promotes code reuse and keeps the command logic clean.
50-50: Consistent use ofGiveServicefor item distributionDelegating item-giving to
GiveServicewithgiveService.giveItem(target, material)maintains consistency and improves code organization.
71-71: Item giving with amount parameter usingGiveServiceUtilizing
giveService.giveItem(player, material, amount)ensures consistent handling of items with quantities.
85-85: Delegation with amount parameter toGiveServiceCalling
giveService.giveItem(target, material, amount)for item giving with quantity enhances code consistency.
106-106: Enhanced item giving with enchantments viaGiveServiceUsing
giveService.giveItem(target, material, amount, enchantment, level)centralizes and streamlines the process of giving enchanted items.
...alcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
Outdated
Show resolved
Hide resolved
...alcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
Outdated
Show resolved
Hide resolved
...alcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
Outdated
Show resolved
Hide resolved
...alcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
Outdated
Show resolved
Hide resolved
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.
Actionable comments posted: 5
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (1)
- eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java (1 hunks)
🧰 Additional context used
🔇 Additional comments (5)
eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java (5)
23-29: LGTM: Constructor properly initializes dependenciesThe constructor is correctly annotated with
@Injectfor dependency injection. It initializes thepluginConfigurationandnoticeServicedependencies, and sets thedefaultGiveAmountfrom the configuration. This approach ensures that the service is properly set up with its required dependencies.
31-37: LGTM: Method correctly handles default item givingThis overloaded
giveItemmethod appropriately checks for invalid material before proceeding to give the item. It uses thedefaultGiveAmountwhen calling thegiveItemsmethod, which is the expected behavior for this version of the method.
116-136: LGTM: Efficient inventory space checkingThe
hasSpacemethod is well-implemented and efficient. It correctly checks for:
- Empty slots in the inventory.
- Existing similar item stacks that have space for more items.
This approach ensures accurate detection of available space for new items, considering both completely empty slots and partially filled stacks.
138-140: LGTM: Concise and effective EnchantmentLevelPair recordThe
EnchantmentLevelPairrecord is a good use of Java's record feature. It provides a compact and clear way to associate an enchantment with its level. This approach enhances code readability and maintainability when dealing with enchantments throughout the class.
1-140: Overall assessment: Well-structured service with room for minor improvementsThe
GiveServiceclass is generally well-implemented, providing a robust solution for giving items to players. Here's a summary of the main points:
- The overall structure and dependency injection are well done.
- Most methods are logically sound and efficient.
- Areas for improvement include:
- Adding input validation for
amountandlevelparameters in public methods.- Fixing the inverted condition in
isInvalidMaterial.- Improving user feedback in
giveItemStackfor different scenarios.- Using record accessor methods correctly for enchantments.
Addressing these points will enhance the reliability and user experience of the item giving functionality. Great job on the implementation, and these small tweaks will make it even better!
...alcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
Outdated
Show resolved
Hide resolved
...alcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
Outdated
Show resolved
Hide resolved
...alcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
Outdated
Show resolved
Hide resolved
...alcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
Outdated
Show resolved
Hide resolved
...alcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
Outdated
Show resolved
Hide resolved
...alcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
Outdated
Show resolved
Hide resolved
...alcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
Outdated
Show resolved
Hide resolved
...alcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
Outdated
Show resolved
Hide resolved
...alcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
Outdated
Show resolved
Hide resolved
...alcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
Outdated
Show resolved
Hide resolved
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.
Actionable comments posted: 0
🧹 Outside diff range and nitpick comments (3)
eternalcore-core/src/main/java/com/eternalcode/core/util/InventoryUtil.java (2)
7-9: Consider making the constructor private.While throwing an exception in the constructor effectively prevents instantiation, it's more idiomatic to use a private constructor for utility classes. This approach prevents instantiation at compile-time rather than runtime.
Here's a suggested change:
-public InventoryUtil() { +private InventoryUtil() { throw new UnsupportedOperationException("This is a utility class and cannot be instantiated"); }
11-31: LGTM: Method logic is correct. Consider using streams for a more concise implementation.The
hasSpacemethod correctly checks for available space in the inventory. It efficiently checks for an empty slot first before iterating through the contents. The null check, similarity check, and stack size check are all appropriate.As a suggestion for improvement, consider using Java streams for a more concise implementation:
public static boolean hasSpace(Inventory inventory, ItemStack itemStack) { if (inventory.firstEmpty() != -1) { return true; } return Arrays.stream(inventory.getContents()) .filter(Objects::nonNull) .filter(item -> item.isSimilar(itemStack)) .anyMatch(item -> item.getAmount() < item.getMaxStackSize()); }This implementation maintains the same logic but is more concise and potentially more readable.
eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveCommand.java (1)
Line range hint
1-124: Overall improvement in code structure and functionalityThe changes in this file consistently implement the new
GiveServiceacross all execute methods, effectively addressing the PR objectives of improving item distribution and handling various scenarios. The refactoring maintains backward compatibility while enhancing the separation of concerns.Suggestion for future improvement:
Consider refactoring the notification logic in the execute methods to reduce code duplication. A helper method could be introduced to handle the creation and sending of notifications, which would further improve the maintainability of the code.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (7)
- eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (1 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveCommand.java (5 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java (1 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (1 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/ENTranslation.java (1 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/PLTranslation.java (1 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/util/InventoryUtil.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
- eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java
- eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
- eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java
- eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/ENTranslation.java
- eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/PLTranslation.java
🧰 Additional context used
🔇 Additional comments (7)
eternalcore-core/src/main/java/com/eternalcode/core/util/InventoryUtil.java (1)
1-6: LGTM: Class structure and package declaration are appropriate.The class is correctly structured as a utility class within the
com.eternalcode.core.utilpackage. Thefinalmodifier prevents inheritance, which is a good practice for utility classes.eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveCommand.java (6)
23-23: Improved design with GiveService integrationThe introduction of
GiveServiceand its integration in the constructor enhances the separation of concerns. This change aligns well with the PR objectives by moving the item-giving logic out of the command class, resulting in a more modular and maintainable design.Also applies to: 26-28
36-36: Consistent use of GiveServiceThe replacement of the direct item-giving logic with a call to
giveService.giveItem()is consistent with the new design. This change maintains the method's functionality while leveraging the new service-oriented approach.
50-50: Consistent use of GiveService for target playerThe implementation of
giveService.giveItem()for giving items to a target player is consistent with the new design. This change maintains the method's functionality while adhering to the new service-oriented approach.
71-71: Effective use of GiveService for custom amountsThe implementation of
giveService.giveItem()with a custom amount parameter effectively delegates the responsibility of handling different item quantities to theGiveService. This change maintains the method's functionality while leveraging the new service-oriented approach and addresses the PR objective of fixing issues related to item stack sizes.
85-85: Consistent use of GiveService for target player with custom amountsThe implementation of
giveService.giveItem()for giving items with a custom amount to a target player is consistent with the new design. This change maintains the method's functionality while adhering to the new service-oriented approach and addresses the PR objective of handling different item quantities correctly.
106-106: Comprehensive use of GiveService for enchanted itemsThe implementation of
giveService.giveItem()with parameters for target player, material, amount, enchantment, and level demonstrates a comprehensive approach to item distribution. This change effectively delegates the complex logic of creating and distributing enchanted items to theGiveService, maintaining consistency with the new design while addressing the PR objectives related to item handling and enchantments.
igoyek
left a comment
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.
If you tested it, looks good, nice job ;)
Rollczi
left a comment
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.
I wait for fix
...alcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
Outdated
Show resolved
Hide resolved
CitralFlo
left a comment
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.
LGTM
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.
Actionable comments posted: 1
🧹 Outside diff range and nitpick comments (6)
eternalcore-core/src/main/java/com/eternalcode/core/util/InventoryUtil.java (1)
7-9: Consider making the constructor private.While throwing an exception in the constructor effectively prevents instantiation, it's better to make the constructor private to enforce this at compile-time rather than runtime.
Apply this change:
- public InventoryUtil() { + private InventoryUtil() { throw new UnsupportedOperationException("This is a utility class and cannot be instantiated"); }eternalcore-core/src/main/java/com/eternalcode/core/notice/EternalCoreBroadcastImpl.java (1)
56-62: LGTM: Newsendermethod enhances command handling.The new
sendermethod effectively differentiates between player and console command senders, aligning with the PR objectives. This enhancement will improve the/givecommand functionality.Consider adding a null check at the beginning of the method to prevent potential NullPointerExceptions:
public B sender(CommandSender sender) { + if (sender == null) { + throw new IllegalArgumentException("CommandSender cannot be null"); + } if (sender instanceof Player player) { return this.player(player.getUniqueId()); } return this.console(); }eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (1)
384-384: LGTM! Consider adding a brief comment for clarity.The addition of
Notice giveNoSpace();is well-placed within theItemSectioninterface and aligns with the PR objectives. It provides a way to notify players when there's no space in their inventory during a/givecommand operation.Consider adding a brief comment above the method to explain its purpose, for consistency with other methods in this file. For example:
// Notification for when there's no space in the inventory during a give operation Notice giveNoSpace();eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (1)
373-374: LGTM! Consider enhancing the description.The new
dropOnFullInventoryfield is well-integrated into theItemsclass and aligns with the PR objectives. The default value oftruemaintains backwards compatibility.Consider enhancing the description to mention the alternative behavior when this option is set to
false. For example:-@Description({ " ", "# Determines whether items should be dropped on the ground when the player's inventory is full" }) +@Description({ " ", "# Determines whether items should be dropped on the ground when the player's inventory is full.", + "# If set to false, the command will return a message indicating that there is no available space." })eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/ENTranslation.java (1)
740-740: LGTM! Consider adding a placeholder for item name.The addition of the
giveNoSpacemessage is consistent with the PR objectives and follows the existing code style. Well done!For improved user experience, consider adding a placeholder for the item name. This would provide more context to the user about which item couldn't be given. For example:
- public Notice giveNoSpace = Notice.chat("<red>✘ <dark_red>Not enough space in inventory!"); + public Notice giveNoSpace = Notice.chat("<red>✘ <dark_red>Not enough space in inventory for {ITEM}!");This change would require updating the corresponding code that uses this message to include the item name.
eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/PLTranslation.java (1)
755-756: LGTM! Consider adding a description for consistency.The addition of the
giveNoSpacefield is appropriate and aligns with the PR objectives. The message is well-formatted and correctly uses the Notice system.For consistency with other fields in this class, consider adding a
@Descriptionannotation above the new field. For example:+ @Description({" ", "# Wiadomość wyświetlana, gdy brakuje miejsca w ekwipunku gracza"}) public Notice giveNoSpace = Notice.chat("<red>✘ <dark_red>Błąd: <red>Brak miejsca w ekwipunku!");This will help maintain the documentation standard throughout the class.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (8)
- eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (1 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveCommand.java (2 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java (1 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/notice/EternalCoreBroadcastImpl.java (2 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (1 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/ENTranslation.java (1 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/PLTranslation.java (1 hunks)
- eternalcore-core/src/main/java/com/eternalcode/core/util/InventoryUtil.java (1 hunks)
🧰 Additional context used
📓 Learnings (1)
eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java (2)
Learnt from: vLuckyyy PR: EternalCodeTeam/EternalCore#865 File: eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java:61-72 Timestamp: 2024-10-14T20:14:03.215Z Learning: In the 'EternalCore' project, input validation for command parameters like `amount` is performed by the command library, so methods such as `giveItems` do not need to add additional validation for these parameters.Learnt from: vLuckyyy PR: EternalCodeTeam/EternalCore#865 File: eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java:0-0 Timestamp: 2024-10-14T20:11:13.610Z Learning: In the 'EternalCore' project, avoid using null in method signatures in Java code.
🪛 ast-grep
eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java
[warning] 34-34: Detected a cookie where the
HttpOnlyflag is either missing or disabled. TheHttpOnlycookie flag instructs the browser to forbid client-side JavaScript to read the cookie. If JavaScript interaction is required, you can ignore this finding. However, set theHttpOnlyflag to true` in all other cases.
Context: (player.getInventory().getStorageContents(), new ItemStack(material, amount))
Note: [CWE-1004]: Sensitive Cookie Without 'HttpOnly' Flag [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration
[warning] 34-34: Detected a cookie where the
Secureflag is either missing or disabled. TheSecurecookie flag instructs the browser to forbid sending the cookie over an insecure HTTP request. Set theSecureflag totrueso the cookie will only be sent over HTTPS.
Context: (player.getInventory().getStorageContents(), new ItemStack(material, amount))
Note: [CWE-614]: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration
🔇 Additional comments (11)
eternalcore-core/src/main/java/com/eternalcode/core/util/InventoryUtil.java (2)
1-6: LGTM: Class structure and package declaration are appropriate.The utility class is correctly placed in the
utilpackage, imports the necessary Bukkit classes, and is declared asfinalto prevent inheritance, which is a good practice for utility classes.
1-32: Overall assessment: Good implementation with room for minor improvements.The
InventoryUtilclass effectively addresses the PR objective of enhancing inventory management. It provides a crucial method for checking available inventory space, which is likely used in theGiveServiceto determine whether items can be added to a player's inventory.The suggested improvements (private constructor, parameter validation, and method optimization) will enhance the robustness and efficiency of the implementation. These changes are recommended but not critical for the functionality of the PR.
eternalcore-core/src/main/java/com/eternalcode/core/notice/EternalCoreBroadcastImpl.java (2)
21-22: LGTM: New imports align with the PR objectives.The added imports for
CommandSenderandPlayerare necessary for the newsendermethod and align with the PR objectives of improving the/givecommand functionality.
Line range hint
1-105: Overall, the changes enhance command sender handling.The modifications to
EternalCoreBroadcastImplimprove its ability to handle different types of command senders, which aligns well with the PR objectives. This enhancement is likely part of a larger refactoring effort to support the new/givecommand functionality and inventory management improvements.The changes are well-implemented and should contribute positively to the overall system architecture.
eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (1)
372-374: Well-integrated configuration option.The new
dropOnFullInventoryfield is seamlessly integrated into the existingItemsclass. This addition maintains the modular structure of the configuration and provides the necessary flexibility for the enhanced/givecommand functionality without disrupting other parts of the configuration.eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveCommand.java (4)
40-41: VerifyCommandSendercompatibility in theexecutemethodBy changing the
senderparameter fromPlayertoCommandSender, ensure that all subsequent method calls and usages ofsenderare compatible with both player and non-player command senders (e.g., the console). Specifically, verify that methods likegiveService.giveItemand the notification system handleCommandSenderappropriately without causing any runtime exceptions.
60-65: Ensure proper handling ofCommandSenderingiveItemmethodIn the
executemethod for giving items to another player, you're callinggiveService.giveItem(sender, target, material, amount)withsenderas aCommandSender. Confirm that thegiveItemmethod and any related logic correctly handleCommandSenderinstances that may not be players. This will prevent potentialClassCastExceptionissues when the command is executed from the console.
Line range hint
67-78: Check notification system for non-player sendersWhen sending notifications using
noticeService, you're setting.sender(sender)in the builder. Ensure that the notification service properly handles scenarios wheresenderis not aPlayer. If the sender is the console, this might lead to exceptions or unintended behavior. Consider adding checks or overloading methods to manage differentCommandSendertypes.
49-55: Consistent notification for item receivedThe notification logic for when an item is successfully given to a player is well-implemented and follows a consistent pattern. Good job on maintaining clarity and user feedback in this section.
eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java (2)
25-53: Code implementation is correctThe
giveItemmethod effectively handles item giving, inventory space checks, and dropping excess items when necessary. The logic is clear and well-structured.🧰 Tools
🪛 ast-grep
[warning] 34-34: Detected a cookie where the
HttpOnlyflag is either missing or disabled. TheHttpOnlycookie flag instructs the browser to forbid client-side JavaScript to read the cookie. If JavaScript interaction is required, you can ignore this finding. However, set theHttpOnlyflag to true` in all other cases.
Context: (player.getInventory().getStorageContents(), new ItemStack(material, amount))
Note: [CWE-1004]: Sensitive Cookie Without 'HttpOnly' Flag [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration
[warning] 34-34: Detected a cookie where the
Secureflag is either missing or disabled. TheSecurecookie flag instructs the browser to forbid sending the cookie over an insecure HTTP request. Set theSecureflag totrueso the cookie will only be sent over HTTPS.
Context: (player.getInventory().getStorageContents(), new ItemStack(material, amount))
Note: [CWE-614]: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration
59-88: Efficient item processing logicThe
processGivemethod correctly iterates through the inventory slots, manages item stacking, and handles any remaining items appropriately. The use of theGiveResultrecord enhances code readability and maintainability.
eternalcore-core/src/main/java/com/eternalcode/core/util/InventoryUtil.java
Outdated
Show resolved
Hide resolved
WalkthroughThe changes in this pull request involve multiple modifications across various classes in the Changes
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (4)
💤 Files with no reviewable changes (1)
🚧 Files skipped from review as they are similar to previous changes (3)
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Rollczi
left a comment
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.
…ve-fix-full-space # Conflicts: # eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/PLTranslation.java
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.
Actionable comments posted: 1
🧹 Outside diff range and nitpick comments (5)
eternalcore-core/src/main/java/com/eternalcode/core/notice/EternalCoreBroadcastImpl.java (1)
56-62: Well-implemented sender handling with good separation of concernsThe new
sendermethod effectively:
- Uses modern Java pattern matching for type checking
- Properly handles both player and console senders
- Maintains clean integration with existing notification methods
- Supports the PR's goal of improving command feedback mechanisms
This implementation aligns well with the PR objectives by providing a clean way to handle notifications for different sender types when executing commands.
Consider adding JavaDoc to document the method's behavior, particularly noting:
- The handling of different sender types
- The return value implications
- Any null handling expectations
eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (1)
373-374: Enhance the configuration descriptionThe implementation looks good! Consider expanding the description to better explain both possible behaviors:
- @Description({ " ", "# Determines whether items should be dropped on the ground when the player's inventory is full" }) + @Description({ " ", + "# Determines the behavior when giving items to a player with a full inventory:", + "# - When true: Items will be dropped on the ground", + "# - When false: A message will be sent indicating no available inventory space" + })eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/PLTranslation.java (1)
754-754: Item messages align with PR objectives and maintain consistency.The
giveNoSpacemessage (line 754) is particularly important as it directly relates to the PR's goal of improving the/givecommand's behavior when the inventory is full. The message format is consistent with other error messages and clearly communicates the issue to users.Consider adding more context to the
giveNoSpacemessage, such as suggesting the player to clear some inventory space or informing them about items being dropped (if that's the configured behavior).- public Notice giveNoSpace = Notice.chat("<red>✘ <dark_red>Brak miejsca w ekwipunku!"); + public Notice giveNoSpace = Notice.chat("<red>✘ <dark_red>Brak miejsca w ekwipunku! <red>Przedmioty zostaną upuszczone na ziemię.");Also applies to: 757-757, 762-762
eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveCommand.java (1)
Line range hint
60-78: Handle non-playerCommandSendersingiveItemand notificationsSince
senderis aCommandSender, it might not always be aPlayer. When callinggiveItemand using.sender(sender)inNoticeService, ensure these methods correctly handle cases wheresenderis not aPlayer. This will prevent runtime exceptions and ensure the command works seamlessly when executed by the console or other non-player entities.To address this issue:
- Modify
GiveService.giveItemto accommodate non-playerCommandSenders, perhaps by logging actions or sending appropriate feedback to the console.- Update the notification logic to check if
senderis aPlayerbefore sending player-specific messages, or adjust theNoticeServiceto handleCommandSenders generically.eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java (1)
104-133: Consider refactoringPlayerContentsclass for clarity.The
PlayerContentsclass utilizes anextraSlotto represent the off-hand slot, adjusting the indexing logic accordingly. For improved readability and maintainability, consider refactoring the class or adding comments to clarify the purpose of theextraSlotand the indexing adjustments.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (9)
eternalcore-core/src/main/java/com/eternalcode/core/bridge/litecommand/LiteCommandsSetup.java(3 hunks)eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java(1 hunks)eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveCommand.java(2 hunks)eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java(1 hunks)eternalcore-core/src/main/java/com/eternalcode/core/notice/EternalCoreBroadcastImpl.java(2 hunks)eternalcore-core/src/main/java/com/eternalcode/core/notice/NoticeService.java(0 hunks)eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java(1 hunks)eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/ENTranslation.java(2 hunks)eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/PLTranslation.java(17 hunks)
💤 Files with no reviewable changes (1)
- eternalcore-core/src/main/java/com/eternalcode/core/notice/NoticeService.java
🧰 Additional context used
📓 Learnings (1)
eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java (2)
Learnt from: vLuckyyy
PR: EternalCodeTeam/EternalCore#865
File: eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java:61-72
Timestamp: 2024-10-14T20:14:03.215Z
Learning: In the 'EternalCore' project, input validation for command parameters like `amount` is performed by the command library, so methods such as `giveItems` do not need to add additional validation for these parameters.
Learnt from: vLuckyyy
PR: EternalCodeTeam/EternalCore#865
File: eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java:0-0
Timestamp: 2024-10-14T20:11:13.610Z
Learning: In the 'EternalCore' project, avoid using null in method signatures in Java code.
🔇 Additional comments (25)
eternalcore-core/src/main/java/com/eternalcode/core/bridge/litecommand/LiteCommandsSetup.java (4)
6-6: LGTM: Import addition is appropriate
The NoticeService import is correctly added to support the new notification functionality.
31-33: LGTM: Parameter addition follows DI pattern
The NoticeService parameter is appropriately added to the bean method, maintaining consistency with the dependency injection pattern.
31-46: Verify integration with /give command fixes
While these changes improve the command framework's error handling, let's verify they properly support the PR's main objective of fixing the /give command issues.
37-46: Verify translation keys and consider adding documentation
The message handlers are well-structured, but let's ensure everything is properly connected:
- Verify that the translation keys exist and are consistent
- Consider adding Javadoc to document the error handling behavior
Consider adding documentation:
+ /**
+ * Configures message handlers for common command errors:
+ * - World not found: When a specified world doesn't exist
+ * - Invalid location: When location format is incorrect
+ *
+ * @param invocation The command invocation context
+ * @param input The invalid input that caused the error
+ */
.message(LiteBukkitMessages.WORLD_NOT_EXIST, (invocation, world) -> noticeService.create()✅ Verification successful
Based on the evidence found, I can now provide a final response:
Translation keys are properly implemented and consistent
The message handlers in LiteCommandsSetup.java are correctly using translation keys that are defined in the Translation.ArgumentSection interface:
worldDoesntExist()is defined and used for WORLD_NOT_EXIST messageincorrectLocation()is defined and used for LOCATION_INVALID_FORMAT message
The implementation follows the established pattern in the codebase for error message handling through the translation system. Documentation can be added as a good practice, but it's not critical as the code is self-documenting through clear method names and consistent usage patterns.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify translation keys exist in language files
# Search for translation keys in language files
echo "Searching for worldDoesntExist translation key..."
rg -l "worldDoesntExist|world.doesnt.exist" --type yaml
echo "Searching for incorrectLocation translation key..."
rg -l "incorrectLocation|location.invalid" --type yaml
Length of output: 632
Script:
#!/bin/bash
# Let's first find all yaml files in the repository
echo "Finding all yaml/yml files..."
fd -e yml -e yaml
# Then let's check the content of these files for translation-related patterns
echo -e "\nSearching for translation/message related content..."
fd -e yml -e yaml --exec cat {}
Length of output: 245
Script:
#!/bin/bash
# Let's look for translation-related files in different common locations
echo "Looking for translation files..."
fd -t f "messages|translations|lang|locale"
# Let's also check the implementation of the translation interface
echo -e "\nLooking for translation interface implementation..."
ast-grep --pattern 'interface Translation {
$$$
}'
# And check where argument-related translations are defined
echo -e "\nLooking for argument translations..."
rg -A 5 "argument\(\)" --type java
Length of output: 32763
Script:
#!/bin/bash
# Let's check the Translation interface to see the argument section structure
echo "Checking Translation interface for argument section..."
rg -A 15 "interface ArgumentSection" --type java
# Let's also check for translation files in resources
echo -e "\nLooking for translation files in resources..."
fd -t f . "src/main/resources"
Length of output: 2246
eternalcore-core/src/main/java/com/eternalcode/core/notice/EternalCoreBroadcastImpl.java (1)
21-22: LGTM! Clean import additions
The new imports for CommandSender and Player are appropriate for the added functionality and follow standard Bukkit API usage.
eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (2)
381-381: LGTM: Addition of giveNoSpace() aligns with PR objectives.
The new translation key supports the full inventory behavior configuration, allowing for proper user feedback when inventory is full.
381-381: Verify the removal of enchantment-related translation methods.
The AI summary indicates that giveReceivedEnchantment() and giveGivenEnchantment() methods were removed, but this change seems unrelated to the PR objectives. Please verify if this removal was intentional and won't break existing enchantment functionality.
✅ Verification successful
The removal of enchantment-related translation methods is intentional and safe
After analyzing the codebase, the removal of giveReceivedEnchantment() and giveGivenEnchantment() methods is part of a cleanup as these methods were not being used. The enchantment functionality is fully maintained through:
EnchantCommand.javawhich usestranslation.item().enchantedMessage(),enchantedMessageFor(), andenchantedMessageBy()- The enchantment-related notices are properly handled in the Translation interface's ItemSection
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for any remaining references to the removed enchantment methods
# Search for any remaining usage of the removed methods
echo "Searching for references to removed enchantment methods..."
rg -l "giveReceivedEnchantment|giveGivenEnchantment"
# Search for enchantment-related command implementations
echo "Searching for enchantment command implementations..."
rg -l "class.*EnchantCommand|class.*GiveCommand"
Length of output: 549
Script:
#!/bin/bash
# Let's examine the content of these command files and any related test files
echo "Content of EnchantCommand.java:"
cat eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/enchant/EnchantCommand.java
echo -e "\nContent of GiveCommand.java:"
cat eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveCommand.java
# Let's also check for any test files that might reference these methods
echo -e "\nSearching for related test files..."
fd -e java -e kt --full-path ".*[Tt]est.*" -x grep -l "giveReceivedEnchantment\|giveGivenEnchantment" {}
Length of output: 8013
Script:
#!/bin/bash
# Let's check the Translation class and its history to understand the context of these removed methods
echo "Checking Translation class content:"
cat eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java
echo -e "\nChecking git history for the Translation class:"
git log -p eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java | grep -A 10 -B 10 "giveReceivedEnchantment\|giveGivenEnchantment"
Length of output: 14162
eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/ENTranslation.java (1)
739-739: LGTM: Clear and consistent error message for full inventory.
The added message follows the established pattern and clearly communicates when the player's inventory is full, which directly addresses the PR objective.
eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/PLTranslation.java (10)
100-120: LGTM! Error messages are consistent and clear.
The error messages follow a consistent format using the red color scheme and "✘" symbol, making them easily recognizable as error notifications.
210-211: LGTM! Teleport cancellation messages are clear.
The messages effectively communicate teleportation status to users.
244-244: LGTM! Random teleport messages maintain consistency.
The error messages maintain the established format and clearly communicate the issues to users.
Also applies to: 252-252
270-271: LGTM! Chat messages are consistent with error format.
The messages maintain the established error format and provide clear feedback.
Also applies to: 297-297
312-313: LGTM! TPA messages maintain error format consistency.
The messages effectively communicate teleport request status and errors.
Also applies to: 331-331, 346-346
368-374: LGTM! Warp messages are consistent with error format.
The messages maintain the established error format and provide clear feedback about warp operations.
443-443: LGTM! Home message maintains format consistency.
The message follows the established error format.
629-630: LGTM! Player-related messages maintain consistency.
The messages follow the established error format and provide clear feedback about player-related operations.
Also applies to: 661-661, 705-705
715-715: LGTM! Spawn message maintains format consistency.
The message follows the established error format.
891-891: LGTM! Jail messages maintain format consistency.
The messages follow the established error format and provide clear feedback about jail-related operations.
Also applies to: 896-896, 911-911, 913-913, 917-917
eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveCommand.java (3)
14-14: Importing CommandSender enhances command flexibility
By importing CommandSender, the command can now be executed by non-player entities such as the console or command blocks, increasing the versatility of the command.
22-29: Good abstraction of item-giving logic into GiveService
Encapsulating the item-giving functionality within GiveService improves modularity and adheres to the Single Responsibility Principle, enhancing code maintainability and readability.
47-55: Item giving and notification logic is correctly implemented
The function successfully delegates item giving to GiveService and sends a notification to the player upon success, ensuring a good user experience.
eternalcore-core/src/main/java/com/eternalcode/core/feature/essentials/item/give/GiveService.java (4)
26-56: Well-implemented giveItem method handling item distribution.
The giveItem method effectively manages item validation, inventory handling, and item distribution to players. It correctly utilizes the processGive method and appropriately handles scenarios where the inventory is full.
58-60: Appropriate material validation in isInvalidMaterial method.
The isInvalidMaterial method correctly checks if the provided material is a valid item, ensuring that only valid items are processed.
62-91: Efficient item processing in processGive method.
The processGive method efficiently iterates over the player's inventory slots, correctly handling item stacking and managing any remainder items when the inventory is full.
93-100: Accurate item stacking logic in processContentSlot method.
The processContentSlot method accurately calculates the amount of items to add to each slot, ensuring that stack limits are respected and item amounts are updated correctly.

I added an option in the config, which determines whether in the case when the inventory is full, the item should be thrown to the floor, or should return information that there is no space. I fixed the problem with IllegalStack being given by a command such as /give DIRT 512, then 99 dirt would appear.
Summary by CodeRabbit
New Features
Bug Fixes