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

fix more cases as the one in #11189 and add check to prevent this issue #11194

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

Conversation

danielnaber
Copy link
Member

@danielnaber danielnaber commented Jan 16, 2025

Summary by CodeRabbit

  • New Features

    • Added new false friend translation rules between English and multiple languages (French, Spanish, Portuguese, German, Polish, Italian, Galician, and Russian).
    • Introduced an option for test mode in the false friend rule handling, enhancing error handling and flexibility.
  • Bug Fixes

    • Improved validation for translation language configurations to prevent incorrect language settings in false friend rules.
  • Tests

    • Added a new test class to validate the syntax of the false friend rules XML file.

@danielnaber danielnaber requested a review from SteVio89 January 16, 2025 11:53
Copy link
Contributor

coderabbitai bot commented Jan 16, 2025

Walkthrough

The pull request introduces a new boolean field inTestMode to the FalseFriendRuleHandler and FalseFriendRuleLoader classes, allowing for enhanced error handling and flexibility in test scenarios. The startElement method in FalseFriendRuleHandler now includes a validation check that throws a RuntimeException if the translation language matches the pattern language while in test mode. Additionally, new false friend rules are added to the false-friends.xml resource file, covering various languages and vocabulary categories.

Changes

File Change Summary
languagetool-core/src/main/java/org/languagetool/rules/patterns/FalseFriendRuleHandler.java Introduced inTestMode boolean field; updated constructor; added validation in startElement method to throw RuntimeException if languages match in test mode.
languagetool-core/src/main/java/org/languagetool/rules/patterns/FalseFriendRuleLoader.java Introduced inTestMode boolean field; updated constructors; modified getRules method to pass inTestMode to FalseFriendRuleHandler.
languagetool-core/src/main/resources/org/languagetool/rules/false-friends.xml Added new false friend rules between English and French, Spanish, Portuguese, German, Polish, Italian, Galician, and Russian, covering various vocabulary categories.
languagetool-standalone/src/test/java/org/languagetool/rules/ValidateFalseFriendsSyntaxTest.java Added new test class ValidateFalseFriendsSyntaxTest with method testFalseFriendsXML to validate the syntax of false-friends.xml.
✨ 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: 0

🧹 Nitpick comments (1)
languagetool-core/src/main/java/org/languagetool/rules/patterns/FalseFriendRuleHandler.java (1)

99-101: LGTM! Consider these improvements for maintainability.

The validation check is well-placed and effectively prevents same-language translations in false friend rules. A few suggestions for improvement:

  1. Consider using a more specific exception type (e.g., XMLValidationException) instead of RuntimeException.
  2. Consider externalizing the error message for i18n support.
  3. Consider extracting the validation to a separate method for better readability.

Here's a suggested refactor:

 if (currentTranslationLanguage == language) {
-  throw new RuntimeException("Translation language (" + currentTranslationLanguage + ") must not be the same as pattern language (" + language + ") for rule " + id);
+  throw new XMLValidationException(MessageFormat.format(messages.getString("translation_same_as_pattern"), 
+    currentTranslationLanguage, language, id));
 }

Add to your resource bundle:

translation_same_as_pattern=Translation language ({0}) must not be the same as pattern language ({1}) for rule {2}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c93f6e4 and 6a50e9d.

📒 Files selected for processing (2)
  • languagetool-core/src/main/java/org/languagetool/rules/patterns/FalseFriendRuleHandler.java (1 hunks)
  • languagetool-core/src/main/resources/org/languagetool/rules/false-friends.xml (9 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (java-kotlin)
🔇 Additional comments (1)
languagetool-core/src/main/resources/org/languagetool/rules/false-friends.xml (1)

3602-3603: LGTM! Good addition of translations.

The new translations "boaster" and "braggart" for the Polish word "bufon" improve the accuracy of the false friends detection by better capturing the semantic difference between English "buffoon" (clown/fool) and Polish "bufon" (boaster/braggart).

@@ -96,6 +96,9 @@ public void startElement(String namespaceURI, String lName,
if (Languages.isLanguageSupported(languageStr)) {
Language tmpLang = Languages.getLanguageForShortCode(languageStr);
currentTranslationLanguage = tmpLang;
if (currentTranslationLanguage == language) {
throw new RuntimeException("Translation language (" + currentTranslationLanguage + ") must not be the same as pattern language (" + language + ") for rule " + id);
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

Wouldn't it be better to test this in a test instead of throwing a RuntimeException (which prevents the server from starting)?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes, let me try it that way

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

🧹 Nitpick comments (2)
languagetool-standalone/src/test/java/org/languagetool/rules/ValidateFalseFriendsSyntaxTest.java (2)

38-38: Replace System.out.println with proper test logging.

Using System.out.println for logging in tests is not recommended. Consider using a proper logging framework or JUnit's TestRule to capture output if needed.

-    System.out.println("Validating false-friends.xml syntax...");
+    // Consider using SLF4J or TestRule for logging
+    logger.info("Validating false-friends.xml syntax...");
-    System.out.println("Validation successfully finished.");
+    logger.info("Validation successfully finished.");

Also applies to: 43-43


34-46: Add more test cases for comprehensive validation.

The current test only validates the basic syntax. Consider adding more test cases to:

  1. Validate error cases (malformed XML, invalid language codes)
  2. Test with different language combinations
  3. Verify specific rule patterns

Would you like me to help generate additional test cases to improve coverage?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6a50e9d and 69a5976.

📒 Files selected for processing (3)
  • languagetool-core/src/main/java/org/languagetool/rules/patterns/FalseFriendRuleHandler.java (2 hunks)
  • languagetool-core/src/main/java/org/languagetool/rules/patterns/FalseFriendRuleLoader.java (2 hunks)
  • languagetool-standalone/src/test/java/org/languagetool/rules/ValidateFalseFriendsSyntaxTest.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • languagetool-core/src/main/java/org/languagetool/rules/patterns/FalseFriendRuleHandler.java
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (java-kotlin)
🔇 Additional comments (3)
languagetool-core/src/main/java/org/languagetool/rules/patterns/FalseFriendRuleLoader.java (3)

42-42: LGTM! Field declaration follows best practices.

The new inTestMode field is correctly declared as final and follows Java naming conventions.


44-58: Well-structured constructor changes.

Good use of constructor chaining pattern and proper initialization of the new field while maintaining backward compatibility.


77-77: Verify the FalseFriendRuleHandler implementation.

The inTestMode flag is now passed to the handler. Let's verify that the FalseFriendRuleHandler properly implements the validation check.

✅ Verification successful

Validation check in FalseFriendRuleHandler is properly implemented

The handler correctly uses the inTestMode flag to validate that translation language differs from pattern language, which is essential for false friend rules.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for FalseFriendRuleHandler implementation to verify the validation check
ast-grep --pattern 'class FalseFriendRuleHandler {
  $$$
  startElement($$$) {
    $$$
    if ($inTestMode$$$ && $$$) {
      throw new RuntimeException($$$);
    }
    $$$
  }
  $$$
}'

Length of output: 187


Script:

#!/bin/bash
# Find the file containing FalseFriendRuleHandler
fd FalseFriendRuleHandler.java

# If found, examine its content
fd FalseFriendRuleHandler.java -x cat {}

Length of output: 9156

Comment on lines +1 to +2
/* LanguageTool, a natural language style checker
* Copyright (C) 2025 Daniel Naber (http://www.danielnaber.de)
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

Update the copyright year.

The copyright year 2025 is incorrect as it's in the future. Please update it to the current year 2024.

-/* LanguageTool, a natural language style checker 
- * Copyright (C) 2025 Daniel Naber (http://www.danielnaber.de)
+/* LanguageTool, a natural language style checker 
+ * Copyright (C) 2024 Daniel Naber (http://www.danielnaber.de)
📝 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
/* LanguageTool, a natural language style checker
* Copyright (C) 2025 Daniel Naber (http://www.danielnaber.de)
/* LanguageTool, a natural language style checker
* Copyright (C) 2024 Daniel Naber (http://www.danielnaber.de)

Comment on lines +37 to +44
public void testFalseFriendsXML() throws IOException, ParserConfigurationException, SAXException {
System.out.println("Validating false-friends.xml syntax...");
InputStream is = JLanguageTool.getDataBroker().getAsStream(getDataBroker().getRulesDir() + "/false-friends.xml");
Language langDE = Languages.getLanguageForShortCode("de");
FalseFriendRuleLoader loader = new FalseFriendRuleLoader(langDE, true);
loader.getRules(is, langDE, Languages.getLanguageForShortCode("en"));
System.out.println("Validation successfully finished.");
}
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

Add assertions and improve resource handling.

The test method has several areas for improvement:

  1. Missing assertions to verify the expected behavior
  2. Resource leak: InputStream should be closed
  3. Hard-coded language codes could be constants

Here's a suggested improvement:

+  private static final String LANG_DE = "de";
+  private static final String LANG_EN = "en";

   @Test
   public void testFalseFriendsXML() throws IOException, ParserConfigurationException, SAXException {
-    System.out.println("Validating false-friends.xml syntax...");
-    InputStream is = JLanguageTool.getDataBroker().getAsStream(getDataBroker().getRulesDir() + "/false-friends.xml");
-    Language langDE = Languages.getLanguageForShortCode("de");
-    FalseFriendRuleLoader loader = new FalseFriendRuleLoader(langDE, true);
-    loader.getRules(is, langDE, Languages.getLanguageForShortCode("en"));
-    System.out.println("Validation successfully finished.");
+    try (InputStream is = JLanguageTool.getDataBroker().getAsStream(getDataBroker().getRulesDir() + "/false-friends.xml")) {
+      Language langDE = Languages.getLanguageForShortCode(LANG_DE);
+      FalseFriendRuleLoader loader = new FalseFriendRuleLoader(langDE, true);
+      List<FalseFriendRule> rules = loader.getRules(is, langDE, Languages.getLanguageForShortCode(LANG_EN));
+      assertNotNull("Rules should not be null", rules);
+      assertFalse("Rules should not be empty", rules.isEmpty());
+    }
   }
📝 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 testFalseFriendsXML() throws IOException, ParserConfigurationException, SAXException {
System.out.println("Validating false-friends.xml syntax...");
InputStream is = JLanguageTool.getDataBroker().getAsStream(getDataBroker().getRulesDir() + "/false-friends.xml");
Language langDE = Languages.getLanguageForShortCode("de");
FalseFriendRuleLoader loader = new FalseFriendRuleLoader(langDE, true);
loader.getRules(is, langDE, Languages.getLanguageForShortCode("en"));
System.out.println("Validation successfully finished.");
}
private static final String LANG_DE = "de";
private static final String LANG_EN = "en";
@Test
public void testFalseFriendsXML() throws IOException, ParserConfigurationException, SAXException {
try (InputStream is = JLanguageTool.getDataBroker().getAsStream(getDataBroker().getRulesDir() + "/false-friends.xml")) {
Language langDE = Languages.getLanguageForShortCode(LANG_DE);
FalseFriendRuleLoader loader = new FalseFriendRuleLoader(langDE, true);
List<FalseFriendRule> rules = loader.getRules(is, langDE, Languages.getLanguageForShortCode(LANG_EN));
assertNotNull("Rules should not be null", rules);
assertFalse("Rules should not be empty", rules.isEmpty());
}
}

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

Successfully merging this pull request may close these issues.

2 participants