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

Add normalize language function and tests #41

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

nvdaes
Copy link
Contributor

@nvdaes nvdaes commented Dec 20, 2024

Issue number

Fixes nvaccess/nvda#17527

Summary of the issue

In the add-on store, sometimes translated add-ons appear as untranslated. This can be produced when an add-on has a locale folder with a non normalized language, like ES instead of es.
In the transformation to build the views Branch using addon-datastore-transform repo, a function is used to get the available languages. Available languages are stored in a set. Moreover, when a folder is created to store json files for each available language, uppercase and lowercase folders with the same name aren't created. Consequently, if a non standard language is available, but in fact add-ons aren't translated to this language, the english translation can be copied in the folder corresponding to the standard language, even overriding the available language for the standard language.
This can be observed for "es" (spanish).

Development approach

A function has been created to normalize language, and this is used in the function to get manifest localizations. Tests have been added just for this function.

Tests performed

Unit tests.

Known issues

None. This should be tested in real life.

Summary by CodeRabbit

  • New Features

    • Introduced a new function for normalizing language codes, ensuring consistent formatting for language-dialect strings.
    • Added unit tests to validate the new normalization functionality.
  • Bug Fixes

    • Enhanced output format for language codes in the localization process.

Copy link

coderabbitai bot commented Dec 20, 2024

Walkthrough

The pull request introduces a new normalizeLanguage function in the manifestLoader.py file to standardize language code handling. This function converts language codes to a consistent format by converting dashes to underscores, ensuring the language part is lowercase and the dialect part is uppercase. Corresponding unit tests are added to test_createJson.py to validate the normalization behavior, covering scenarios with and without country information.

Changes

File Change Summary
_validate/manifestLoader.py Added normalizeLanguage function to normalize language codes
_tests/test_createJson.py Added Test_normalizeLanguage test class with two test methods to verify language code normalization

Assessment against linked issues

Objective Addressed Explanation
Fix inconsistent language translation in add-on store [#17527]
Normalize language code handling [#17527]

Poem

🐰 A rabbit's tale of code so bright,
Language codes now aligned just right
Dashes to underscores, with care
Lowercase and uppercase, a perfect pair
Translations dancing with delight! 🌈


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4f8512a and 6ac293c.

📒 Files selected for processing (1)
  • _validate/manifestLoader.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • _validate/manifestLoader.py

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.

@nvdaes
Copy link
Contributor Author

nvdaes commented Dec 20, 2024

cc: @SaschaCowley , @seanbudd

@nvdaes nvdaes marked this pull request as ready for review December 20, 2024 17:56
Copy link

@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 (2)
_validate/manifestLoader.py (1)

55-68: Consider adding input validation and improving documentation

The implementation looks good but could benefit from some improvements:

  1. Add input validation to handle edge cases
  2. Fix typos in docstring ("in to" → "into", "upercase" → "uppercase")
  3. Add examples to the docstring

Consider this enhanced implementation:

 def normalizeLanguage(lang: str) -> str:
     """
-    Normalizes a  language-dialect string  in to a standard form we can deal with.
-    Converts  any dash to underline, and makes sure that language is lowercase and dialect is upercase.
+    Normalizes a language-dialect string into a standard form we can deal with.
+    Converts any dash to underscore, and makes sure that language is lowercase and dialect is uppercase.
     Based on NVDA`s `languageHandler` module.
+
     :param lang: A language code.
+    :raises ValueError: If the language code is empty or None
+    :examples:
+        >>> normalizeLanguage("en")
+        'en'
+        >>> normalizeLanguage("pt-BR")
+        'pt_BR'
     :return: A normalized language code.
     """
+    if not lang:
+        raise ValueError("Language code cannot be empty")
     lang = lang.replace("-", "_")
     ld = lang.split("_")
+    if not ld[0]:
+        raise ValueError("Language part cannot be empty")
     ld[0] = ld[0].lower()
     if len(ld) >= 2:
         ld[1] = ld[1].upper()
     return "_".join(ld)
_tests/test_createJson.py (1)

116-129: Consider adding more test cases for edge cases

While the current tests cover the basic functionality well, consider adding tests for:

  1. Edge cases:

    • Empty string input
    • None input
    • Multiple separators (e.g., "en_US_POSIX")
    • Invalid formats (e.g., "en__US")
  2. Additional valid cases:

    • Mixed case with dash (e.g., "En-us")
    • Multiple dashes (e.g., "zh-Hans-CN")

Here are some additional test methods to consider:

def test_edge_cases(self):
    """Test handling of invalid inputs."""
    with self.assertRaises(ValueError):
        manifestLoader.normalizeLanguage("")
    with self.assertRaises(ValueError):
        manifestLoader.normalizeLanguage("_US")
    with self.assertRaises(TypeError):
        manifestLoader.normalizeLanguage(None)

def test_complex_language_codes(self):
    """Test handling of complex language codes."""
    self.assertEqual("zh_HANS_CN", manifestLoader.normalizeLanguage("zh-Hans-CN"))
    self.assertEqual("en_US", manifestLoader.normalizeLanguage("En-us"))
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 354918f and 4f8512a.

📒 Files selected for processing (2)
  • _tests/test_createJson.py (2 hunks)
  • _validate/manifestLoader.py (1 hunks)
🔇 Additional comments (1)
_validate/manifestLoader.py (1)

50-53: LGTM: Clean integration of language normalization

The normalization is correctly integrated into the existing workflow, maintaining the error handling while ensuring language codes are standardized before being yielded.

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.

In the add-on store, add-ons seem not to be translated randomly
1 participant