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

Merged
merged 10 commits into from
Dec 6, 2024

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.

🗂️ Base branches to auto review (1)
  • develop

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)}")

Copy link
Collaborator

Choose a reason for hiding this comment

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

This very long Kypso comment seems to just suggest adding a catchall Exception at the end?

Copy link
Collaborator

Choose a reason for hiding this comment

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

We should probably throw a TypeError in parse() if we get an invalid value - anything other than a string?

| 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.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Do we have such a range? I'm not very familiar with the Hebrew calendar, but it looks like the AM systems starts at Biblical creation (3761 BCE) - so anything prior to that is likely invalid? But no future limit?

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")

Copy link
Collaborator

Choose a reason for hiding this comment

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

Think handling this upstream in the converter and checking it here makes sense


@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):

Copy link
Collaborator

@ColeDCrawford ColeDCrawford left a comment

Choose a reason for hiding this comment

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

It looks like the unit tests don't run when the target branch isn't develop - do we want to change that if we're going to have feature to feature merges? I ran them on a fresh codespace with this branch and they all pass, so looks good on that front

Is the plan to merge this PR first and then the Hijri PR to develop?

Copy link
Collaborator

Choose a reason for hiding this comment

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

The change here makes gregorian the default if no calendar is specified? It seems a bit cleaner to keep these unimplemented in converters/base.py and then implement the needed methods in the specific calendars, but maybe I'm missing something.


def max_day(self, year: int, month: int) -> int:
"""maximum numeric day for the specified year and month in this calendar"""
# NOTE: unreleased v2.4.1 of convertdate standardizes month_days to month_length
Copy link
Collaborator

Choose a reason for hiding this comment

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

Is there a maintainer for convertdate? Looks like that branch has been hanging for a couple of years. Not sure if that's an issue if the library is doing what we need it to

Copy link
Member Author

Choose a reason for hiding this comment

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

You're right, it does look pretty unmaintained. My PR a couple of years ago was merged in pretty quickly but never released. I see some open PRs hanging out that look kind of old...

Not great, but the existing calendar conversion logic is enough for what we need now, so I'm inclined to keep using it until it becomes a problem. I'm not aware of another comparable option in python.

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
Collaborator

Choose a reason for hiding this comment

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

This very long Kypso comment seems to just suggest adding a catchall Exception at the end?

// 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
Collaborator

Choose a reason for hiding this comment

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

Do we have such a range? I'm not very familiar with the Hebrew calendar, but it looks like the AM systems starts at Biblical creation (3761 BCE) - so anything prior to that is likely invalid? But no future limit?

@@ -0,0 +1,3 @@
from undate.converters.calendars.hijri.converter import HijriDateConverter

__all__ = ["HijriDateConverter"]
Copy link
Collaborator

Choose a reason for hiding this comment

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

We want to be able to import HijriDateConverter from undate.converters.calendars.hebrew?

Copy link
Member Author

Choose a reason for hiding this comment

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

no, whoops, I just missed some things when I copied hijri calendar code over for hebrew calendar (caught some but not all)

Copy link
Collaborator

Choose a reason for hiding this comment

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

Really liking how clean lark is here

Comment on lines -27 to -30
def max_month(self, year: int) -> int:
"""maximum numeric month for the specified year in this calendar"""
return 12

Copy link
Collaborator

Choose a reason for hiding this comment

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

This is being pulled because the base converter now defaults to 12?

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, does that makes sense to you?

Copy link
Collaborator

Choose a reason for hiding this comment

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

I think I prefer keeping the unimplemented methods as stubs in the base and requiring specific converters to implement them, since there aren't too many. But it makes sense either way

max_month = self.calendar_converter.max_month(max_year)
# get first and last month from the calendar, since it is not
# always 1 and 12
# TODO need to differentiate between min/max and first/last!
Copy link
Collaborator

Choose a reason for hiding this comment

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

Is this also an issue in Hebrew? It looks like there are two different start months (Tishri which is ~September for calendar year, and Nisan for religious year which is ~March/April?)

Copy link
Member Author

Choose a reason for hiding this comment

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

I think it only applies to Hebrew calendar and not Hijri - but maybe others I'm not aware of

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
Collaborator

Choose a reason for hiding this comment

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

We should probably throw a TypeError in parse() if we get an invalid value - anything other than a string?

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

Choose a reason for hiding this comment

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

Think handling this upstream in the converter and checking it here makes sense

@rlskoeser
Copy link
Member Author

It looks like the unit tests don't run when the target branch isn't develop - do we want to change that if we're going to have feature to feature merges? I ran them on a fresh codespace with this branch and they all pass, so looks good on that front

Is the plan to merge this PR first and then the Hijri PR to develop?

I was trying to do stacked prs, so once the hijri is merged this one would be updated to point to develop.

But if I'm doing that I should probably make unit tests run on any pr...

@ColeDCrawford
Copy link
Collaborator

It looks like the unit tests don't run when the target branch isn't develop - do we want to change that if we're going to have feature to feature merges? I ran them on a fresh codespace with this branch and they all pass, so looks good on that front
Is the plan to merge this PR first and then the Hijri PR to develop?

I was trying to do stacked prs, so once the hijri is merged this one would be updated to point to develop.

But if I'm doing that I should probably make unit tests run on any pr...

Yeah, I think that change makes sense.

Comment on lines 140 to 146
def min_month(self) -> int:
"""First month for this calendar. Defaults to 1."""
return 1

def max_month(self) -> int:
"""Last month for this calendar. Defaults to 12."""
return 12
Copy link
Contributor

Choose a reason for hiding this comment

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

Why is min_month / max_month set to 1 and 12 in this base class? Should this not be abstract here and set in the gregorian class?

Comment on lines 18 to 21
def max_month(self, year: int) -> int:
"""Maximum month for this calendar for this year"""
return 12

Copy link
Contributor

Choose a reason for hiding this comment

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

Shouldn't min_month and max_month be defined in this class? (see comment above)

Comment on lines 1 to 3
from undate.converters.calendars.hijri.converter import HijriDateConverter

__all__ = ["HijriDateConverter"]
Copy link
Contributor

Choose a reason for hiding this comment

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

Why does this export HijriDateConverter? (copy/paste error?)


__all__ = ["HijriDateConverter"]
__all__ = ["HijriDateConverter", "HebrewDateConverter"]
Copy link
Contributor

Choose a reason for hiding this comment

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

Why does this export HebrewDateConverter? (copy/paste error?)

Comment on lines -27 to -30
def max_month(self, year: int) -> int:
"""maximum numeric month for the specified year in this calendar"""
return 12

Copy link
Contributor

Choose a reason for hiding this comment

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

Shouldn't concrete min/max_month definitions stay in the concrete classes? (see above)

@rlskoeser rlskoeser merged commit 333e740 into feature/convert-hijri Dec 6, 2024
7 checks passed
@rlskoeser rlskoeser deleted the feature/convert-hebrew branch December 6, 2024 10:42
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.

3 participants