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 converter for hebrew calendar based on hijri calendar #108

Open
wants to merge 2 commits into
base: feature/convert-hijri
Choose a base branch
from

Conversation

rlskoeser
Copy link
Member

No description provided.

Copy link
Contributor

coderabbitai bot commented Nov 27, 2024

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@rlskoeser rlskoeser changed the base branch from develop to feature/convert-hijri November 27, 2024 00:22
Copy link

@kypso-io kypso-io bot left a comment

Choose a reason for hiding this comment

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

📋 Review Summary

  • Number of files reviewed: 13
  • Number of comments: 5
  • Number of suggestions: 3

📚 File changes

File path File changes
src/undate/converters/base.py Modified the documentation for adding a new calendar converter and adjusted the method definitions in the BaseCalendarConverter class.
src/undate/converters/calendars/gregorian.py Removed the max_month method that defined the maximum month for the Gregorian calendar.
src/undate/converters/calendars/hebrew/init.py Added import for HijriDateConverter and updated __all__.
src/undate/converters/calendars/hebrew/converter.py Added a converter for Hebrew calendar based on Hijri calendar.
src/undate/converters/calendars/hebrew/hebrew.lark Added a converter for the Hebrew calendar based on the Hijri calendar.
src/undate/converters/calendars/hebrew/parser.py Added imports and parser initialization for Hebrew calendar.
src/undate/converters/calendars/hebrew/transformer.py Added a Hebrew calendar converter based on the Hijri calendar.
src/undate/converters/calendars/hijri/init.py Added import for HebrewDateConverter and updated __all__ to include it.
src/undate/converters/calendars/hijri/converter.py Removed the max_month method and modified the docstring in the parse method.
src/undate/undate.py Added support for the Hebrew calendar in the Calendar enum and adjusted month handling.
tests/test_converters/test_calendars/test_hebrew/test_hebrew_converter.py Added tests for Hebrew date conversion.
tests/test_converters/test_calendars/test_hebrew/test_hebrew_parser.py Added test cases for valid and invalid Hebrew calendar dates.
tests/test_converters/test_calendars/test_hebrew/test_hebrew_transformer.py Added tests for Hebrew calendar conversions.
Ignored comments

src/undate/converters/base.py

  • refactor_suggestion: The method max_month is defined twice, once with a parameter year and once without. This could lead to confusion about which method should be used. Consider removing the first definition and keeping the one without parameters, or clarify the purpose of each method if both are necessary.

  • refactor_suggestion: The method min_month is defined after max_month, which may lead to confusion regarding the order of methods. Consider reordering the methods to group similar functionalities together for better readability.

src/undate/converters/calendars/gregorian.py

  • refactor_suggestion: The max_month method has been removed, but it may be useful to retain a method that explicitly defines the maximum month for the Gregorian calendar. Consider keeping this method for clarity and future extensibility.

src/undate/converters/calendars/hebrew/init.py

  • refactor_suggestion: Consider using a more descriptive name for the __all__ variable to indicate that it includes converters for the Hebrew calendar, especially if more converters are added in the future.
    all = ["HebrewDateConverter", "HijriDateConverter"]

src/undate/converters/calendars/hebrew/hebrew.lark

  • refactor_suggestion: The hebrew_date rule currently supports multiple formats, but it may be beneficial to explicitly define the expected formats for clarity. Consider breaking down the formats into separate rules or providing a more detailed comment on the expected input formats.

src/undate/converters/calendars/hebrew/parser.py

  • refactor_suggestion: Consider using a context manager for opening files to ensure proper handling of file resources. This can help prevent potential resource leaks if the file is not closed properly in case of an error.
with open(grammar_path, 'r') as grammar:
    hebrew_parser = Lark(grammar.read(), start="hebrew_date", strict=True)

src/undate/converters/calendars/hijri/init.py

  • refactor_suggestion: Consider organizing the imports alphabetically for better readability and maintainability.

src/undate/converters/calendars/hijri/converter.py

  • refactor_suggestion: The max_month method has been removed, but it may be useful to keep it for clarity or future use. If it is not needed, consider removing any references to it in the documentation or comments to avoid confusion.

  • refactor_suggestion: The comment in the parse method's docstring has been modified. Ensure that the documentation accurately reflects the method's functionality and does not mislead users about the return types.

src/undate/undate.py

  • refactor_suggestion: The addition of the HEBREW calendar enum is appropriate, but ensure that the corresponding converter is implemented and available in the BaseDateConverter class. Without this, the get_converter method will raise a KeyError if HEBREW is used without a defined converter.

  • refactor_suggestion: The comments regarding the differentiation between min/max and first/last months should be addressed in the code. Consider implementing a method to clarify this distinction, especially since it can affect how dates are calculated for different calendars.

  • refactor_suggestion: The _missing_digit_minmax method is being called with hardcoded values for min and max (1 and 12). It would be more flexible to pass these values as parameters to the method, allowing for better adaptability to different calendar systems.

tests/test_converters/test_calendars/test_hebrew/test_hebrew_transformer.py

  • refactor_suggestion: Consider organizing the test cases into a more structured format, such as a dictionary, to improve clarity and maintainability. This can help in easily adding new test cases in the future.
testcases = {
    "26 Tammuz 4816": (HebrewUndate(4816, 4, 26), DatePrecision.DAY),
    "Tammuz 4816": (HebrewUndate(4816, 4), DatePrecision.MONTH),
    "4816": (HebrewUndate(4816), DatePrecision.YEAR),
    "26 Tishrei 5416": (HebrewUndate(5416, 7, 26), DatePrecision.DAY),
    "Ṭevet 5362": (HebrewUndate(5362, 10), DatePrecision.MONTH),
    "5362": (HebrewUndate(5362), DatePrecision.YEAR),
}

@pytest.mark.parametrize("date_string, expected, expected_precision", testcases.items())
def test_transform(date_string, expected, expected_precision):

Comment on lines +55 to +68
if not value:
raise ValueError("Parsing empty string is not supported")

# parse the input string, then transform to undate object
try:
# parse the string with our Hebrew date parser
parsetree = hebrew_parser.parse(value)
# transform the parse tree into an undate or undate interval
undate_obj = self.transformer.transform(parsetree)
# set the original date as a label, with the calendar name
undate_obj.label = f"{value} {self.calendar_name}"
return undate_obj
except UnexpectedCharacters as err:
raise ValueError(f"Could not parse '{value}' as a Hebrew date") from err
Copy link

Choose a reason for hiding this comment

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

error_handling_issue
The parse method currently raises a ValueError for an empty string, which is good. However, it would be beneficial to also handle cases where the input string does not conform to expected Hebrew date formats. Consider adding a more specific exception handling for such cases to provide clearer feedback to the user.

Potential fix 🚨
Suggested change
if not value:
raise ValueError("Parsing empty string is not supported")
# parse the input string, then transform to undate object
try:
# parse the string with our Hebrew date parser
parsetree = hebrew_parser.parse(value)
# transform the parse tree into an undate or undate interval
undate_obj = self.transformer.transform(parsetree)
# set the original date as a label, with the calendar name
undate_obj.label = f"{value} {self.calendar_name}"
return undate_obj
except UnexpectedCharacters as err:
raise ValueError(f"Could not parse '{value}' as a Hebrew date") from err
if not value:
raise ValueError("Parsing empty string is not supported")
# parse the input string, then transform to undate object
try:
# parse the string with our Hebrew date parser
parsetree = hebrew_parser.parse(value)
# transform the parse tree into an undate or undate interval
undate_obj = self.transformer.transform(parsetree)
# set the original date as a label, with the calendar name
undate_obj.label = f"{value} {self.calendar_name}"
return undate_obj
except UnexpectedCharacters as err:
raise ValueError(f"Could not parse '{value}' as a Hebrew date") from err
except Exception as e:
raise ValueError(f"An error occurred while parsing '{value}': {str(e)}")

| month_12
| month_13
// months have 29 or 30 days; we do not expect leading zeroes
day: /[1-9]/ | /[12][0-9]/ | /30/
Copy link

Choose a reason for hiding this comment

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

error_handling_issue
The day rule allows for days 1-30, but does not account for the varying number of days in Hebrew months. This could lead to invalid dates being parsed. Consider implementing a validation mechanism to ensure that the day corresponds correctly to the month and year provided.

// PGP dates use qualifiers like "first decade of" (for beginning of month)
// "first third of", seasons (can look for more examples)

year: /\d+/
Copy link

Choose a reason for hiding this comment

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

error_handling_issue
The year rule currently accepts any numeric input. It would be prudent to restrict this to a valid range of years for the Hebrew calendar to prevent invalid year inputs from being processed.

Comment on lines +66 to +69
HebrewDateConverter().parse("January 2, 1991")
# empty string should also error
with pytest.raises(ValueError):
HebrewDateConverter().parse("")
Copy link

Choose a reason for hiding this comment

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

error_handling_issue
The error handling for parsing invalid strings is good, but it would be beneficial to also handle cases where the input is not a string type (e.g., integers, None). This can prevent unexpected crashes in the application. Consider adding a type check before parsing the date string.

Potential fix 🚨
Suggested change
HebrewDateConverter().parse("January 2, 1991")
# empty string should also error
with pytest.raises(ValueError):
HebrewDateConverter().parse("")
if not isinstance(date_str, str):
raise ValueError("Input must be a string")


@pytest.mark.parametrize("date_string", error_cases)
def test_should_error(date_string):
with pytest.raises(Exception):
Copy link

Choose a reason for hiding this comment

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

error_handling_issue
Using a generic Exception in the pytest.raises context can make it difficult to identify the specific error that occurred. It is better to catch a more specific exception that the hebrew_parser.parse function is expected to raise for invalid inputs.

Potential fix 🚨
Suggested change
with pytest.raises(Exception):
with pytest.raises(ValueError):

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.

1 participant