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

Replace pendulum with aniso8601 #146

Merged
merged 7 commits into from
Jan 15, 2025
Merged

Replace pendulum with aniso8601 #146

merged 7 commits into from
Jan 15, 2025

Conversation

jschlyter
Copy link
Member

@jschlyter jschlyter commented Jan 15, 2025

Summary by CodeRabbit

Release Notes

  • Dependencies

    • Replaced pendulum library with aniso8601 for improved date and time interval parsing
    • Updated Python version compatibility in testing workflow
  • New Features

    • Enhanced ISO8601 interval parsing with more robust error handling
    • Improved default time interval generation for aggregation
  • Tests

    • Added comprehensive tests for new ISO8601 interval parsing functionality

@jschlyter jschlyter requested a review from a team as a code owner January 15, 2025 12:28
Copy link

coderabbitai bot commented Jan 15, 2025

Warning

Rate limit exceeded

@jschlyter has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 18 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 91434df and 9898b4e.

📒 Files selected for processing (1)
  • aggrec/helpers.py (2 hunks)

Walkthrough

The pull request modifies the project's date and time handling by replacing the pendulum library with aniso8601 for parsing ISO 8601 intervals. This includes updates across multiple files, such as removing pendulum dependencies, introducing a new parse_iso8601_interval function, and revising interval parsing logic. Additionally, the GitHub Actions workflow is updated to use Python version 3.13. These changes streamline date-time manipulation and enhance error handling while reducing external library reliance.

Changes

File Change Summary
.github/workflows/test.yml Updated Python version from 3.12 to 3.13 in test workflow
aggrec/aggregates.py - Removed pendulum import
- Added parse_iso8601_interval import
- Replaced interval parsing logic
aggrec/client.py Replaced pendulum.now() with datetime.now(tz=timezone.utc) for default interval generation
aggrec/helpers.py - Added aniso8601 import
- Removed pendulum_as_datetime function
- Added parse_iso8601_interval function
pyproject.toml - Removed pendulum dependency
- Added aniso8601 dependency
tests/test_iso8601.py Added new test function test_parse_iso8601_interval

Sequence Diagram

sequenceDiagram
    participant Client
    participant Helpers
    participant AggregateFunction
    
    Client->>Helpers: parse_iso8601_interval(interval)
    Helpers-->>Client: Returns (start_time, duration)
    Client->>AggregateFunction: Use parsed interval
    AggregateFunction-->>Client: Process aggregate
Loading

Poem

🐰 A Rabbit's Ode to Time's New Dance 🕰️
Pendulum swings, now put to rest,
Aniso8601 passes the test!
Intervals parsed with rabbit-like might,
Dates and times now shine so bright!
Code refactored, dependencies light! 🌟


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

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

🧹 Nitpick comments (3)
tests/test_iso8601.py (1)

6-13: Enhance test coverage with additional test cases.

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

  • Invalid interval formats to verify error handling
  • Negative durations
  • Different timezone formats (e.g., -0500, +0530)
  • Microsecond precision
def test_parse_iso8601_interval():
    # Existing tests...

    # Invalid format
    with pytest.raises(ValueError):
        parse_iso8601_interval("invalid")
    
    # Different timezone formats
    start, duration = parse_iso8601_interval("2025-01-15T08:56:58-05:00/PT1M")
    assert start == datetime(year=2025, month=1, day=15, hour=13, minute=56, second=58, tzinfo=timezone.utc)
    
    # Microsecond precision
    start, duration = parse_iso8601_interval("2025-01-15T08:56:58.123456+00:00/PT1M")
    assert start == datetime(year=2025, month=1, day=15, hour=8, minute=56, second=58, microsecond=123456, tzinfo=timezone.utc)
aggrec/helpers.py (1)

117-119: Add docstring and improve type safety.

The function would benefit from:

  1. A docstring explaining its purpose, parameters, and return values
  2. Type hints for better IDE support
  3. Validation of the returned values
 def parse_iso8601_interval(interval: str) -> tuple[datetime, timedelta]:
+    """Parse an ISO 8601 time interval string into start time and duration.
+
+    Args:
+        interval: An ISO 8601 time interval string (e.g., "2024-01-01T00:00:00Z/PT1H")
+
+    Returns:
+        A tuple containing:
+        - start time as datetime (UTC)
+        - duration as timedelta
+
+    Raises:
+        ValueError: If the interval string is invalid or cannot be parsed
+    """
     t1, t2 = aniso8601.parse_interval(interval)
+    if not isinstance(t1, datetime) or not isinstance(t2, datetime):
+        raise ValueError("Invalid interval format")
     return t1, timedelta(seconds=(t2 - t1).total_seconds())
aggrec/client.py (1)

51-51: Consider moving default_interval to a constant and ensure consistent ISO format.

  1. Move the default interval to a constant at module level
  2. Specify timespec in isoformat() for consistent output
+DEFAULT_AGGREGATE_INTERVAL_DURATION = "PT1M"
+
 def main() -> None:
-    default_interval = f"{datetime.now(tz=timezone.utc).isoformat()}/PT1M"
+    default_interval = f"{datetime.now(tz=timezone.utc).isoformat(timespec='seconds')}/{DEFAULT_AGGREGATE_INTERVAL_DURATION}"

Also applies to: 61-62

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between eb2dbda and a827347.

⛔ Files ignored due to path filters (1)
  • poetry.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • .github/workflows/test.yml (1 hunks)
  • aggrec/aggregates.py (2 hunks)
  • aggrec/client.py (3 hunks)
  • aggrec/helpers.py (2 hunks)
  • pyproject.toml (1 hunks)
  • tests/test_iso8601.py (1 hunks)
🔇 Additional comments (3)
aggrec/aggregates.py (2)

287-294: LGTM! Well-structured error handling.

The changes look good with:

  • Proper error handling using try-except
  • Clear error message with a helpful example
  • Clean integration with the new parse_iso8601_interval function

Line range hint 1-1: Verify complete removal of pendulum.

Let's verify that all pendulum imports and usages have been removed from the codebase.

✅ Verification successful

Pendulum has been completely removed from the codebase

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining pendulum imports or usages

echo "Checking for pendulum imports..."
rg "import pendulum" -l

echo "Checking for pendulum usage..."
rg "pendulum\." -l

echo "Checking for pendulum in requirements..."
rg "pendulum" pyproject.toml setup.py requirements.txt

Length of output: 444


Script:

#!/bin/bash
# Description: Broader check for pendulum references

echo "Checking for 'from pendulum' imports..."
rg "from pendulum" -l

echo "Checking for 'as pendulum' imports..."
rg "as pendulum" -l

echo "Checking pyproject.toml content..."
cat pyproject.toml

echo "Checking for any file containing 'pendulum' string..."
rg -i "pendulum" -l

Length of output: 1938

pyproject.toml (1)

28-28: Verify dependency compatibility.

  1. The Python version in CI (3.13) conflicts with the project's requirement (^3.12). This needs to be aligned.
  2. Let's verify that no other dependencies require pendulum and that they're all compatible with aniso8601.
✅ Verification successful

Dependencies verified successfully

The migration from pendulum to aniso8601 is clean and properly implemented. No dependency conflicts or remaining pendulum usage found in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential dependency conflicts and pendulum requirements

# Check if any dependency still requires pendulum
poetry show --tree | grep -B2 -A2 pendulum

# List all dependencies that might conflict with aniso8601
poetry show --tree | grep -B2 -A2 aniso8601

# Check if any Python files still import pendulum
rg -l 'import\s+pendulum|from\s+pendulum'

Length of output: 328


Script:

#!/bin/bash
# Check for pendulum imports and usage
rg -l "pendulum"

# Check for aniso8601 imports and usage
rg -l "aniso8601"

# Look at pyproject.toml content
cat pyproject.toml

# Look for datetime handling patterns
ast-grep --pattern 'from datetime import $$$'
ast-grep --pattern 'import datetime'

Length of output: 1969


Script:

#!/bin/bash
# Check how aniso8601 is used in the codebase
rg -A 5 "aniso8601" aggrec/helpers.py

# Look for any ISO8601 related functions
ast-grep --pattern 'def $_($$$) {
  $$$
  aniso8601
  $$$
}'

Length of output: 385

.github/workflows/test.yml Show resolved Hide resolved
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)
tests/test_iso8601.py (1)

8-32: LGTM! Comprehensive test coverage for ISO8601 interval parsing.

The test cases effectively cover various scenarios including timestamp/duration, timestamp/timestamp, invalid formats, timezone handling, and microsecond precision.

Consider adding these additional test cases to enhance coverage:

  1. Duration with different units (hours, days, weeks)
  2. Edge cases (leap years, DST transitions)
  3. Negative durations
  4. Empty or null input
aggrec/helpers.py (1)

117-122: Enhance documentation and error handling.

While the implementation is correct, consider these improvements:

  1. Add docstring examples of supported formats
  2. Add timezone normalization
  3. Enhance error handling for edge cases

Here's a suggested implementation:

 def parse_iso8601_interval(interval: str) -> tuple[datetime, timedelta]:
-    """Parse ISO8601 interval and return resulting datetime and timedelta"""
+    """Parse ISO8601 interval and return resulting datetime and timedelta.
+    
+    Args:
+        interval: ISO8601 interval string (e.g., "2025-01-15T08:56:58+00:00/PT1M"
+                 or "19840101T000000Z/19840115T000000Z")
+    
+    Returns:
+        Tuple of (start datetime in UTC, duration)
+    
+    Raises:
+        ValueError: If interval format is invalid or results in negative duration
+    """
     t1, t2 = aniso8601.parse_interval(interval)
     if not isinstance(t1, datetime) or not isinstance(t2, datetime):
         raise ValueError("Invalid interval format")
+    # Ensure both datetimes are in UTC
+    if t1.tzinfo is None:
+        raise ValueError("Start time must include timezone")
+    if t2.tzinfo is None:
+        raise ValueError("End time must include timezone")
+    t1 = t1.astimezone(timezone.utc)
+    t2 = t2.astimezone(timezone.utc)
+    duration = timedelta(seconds=(t2 - t1).total_seconds())
+    if duration.total_seconds() < 0:
+        raise ValueError("Duration cannot be negative")
-    return t1, timedelta(seconds=(t2 - t1).total_seconds())
+    return t1, duration
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a827347 and 91434df.

📒 Files selected for processing (3)
  • aggrec/client.py (3 hunks)
  • aggrec/helpers.py (2 hunks)
  • tests/test_iso8601.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • aggrec/client.py
🔇 Additional comments (1)
aggrec/helpers.py (1)

3-5: Verify complete removal of pendulum dependency.

Let's ensure all pendulum usages have been replaced across the codebase.

✅ Verification successful

✓ Pendulum dependency has been completely removed

The codebase has been thoroughly checked and shows no remaining traces of pendulum in imports, type hints, or dependencies.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any remaining pendulum imports or usages
echo "Checking for pendulum imports..."
rg "import pendulum|from pendulum" -l

echo "Checking for pendulum type hints..."
rg "pendulum\." -l

echo "Checking if pendulum is still in dependencies..."
if [ -f "pyproject.toml" ]; then
    rg "pendulum" pyproject.toml
fi

Length of output: 380


Script:

#!/bin/bash
# Verify we can find Python files and detect imports
echo "Checking Python files exist..."
fd '\.py$'

echo -e "\nVerifying import detection works..."
# Check for datetime import which we know exists in helpers.py
rg "from datetime import|import datetime" -l

Length of output: 543

@jschlyter jschlyter merged commit 33092c9 into main Jan 15, 2025
5 checks passed
@jschlyter jschlyter deleted the sans_pendulum branch January 15, 2025 17:50
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