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

GH-835 Add permission-based access to warps #856

Open
wants to merge 5 commits into
base: master
Choose a base branch
from

Conversation

eripe14
Copy link
Member

@eripe14 eripe14 commented Oct 1, 2024

Add permission-based access to warps.
Fixes: #835

Summary by CodeRabbit

  • New Features

    • Added warp permission management system
    • Introduced commands to add and remove warp permissions
    • Enhanced warp configuration with permission support
  • Bug Fixes

    • Improved warp teleportation permission checks
  • Documentation

    • Updated translations for warp permission-related messages in English and Polish
  • Refactor

    • Restructured warp configuration and repository classes
    • Updated warp service implementation

@eripe14 eripe14 self-assigned this Oct 1, 2024
@eripe14 eripe14 requested review from vLuckyyy, CitralFlo, imDMK, Rollczi, Jakubk15 and P1otrulla and removed request for vLuckyyy and CitralFlo October 1, 2024 21:46
Copy link
Member

@P1otrulla P1otrulla left a comment

Choose a reason for hiding this comment

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

Zrobione trochę na odpierdol, można dodać komendę która ustawia uprawnienie, która usuwa uprawnienie, dodać optional argument do tworzenia warpa przez admina oraz generalnie zdaję mi się że obiekt warp może przechowywać czy jest potrzebne uprawnienie a jak jest to jakie.

@CitralFlo CitralFlo removed their request for review October 1, 2024 22:47
@Jakubk15 Jakubk15 removed their request for review October 3, 2024 06:07
@Jakubk15
Copy link
Member

Jakubk15 commented Oct 3, 2024

I'm unable to perform a thorough review on this PR since I'm on a school trip right now.

@Rollczi Rollczi marked this pull request as draft October 6, 2024 17:23
@eripe14 eripe14 marked this pull request as ready for review October 8, 2024 16:47
public interface Warp {

Location getLocation();

String getName();

List<String> getPermissions();

void setPermissions(List<String> permissions);
Copy link
Member

Choose a reason for hiding this comment

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

Remove this method from public API

import java.util.Map;

@ConfigurationFile
public class WarpsConfiguration implements ReloadableConfig {
Copy link
Member

Choose a reason for hiding this comment

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

More like WarpsLocation, configuration is in config

editor.accept(warps);

this.locationsConfiguration.warps = warps;
this.configurationManager.save(this.locationsConfiguration);
warps.forEach((key, value) -> System.out.println(key + ": " + value));
Copy link
Member

Choose a reason for hiding this comment

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

is it needed here System.out.println ??

import java.util.List;

@Contextual
public class WarpConfigEntry {
Copy link
Member

Choose a reason for hiding this comment

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

What is the difference between WarpConfigEntry and WarpImpl ? Why are we using both when this could be one class?

@@ -602,6 +607,7 @@ public static class PLInventorySection implements InventorySection {
@Description({
" ",
"# Ta sekcja odpowiada za interakcję z graczami za pomocą komend",
"# Ta sekcja odpowiada za interakcję z graczami za pomocą komend",
Copy link
Member

Choose a reason for hiding this comment

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

image

Copy link
Member Author

Choose a reason for hiding this comment

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

What do you mean?

Copy link
Member

Choose a reason for hiding this comment

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

Duplicated, review ai says same. #856 (comment)

Co-authored-by: Michał Wojtas <[email protected]>
@vLuckyyy
Copy link
Member

vLuckyyy commented Oct 8, 2024

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Oct 8, 2024

✅ Actions performed

Full review triggered.

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: 13

🧹 Outside diff range and nitpick comments (14)
eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/Warp.java (1)

13-14: LGTM: New method getPermissions() added.

The getPermissions() method is a good addition for implementing permission-based access to warps. It allows retrieval of multiple permissions associated with a warp.

Consider adding Javadoc comments to describe the purpose and expected behavior of this method. For example:

/**
 * Retrieves the list of permissions associated with this warp.
 *
 * @return A list of permission strings required to access this warp.
 */
List<String> getPermissions();
eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/WarpService.java (1)

14-21: Good progress on implementing permission-based access to warps

The additions to the WarpService interface provide a solid foundation for implementing permission-based access to warps, addressing the objectives outlined in issue #835. The new methods for adding, removing, and checking warp permissions are well-designed and consistent.

To fully implement permission-based access control, consider the following suggestions:

  1. Update the createWarp method to optionally accept initial permissions.
  2. Modify the findWarp method to consider permissions when returning results.
  3. Add a method to retrieve all permissions for a given warp.
  4. Consider adding a method to check if a player has permission to access a specific warp.

These additions would provide a more comprehensive API for managing and enforcing warp permissions.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpImpl.java (3)

14-14: LGTM: New permissions field added correctly.

The permissions field is correctly declared as private and uses an appropriate type. Consider making it final for immutability:

-    private List<String> permissions;
+    private final List<String> permissions;

This change would ensure that the reference to the list cannot be changed after initialization, improving the class's thread-safety and immutability.


32-39: Approve getPermissions(), but consider revising setPermissions().

The getPermissions() method correctly returns an unmodifiable view of the list, which is good practice. However, the setPermissions() method could be improved:

  1. It allows direct modification of the internal list, which could lead to unexpected behavior.
  2. It's inconsistent with the immutable design suggested by the getPermissions() method.

Consider the following changes:

  1. Remove the setPermissions() method entirely if permissions should not be modifiable after creation.
  2. If permissions must be modifiable, implement methods to add or remove individual permissions instead:
public void addPermission(String permission) {
    this.permissions.add(permission);
}

public void removePermission(String permission) {
    this.permissions.remove(permission);
}
  1. If a setter is necessary, create a defensive copy:
public void setPermissions(List<String> permissions) {
    this.permissions = new ArrayList<>(permissions);
}

These changes will improve encapsulation and maintain consistency in the class design.


Line range hint 1-39: Summary: Implementation aligns with PR objectives, with room for improvement.

The changes to WarpImpl.java successfully implement permission-based access to warps, addressing the main objective of the PR. The new permissions field and related methods provide the necessary functionality to restrict access to specific warps based on player permissions.

However, there are opportunities to enhance the implementation:

  1. Consider making the permissions field final for improved immutability.
  2. Implement defensive copying in the constructor and setter (if retained) to prevent external modifications of the internal list.
  3. Reconsider the need for a setPermissions() method, or replace it with more granular methods for adding/removing individual permissions.

These improvements will strengthen the encapsulation and thread-safety of the WarpImpl class while maintaining the desired functionality.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/AddWarpPermissionCommand.java (1)

29-48: LGTM with a suggestion: Consider adding error handling.

The addPermission method correctly implements the functionality described in the PR objectives. It handles the case when no permissions are provided and uses NoticeService for user feedback, which is good.

However, consider adding error handling for potential exceptions that might be thrown by warpService.addPermissions(warp.getName(), permissions). This would make the command more robust and provide better feedback to users in case of failures.

Here's a suggested improvement:

 @Execute
 void addPermission(@Context Player player, @Arg Warp warp, @Arg String... permissions) {
     UUID uniqueId = player.getUniqueId();

     if (permissions.length == 0) {
         this.noticeService.create()
             .player(uniqueId)
             .notice(translation -> translation.warp().noPermissionsProvided())
             .send();
         return;
     }

-    this.warpService.addPermissions(warp.getName(), permissions);
-
-    this.noticeService.create()
-        .player(uniqueId)
-        .placeholder("{WARP}", warp.getName())
-        .notice(translation -> translation.warp().addPermissions())
-        .send();
+    try {
+        this.warpService.addPermissions(warp.getName(), permissions);
+        this.noticeService.create()
+            .player(uniqueId)
+            .placeholder("{WARP}", warp.getName())
+            .notice(translation -> translation.warp().addPermissions())
+            .send();
+    } catch (Exception e) {
+        this.noticeService.create()
+            .player(uniqueId)
+            .placeholder("{WARP}", warp.getName())
+            .notice(translation -> translation.warp().addPermissionsError())
+            .send();
+        // Consider logging the exception
+    }
 }

This change assumes you have an appropriate translation for addPermissionsError(). If not, you'll need to add it to your translation system.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/RemoveWarpPermissionCommand.java (1)

29-50: LGTM with a minor suggestion: Method implementation is correct and thorough.

The removePermission method is well-implemented with proper error handling and user feedback. It correctly checks for the existence of the permission before attempting to remove it and uses the appropriate services for warp management and player notifications.

A minor suggestion for improvement:

Consider adding a null check for the warp argument at the beginning of the method. Although it's likely handled by the command framework, an explicit check would improve robustness:

 @Execute
 void removePermission(@Context Player player, @Arg Warp warp, @Arg String permission) {
     UUID uniqueId = player.getUniqueId();
+
+    if (warp == null) {
+        this.noticeService.create()
+            .player(uniqueId)
+            .notice(translation -> translation.warp().notFound())
+            .send();
+        return;
+    }

     if (!warp.getPermissions().contains(permission)) {
         // ... (rest of the method)
     }
 }

This addition would ensure that the method gracefully handles cases where the warp might not exist, improving the overall robustness of the command.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/SetWarpCommand.java (2)

Line range hint 41-45: LGTM: Player UUID now passed to createWarp.

The change correctly passes the player's UUID to the createWarp method, aligning with the updated method signature. This allows for more specific player-related operations within createWarp.

Consider extracting player.getUniqueId() to a local variable for improved readability:

 void add(@Context Player player, @Arg String warpName) {
-    UUID uniqueId = player.getUniqueId();
+    UUID playerUuid = player.getUniqueId();
 
-    this.createWarp(player, warpName, uniqueId);
+    this.createWarp(player, warpName, playerUuid);
 }

Line range hint 47-89: Improved warp creation logic and user feedback.

The changes to the createWarp method significantly enhance its functionality and user experience. The method now checks for existing warps, provides clear notifications, and respects configuration settings.

Consider the following improvements:

  1. Extract the notification logic into separate methods to reduce the method's length and improve readability.
  2. Use early returns to reduce nesting and improve the flow of the method.
  3. Consider using constants for magic numbers like MAX_WARPS_IN_GUI.

Here's a suggested refactor:

private void createWarp(Player player, String warp, UUID uniqueId) {
    if (this.warpService.warpExists(warp)) {
        sendWarpExistsNotification(uniqueId, warp);
        return;
    }

    Warp createdWarp = this.warpService.createWarp(warp, player.getLocation());
    sendWarpCreatedNotification(uniqueId, warp);

    if (!this.config.warp.autoAddNewWarps) {
        return;
    }

    if (this.warpService.getNamesOfWarps().size() > MAX_WARPS_IN_GUI) {
        sendWarpLimitReachedNotification(uniqueId);
        return;
    }

    this.warpInventory.addWarp(createdWarp);
    sendWarpAddedToInventoryNotification(uniqueId);
}

private void sendWarpExistsNotification(UUID uniqueId, String warp) {
    this.noticeService.create()
        .player(uniqueId)
        .placeholder("{WARP}", warp)
        .notice(translation -> translation.warp().warpAlreadyExists())
        .send();
}

// ... (similar methods for other notifications)

This refactoring improves readability and maintainability while preserving the existing functionality.

eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (1)

150-154: LGTM: New permission-related methods added

The addition of these five methods to the WarpSection interface aligns well with the PR's objective of implementing permission-based access to warps. The method names are descriptive and follow a consistent naming convention.

Consider adding brief comments above each method to describe their specific purposes, especially for methods like permissionDoesNotExist() and noPermissionsProvided() where the exact use case might not be immediately clear to other developers.

eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (2)

Line range hint 331-343: New HelpOp configuration section looks good

The new HelpOp configuration section is well-structured and consistent with other parts of the configuration. It correctly implements the HelpOpSettings interface, ensuring system-wide consistency.

Consider making the default helpOpDelay value a constant at the class level for easier configuration and maintenance. For example:

private static final Duration DEFAULT_HELPOP_DELAY = Duration.ofSeconds(60);

@Description("# Delay to send the next message under /helpop")
public Duration helpOpDelay = DEFAULT_HELPOP_DELAY;

This change would make it easier to adjust the default value in the future if needed.


Line range hint 461-461: Jail configuration enhancements look good

The changes to the Jail configuration section, including the implementation of the JailSettings interface and the addition of allowed commands for jailed players, are well-implemented and provide good security control.

Consider making the set of allowed commands more flexible by providing a method to add or remove commands programmatically. This could be achieved by using a mutable set and adding methods like:

public void addAllowedCommand(String command) {
    this.allowedCommands.add(command.toLowerCase());
}

public void removeAllowedCommand(String command) {
    this.allowedCommands.remove(command.toLowerCase());
}

This would allow for easier customization of allowed commands without modifying the configuration file.

Also applies to: 467-468, 477-479

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpPermissionController.java (1)

44-47: Consider renaming isPlayerAllowedToUseWarp for clarity

The variable isPlayerAllowedToUseWarp is an Optional<String> that holds a matching permission string. The name suggests a boolean value, which might be misleading. Consider renaming it to matchingPermission or grantedPermission to better reflect its purpose and improve code readability.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpServiceImpl.java (1)

7-13: Organize Imports for Clarity and Maintainability

Consider organizing your import statements for better readability. Grouping related imports together and removing any unused imports can enhance code clarity.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 38ba610 and f1a6ada.

📒 Files selected for processing (19)
  • eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/Warp.java (1 hunks)
  • eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/WarpService.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/configuration/ConfigurationManager.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/LocationsConfiguration.java (2 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (2 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/WarpsConfiguration.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpConfigEntry.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpConfigRepository.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpImpl.java (2 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpInventory.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpPermissionController.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpRepository.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpServiceImpl.java (3 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/AddWarpPermissionCommand.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/RemoveWarpPermissionCommand.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/SetWarpCommand.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (2 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 (3 hunks)
✅ Files skipped from review due to trivial changes (2)
  • eternalcore-core/src/main/java/com/eternalcode/core/configuration/ConfigurationManager.java
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpInventory.java
🧰 Additional context used
🔇 Additional comments (32)
eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/Warp.java (2)

5-6: LGTM: Import statement added correctly.

The import for java.util.List is necessary for the new methods and has been added appropriately.


15-16: New method setPermissions() added, but consider potential misuse.

The setPermissions(List<String> permissions) method is a good addition for implementing permission-based access to warps. It allows setting multiple permissions for a warp.

However, exposing a setter method in the public API might lead to unexpected behavior if not used carefully. Consider the following:

  1. Is there a need to modify permissions after a warp is created?
  2. Should this operation be restricted to certain parts of the codebase?

If modifying permissions should be a restricted operation, consider moving this method to a separate administrative interface or service.

Add Javadoc comments to describe the purpose and expected behavior of this method. For example:

/**
 * Sets the list of permissions required to access this warp.
 *
 * @param permissions A list of permission strings to be associated with this warp.
 */
void setPermissions(List<String> permissions);

To ensure this method is used appropriately, let's check its usage across the codebase:

✅ Verification successful

Verification of setPermissions() usage confirmed. No issues found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usages of setPermissions method
rg "setPermissions\(" --type java

Length of output: 568

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpRepository.java (3)

13-13: LGTM: New method addPermissions is well-designed.

The addPermissions method is a good addition to the WarpRepository interface. It allows for flexible addition of multiple permissions to a warp, which aligns with the PR objective of implementing permission-based access to warps. The method signature is consistent with the existing interface style.


15-15: LGTM: New method removePermission complements the permission management functionality.

The removePermission method is a valuable addition to the WarpRepository interface. It provides the ability to remove a single permission from a warp, offering fine-grained control over warp access. This method, along with addPermissions, provides comprehensive permission management for warps, fulfilling the PR objective.


Line range hint 1-21: Overall, the changes to WarpRepository.java are well-implemented and align with the PR objectives.

The additions to the WarpRepository interface successfully implement the required functionality for permission-based access to warps. The new methods addPermissions and removePermission complement the existing warp management methods, providing a comprehensive interface for warp operations.

The only suggestion for improvement is to consider using CompletableFuture for the new methods to maintain consistency with the existing asynchronous methods in the interface.

These changes effectively address the requirements outlined in issue #835 and contribute to a more robust warp management system.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpConfigEntry.java (1)

9-9: Clarify the relationship between WarpConfigEntry and WarpImpl

Addressing a previous comment by CitralFlo: The difference between WarpConfigEntry and WarpImpl is not clear from this file alone. It appears that WarpConfigEntry is specifically designed for configuration purposes, possibly for serialization/deserialization of warp data.

To clarify this:

  1. Could you provide more context on the WarpImpl class and its purpose?
  2. Is WarpConfigEntry intended to be a simplified version of WarpImpl for configuration purposes?
  3. Are there any specific reasons why these need to be separate classes?

Understanding the relationship between these classes would help in determining if they can be combined or if they serve distinct purposes in the system.

To help clarify this, let's check for the existence and structure of the WarpImpl class:

This will help us understand the structure of both classes and determine if they can be combined or if they serve different purposes.

✅ Verification successful

Relationship Between WarpConfigEntry and WarpImpl Verified

Based on the analysis:

  • WarpConfigEntry serves as a configuration data holder with position and permissions fields.
  • WarpImpl is the implementation of the Warp interface, extending the configuration with an additional name field.

This separation ensures clear responsibilities within the system.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for WarpImpl class definition
echo "Searching for WarpImpl class:"
rg --type java -A 5 "class WarpImpl"

# Compare fields between WarpConfigEntry and WarpImpl
echo "Comparing fields:"
rg --type java -A 10 "class WarpConfigEntry|class WarpImpl"

Length of output: 3258

eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/WarpService.java (3)

14-14: LGTM: Well-designed method for adding permissions

The addPermissions method is a good addition to the WarpService interface. It allows for flexible addition of one or more permissions to a warp. The use of varargs for the permissions parameter is appropriate and provides a convenient API for callers.


16-16: LGTM: Complementary method for permission removal

The removePermission method is a good complement to the addPermissions method. It provides a way to remove a single permission from a warp, which is essential for managing warp permissions effectively.


20-20: LGTM: Useful method for permission checking

The doesWarpPermissionExist method is a valuable addition to the WarpService interface. It provides a way to check if a specific permission exists for a given warp, which is crucial for implementing permission-based access control.

The method signature matches the suggestion from the previous review, which is good to see.

eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/WarpsConfiguration.java (2)

14-15: LGTM: Class declaration and annotations are appropriate.

The class name WarpsConfiguration accurately represents its purpose as a configuration class for warps. Implementing ReloadableConfig is a good practice for dynamic configuration management. The @ConfigurationFile annotation appropriately marks this class for special handling in the configuration system.

Regarding the past comment suggesting renaming to WarpsLocation, I believe the current name WarpsConfiguration is more suitable as it emphasizes its role in the configuration system rather than just representing locations.


20-23: LGTM: The resource method is well-implemented.

The resource method correctly overrides the method from the ReloadableConfig interface. It efficiently creates a Resource object pointing to the warps.yml file within the given folder. Using a YAML file for configuration is a good choice for readability and maintainability.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpImpl.java (1)

7-9: LGTM: Import statements are correctly added.

The new imports for Collections and List are necessary for the added functionality and are correctly placed.

eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/LocationsConfiguration.java (1)

3-3: LGTM: Import statement uncommented and moved.

The import for Position has been correctly uncommented and moved. This change aligns with the usage of Position in the warps field.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/AddWarpPermissionCommand.java (2)

1-18: LGTM: Class structure and annotations are well-defined.

The class structure, package, and annotations are appropriate for the intended functionality. The command name and permission align well with the PR objectives of implementing permission-based access to warps.


20-27: LGTM: Constructor and dependency injection are well-implemented.

The use of dependency injection for WarpService and NoticeService is a good practice. These services are appropriate for managing warps and providing user feedback, respectively.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/RemoveWarpPermissionCommand.java (3)

1-18: LGTM: Class structure and annotations are well-defined.

The class structure, package, and annotations are correctly implemented. The command name "removewarp-permission" and the required permission "eternalcore.warp.changepermissions" are appropriately specified.


20-27: LGTM: Constructor and dependency injection are correctly implemented.

The constructor uses dependency injection correctly with the @Inject annotation. The WarpService and NoticeService are properly initialized, and the use of final fields ensures immutability, which is a good practice for thread-safety and maintaining the integrity of the dependencies throughout the lifecycle of the command object.


1-52: Overall assessment: Well-implemented command for managing warp permissions.

This new RemoveWarpPermissionCommand class effectively implements the functionality to remove permissions from warps, aligning well with the PR objectives. The code is well-structured, uses dependency injection appropriately, and includes proper error handling and user feedback.

Key strengths:

  1. Correct use of annotations for command definition and permissions.
  2. Proper dependency injection for required services.
  3. Thorough implementation of the removePermission method with appropriate checks and error handling.
  4. Support for internationalization through the use of translation services.

The minor suggestion for adding a null check for the warp argument would further improve the robustness of the implementation. Overall, this addition to the EternalCore project effectively contributes to the goal of implementing permission-based access to warps.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/SetWarpCommand.java (2)

17-18: LGTM: Import statement reorganized.

The import for java.util.UUID has been moved. This change doesn't affect functionality and likely improves code organization.


Line range hint 1-89: Overall assessment: Improved warp management with room for minor enhancements.

The changes in this file significantly improve the warp creation process and user feedback, aligning well with the PR objectives. The implementation is correct and enhances the functionality of the SetWarpCommand class.

Key improvements:

  1. Warp existence check prevents duplicates.
  2. Clear user notifications for different scenarios.
  3. Respect for configuration settings in warp creation.
  4. Prevention of exceeding GUI limits for warps.

While the changes are good, consider the refactoring suggestions to further improve code readability and maintainability. These minor enhancements will make the code even more robust and easier to maintain in the future.

eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (2)

5-5: LGTM: Import statement uncommented

Uncommenting the import for WarpInventoryItem is consistent with the PR's objective of enhancing warp functionality. This change suggests that WarpInventoryItem is now being utilized in the file.


Line range hint 1-554: Overall assessment: Changes align with PR objectives

The modifications to the Translation interface, particularly in the WarpSection, successfully introduce the necessary language support for the new permission-based access to warps feature. These changes are consistent with the PR objectives and enhance the project's internationalization capabilities for the new functionality.

To ensure comprehensive coverage of translation keys, please run the following script to check for any missing translations in other language files:

This script will help identify any translation keys that might be missing in other language files, ensuring consistency across all supported languages for the new warp permission features.

eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (2)

9-9: Import changes are consistent with new features

The addition of HelpOpSettings import and the changes to collection imports (LinkedHashMap removed, Set added) align well with the introduction of the HelpOp feature and potential modifications in other parts of the configuration. These changes appear to be appropriate for the new functionality being added.

Also applies to: 26-26, 28-28


Line range hint 1-481: Overall, the changes to PluginConfiguration.java look good

The modifications to the PluginConfiguration class, including the addition of the HelpOp section and enhancements to the Jail section, are well-implemented and consistent with the existing codebase structure. These changes align well with the PR objectives of adding permission-based access to warps and enhancing the plugin's functionality.

The new features are implemented in a way that allows for easy configuration and future extension. The use of interfaces (HelpOpSettings, JailSettings) ensures consistency across the system.

While the implementation is solid, consider the minor suggestions provided in the previous comments to further improve configurability and flexibility.

eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/ENTranslation.java (4)

1-23: LGTM: Import statements and class declaration look good.

The changes to the import statements, including the addition of WarpInventoryItem and reinstatement of HashMap, are consistent with the modifications described in the summary. The overall structure of the class declaration remains appropriate.


374-378: Excellent addition of permission-related messages.

The new Notice fields in the ENWarpSection class effectively support the implementation of permission-based access to warps, which is the primary objective of this PR. The messages cover various scenarios such as lack of permission, adding/removing permissions, and handling non-existent permissions. This enhancement improves the user experience by providing clear feedback on warp accessibility.


Line range hint 385-391: Improved warp inventory structure with Map implementation.

The modification of the items field to use a Map<String, WarpInventoryItem> is a positive change. This approach allows for more efficient and flexible management of warp inventory items, enabling easier lookup and manipulation of items based on their identifiers. This refinement aligns well with best practices for inventory management in Minecraft plugins and supports the overall goal of enhancing the warp functionality.


Line range hint 1-1000: Summary: Excellent implementation of permission-based warp access.

The changes in this file successfully implement the permission-based access to warps, which was the primary objective of this PR. Key improvements include:

  1. Addition of permission-related messages in the ENWarpSection class.
  2. Refinement of the warp inventory structure using a Map in the ENWarpInventory class.

These modifications enhance the functionality and user experience of the warp system while maintaining consistency with the existing codebase. The changes are well-integrated and do not introduce any apparent issues or inconsistencies.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpServiceImpl.java (1)

40-40: Ensure Consistency with Constructor Parameters

The WarpImpl constructor now includes a new parameter new ArrayList<>() for permissions. Ensure that this change aligns with the WarpImpl class constructor definition and that all instantiations of WarpImpl are updated accordingly.

Would you like to confirm that the WarpImpl constructor accepts the new parameter and that there are no side effects from this change?

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpConfigRepository.java (1)

88-88: Previous comment still applicable: Remove unnecessary System.out.println

The System.out.println statement at line 88 seems to be for debugging purposes. It should be removed to prevent unnecessary console output in production code.

eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/PLTranslation.java (2)

5-5: Import of WarpInventoryItem is necessary and correctly added

The import statement import com.eternalcode.core.feature.warp.WarpInventoryItem; is appropriately added, as WarpInventoryItem is used within the PLWarpInventory class.


20-20: Reintroduction of HashMap import is appropriate

The addition of import java.util.HashMap; is necessary for the usage of new HashMap<>() in initializing the items map.

Comment on lines +13 to +15
void addPermissions(String warp, String... permissions);

void removePermission(String warp, String permission);
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 using CompletableFuture for new methods to maintain consistency.

The new methods addPermissions and removePermission integrate well with the existing interface. However, to maintain consistency with the existing asynchronous methods like getWarp and getWarps, consider using CompletableFuture for these new methods as well. This would ensure a uniform approach to potentially long-running operations across the interface.

Example:

CompletableFuture<Void> addPermissions(String warp, String... permissions);
CompletableFuture<Void> removePermission(String warp, String permission);

This change would make the interface more consistent and potentially more scalable for future asynchronous implementations.

Comment on lines +8 to +20
@Contextual
public class WarpConfigEntry {
public Position position;
public List<String> permissions;

public WarpConfigEntry() {
}

public WarpConfigEntry(Position position, List<String> permissions) {
this.position = position;
this.permissions = permissions;
}
}
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 enhancing encapsulation and adding documentation

The WarpConfigEntry class seems to be designed as a data container for warp configurations. While the current structure works, there are a few suggestions to improve it:

  1. Consider using private fields with getter and setter methods to improve encapsulation. This would allow for better control over access and modification of the fields.

  2. Add JavaDoc comments to explain the purpose of the class and its fields. This will help other developers understand how to use this class correctly.

  3. Consider making the class immutable by making the fields final and removing the default constructor. This can help prevent unintended modifications to the warp configurations.

Here's an example of how you could refactor the class:

/**
 * Represents a configuration entry for a warp.
 */
@Contextual
public class WarpConfigEntry {
    private final Position position;
    private final List<String> permissions;

    /**
     * Constructs a new WarpConfigEntry.
     *
     * @param position The position of the warp.
     * @param permissions The list of permissions required to access the warp.
     */
    public WarpConfigEntry(Position position, List<String> permissions) {
        this.position = position;
        this.permissions = List.copyOf(permissions); // Create an immutable copy
    }

    public Position getPosition() {
        return position;
    }

    public List<String> getPermissions() {
        return List.copyOf(permissions); // Return an immutable copy
    }
}

This refactored version provides better encapsulation, immutability, and documentation.

@Contextual
public class WarpConfigEntry {
public Position position;
public List<String> permissions;
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 using a Set for permissions and add validation

The current implementation uses a List<String> for storing permissions. This could lead to potential issues:

  1. Duplicate permissions could be added unintentionally.
  2. Permission checks might be case-sensitive, leading to inconsistencies (e.g., "ADMIN" vs "admin").
  3. Checking for the existence of a permission is not as efficient as it could be with a Set.

Consider the following improvements:

  1. Use a Set<String> instead of a List<String> for permissions. This will automatically prevent duplicates and provide more efficient permission checks.
  2. Implement permission normalization (e.g., converting to lowercase) to ensure consistency.
  3. Add validation in the constructor to ensure that the permissions are not null and don't contain empty strings.

Here's an example of how you could implement these changes:

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

public class WarpConfigEntry {
    private final Position position;
    private final Set<String> permissions;

    public WarpConfigEntry(Position position, List<String> permissions) {
        this.position = position;
        this.permissions = normalizePermissions(permissions);
    }

    private Set<String> normalizePermissions(List<String> permissions) {
        if (permissions == null) {
            throw new IllegalArgumentException("Permissions list cannot be null");
        }
        return permissions.stream()
            .filter(p -> p != null && !p.trim().isEmpty())
            .map(String::toLowerCase)
            .collect(Collectors.toCollection(HashSet::new));
    }

    // ... getters and other methods
}

This implementation ensures that the permissions are stored efficiently, normalized, and validated.

Comment on lines +1 to +25
package com.eternalcode.core.configuration.implementation;

import com.eternalcode.core.configuration.ReloadableConfig;
import com.eternalcode.core.feature.warp.WarpConfigEntry;
import com.eternalcode.core.injector.annotations.component.ConfigurationFile;
import net.dzikoysk.cdn.entity.Description;
import net.dzikoysk.cdn.source.Resource;
import net.dzikoysk.cdn.source.Source;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@ConfigurationFile
public class WarpsConfiguration implements ReloadableConfig {

@Description({"# Warps configuration", "# These are warp locations, for your own safety, please don't touch it."})
public Map<String, WarpConfigEntry> warps = new HashMap<>();

@Override
public Resource resource(File folder) {
return Source.of(folder, "warps.yml");
}

}
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 adding utility methods and validation logic.

While the current implementation is functional, consider the following enhancements to improve the robustness and usability of the WarpsConfiguration class:

  1. Add a method to validate warp entries, ensuring they meet any required criteria.
  2. Implement a method to merge or update the configuration with new entries.
  3. Consider adding utility methods for common operations, such as checking if a warp exists.

Here are some suggested method signatures:

public boolean isValidWarp(WarpConfigEntry entry) {
    // Implement validation logic
}

public void mergeConfiguration(Map<String, WarpConfigEntry> newWarps) {
    // Implement merge logic
}

public boolean hasWarp(String warpName) {
    return warps.containsKey(warpName);
}

These additions would enhance the functionality and make the class more robust and easier to use in other parts of the system.

Comment on lines +16 to +19
WarpImpl(String name, Position position, List<String> permissions) {
this.name = name;
this.position = position;
this.permissions = permissions;
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 using defensive copying for the permissions list.

While the constructor correctly initializes the new permissions field, it's advisable to create a defensive copy of the input list to prevent external modifications. This ensures that the internal state of the WarpImpl object remains consistent.

Consider applying this change:

     WarpImpl(String name, Position position, List<String> permissions) {
         this.name = name;
         this.position = position;
-        this.permissions = permissions;
+        this.permissions = new ArrayList<>(permissions);
     }

Don't forget to add the import for java.util.ArrayList if it's not already present.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
WarpImpl(String name, Position position, List<String> permissions) {
this.name = name;
this.position = position;
this.permissions = permissions;
WarpImpl(String name, Position position, List<String> permissions) {
this.name = name;
this.position = position;
this.permissions = new ArrayList<>(permissions);
}

Comment on lines +95 to +103
public boolean doestWarpPermissionExist(String warpName, String permission) {
Warp warp = this.warpMap.get(warpName);

if (warp == null) {
return false;
}

return warp.getPermissions().contains(permission);
}
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

Correct Typo in Method Name

The method name doestWarpPermissionExist contains a typo. It should be doesWarpPermissionExist. Correcting this will improve code readability and prevent confusion.

Apply this diff to fix the method name:

-public boolean doestWarpPermissionExist(String warpName, String permission) {
+public boolean doesWarpPermissionExist(String warpName, String permission) {
     Warp warp = this.warpMap.get(warpName);

     if (warp == null) {
         return false;
     }

     return warp.getPermissions().contains(permission);
 }

Also, update any references to this method accordingly.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public boolean doestWarpPermissionExist(String warpName, String permission) {
Warp warp = this.warpMap.get(warpName);
if (warp == null) {
return false;
}
return warp.getPermissions().contains(permission);
}
public boolean doesWarpPermissionExist(String warpName, String permission) {
Warp warp = this.warpMap.get(warpName);
if (warp == null) {
return false;
}
return warp.getPermissions().contains(permission);
}

Comment on lines +59 to +72
@Override
public void addPermissions(String warpName, String... permissions) {
Warp warp = this.warpMap.get(warpName);

if (warp == null) {
return;
}

List<String> updatedPermissions = new ArrayList<>(warp.getPermissions());
updatedPermissions.addAll(List.of(permissions));

warp.setPermissions(updatedPermissions);
this.warpRepository.addPermissions(warpName, permissions);
}
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

Handle Null Permissions Parameter Safely

In the addPermissions method, if permissions is null, calling List.of(permissions) will throw a NullPointerException. Consider adding a null check for the permissions parameter to prevent potential runtime errors.

Apply this diff to add a null check:

 public void addPermissions(String warpName, String... permissions) {
     Warp warp = this.warpMap.get(warpName);

     if (warp == null) {
         return;
     }

+    if (permissions == null) {
+        return;
+    }

     List<String> updatedPermissions = new ArrayList<>(warp.getPermissions());
     updatedPermissions.addAll(List.of(permissions));

     warp.setPermissions(updatedPermissions);
     this.warpRepository.addPermissions(warpName, permissions);
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@Override
public void addPermissions(String warpName, String... permissions) {
Warp warp = this.warpMap.get(warpName);
if (warp == null) {
return;
}
List<String> updatedPermissions = new ArrayList<>(warp.getPermissions());
updatedPermissions.addAll(List.of(permissions));
warp.setPermissions(updatedPermissions);
this.warpRepository.addPermissions(warpName, permissions);
}
@Override
public void addPermissions(String warpName, String... permissions) {
Warp warp = this.warpMap.get(warpName);
if (warp == null) {
return;
}
if (permissions == null) {
return;
}
List<String> updatedPermissions = new ArrayList<>(warp.getPermissions());
updatedPermissions.addAll(List.of(permissions));
warp.setPermissions(updatedPermissions);
this.warpRepository.addPermissions(warpName, permissions);
}

Comment on lines +74 to +87
@Override
public void removePermission(String warpName, String permission) {
Warp warp = this.warpMap.get(warpName);

if (warp == null) {
return;
}

List<String> updatedPermissions = new ArrayList<>(warp.getPermissions());
updatedPermissions.remove(permission);

warp.setPermissions(updatedPermissions);
this.warpRepository.removePermission(warpName, permission);
}
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

Synchronize Permission Updates Across Warp Instances

When modifying the permissions of a warp, ensure that all references to the warp are aware of the changes. If Warp objects are shared across different parts of the system, consider making warpMap thread-safe or synchronizing access to prevent concurrent modification issues.

Consider using a concurrent map or synchronizing access methods:

-import java.util.HashMap;
+import java.util.concurrent.ConcurrentHashMap;

...

-private final Map<String, Warp> warpMap = new HashMap<>();
+private final Map<String, Warp> warpMap = new ConcurrentHashMap<>();

Committable suggestion was skipped due to low confidence.

Comment on lines +95 to +96
return CompletableFuture.completedFuture(Optional.of(this.warpsConfiguration.warps.get(name))
.map(warpConfigEntry -> new WarpImpl(name, warpConfigEntry.position, warpConfigEntry.permissions)));
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 NullPointerException by using Optional.ofNullable

In the getWarp method, using Optional.of(this.warpsConfiguration.warps.get(name)) can cause a NullPointerException if get(name) returns null. Replace Optional.of with Optional.ofNullable to safely handle null values.

Here's the suggested fix:

-return CompletableFuture.completedFuture(Optional.of(this.warpsConfiguration.warps.get(name))
+return CompletableFuture.completedFuture(Optional.ofNullable(this.warpsConfiguration.warps.get(name))
     .map(warpConfigEntry -> new WarpImpl(name, warpConfigEntry.position, warpConfigEntry.permissions)));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return CompletableFuture.completedFuture(Optional.of(this.warpsConfiguration.warps.get(name))
.map(warpConfigEntry -> new WarpImpl(name, warpConfigEntry.position, warpConfigEntry.permissions)));
return CompletableFuture.completedFuture(Optional.ofNullable(this.warpsConfiguration.warps.get(name))
.map(warpConfigEntry -> new WarpImpl(name, warpConfigEntry.position, warpConfigEntry.permissions)));

Comment on lines 377 to 381
public Notice noPermission = Notice.chat("<red>✘ <dark_red>Błąd: <red>Nie masz uprawnień do skorzystania z tego warpa ({WARP})!");
public Notice addPermissions = Notice.chat("<green>► <white>Dodano uprawnienia do warpa <green>{WARP}<white>!");
public Notice removePermission = Notice.chat("<red>► <white>Usunięto uprawnienie <red>{PERMISSION}</red> do warpa <red>{WARP}</red>!");
public Notice noPermissionsProvided = Notice.chat("<red>✘ <dark_red>Błąd: <red>Nie podano żadnych uprawnień!");
public Notice permissionDoesNotExist = Notice.chat("<red>✘ <dark_red>Błąd: <red>Podane uprawnienie nie istnieje ({PERMISSION})!");
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

Align placeholder formatting for consistency

In the newly added Notice messages, placeholders like {WARP} and {PERMISSION} are enclosed within parentheses, which is inconsistent with the formatting in other messages where placeholders are not enclosed and have consistent color styling.

For consistency and improved readability, consider removing the parentheses and applying color formatting to the placeholders similar to existing messages. For example:

- public Notice noPermission = Notice.chat("<red>✘ <dark_red>Błąd: <red>Nie masz uprawnień do skorzystania z tego warpa ({WARP})!");
+ public Notice noPermission = Notice.chat("<red>✘ <dark_red>Błąd: <red>Nie masz uprawnień do skorzystania z tego warpa <dark_red>{WARP}<red>!");

Committable suggestion was skipped due to low confidence.

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: 21

🧹 Outside diff range and nitpick comments (14)
eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/Warp.java (1)

15-16: LGTM: New method setPermissions() is well-defined, consider adding documentation.

The setPermissions(List<String> permissions) method is a good addition for setting the list of permissions associated with a warp. The parameter type List<String> is consistent with the getPermissions() method.

Consider adding Javadoc comments to both new methods to describe their purpose, parameters, and any potential exceptions that might be thrown (e.g., if null is passed to setPermissions).

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpRepository.java (1)

13-16: Summary: New methods address PR objectives but could be improved for consistency.

The addition of addPermissions and removePermission methods successfully addresses the PR objective of implementing permission-based access to warps. These methods provide the necessary functionality to manage permissions for specific warps, which aligns with the goal of restricting access to certain warps (e.g., for VIP players).

However, to fully meet the project's standards and maintain consistency:

  1. Consider implementing these methods using CompletableFuture to align with the existing asynchronous methods in the interface.
  2. Review the naming convention for consistency between singular and plural forms of "permission" in method names.
  3. Ensure that the implementation of these methods in the concrete class properly handles the permission nodes (e.g., eternalcore.warp.vipzone) as described in the PR objectives.

These changes will not only fulfill the immediate requirements but also contribute to a more robust and maintainable codebase.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpConfigEntry.java (2)

8-9: LGTM! Consider adding class-level documentation.

The class declaration and @Contextual annotation look good. To improve code readability and maintainability, consider adding a JavaDoc comment explaining the purpose of this class and the significance of the @Contextual annotation.

Example:

/**
 * Represents a configuration entry for a warp.
 * This class is used in the context of warp configuration serialization/deserialization.
 */
@Contextual
public class WarpConfigEntry {
    // ...
}

1-20: Overall class structure needs improvement

While the WarpConfigEntry class serves its basic purpose, there are several areas where it could be improved:

  1. Encapsulation: Use private fields with getter methods.
  2. Immutability: Consider making the class immutable to prevent unintended modifications.
  3. Validation: Add null checks and other necessary validations in the constructor.
  4. Data structure: Use a Set for permissions instead of a List.
  5. Documentation: Add JavaDoc comments to explain the purpose of the class and its fields.
  6. Functionality: Consider adding methods for permission checking or position comparison if needed.

Here's a sketch of how the improved class might look:

/**
 * Represents an immutable configuration entry for a warp.
 * This class is used in the context of warp configuration serialization/deserialization.
 */
@Contextual
public class WarpConfigEntry {
    private final Position position;
    private final Set<String> permissions;

    /**
     * Constructs a new WarpConfigEntry.
     *
     * @param position The position of the warp. Must not be null.
     * @param permissions The permissions required for the warp. Must not be null.
     * @throws NullPointerException if either parameter is null.
     */
    public WarpConfigEntry(Position position, List<String> permissions) {
        this.position = Objects.requireNonNull(position, "Position cannot be null");
        this.permissions = Collections.unmodifiableSet(new HashSet<>(
            Objects.requireNonNull(permissions, "Permissions cannot be null")
        ));
    }

    public Position getPosition() {
        return position;
    }

    public Set<String> getPermissions() {
        return permissions; // Already unmodifiable
    }

    /**
     * Checks if the given permission is required for this warp.
     *
     * @param permission The permission to check.
     * @return true if the permission is required, false otherwise.
     */
    public boolean hasPermission(String permission) {
        return permissions.contains(permission.toLowerCase());
    }

    // ... (other methods as needed)
}

This structure provides better encapsulation, immutability, and additional functionality while maintaining the original purpose of the class.

eternalcore-core/src/main/java/com/eternalcode/core/configuration/ConfigurationManager.java (1)

20-23: Improved import organization

The reordering of import statements follows a good practice of grouping imports by package, with Java standard library imports at the end. This change enhances code readability by clearly separating third-party imports from standard library imports.

Consider adopting this import ordering convention throughout the project for consistency.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/SetWarpCommand.java (1)

17-18: Approved: Import statement reorganization

The relocation of the java.util.UUID import statement improves code organization. This change is consistent with common Java coding practices.

Consider grouping imports by package (java.util, com.eternalcode, org.bukkit, etc.) and sorting them alphabetically within each group for even better organization. For example:

import java.util.UUID;

import org.bukkit.entity.Player;

import com.eternalcode.annotations.scan.command.DescriptionDocs;
import com.eternalcode.core.configuration.implementation.PluginConfiguration;
// ... other com.eternalcode imports ...

import dev.rollczi.litecommands.annotations.argument.Arg;
// ... other dev.rollczi imports ...
eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (1)

150-154: LGTM: New permission-related methods added

The addition of these five methods to the WarpSection interface aligns well with the PR objectives of implementing permission-based access to warps. The method names are clear and descriptive, and the return type Notice is consistent with other methods in the interface.

However, there's a minor inconsistency in the naming convention:

  • addPermissions() uses plural
  • removePermission() uses singular

Consider standardizing these method names for consistency, either both plural or both singular.

Suggestion for consistency:

 Notice noPermission();
-Notice addPermissions();
-Notice removePermission();
+Notice addPermission();
+Notice removePermission();
 Notice permissionDoesNotExist();
 Notice noPermissionsProvided();
eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (1)

Line range hint 321-335: LGTM: HelpOp section is well-implemented.

The new HelpOp section is correctly structured and implements the HelpOpSettings interface as expected. The default delay of 60 seconds seems reasonable.

Consider adding a brief comment explaining the purpose of the helpOpDelay, e.g., "Prevents spam and abuse of the helpop command."

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/AddWarpPermissionCommand.java (3)

24-27: Annotate constructor parameters with @NotNull

To improve code safety and clarity, consider adding @NotNull annotations to the constructor parameters. This explicitly indicates that these dependencies should not be null.

Apply this diff:

 public AddWarpPermissionCommand(
+    @NotNull WarpService warpService,
+    @NotNull NoticeService noticeService
 ) {
     this.warpService = warpService;
     this.noticeService = noticeService;
 }

30-48: Add JavaDoc comments for better maintainability

Including JavaDoc comments for the addPermission method will enhance readability and assist other developers in understanding the method's purpose and usage.

Apply this diff:

+/**
+ * Adds permissions to a warp and notifies the player.
+ *
+ * @param player      the player executing the command
+ * @param warp        the warp to which permissions will be added
+ * @param permissions the permissions to add to the warp
+ */
 void addPermission(@Context Player player, @Arg Warp warp, @Arg String... permissions) {

33-39: Provide feedback when no permissions are provided

The notice sent when no permissions are provided could include additional guidance to the player on how to use the command correctly.

Consider modifying the notice to include usage instructions or an example.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpPermissionController.java (1)

55-59: Consider adding a permission placeholder in the notice message

Including a placeholder for the required permission(s) in the notice message can inform the player which permission is needed to access the warp. This enhances user feedback and can assist in troubleshooting permission issues.

Apply this diff to add the permission placeholder:

 this.noticeService.create()
     .player(player.getUniqueId())
     .placeholder("{WARP}", warp.getName())
+    .placeholder("{PERMISSION}", permissions.toString())
     .notice(translation -> translation.warp().noPermission())
     .send();

Note: Ensure that the translation string noPermission() accommodates the {PERMISSION} placeholder.

eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/ENTranslation.java (2)

376-376: Inconsistent closing tag in color formatting

The removePermission message includes a closing </red> tag, which is inconsistent with the rest of the codebase where color tags are typically not closed. To maintain consistency, consider removing the closing tag.

Apply this diff to correct the inconsistency:

-public Notice removePermission = Notice.chat("<red>► <white>Removed permission <red>{PERMISSION}</red> <white>from warp <red>{WARP}<white>!");
+public Notice removePermission = Notice.chat("<red>► <white>Removed permission <red>{PERMISSION} <white>from warp <red>{WARP}<white>!");

378-378: Typographical correction: standardize contraction usage

In the permissionDoesNotExist message, consider replacing "doesn't" with "does not" for formality and consistency with similar messages like "This warp doesn't exist" used elsewhere in the code.

Apply this diff to standardize the contraction:

-public Notice permissionDoesNotExist = Notice.chat("<red>✘ <dark_red>Permission <red>{PERMISSION} <dark_red>doesn't exist!");
+public Notice permissionDoesNotExist = Notice.chat("<red>✘ <dark_red>Permission <red>{PERMISSION} <dark_red>does not exist!");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 38ba610 and f1a6ada.

📒 Files selected for processing (19)
  • eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/Warp.java (1 hunks)
  • eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/WarpService.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/configuration/ConfigurationManager.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/LocationsConfiguration.java (2 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (2 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/WarpsConfiguration.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpConfigEntry.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpConfigRepository.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpImpl.java (2 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpInventory.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpPermissionController.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpRepository.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpServiceImpl.java (3 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/AddWarpPermissionCommand.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/RemoveWarpPermissionCommand.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/SetWarpCommand.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (2 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 (3 hunks)
🧰 Additional context used
🔇 Additional comments (24)
eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/Warp.java (3)

5-6: LGTM: Import statement addition is appropriate.

The addition of import java.util.List; is necessary and correct for the new methods using List<String>.


13-14: LGTM: New method getPermissions() is well-defined.

The getPermissions() method is a good addition for retrieving the list of permissions associated with a warp. The return type List<String> is appropriate for this purpose.


Line range hint 1-18: Summary: Changes align well with PR objectives.

The additions to the Warp interface successfully implement the foundation for permission-based access to warps, as outlined in the PR objectives and issue #835. The new methods getPermissions() and setPermissions(List<String> permissions) provide the necessary functionality to manage warp-specific permissions.

These changes will enable the implementation of features such as restricting access to specific warps (e.g., VIP zones) based on player permissions, addressing the core requirement described in the linked issue.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpRepository.java (2)

13-14: 🛠️ Refactor suggestion

Consider using CompletableFuture for consistency with existing methods.

The addPermissions method is currently synchronous, which is inconsistent with other methods in the interface like getWarp and getWarps that use CompletableFuture. To maintain a uniform approach to potentially long-running operations, consider modifying the method signature as follows:

CompletableFuture<Void> addPermissions(String warp, String... permissions);

This change would improve consistency across the interface and potentially enhance scalability for future asynchronous implementations.


15-16: 🛠️ Refactor suggestion

Consider using CompletableFuture and review method naming for consistency.

  1. Similar to the addPermissions method, removePermission is currently synchronous. For consistency with other methods in the interface, consider modifying the method signature to use CompletableFuture:
CompletableFuture<Void> removePermission(String warp, String permission);
  1. There's a slight naming inconsistency between addPermissions (plural) and removePermission (singular). Consider either:
    • Changing this method to removePermissions and allowing multiple permissions to be removed:
      CompletableFuture<Void> removePermissions(String warp, String... permissions);
    • Or changing addPermissions to addPermission for consistency:
      CompletableFuture<Void> addPermission(String warp, String permission);

Choose the option that best fits your use cases and maintains consistency throughout your codebase.

eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/WarpService.java (4)

14-15: LGTM: New method for adding permissions

The addPermissions method is a good addition to the WarpService interface. It allows for flexible addition of one or more permissions to a warp.


16-17: LGTM: New method for removing a permission

The removePermission method is a good addition, complementing the addPermissions method. It allows for the removal of a specific permission from a warp.


20-21: LGTM: New method for checking permission existence

The doesWarpPermissionExist method is a valuable addition to the interface. It provides a way to check if a specific permission exists for a given warp.

Regarding the past suggestion to rename this method, I believe the current name is more descriptive and follows better naming conventions. It clearly indicates that it's checking for the existence of a warp permission.


14-21: Overall: Good implementation of permission-based access to warps

The additions to the WarpService interface align well with the PR objectives and the requirements outlined in issue #835. The new methods provide a complete set of operations for managing warp permissions:

  1. addPermissions: Allows adding one or more permissions to a warp.
  2. removePermission: Enables removal of a specific permission from a warp.
  3. doesWarpPermissionExist: Provides a way to check if a specific permission exists for a warp.

These changes lay a solid foundation for implementing permission-based access to warps, which will allow for better control over warp accessibility, particularly for scenarios involving VIP players or restricted areas.

eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/WarpsConfiguration.java (2)

14-15: LGTM: Class declaration and annotations are appropriate.

The WarpsConfiguration class is correctly annotated with @ConfigurationFile and implements the ReloadableConfig interface, which aligns well with its purpose as a configuration class for managing warp locations.


20-23: LGTM: resource method implementation is appropriate.

The resource method is correctly implemented to return a Resource object pointing to the "warps.yml" file in the specified folder. This aligns well with the purpose of the class and the ReloadableConfig interface.

eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/LocationsConfiguration.java (1)

3-3: LGTM: Import statement uncommented

The import for Position has been correctly uncommented, which aligns with its usage in the class.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpInventory.java (1)

24-26: Reintroduction of necessary imports approved.

The reintroduction of these import statements is correct and necessary. These imports are used throughout the class:

  • Collections is used for creating a singleton list (line 270).
  • List is used in method signatures and as return types (e.g., lines 146-150).
  • Optional is used when finding a warp (line 186).

Their removal would have caused compilation errors, so reintroducing them resolves potential issues without changing the functionality of the class.

eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (1)

5-5: LGTM: Import statement uncommented

The uncommented import for WarpInventoryItem is appropriate, as it aligns with the PR objectives of enhancing the warp management system. This change suggests that WarpInventoryItem is now being used or will be used in the future within this file.

eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (2)

9-9: LGTM: Import changes are appropriate.

The addition of the HelpOpSettings import and the reordering of existing imports improve the organization and support the new HelpOp functionality.

Also applies to: 26-26, 28-28


Line range hint 1-579: Summary: Changes are minimal and well-integrated.

The additions to this file are focused and consistent with the existing structure. The new HelpOp section aligns with the PR objectives and doesn't introduce any apparent issues. The changes maintain the overall integrity of the PluginConfiguration class.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpImpl.java (1)

32-35: Good use of unmodifiable list in the getter

Returning an unmodifiable view of the permissions list ensures that the internal list cannot be modified externally. This is a good practice to maintain encapsulation.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/AddWarpPermissionCommand.java (1)

20-21: Ensure services are not null before use

Although constructor injection should guarantee that warpService and noticeService are not null, adding checks or assertions can prevent potential NullPointerException issues if the injection fails.

Verify that the dependency injection framework properly initializes these services in all contexts.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpPermissionController.java (1)

1-62: Well-structured implementation of warp permission checking

The WarpPermissionController class effectively handles permission checks for warp usage. The code is clean, follows good practices, and utilizes dependency injection appropriately.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpConfigRepository.java (1)

95-96: Consider addressing the previous review comment regarding Optional.ofNullable

The getWarp method is still using Optional.of, which can throw a NullPointerException if this.warpsConfiguration.warps.get(name) returns null. As previously suggested, replacing Optional.of with Optional.ofNullable will safely handle null values.

eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/ENTranslation.java (1)

374-378: New permission messages are clear and consistent

The added Notice messages for warp permission management are clear and align well with the existing messaging style. They effectively communicate permission-related information to the user.

eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/PLTranslation.java (3)

5-5: Import WarpInventoryItem added correctly

The import of WarpInventoryItem is necessary for the items map in the PLWarpInventory class.


20-20: Import HashMap added appropriately

The HashMap import is required for initializing the items map in PLWarpInventory.


377-381: New permission-related notices added

The new Notice fields for warp permissions enhance user feedback when managing warp access permissions.

Comment on lines +17 to +18
@Description({"# Warps configuration", "# These are warp locations, for your own safety, please don't touch it."})
public Map<String, WarpConfigEntry> warps = new HashMap<>();
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

⚠️ Potential issue

Improve encapsulation and naming of the warps field.

While the field is appropriately typed and described, there are several improvements that can be made:

  1. As suggested by CitralFlo, consider renaming the field to warpsLocation for clarity.
  2. Implement better encapsulation as suggested in the previous review:
    • Make the field private and final.
    • Provide controlled access methods.
    • Return an unmodifiable view of the map to prevent external modifications.

Here's a suggested refactor:

@Description({"# Warps configuration", "# These are warp locations, for your own safety, please don't modify directly."})
private final Map<String, WarpConfigEntry> warpsLocation = new HashMap<>();

public Map<String, WarpConfigEntry> getWarpsLocation() {
    return Collections.unmodifiableMap(warpsLocation);
}

public void setWarp(String key, WarpConfigEntry value) {
    warpsLocation.put(key, value);
}

public void removeWarp(String key) {
    warpsLocation.remove(key);
}

This approach maintains functionality while providing better control over how the warps are accessed and modified.

Comment on lines +150 to +154
Notice noPermission();
Notice addPermissions();
Notice removePermission();
Notice permissionDoesNotExist();
Notice noPermissionsProvided();
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Missing implementations for new WarpSection methods

The following classes implementing WarpSection are missing implementations for the new permission-related methods:

  • eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/ENTranslation.java:

    • noPermission()
    • addPermissions()
    • removePermission()
    • permissionDoesNotExist()
    • noPermissionsProvided()
  • eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/PLTranslation.java:

    • noPermission()
    • addPermissions()
    • removePermission()
    • permissionDoesNotExist()
    • noPermissionsProvided()

Please ensure these methods are implemented to maintain consistency across the codebase.

🔗 Analysis chain

Verify implementation of new methods

The new permission-related methods added to the WarpSection interface align well with the PR objectives. However, we should ensure that these methods are properly implemented in all classes that implement this interface.

To verify the implementation, please run the following script:

This script will help identify any classes that implement WarpSection but haven't yet implemented the new methods, ensuring consistency across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all classes implementing the WarpSection interface and check if they implement the new methods

# Find all Java files that likely implement WarpSection
implementers=$(fd -e java | xargs grep -l "implements.*WarpSection")

# Check each file for the new method implementations
for file in $implementers; do
  echo "Checking $file:"
  grep -n "noPermission()" "$file" || echo "  Missing noPermission()"
  grep -n "addPermissions()" "$file" || echo "  Missing addPermissions()"
  grep -n "removePermission()" "$file" || echo "  Missing removePermission()"
  grep -n "permissionDoesNotExist()" "$file" || echo "  Missing permissionDoesNotExist()"
  grep -n "noPermissionsProvided()" "$file" || echo "  Missing noPermissionsProvided()"
  echo
done

Length of output: 2781

Comment on lines +37 to +39
public void setPermissions(List<String> permissions) {
this.permissions = permissions;
}
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

Ensure the permissions list is non-null and make a defensive copy in the setter

To prevent NullPointerException and protect the internal state of the object, consider adding a null check and creating a defensive copy of the permissions list in the setPermissions method.

Apply this diff to enhance the method:

 public void setPermissions(List<String> permissions) {
+    if (permissions == null) {
+        throw new IllegalArgumentException("Permissions list cannot be null");
+    }
-    this.permissions = permissions;
+    this.permissions = new ArrayList<>(permissions);
 }

Don't forget to import java.util.ArrayList if it's not already present.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public void setPermissions(List<String> permissions) {
this.permissions = permissions;
}
public void setPermissions(List<String> permissions) {
if (permissions == null) {
throw new IllegalArgumentException("Permissions list cannot be null");
}
this.permissions = new ArrayList<>(permissions);
}

Comment on lines +16 to +18
@Command(name = "addwarp-permissions")
@Permission("eternalcore.warp.changepermissions")
public class AddWarpPermissionCommand {
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 renaming the command and class for consistency

The command name "addwarp-permissions" could be more consistent with existing command naming conventions in the project. Consider renaming it to "warp add-permission" to align with other warp-related commands. Additionally, renaming the class to WarpAddPermissionCommand would enhance clarity and maintain consistency.

Apply this diff to rename the command and class:

-@Command(name = "addwarp-permissions")
+@Command(name = "warp add-permission")
-public class AddWarpPermissionCommand {
+public class WarpAddPermissionCommand {

Committable suggestion was skipped due to low confidence.

return;
}

this.warpService.addPermissions(warp.getName(), permissions);
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

Handle potential exceptions when adding permissions

The call to this.warpService.addPermissions(warp.getName(), permissions); may throw exceptions if the warp does not exist or if an error occurs in the service layer. To enhance user experience, consider adding exception handling to provide informative feedback.

Apply this diff to add exception handling:

+try {
    this.warpService.addPermissions(warp.getName(), permissions);
+} catch (WarpNotFoundException e) {
+    this.noticeService.create()
+        .player(uniqueId)
+        .placeholder("{WARP}", warp.getName())
+        .notice(translation -> translation.warp().warpNotFound())
+        .send();
+    return;
+} catch (Exception e) {
+    this.noticeService.create()
+        .player(uniqueId)
+        .notice(translation -> translation.warp().unexpectedError())
+        .send();
+    return;
+}

Committable suggestion was skipped due to low confidence.

Comment on lines +110 to +112
if (this.locationsConfiguration.warps.isEmpty()) {
return;
}
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

Handle potential NullPointerException when accessing locationsConfiguration.warps

In the migrateWarps method, if this.locationsConfiguration.warps is null, calling isEmpty() will throw a NullPointerException. Ensure that warps is not null before invoking methods on it.

Add a null check before proceeding:

 if (this.locationsConfiguration.warps == null || this.locationsConfiguration.warps.isEmpty()) {
     return;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (this.locationsConfiguration.warps.isEmpty()) {
return;
}
if (this.locationsConfiguration.warps == null || this.locationsConfiguration.warps.isEmpty()) {
return;
}

Comment on lines +77 to +80
List<String> newPermissions = new ArrayList<>(warpConfigEntry.permissions);
newPermissions.remove(permission);

warpConfigEntry.permissions = newPermissions;
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

Handle null permissions list to avoid NullPointerException

In the removePermission method, if warpConfigEntry.permissions is null, attempting to create a new ArrayList from it will result in a NullPointerException. Ensure the permissions list is initialized before attempting to remove a permission.

Initialize the permissions list if it's null:

 if (warpConfigEntry == null) {
     return;
 }

+if (warpConfigEntry.permissions == null) {
+    warpConfigEntry.permissions = new ArrayList<>();
+}

 List<String> newPermissions = new ArrayList<>(warpConfigEntry.permissions);
 newPermissions.remove(permission);

 warpConfigEntry.permissions = newPermissions;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
List<String> newPermissions = new ArrayList<>(warpConfigEntry.permissions);
newPermissions.remove(permission);
warpConfigEntry.permissions = newPermissions;
if (warpConfigEntry.permissions == null) {
warpConfigEntry.permissions = new ArrayList<>();
}
List<String> newPermissions = new ArrayList<>(warpConfigEntry.permissions);
newPermissions.remove(permission);
warpConfigEntry.permissions = newPermissions;

Comment on lines +61 to +64
List<String> newPermissions = new ArrayList<>(warpConfigEntry.permissions);
newPermissions.addAll(List.of(permissions));

warpConfigEntry.permissions = newPermissions;
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 possible NullPointerException when permissions list is null

In the addPermissions method, if warpConfigEntry.permissions is null, creating a new ArrayList from it will throw a NullPointerException. To prevent this, ensure that the permissions list is initialized before adding new permissions.

Consider initializing the permissions list when it's null:

 if (warpConfigEntry == null) {
     return;
 }

+if (warpConfigEntry.permissions == null) {
+    warpConfigEntry.permissions = new ArrayList<>();
+}

 List<String> newPermissions = new ArrayList<>(warpConfigEntry.permissions);
 newPermissions.addAll(List.of(permissions));

 warpConfigEntry.permissions = newPermissions;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
List<String> newPermissions = new ArrayList<>(warpConfigEntry.permissions);
newPermissions.addAll(List.of(permissions));
warpConfigEntry.permissions = newPermissions;
if (warpConfigEntry.permissions == null) {
warpConfigEntry.permissions = new ArrayList<>();
}
List<String> newPermissions = new ArrayList<>(warpConfigEntry.permissions);
newPermissions.addAll(List.of(permissions));
warpConfigEntry.permissions = newPermissions;

editor.accept(warps);

this.locationsConfiguration.warps = warps;
this.configurationManager.save(this.locationsConfiguration);
warps.forEach((key, value) -> System.out.println(key + ": " + value));
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

Replace System.out.println with a proper logging framework

Using System.out.println for logging is not recommended in production code, as it doesn't provide log levels or configurable output. Consider using a logging framework like SLF4J or Log4j to handle logging more effectively.

Apply this change to use a logger:

+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;

+private static final Logger logger = LoggerFactory.getLogger(WarpConfigRepository.class);

...

-warps.forEach((key, value) -> System.out.println(key + ": " + value));
+warps.forEach((key, value) -> logger.debug("{}: {}", key, value));

Committable suggestion was skipped due to low confidence.

@@ -602,6 +607,7 @@ public static class PLInventorySection implements InventorySection {
@Description({
" ",
"# Ta sekcja odpowiada za interakcję z graczami za pomocą komend",
"# Ta sekcja odpowiada za interakcję z graczami za pomocą komend",
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

Remove duplicate description comment

The description at line 610 is a duplicate of an earlier comment. To maintain code clarity, consider removing the duplicate line.

Apply this diff to remove the duplicate comment:

- "# Ta sekcja odpowiada za interakcję z graczami za pomocą komend",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"# Ta sekcja odpowiada za interakcję z graczami za pomocą komend",

@EternalCodeTeam EternalCodeTeam deleted a comment from coderabbitai bot Oct 8, 2024
@vLuckyyy
Copy link
Member

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Oct 14, 2024

✅ Actions performed

Full review triggered.

Copy link
Contributor

coderabbitai bot commented Oct 14, 2024

Walkthrough

The pull request introduces a comprehensive permission-based access system for warps in the EternalCore plugin. The changes include adding methods to manage warp-specific permissions, creating new configuration classes to store warp data, implementing permission controllers, and updating translation files to support new permission-related messages. The implementation allows administrators to add, remove, and check permissions for individual warps, enabling more granular control over warp access.

Changes

File Change Summary
eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/WarpService.java Added methods for managing warp permissions
eternalcore-core/src/main/java/com/eternalcode/core/configuration/* Updated/Added configuration classes for warp management
eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/* Introduced new classes for warp permission handling and repository management
eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/* Added commands for adding and removing warp permissions
eternalcore-core/src/main/java/com/eternalcode/core/translation/* Updated translation files with new permission-related messages

Assessment against linked issues

Objective Addressed Explanation
Add permission-based warp access
Implement permission node for warp access

Sequence Diagram

sequenceDiagram
    participant Player
    participant WarpPermissionController
    participant WarpService
    
    Player->>WarpPermissionController: Attempt warp teleport
    WarpPermissionController->>WarpService: Check warp permissions
    WarpService-->>WarpPermissionController: Permission status
    alt Has Permission
        WarpPermissionController->>Player: Allow teleportation
    else No Permission
        WarpPermissionController->>Player: Deny teleportation, show message
    end
Loading

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 14

🧹 Outside diff range and nitpick comments (16)
eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/Warp.java (1)

13-14: LGTM: New method getPermissions() is well-defined.

The getPermissions() method is a good addition for retrieving warp-specific permissions.

Consider adding Javadoc to describe the method's purpose and return value, e.g.:

/**
 * Retrieves the list of permissions associated with this warp.
 *
 * @return A list of permission strings required to access this warp.
 */
List<String> getPermissions();
eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpConfigEntry.java (1)

8-9: LGTM! Consider adding class-level documentation.

The class structure and naming are appropriate. The @Contextual annotation suggests this class is used in a specific context, possibly for serialization/deserialization.

Consider adding JavaDoc comments to explain the purpose of this class and its usage within the warp system.

eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/WarpsConfiguration.java (1)

1-25: Overall, the WarpsConfiguration class is well-structured with room for improvement.

The class correctly implements the ReloadableConfig interface and uses appropriate annotations. The resource method is correctly implemented for loading the configuration file.

The main area for improvement is the encapsulation of the warps field. Consider implementing the suggested refactoring to enhance the robustness and safety of the class.

Additionally, as suggested in a previous review, consider adding utility methods for common operations and validation logic to further improve the usability and reliability of this configuration class.

eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (1)

Line range hint 326-340: LGTM: New HelpOp section added

The new HelpOp section is well-structured and correctly implements the HelpOpSettings interface. It provides a configurable delay for the /helpop command, which aligns with the PR objectives.

Consider adding a brief comment explaining the purpose of the helpOpDelay setting to improve clarity for users configuring the plugin.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/AddWarpPermissionCommand.java (1)

30-48: Add unit tests for the addPermission method

To ensure the AddWarpPermissionCommand functions as expected under various scenarios, consider adding unit tests. These tests could cover:

  • Providing no permissions (expecting a notice indicating no permissions were provided)
  • Providing null or empty permission strings
  • Adding permissions successfully to an existing warp
  • Handling the case when the warp does not exist
eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/RemoveWarpPermissionCommand.java (2)

31-31: Simplify by using player.getUniqueId() directly

The uniqueId variable is only used once in the method. You can simplify the code by using player.getUniqueId() directly in the notice creation.

Apply this diff to simplify the code:

- UUID uniqueId = player.getUniqueId();
...
-     .player(uniqueId)
+     .player(player.getUniqueId())

33-40: Handle case sensitivity in permission checks

When checking if the permission exists in the warp's permissions, consider normalizing the permission strings to avoid case sensitivity issues.

Modify the check to compare permissions in a case-insensitive manner:

- if (!warp.getPermissions().contains(permission)) {
+ if (!warp.getPermissions().stream()
+       .anyMatch(perm -> perm.equalsIgnoreCase(permission))) {

This ensures that permissions like "MyPermission" and "mypermission" are considered equal.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpPermissionController.java (1)

34-34: Add access modifier to event handler method

For clarity and consistency, consider explicitly specifying the access modifier for the onWarpPreTeleportation method. Event handler methods are often declared as public.

Apply this diff:

-    void onWarpPreTeleportation(PreWarpTeleportEvent event) {
+    public void onWarpPreTeleportation(PreWarpTeleportEvent event) {
eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/SetWarpCommand.java (4)

Line range hint 28-31: Avoid Passing Redundant Parameters

Since the uniqueId can be obtained from the Player object within the createWarp method, consider removing the uniqueId parameter to streamline the code.

Apply this diff to simplify the method call:

 void add(@Context Player player, @Arg String warpName) {
-    UUID uniqueId = player.getUniqueId();
-
-    this.createWarp(player, warpName, uniqueId);
+    this.createWarp(player, warpName);
 }

-private void createWarp(Player player, String warp, UUID uniqueId) {
+private void createWarp(Player player, String warp) {
     UUID uniqueId = player.getUniqueId();
     // existing code...
 }

Line range hint 48-60: Potential Off-by-One Error in Warp Limit Check

The condition <= MAX_WARPS_IN_GUI may lead to exceeding the maximum number of warps allowed. When the number of warps equals MAX_WARPS_IN_GUI, adding another warp will exceed the limit.

To fix the off-by-one error, modify the condition as follows:

 if (this.config.warp.autoAddNewWarps) {
-    if (this.warpService.getNamesOfWarps().size() <= MAX_WARPS_IN_GUI) {
+    if (this.warpService.getNamesOfWarps().size() < MAX_WARPS_IN_GUI) {
         this.warpInventory.addWarp(createdWarp);
         // existing code...

Line range hint 36-46: Enhance Nested Conditional Structure for Readability

Consider flattening the nested if statements to improve code readability.

Refactor the code as follows:

 if (this.config.warp.autoAddNewWarps && this.warpService.getNamesOfWarps().size() < MAX_WARPS_IN_GUI) {
     this.warpInventory.addWarp(createdWarp);
     this.noticeService.create()
         .player(uniqueId)
         .notice(translation -> translation.warp().itemAdded())
         .send();
 } else if (this.config.warp.autoAddNewWarps) {
     this.noticeService.create()
         .player(uniqueId)
         .notice(translation -> translation.warp().itemLimit())
         .placeholder("{LIMIT}", String.valueOf(MAX_WARPS_IN_GUI))
         .send();
 }

Line range hint 50-57: Ensure Consistent Player Notification

When the warp limit is reached, consider notifying the player even if autoAddNewWarps is disabled. This provides feedback on why the warp was not added to the inventory.

Adjust the code to send a notice regardless of the autoAddNewWarps setting:

 if (this.config.warp.autoAddNewWarps && this.warpService.getNamesOfWarps().size() < MAX_WARPS_IN_GUI) {
     this.warpInventory.addWarp(createdWarp);
     this.noticeService.create()
         .player(uniqueId)
         .notice(translation -> translation.warp().itemAdded())
         .send();
 } else {
     this.noticeService.create()
         .player(uniqueId)
         .notice(translation -> translation.warp().itemLimit())
         .placeholder("{LIMIT}", String.valueOf(MAX_WARPS_IN_GUI))
         .send();
 }
eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/ENTranslation.java (4)

374-374: Ensure consistent message formatting: Remove parentheses and apply color to {WARP}.

In the message on line 374, the warp name {WARP} is enclosed in parentheses and lacks a color code, which is inconsistent with other messages in the codebase. For consistency, remove the parentheses and apply the <red> color code to {WARP}.

-public Notice noPermission = Notice.chat("<red>✘ <dark_red>You don't have permission to use this warp ({WARP})!");
+public Notice noPermission = Notice.chat("<red>✘ <dark_red>You don't have permission to use this warp <red>{WARP}<dark_red>!");

375-375: Consider renaming addPermissions to addPermission for consistency.

The field name addPermissions on line 375 is plural, whereas similar field names in the class are singular (e.g., create, remove). For consistency, consider renaming it to addPermission. Additionally, update the message to use the singular form "Added permission".

-public Notice addPermissions = Notice.chat("<green>► <white>Added permissions to warp <green>{WARP}<white>!");
+public Notice addPermission = Notice.chat("<green>► <white>Added permission to warp <green>{WARP}<white>!");

376-376: Remove unnecessary closing </red> tag in the message.

In the message on line 376, there's an unnecessary closing </red> tag after {PERMISSION}. This is inconsistent with other messages and may not be needed. Consider removing it for consistency.

-public Notice removePermission = Notice.chat("<red>► <white>Removed permission <red>{PERMISSION}</red> <white>from warp <red>{WARP}<white>!");
+public Notice removePermission = Notice.chat("<red>► <white>Removed permission <red>{PERMISSION} <white>from warp <red>{WARP}<white>!");

378-378: Add closing </red> tag after {PERMISSION} for correct color formatting.

In the message on line 378, the <red> color code is applied to {PERMISSION} but not closed, which may lead to formatting issues in the rest of the message. Consider adding a closing </red> tag after {PERMISSION} to ensure proper color formatting.

-public Notice permissionDoesNotExist = Notice.chat("<red>✘ <dark_red>Permission <red>{PERMISSION} <dark_red>doesn't exist!");
+public Notice permissionDoesNotExist = Notice.chat("<red>✘ <dark_red>Permission <red>{PERMISSION}</red> <dark_red>doesn't exist!");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 38ba610 and f1a6ada.

📒 Files selected for processing (19)
  • eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/Warp.java (1 hunks)
  • eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/WarpService.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/configuration/ConfigurationManager.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/LocationsConfiguration.java (2 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (2 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/WarpsConfiguration.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpConfigEntry.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpConfigRepository.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpImpl.java (2 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpInventory.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpPermissionController.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpRepository.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpServiceImpl.java (3 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/AddWarpPermissionCommand.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/RemoveWarpPermissionCommand.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/SetWarpCommand.java (1 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (2 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 (3 hunks)
🧰 Additional context used
🔇 Additional comments (41)
eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/Warp.java (1)

5-6: LGTM: Import statement addition is appropriate.

The addition of import java.util.List; is necessary and correct for the new methods using List<String>.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpRepository.java (3)

13-16: LGTM with minor suggestions.

The new methods addPermissions and removePermission are valuable additions to the WarpRepository interface, enhancing its functionality for managing warp permissions. The implementation looks good, but consider the suggestions about using CompletableFuture for consistency with other methods in the interface.


13-14: 🛠️ Refactor suggestion

Consider using CompletableFuture for consistency with other methods.

The addPermissions method is a good addition for managing warp permissions. However, to maintain consistency with other methods in the interface (e.g., getWarp, getWarps), consider using CompletableFuture:

CompletableFuture<Void> addPermissions(String warp, String... permissions);

This change would ensure a uniform approach to potentially long-running operations across the interface and improve scalability for future asynchronous implementations.


15-16: 🛠️ Refactor suggestion

Consider using CompletableFuture for consistency with other methods.

The removePermission method is a valuable addition for managing warp permissions. However, to maintain consistency with other methods in the interface (e.g., getWarp, getWarps), consider using CompletableFuture:

CompletableFuture<Void> removePermission(String warp, String permission);

This change would ensure a uniform approach to potentially long-running operations across the interface and improve scalability for future asynchronous implementations.

eternalcore-api/src/main/java/com/eternalcode/core/feature/warp/WarpService.java (4)

14-14: LGTM: Well-designed method for adding permissions

The addPermissions method is a good addition to the WarpService interface. It provides a clear and flexible way to add multiple permissions to a warp in a single call.


16-16: LGTM: Appropriate method for removing a single permission

The removePermission method complements the addPermissions method well, allowing for granular control over warp permissions.


20-20: LGTM: Useful method for checking warp permissions

The doesWarpPermissionExist method is a valuable addition, allowing for easy verification of warp permissions.

Regarding the past review comment:

CitralFlo: ```suggestion
    boolean doesWarpPermissionExist(String warp, String permission);
This suggestion has already been implemented in the current version, so no changes are needed.

---

`14-21`: **Summary: Excellent implementation of permission-based access for warps**

The additions to the `WarpService` interface effectively address the PR objectives (GH-835) by implementing permission-based access for warps. The new methods (`addPermissions`, `removePermission`, and `doesWarpPermissionExist`) provide a comprehensive API for managing warp permissions, allowing server administrators to control access to specific warps as requested.

These changes align perfectly with the requirement to introduce functionality like `eternalcore.warp.vipzone` for restricting access to certain warps. The interface remains cohesive and focused on warp-related operations while extending its capabilities to handle permissions.

</blockquote></details>
<details>
<summary>eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/WarpsConfiguration.java (4)</summary><blockquote>

`1-13`: **LGTM: Package declaration and imports are correct.**

The package declaration and imports are appropriate for the functionality of the class. All necessary classes are imported, and there are no unused imports.

---

`14-15`: **LGTM: Class declaration and annotations are appropriate.**

The `WarpsConfiguration` class is correctly annotated with `@ConfigurationFile` and implements the `ReloadableConfig` interface. This setup is suitable for a configuration class that can be dynamically reloaded.

---

`20-23`: **LGTM: Resource method implementation is correct.**

The `resource` method is correctly implemented to return a `Resource` object pointing to the "warps.yml" file in the given folder. This implementation is appropriate for loading a YAML configuration file for the warps.

---

`17-18`: _:hammer_and_wrench: Refactor suggestion_

**Improve encapsulation and naming of the `warps` field.**

While the field is appropriately typed and described, there are several improvements that can be made:

1. Consider renaming the field to `warpsLocation` for clarity, as suggested in a previous review.
2. Implement better encapsulation:
   - Make the field private and final.
   - Provide controlled access methods.
   - Return an unmodifiable view of the map to prevent external modifications.

Here's a suggested refactor:

```java
@Description({"# Warps configuration", "# These are warp locations, for your own safety, please don't modify directly."})
private final Map<String, WarpConfigEntry> warpsLocation = new HashMap<>();

public Map<String, WarpConfigEntry> getWarpsLocation() {
    return Collections.unmodifiableMap(warpsLocation);
}

public void setWarp(String key, WarpConfigEntry value) {
    warpsLocation.put(key, value);
}

public void removeWarp(String key) {
    warpsLocation.remove(key);
}

This approach maintains functionality while providing better control over how the warps are accessed and modified.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpImpl.java (5)

7-8: LGTM: New imports are correctly added.

The new imports for Collections and List are necessary for the permission management functionality and are correctly placed.


14-14: LGTM: New permissions field is correctly declared.

The permissions field is appropriately declared as a private List<String>, which is suitable for storing permission strings and follows good encapsulation practices.


32-35: LGTM: getPermissions() method is correctly implemented.

The getPermissions() method appropriately returns an unmodifiable view of the permissions list using Collections.unmodifiableList(). This prevents external modifications to the internal list, maintaining encapsulation.


16-19: 🛠️ Refactor suggestion

Implement defensive copying for the permissions list.

While the constructor correctly initializes the new permissions field, it's advisable to create a defensive copy of the input list to prevent external modifications. This ensures that the internal state of the WarpImpl object remains consistent.

Consider applying this change:

     WarpImpl(String name, Position position, List<String> permissions) {
         this.name = name;
         this.position = position;
-        this.permissions = permissions;
+        this.permissions = new ArrayList<>(permissions);
     }

Don't forget to add the import for java.util.ArrayList if it's not already present.


37-39: ⚠️ Potential issue

Enhance setPermissions() method with null check and defensive copying.

To prevent NullPointerException and protect the internal state of the object, consider adding a null check and creating a defensive copy of the permissions list in the setPermissions method.

Apply this diff to enhance the method:

 public void setPermissions(List<String> permissions) {
+    if (permissions == null) {
+        throw new IllegalArgumentException("Permissions list cannot be null");
+    }
-    this.permissions = permissions;
+    this.permissions = new ArrayList<>(permissions);
 }

Don't forget to import java.util.ArrayList if it's not already present.

eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/LocationsConfiguration.java (1)

3-3: LGTM: Import statement uncommented

The uncommented import for Position is correct and necessary for the usage of the Position class in this file.

eternalcore-core/src/main/java/com/eternalcode/core/configuration/ConfigurationManager.java (3)

20-23: Improved import organization.

The reordering of import statements enhances code readability by grouping Java standard library imports at the end. This change follows common coding conventions and does not affect the functionality of the class.


Line range hint 25-95: No functional changes in ConfigurationManager.

I've verified that no changes have been made to the class structure, fields, constructor, or methods. The functionality of the ConfigurationManager remains intact, which is appropriate given that this PR focuses on adding permission-based access to warps.


Line range hint 1-95: LGTM: Minor improvements with no functional changes.

The changes in this file are limited to reorganizing import statements, which improves code readability. There are no functional changes to the ConfigurationManager class, which is appropriate given the PR's focus on adding permission-based access to warps. The file is in good shape and doesn't require any further modifications.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpInventory.java (4)

24-26: LGTM: Reintroduction of necessary imports

The reintroduction of these import statements is correct and necessary. These classes (Collections, List, and Optional) are used throughout the file, and their import is required for the code to compile and function properly.


24-26: Impact Analysis: No functional changes

The reintroduction of these import statements doesn't alter the functionality of the WarpInventory class. This change is a necessary bug fix that allows the code to compile and function as intended. No further modifications to the codebase should be required as a result of these changes.


24-26: Overall Assessment: Minor but necessary changes

The reintroduction of these import statements is a minor but necessary change. It corrects what appears to be an oversight in a previous commit, ensuring that the WarpInventory class can compile and function correctly. While these changes don't directly implement the permission-based access mentioned in the PR objectives, they don't hinder that implementation either. The core functionality of the WarpInventory class remains unchanged.

To fully assess if the PR meets its objectives, it would be beneficial to review other changed files, particularly those that might implement the permission-based access for warps.


24-26: Note: Changes don't directly address PR objectives

While these import statements are necessary for the proper functioning of the WarpInventory class, they don't directly contribute to the stated PR objective of implementing permission-based access for warps. It's likely that the main implementation of this feature is in other files not shown in this review.

To ensure the PR objectives are met, please run the following script to check for permission-related changes:

✅ Verification successful

Changes do not affect PR objectives

The modifications in WarpInventory.java consist solely of import statements that do not directly contribute to implementing permission-based access for warps. The permission-related changes are likely handled in other parts of the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for permission-related changes in the codebase

# Test: Look for new permission-related code
rg --type java -e "permission" -e "eternalcore\.warp\." --stats

Length of output: 33227


Script:

#!/bin/bash
# Description: Check for permission-related changes in WarpInventory.java

rg --type java -e "permission" eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpInventory.java

Length of output: 114

eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (2)

Line range hint 1-154: Summary of changes

The changes to the Translation interface, specifically in the WarpSection, successfully implement the groundwork for permission-based access to warps. The reactivation of the WarpInventoryItem import and the addition of five new permission-related methods align well with the PR objectives.

These changes enhance the warp system's functionality while maintaining consistency with the existing interface structure. The provided verification scripts will help ensure that these changes are properly implemented across the codebase.

Overall, this update effectively addresses the requirements outlined in issue #835, providing server administrators with the tools to control access to specific warps.


150-154: Approve new permission-related methods with minor suggestion

The addition of these five new methods (noPermission(), addPermissions(), removePermission(), permissionDoesNotExist(), and noPermissionsProvided()) to the WarpSection interface aligns well with the PR objectives of implementing permission-based access for warps. These methods cover various scenarios related to permission management and maintain consistency with the existing interface structure.

Consider renaming addPermissions() to addPermission() for consistency with removePermission(), unless there's a specific reason for the plural form.

As mentioned in a previous review comment, we need to ensure that these new methods are implemented in all classes that implement the WarpSection interface. Let's verify this:

#!/bin/bash
# Description: Find all classes implementing WarpSection and check for new method implementations

# Find all Java files that likely implement WarpSection
implementers=$(fd -e java | xargs grep -l "implements.*WarpSection")

# Check each file for the new method implementations
for file in $implementers; do
  echo "Checking $file:"
  grep -n "noPermission()" "$file" || echo "  Missing noPermission()"
  grep -n "addPermissions()" "$file" || echo "  Missing addPermissions()"
  grep -n "removePermission()" "$file" || echo "  Missing removePermission()"
  grep -n "permissionDoesNotExist()" "$file" || echo "  Missing permissionDoesNotExist()"
  grep -n "noPermissionsProvided()" "$file" || echo "  Missing noPermissionsProvided()"
  echo
done

This script will help identify any classes that implement WarpSection but haven't yet implemented the new methods, ensuring consistency across the codebase.

eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (1)

9-9: LGTM: Import added for new HelpOp feature

The import for HelpOpSettings is correctly added and aligns with the new HelpOp feature being implemented.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/RemoveWarpPermissionCommand.java (1)

42-42: Verify successful permission removal

After calling this.warpService.removePermission(warp.getName(), permission);, consider verifying that the permission was actually removed. This helps ensure robustness in case of unexpected issues during the removal process.

If removePermission returns a boolean or throws an exception, handle these cases appropriately. For example:

boolean removed = this.warpService.removePermission(warp.getName(), permission);
if (!removed) {
    // Notify the player that the permission could not be removed
    return;
}
eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/command/SetWarpCommand.java (2)

17-17: Import Statement Properly Placed

The import statement for java.util.UUID has been correctly added and positioned for consistency.


Line range hint 23-25: Add Null Check for Dependencies

Ensure that injected dependencies are not null to prevent potential NullPointerException.

Run the following script to check for @Inject annotations without corresponding null checks:

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpServiceImpl.java (5)

40-43: Initialization of Warp with Empty Permissions List

Initializing the Warp object with an empty permissions list in the createWarp method ensures that all warps start with a consistent permissions state, which is a good practice.


59-65: Handle Potential Null permissions Parameter

If the permissions parameter is null, calling List.of(permissions) will throw a NullPointerException. Consider adding a null check for the permissions parameter to prevent potential runtime errors.


67-68: Prevent Adding Duplicate Permissions

Adding permissions without checking for existing ones may introduce duplicates. To maintain a clean permissions list, check if each permission already exists before adding it.


74-81: Ensure Thread Safety When Modifying warpMap

Modifying the shared warpMap without synchronization may lead to concurrency issues. Consider using a thread-safe map implementation or synchronizing access to the warpMap.


95-103: Correct Typo in Method Name

The method name doestWarpPermissionExist contains a typo. It should be doesWarpPermissionExist. Correcting this will improve code readability and prevent confusion.

eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpConfigRepository.java (2)

27-36: Constructor Enhancement and Data Migration

The constructor has been updated to include WarpsConfiguration, and the call to this.migrateWarps(); ensures that existing warp data is properly migrated to the new configuration structure. This proactive approach maintains data integrity during the transition.


41-45: Updating addWarp to Handle Permissions

The addWarp method now creates a WarpConfigEntry that includes both the position and permissions of the warp. This enhancement aligns with the new permission-based access system and ensures that warp permissions are stored correctly.

eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/PLTranslation.java (3)

5-5: Import statement is appropriate

The import of WarpInventoryItem is necessary for the code changes and is correctly included.


20-20: Import of HashMap is required

The import of java.util.HashMap is necessary for initializing the items map in the WarpInventory class.


610-610: Remove duplicate description comment

The comment at line 610 is a duplicate of an earlier description. To maintain clarity, please remove the duplicate comment.

Comment on lines +15 to +16
void setPermissions(List<String> permissions);

Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Thread-Safety Issue: Concurrent Access to Warp Objects

The setPermissions(List<String> permissions) method allows modifying permissions, which may be accessed concurrently by multiple threads. However, the current implementations of the Warp interface do not employ synchronization mechanisms, posing potential thread-safety risks.

Consider implementing synchronization or using thread-safe data structures to manage permissions safely and prevent race conditions.

🔗 Analysis chain

LGTM: New method setPermissions() is well-defined, but consider thread-safety.

The setPermissions(List<String> permissions) method is a good addition for managing warp-specific permissions.

Consider adding Javadoc to describe the method's purpose and parameters, e.g.:

/**
 * Sets the list of permissions required to access this warp.
 *
 * @param permissions A list of permission strings to be associated with this warp.
 */
void setPermissions(List<String> permissions);

Additionally, consider the thread-safety implications of this setter method. If this interface is implemented by mutable objects that might be accessed concurrently, you may want to ensure thread-safe operations or document any synchronization requirements.

To verify the usage and potential concurrency issues, you can run the following script:

This script will help identify potential concurrency issues and how Warp objects are being used throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential concurrency issues with Warp implementations

# Search for classes implementing the Warp interface
echo "Classes implementing Warp interface:"
rg --type java "class\s+\w+\s+implements\s+.*Warp"

# Search for synchronized methods or blocks in Warp implementations
echo "\nSynchronized methods or blocks in Warp implementations:"
rg --type java "class\s+\w+\s+implements\s+.*Warp" -A 20 | rg "synchronized"

# Search for concurrent access to Warp objects
echo "\nPotential concurrent access to Warp objects:"
rg --type java "getWarp|setWarp|createWarp|deleteWarp"

Length of output: 4222

Comment on lines +10 to +11
public Position position;
public List<String> permissions;
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

⚠️ Potential issue

Enhance encapsulation and optimize data structures.

The current implementation with public fields violates encapsulation principles and might lead to inconsistent object state. Consider the following improvements:

  1. Make the fields private and provide getter methods (and setter methods if necessary).
  2. Use a Set<String> instead of List<String> for permissions to prevent duplicates and improve lookup efficiency.
  3. Consider making the fields final to ensure immutability.

Example refactoring:

private final Position position;
private final Set<String> permissions;

public Position getPosition() {
    return position;
}

public Set<String> getPermissions() {
    return Collections.unmodifiableSet(permissions);
}

This refactoring improves encapsulation, prevents duplicate permissions, and ensures immutability of the object state.

Comment on lines +13 to +19
public WarpConfigEntry() {
}

public WarpConfigEntry(Position position, List<String> permissions) {
this.position = position;
this.permissions = permissions;
}
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

⚠️ Potential issue

Improve constructor implementation and consider removing the default constructor.

The current constructor implementation has potential issues:

  1. The default constructor allows the creation of objects with null fields, which might lead to NullPointerExceptions.
  2. The parameterized constructor doesn't perform any validation or defensive copying.

Consider the following improvements:

  1. Remove the default constructor if it's not necessary for serialization/deserialization.
  2. In the parameterized constructor, add null checks and create defensive copies of mutable objects.

Example refactoring:

public WarpConfigEntry(Position position, Set<String> permissions) {
    this.position = Objects.requireNonNull(position, "Position cannot be null");
    this.permissions = Collections.unmodifiableSet(new HashSet<>(
        Objects.requireNonNull(permissions, "Permissions cannot be null")
    ));
}

This refactoring ensures that the object is always in a valid state and prevents external modification of the permissions set.

Comment on lines +1 to +20
package com.eternalcode.core.feature.warp;

import com.eternalcode.commons.bukkit.position.Position;
import net.dzikoysk.cdn.entity.Contextual;

import java.util.List;

@Contextual
public class WarpConfigEntry {
public Position position;
public List<String> permissions;

public WarpConfigEntry() {
}

public WarpConfigEntry(Position position, List<String> permissions) {
this.position = position;
this.permissions = permissions;
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Clarify the responsibilities and naming conventions of Warp-related classes.

The current structure shows potential naming inconsistencies and unclear relationships between WarpConfigEntry, WarpImpl, and the Warp interface. To improve clarity and maintainability, please consider the following:

  • Review and possibly rename the Warp interface to better reflect its purpose, avoiding confusion with repository patterns.
  • Clarify the role of WarpConfigEntry in relation to WarpImpl to ensure a clear separation of concerns.
  • Assess the potential for consolidating classes where responsibilities overlap to reduce complexity and enhance cohesion.

This will help in streamlining the warp system's architecture and making the design decisions more transparent.

🔗 Analysis chain

Clarify the purpose and relationship of WarpConfigEntry in the warp system.

The purpose and usage of WarpConfigEntry in the broader context of the warp system are not immediately clear. Please provide clarification on the following points:

  1. What is the specific role of WarpConfigEntry in the warp system?
  2. How does this class relate to other classes like WarpImpl?
  3. Is there a potential for consolidation with other classes to reduce duplication and improve cohesion?

This information will help in understanding the design decisions and potentially identifying opportunities for system-wide improvements.

To help clarify the relationship between WarpConfigEntry and other parts of the warp system, please run the following script:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find usages and related classes of WarpConfigEntry

echo "Searching for WarpConfigEntry usages:"
rg --type java -n "WarpConfigEntry"

echo "\nSearching for other Warp-related classes:"
rg --type java -l "class.*Warp"

echo "\nSearching for WarpImpl class definition:"
rg --type java -n "class WarpImpl"

Length of output: 4339


Script:

#!/bin/bash
# Description: Find interactions between WarpImpl and WarpConfigEntry

echo "Searching for WarpImpl usages of WarpConfigEntry:"
rg --type java "WarpConfigEntry" eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpImpl.java

echo "\nSearching for methods in WarpConfigRepository that use WarpConfigEntry:"
rg --type java "WarpConfigEntry" eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/WarpConfigRepository.java

Length of output: 1071


Script:

#!/bin/bash
# Description: Retrieve the definition of the Warp interface

echo "Fetching Warp interface definition:"
rg --type java "interface Warp" eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/

echo "\nFetching all implementations of the Warp interface:"
rg --type java "implements Warp" eternalcore-core/src/main/java/com/eternalcode/core/feature/warp/

echo "\nFinding usages of WarpImpl in the codebase:"
rg --type java "WarpImpl" 

Length of output: 1883

Comment on lines +24 to 26
@Description("# Warps now are stored in warps.yml. This is deprecated.")
@Deprecated
public Map<String, Position> warps = new HashMap<>();
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Action Required: Deprecated warps Field Still In Use

The deprecated warps field is still being accessed in the following locations:

  • WarpConfigRepository.java:
    • Multiple direct accesses to this.warpsConfiguration.warps.
  • WarpPermissionController.java
  • WarpInventory.java
  • SetWarpCommand.java
  • DelWarpCommand.java
  • WarpTeleportService.java
  • WarpRepository.java
  • WarpServiceImpl.java
  • WarpService.java
  • WarpTeleportEvent.java
  • PreWarpTeleportEvent.java

Please update these usages to utilize the new warps.yml storage system to fully deprecate the warps field and prevent potential issues.

🔗 Analysis chain

Approved: Warps field deprecated and description updated

The changes to the warps field are appropriate:

  1. The updated description clearly informs users about the new storage location for warps.
  2. The @Deprecated annotation correctly marks this field as no longer preferred.

These modifications align with the PR objectives of implementing permission-based access to warps.

However, please ensure the following:

  1. Address the usage of this deprecated field in other parts of the codebase, as mentioned in the previous review comments.
  2. Consider adding a deprecation warning message to guide users on migrating to the new warp storage system.

To verify the current usage of the deprecated warps field, run the following script:

Please review the results and update the affected code as necessary to use the new warps.yml storage method.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find usages of the deprecated warps field

# Search for direct accesses to the warps field
echo "Searching for direct accesses to the warps field:"
rg --type java "\.warps\b" --glob '!LocationsConfiguration.java'

# Search for method calls that might be using the warps field
echo "Searching for potential method calls using the warps field:"
rg --type java "\b(get|set|add|remove|clear)Warp(s)?\b" --glob '!LocationsConfiguration.java'

Length of output: 4910

Comment on lines +25 to +31
private final PluginConfiguration pluginConfiguration;

@Inject
public WarpPermissionController(NoticeService noticeService, PluginConfiguration pluginConfiguration) {
this.noticeService = noticeService;
this.pluginConfiguration = pluginConfiguration;
}
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

Remove unused PluginConfiguration dependency

The pluginConfiguration field and its corresponding constructor parameter are declared but not used within the class. Removing unused fields helps keep the codebase clean and maintainable.

Apply this diff to remove the unused field and constructor parameter:

     private final NoticeService noticeService;
-    private final PluginConfiguration pluginConfiguration;

     @Inject
-    public WarpPermissionController(NoticeService noticeService, PluginConfiguration pluginConfiguration) {
+    public WarpPermissionController(NoticeService noticeService) {
         this.noticeService = noticeService;
-        this.pluginConfiguration = pluginConfiguration;
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private final PluginConfiguration pluginConfiguration;
@Inject
public WarpPermissionController(NoticeService noticeService, PluginConfiguration pluginConfiguration) {
this.noticeService = noticeService;
this.pluginConfiguration = pluginConfiguration;
}
private final NoticeService noticeService;
@Inject
public WarpPermissionController(NoticeService noticeService) {
this.noticeService = noticeService;
}

Comment on lines +55 to +59
this.noticeService.create()
.player(uniqueId)
.placeholder("{WARP}", warp.getName())
.notice(translation -> translation.warp().noPermission())
.send();
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

Enhance player feedback by including required permissions

Currently, the player is notified that they lack permission to use the warp but does not know which permission is needed. Providing the specific permissions required can help players understand what is needed to access the warp.

Consider modifying the notice to include the missing permissions:

 this.noticeService.create()
     .player(uniqueId)
     .placeholder("{WARP}", warp.getName())
+    .placeholder("{PERMISSIONS}", String.join(", ", permissions))
     .notice(translation -> translation.warp().noPermission())
     .send();

Ensure that the {PERMISSIONS} placeholder is appropriately handled in the noPermission() message template.

Committable suggestion was skipped due to low confidence.

Comment on lines +59 to +87
@Override
public void addPermissions(String warpName, String... permissions) {
Warp warp = this.warpMap.get(warpName);

if (warp == null) {
return;
}

List<String> updatedPermissions = new ArrayList<>(warp.getPermissions());
updatedPermissions.addAll(List.of(permissions));

warp.setPermissions(updatedPermissions);
this.warpRepository.addPermissions(warpName, permissions);
}

@Override
public void removePermission(String warpName, String permission) {
Warp warp = this.warpMap.get(warpName);

if (warp == null) {
return;
}

List<String> updatedPermissions = new ArrayList<>(warp.getPermissions());
updatedPermissions.remove(permission);

warp.setPermissions(updatedPermissions);
this.warpRepository.removePermission(warpName, permission);
}
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

Refactor to Eliminate Code Duplication in Permission Methods

The addPermissions and removePermission methods share similar code for retrieving the warp, checking for null, and updating permissions. Refactoring this common logic into a private helper method can improve maintainability and reduce code duplication.

Consider extracting the shared code into a method like modifyPermissions:

private void modifyPermissions(String warpName, Consumer<List<String>> modifier) {
    Warp warp = this.warpMap.get(warpName);

    if (warp == null) {
        return;
    }

    List<String> updatedPermissions = new ArrayList<>(warp.getPermissions());
    modifier.accept(updatedPermissions);

    warp.setPermissions(updatedPermissions);
}

Then update the addPermissions and removePermission methods:

public void addPermissions(String warpName, String... permissions) {
-    Warp warp = this.warpMap.get(warpName);
-
-    if (warp == null) {
-        return;
-    }
-
-    List<String> updatedPermissions = new ArrayList<>(warp.getPermissions());
-    updatedPermissions.addAll(List.of(permissions));
-
-    warp.setPermissions(updatedPermissions);
+    modifyPermissions(warpName, perms -> perms.addAll(List.of(permissions)));
    this.warpRepository.addPermissions(warpName, permissions);
}

public void removePermission(String warpName, String permission) {
-    Warp warp = this.warpMap.get(warpName);
-
-    if (warp == null) {
-        return;
-    }
-
-    List<String> updatedPermissions = new ArrayList<>(warp.getPermissions());
-    updatedPermissions.remove(permission);
-
-    warp.setPermissions(updatedPermissions);
+    modifyPermissions(warpName, perms -> perms.remove(permission));
    this.warpRepository.removePermission(warpName, permission);
}

Comment on lines +53 to +66
@Override
public void addPermissions(String warp, String... permissions) {
this.edit(warps -> {
WarpConfigEntry warpConfigEntry = warps.get(warp);
if (warpConfigEntry == null) {
return;
}

List<String> newPermissions = new ArrayList<>(warpConfigEntry.permissions);
newPermissions.addAll(List.of(permissions));

warpConfigEntry.permissions = newPermissions;
});
}
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

Refactor Suggestion: Reduce Code Duplication in Permission Methods

The addPermissions and removePermission methods have similar logic for retrieving the WarpConfigEntry, checking for null, and updating the permissions list. To improve maintainability and adhere to the DRY (Don't Repeat Yourself) principle, consider refactoring the common code into a private method.

You could implement a private method that handles permission updates, parameterized by the action to perform (add or remove):

private void updatePermissions(String warp, Consumer<List<String>> permissionUpdater) {
    this.edit(warps -> {
        WarpConfigEntry warpConfigEntry = warps.get(warp);
        if (warpConfigEntry == null) {
            return;
        }

        List<String> newPermissions = new ArrayList<>(warpConfigEntry.permissions);
        permissionUpdater.accept(newPermissions);
        warpConfigEntry.permissions = newPermissions;
    });
}

Then, refactor addPermissions and removePermission to use this method:

@Override
public void addPermissions(String warp, String... permissions) {
    this.updatePermissions(warp, perms -> perms.addAll(List.of(permissions)));
}

@Override
public void removePermission(String warp, String permission) {
    this.updatePermissions(warp, perms -> perms.remove(permission));
}

Also applies to: 68-82

@@ -373,6 +374,11 @@ public static class PLWarpSection implements WarpSection {
public Notice itemAdded = Notice.chat("<green>► <white>Dodano warp do GUI!");
public Notice noWarps = Notice.chat("<red>✘ <dark_red>Błąd: <red>Nie ma dostępnych warpów!");
public Notice itemLimit = Notice.chat("<red>✘ <dark_red>Błąd: <red>Osiągnąłeś limit warpów w GUI! Limit to: {LIMIT}!");
public Notice noPermission = Notice.chat("<red>✘ <dark_red>Błąd: <red>Nie masz uprawnień do skorzystania z tego warpa ({WARP})!");
public Notice addPermissions = Notice.chat("<green>► <white>Dodano uprawnienia do warpa <green>{WARP}<white>!");
public Notice removePermission = Notice.chat("<red>► <white>Usunięto uprawnienie <red>{PERMISSION}</red> do warpa <red>{WARP}</red>!");
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

Correct the preposition in the message

In the removePermission notice, the phrase "do warpa" implies adding to the warp. Since the permission is being removed, consider changing "do warpa" to "z warpa" to accurately reflect the action.

Apply this diff to correct the message:

-public Notice removePermission = Notice.chat("<red>► <white>Usunięto uprawnienie <red>{PERMISSION}</red> do warpa <red>{WARP}</red>!");
+public Notice removePermission = Notice.chat("<red>► <white>Usunięto uprawnienie <red>{PERMISSION}</red> z warpa <red>{WARP}</red>!");
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public Notice removePermission = Notice.chat("<red>► <white>Usunięto uprawnienie <red>{PERMISSION}</red> do warpa <red>{WARP}</red>!");
public Notice removePermission = Notice.chat("<red>► <white>Usunięto uprawnienie <red>{PERMISSION}</red> z warpa <red>{WARP}</red>!");

@vLuckyyy vLuckyyy removed their request for review October 22, 2024 08:42
@igoyek igoyek removed their request for review October 23, 2024 17:53
Copy link
Member

@Jakubk15 Jakubk15 left a comment

Choose a reason for hiding this comment

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

@coderabbitai carried the whole review as always <3

Copy link
Member

@P1otrulla P1otrulla left a comment

Choose a reason for hiding this comment

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

Follow others commets and we can merge it

boolean warpExists(String name);

boolean doesWarpPermissionExist(String warp, String permission);
Copy link
Member

Choose a reason for hiding this comment

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

Is permission needed here? We can just check it using isEmpty on permissions list in object

void addPermissions(String warp, String... permissions);

void removePermission(String warp, String permission);

Copy link
Member

Choose a reason for hiding this comment

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

Missing return of all permissions

@vLuckyyy vLuckyyy assigned vLuckyyy and unassigned eripe14 Jan 10, 2025
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: 0

♻️ Duplicate comments (1)
eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (1)

155-159: ⚠️ Potential issue

Implement the new methods in translation classes

The new permission-related methods need to be implemented in:

  • ENTranslation.java
  • PLTranslation.java

This is required to maintain consistency across the translation system.

🧹 Nitpick comments (1)
eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (1)

155-159: Consider consistent plural/singular naming

The method names show inconsistency in plural/singular form:

  • addPermissions() (plural)
  • removePermission() (singular)

Consider making them consistent, preferably using singular form for both:

- Notice addPermissions();
+ Notice addPermission();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f1a6ada and 7eb3bfc.

📒 Files selected for processing (4)
  • eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java (2 hunks)
  • eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (2 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 (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • eternalcore-core/src/main/java/com/eternalcode/core/configuration/implementation/PluginConfiguration.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/PLTranslation.java
🔇 Additional comments (3)
eternalcore-core/src/main/java/com/eternalcode/core/translation/implementation/ENTranslation.java (2)

5-5: LGTM!

The import is correctly placed and used by the ENWarpInventory class.


385-389: Well-structured permission messages that align with PR objectives!

The new messages effectively support the permission-based access feature for warps:

  • Follow consistent formatting and color scheme
  • Include appropriate placeholders for warp names and permission nodes
  • Cover all necessary permission management scenarios
eternalcore-core/src/main/java/com/eternalcode/core/translation/Translation.java (1)

5-5: LGTM!

The import statement for WarpInventoryItem is correctly reactivated as it's required by the WarpSection.WarpInventorySection interface.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add Permission-Based Access to Warps
7 participants