From 3b00a0aeac1c08636bbaa7867a6de5c50bdcd51a Mon Sep 17 00:00:00 2001 From: shay Date: Mon, 20 Apr 2026 11:42:59 -0400 Subject: [PATCH] feat(streaks): compute current and max streak with grace day Co-Authored-By: Claude Sonnet 4.6 --- generator/src/processor.py | 110 ++++++++++++++++++++++++++++++++ generator/tests/test_streaks.py | 108 +++++++++++++++++++++++++++++++ 2 files changed, 218 insertions(+) create mode 100644 generator/tests/test_streaks.py diff --git a/generator/src/processor.py b/generator/src/processor.py index bde2321..6097bfc 100644 --- a/generator/src/processor.py +++ b/generator/src/processor.py @@ -11,6 +11,7 @@ from .models import ( FocusCategory, LanguageData, AchievementData, + StreakData, ) from .widgets import ( render_grade_widget, @@ -533,6 +534,115 @@ def compute_languages(github_data: dict, hidden_languages: list[str] = None) -> ] +def compute_streaks(github_data: dict, stored: dict | None) -> StreakData: + """ + Compute the user's current and longest contribution streaks. + + Current streak: starts at today if today has contributions; else at + yesterday if yesterday has contributions (1-day grace for end-of-UTC). + Walks backward while consecutive days are all active. + + Max streak: scans the contribution window for the longest consecutive run, + then merges with `stored["max_streak"]`. The greater value wins; when the + stored value wins, its start/end dates are preserved. + + Args: + github_data: Raw fetcher payload; reads "commits" as a list of + {"date": "YYYY-MM-DD", "count": N}. Zero-count entries are ignored. + stored: Optional dict from db.get_user_streak(username). None on first + observation. + """ + entries = github_data.get("commits") or [] + active = set() + for e in entries: + if not isinstance(e, dict): + continue + d = e.get("date") + n = e.get("count") or 0 + if d and n > 0: + active.add(d) + + stored = stored or {} + prior_max = int(stored.get("max_streak", 0) or 0) + prior_max_start = stored.get("max_start", "") or "" + prior_max_end = stored.get("max_end", "") or "" + stored_last = stored.get("last_active_date", "") or "" + + if not active: + return StreakData( + current=0, + max=prior_max, + current_start="", + last_active_date=stored_last, + max_start=prior_max_start, + max_end=prior_max_end, + ) + + today = datetime.utcnow().date() + yesterday = today - timedelta(days=1) + + if today.isoformat() in active: + cursor = today + elif yesterday.isoformat() in active: + cursor = yesterday + else: + cursor = None + + current = 0 + current_start = "" + if cursor is not None: + start = cursor + while start.isoformat() in active: + current += 1 + start -= timedelta(days=1) + current_start = (start + timedelta(days=1)).isoformat() + + sorted_dates = sorted(active) + from datetime import date as _date + max_len = 0 + max_start_iso = "" + max_end_iso = "" + run_start = sorted_dates[0] + run_len = 1 + prev = _date.fromisoformat(run_start) + for ds in sorted_dates[1:]: + cur = _date.fromisoformat(ds) + if (cur - prev).days == 1: + run_len += 1 + else: + if run_len > max_len: + max_len = run_len + max_start_iso = run_start + max_end_iso = prev.isoformat() + run_start = ds + run_len = 1 + prev = cur + if run_len > max_len: + max_len = run_len + max_start_iso = run_start + max_end_iso = prev.isoformat() + + if max_len > prior_max: + merged_max = max_len + merged_start = max_start_iso + merged_end = max_end_iso + else: + merged_max = prior_max + merged_start = prior_max_start + merged_end = prior_max_end + + last_active = sorted_dates[-1] + + return StreakData( + current=current, + max=merged_max, + current_start=current_start, + last_active_date=last_active, + max_start=merged_start, + max_end=merged_end, + ) + + def generate_widgets_from_github( github_data: dict, theme: str = "dark", diff --git a/generator/tests/test_streaks.py b/generator/tests/test_streaks.py new file mode 100644 index 0000000..db7c9a4 --- /dev/null +++ b/generator/tests/test_streaks.py @@ -0,0 +1,108 @@ +from datetime import date, timedelta +from unittest.mock import patch + +import pytest + +from src import processor +from src.models import StreakData + + +TODAY = date(2026, 4, 19) + + +@pytest.fixture +def freeze_today(monkeypatch): + """Pin processor's notion of 'today' so the grace rule is testable.""" + class _FakeDatetime: + @staticmethod + def utcnow(): + from datetime import datetime + return datetime(TODAY.year, TODAY.month, TODAY.day, 12, 0, 0) + monkeypatch.setattr(processor, "datetime", _FakeDatetime) + return TODAY + + +def _days(dates): + """Turn a list of date objects into the fetcher's commits-array shape.""" + return [{"date": d.isoformat(), "count": 1} for d in dates] + + +def test_compute_streaks_empty_preserves_stored_max(freeze_today): + stored = { + "max_streak": 30, "max_start": "2024-06-01", "max_end": "2024-06-30", + "current_streak": 0, "current_start": "", + "last_active_date": "2024-06-30", + } + s = processor.compute_streaks({"commits": []}, stored) + assert s.current == 0 + assert s.max == 30 + assert s.max_start == "2024-06-01" + assert s.max_end == "2024-06-30" + + +def test_compute_streaks_current_today(freeze_today): + dates = [freeze_today - timedelta(days=i) for i in range(5)] + s = processor.compute_streaks({"commits": _days(dates)}, None) + assert s.current == 5 + assert s.current_start == (freeze_today - timedelta(days=4)).isoformat() + assert s.last_active_date == freeze_today.isoformat() + + +def test_compute_streaks_grace_day(freeze_today): + yesterday = freeze_today - timedelta(days=1) + dates = [yesterday - timedelta(days=i) for i in range(4)] + s = processor.compute_streaks({"commits": _days(dates)}, None) + assert s.current == 4 + assert s.current_start == (yesterday - timedelta(days=3)).isoformat() + assert s.last_active_date == yesterday.isoformat() + + +def test_compute_streaks_current_broken(freeze_today): + two_days_ago = freeze_today - timedelta(days=2) + dates = [two_days_ago - timedelta(days=i) for i in range(10)] + s = processor.compute_streaks({"commits": _days(dates)}, None) + assert s.current == 0 + assert s.current_start == "" + assert s.last_active_date == two_days_ago.isoformat() + + +def test_compute_streaks_max_within_window_beats_stored(freeze_today): + start = freeze_today - timedelta(days=30) + dates = [start + timedelta(days=i) for i in range(10)] + stored = { + "max_streak": 5, "max_start": "2020-01-01", "max_end": "2020-01-05", + "current_streak": 0, "current_start": "", "last_active_date": "", + } + s = processor.compute_streaks({"commits": _days(dates)}, stored) + assert s.max == 10 + assert s.max_start == start.isoformat() + assert s.max_end == (start + timedelta(days=9)).isoformat() + + +def test_compute_streaks_stored_max_preserved(freeze_today): + start = freeze_today - timedelta(days=10) + dates = [start + timedelta(days=i) for i in range(3)] + stored = { + "max_streak": 50, "max_start": "2023-04-01", "max_end": "2023-05-20", + "current_streak": 0, "current_start": "", "last_active_date": "", + } + s = processor.compute_streaks({"commits": _days(dates)}, stored) + assert s.max == 50 + assert s.max_start == "2023-04-01" + assert s.max_end == "2023-05-20" + + +def test_compute_streaks_current_equals_new_max(freeze_today): + dates = [freeze_today - timedelta(days=i) for i in range(100)] + s = processor.compute_streaks({"commits": _days(dates)}, None) + assert s.current == 100 + assert s.max == 100 + assert s.max_end == freeze_today.isoformat() + + +def test_compute_streaks_ignores_zero_count_entries(freeze_today): + dates = [freeze_today - timedelta(days=i) for i in range(3)] + commits = _days(dates) + [{"date": (freeze_today - timedelta(days=5)).isoformat(), "count": 0}] + s = processor.compute_streaks({"commits": commits}, None) + assert s.current == 3 + assert s.max == 3