mirror of
https://github.com/ShayManor/github-readme-stats.git
synced 2026-12-02 11:53:48 +05:30
Merge pull request #3 from ShayManor/feat/streaks-widget
Feat/streaks widget
This commit is contained in:
@@ -47,10 +47,10 @@ DATA_SOURCE_TYPE = os.getenv("DATA_SOURCE", "direct")
|
||||
"""Data source type: 'direct' for immediate API calls, 'queued' for batch processing."""
|
||||
|
||||
# Widget settings
|
||||
WIDGET_ORDER = ["grade", "impact", "collaborators", "focus", "languages", "achievements"]
|
||||
WIDGET_ORDER = ["grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"]
|
||||
"""Default order of widgets. Customize by reordering this list."""
|
||||
|
||||
ENABLED_WIDGETS = ["grade", "impact", "collaborators", "focus", "languages", "achievements"]
|
||||
ENABLED_WIDGETS = ["grade", "impact", "streaks", "collaborators", "focus", "languages", "achievements"]
|
||||
"""Which widgets to display. Remove any you don't want to show."""
|
||||
|
||||
# Language filtering
|
||||
|
||||
@@ -44,6 +44,16 @@ CREATE TABLE IF NOT EXISTS jobs (
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_jobs_pending ON jobs(status, created_at);
|
||||
CREATE TABLE IF NOT EXISTS user_streaks (
|
||||
username TEXT PRIMARY KEY,
|
||||
current_streak INTEGER NOT NULL DEFAULT 0,
|
||||
current_start TEXT NOT NULL DEFAULT '',
|
||||
last_active_date TEXT NOT NULL DEFAULT '',
|
||||
max_streak INTEGER NOT NULL DEFAULT 0,
|
||||
max_start TEXT NOT NULL DEFAULT '',
|
||||
max_end TEXT NOT NULL DEFAULT '',
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
|
||||
_WIDGETS_SCHEMA = """
|
||||
@@ -253,6 +263,56 @@ def set_last_fetcher_hash(username: str, h: str) -> None:
|
||||
c.commit()
|
||||
|
||||
|
||||
def get_user_streak(username: str) -> Optional[dict]:
|
||||
"""Return the persisted streak row for a user, or None if never written."""
|
||||
with _settings_conn() as c:
|
||||
row = c.execute(
|
||||
"SELECT * FROM user_streaks WHERE username=?", (username,)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return {
|
||||
"current_streak": row["current_streak"],
|
||||
"current_start": row["current_start"],
|
||||
"last_active_date": row["last_active_date"],
|
||||
"max_streak": row["max_streak"],
|
||||
"max_start": row["max_start"],
|
||||
"max_end": row["max_end"],
|
||||
"updated_at": row["updated_at"],
|
||||
}
|
||||
|
||||
|
||||
def put_user_streak(username: str, streak: dict) -> None:
|
||||
"""UPSERT the streak row for a user. Caller supplies the merged values."""
|
||||
now = _now()
|
||||
with _settings_conn() as c:
|
||||
c.execute(
|
||||
"""INSERT INTO user_streaks(
|
||||
username, current_streak, current_start, last_active_date,
|
||||
max_streak, max_start, max_end, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(username) DO UPDATE SET
|
||||
current_streak=excluded.current_streak,
|
||||
current_start=excluded.current_start,
|
||||
last_active_date=excluded.last_active_date,
|
||||
max_streak=excluded.max_streak,
|
||||
max_start=excluded.max_start,
|
||||
max_end=excluded.max_end,
|
||||
updated_at=excluded.updated_at""",
|
||||
(
|
||||
username,
|
||||
int(streak.get("current_streak", 0)),
|
||||
streak.get("current_start", ""),
|
||||
streak.get("last_active_date", ""),
|
||||
int(streak.get("max_streak", 0)),
|
||||
streak.get("max_start", ""),
|
||||
streak.get("max_end", ""),
|
||||
now,
|
||||
),
|
||||
)
|
||||
c.commit()
|
||||
|
||||
|
||||
def set_github_profile(username: str, github_id: int, github_avatar_url: str) -> None:
|
||||
with _settings_conn() as c:
|
||||
c.execute(
|
||||
|
||||
@@ -8,6 +8,7 @@ from .types import (
|
||||
FocusCategory,
|
||||
LanguageData,
|
||||
AchievementData,
|
||||
StreakData,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
@@ -18,4 +19,5 @@ __all__ = [
|
||||
"FocusCategory",
|
||||
"LanguageData",
|
||||
"AchievementData",
|
||||
"StreakData",
|
||||
]
|
||||
|
||||
@@ -56,3 +56,13 @@ class AchievementData:
|
||||
subtitle: str = ""
|
||||
event_date: str = ""
|
||||
icon: str = "trophy" # trophy, medal, star, hackathon
|
||||
|
||||
|
||||
@dataclass
|
||||
class StreakData:
|
||||
current: int = 0 # consecutive days ending today (or yesterday under grace)
|
||||
max: int = 0 # all-time longest observed streak
|
||||
current_start: str = "" # ISO date the current streak started, "" if current == 0
|
||||
last_active_date: str = "" # most recent date with contributions in the window
|
||||
max_start: str = "" # ISO date the max streak started (best-effort)
|
||||
max_end: str = "" # ISO date the max streak ended (best-effort)
|
||||
|
||||
@@ -11,6 +11,7 @@ from .models import (
|
||||
FocusCategory,
|
||||
LanguageData,
|
||||
AchievementData,
|
||||
StreakData,
|
||||
)
|
||||
from .widgets import (
|
||||
render_grade_widget,
|
||||
@@ -19,6 +20,7 @@ from .widgets import (
|
||||
render_focus_widget,
|
||||
render_languages_widget,
|
||||
render_achievements_widget,
|
||||
render_streaks_widget,
|
||||
)
|
||||
|
||||
|
||||
@@ -533,6 +535,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",
|
||||
@@ -541,6 +652,7 @@ def generate_widgets_from_github(
|
||||
enabled: list[str] = None,
|
||||
widget_settings: dict[str, dict] | None = None,
|
||||
achievements: list[dict] | None = None,
|
||||
stored_streak: dict | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""
|
||||
Takes raw GitHub API data and returns rendered SVG strings
|
||||
@@ -555,6 +667,8 @@ def generate_widgets_from_github(
|
||||
Defaults to ENABLED_WIDGETS from config.
|
||||
widget_settings: Optional per-widget settings dict, keyed by widget name.
|
||||
Each value is a dict of settings for that widget's renderer.
|
||||
stored_streak: Optional dict from db.get_user_streak(username); carries
|
||||
the all-time longest streak forward across refreshes.
|
||||
"""
|
||||
from .config import ENABLED_WIDGETS
|
||||
|
||||
@@ -585,6 +699,10 @@ def generate_widgets_from_github(
|
||||
languages = compute_languages(github_data, hidden_languages=hidden_languages)
|
||||
widgets["languages"] = render_languages_widget(languages, theme, settings=ws.get("languages"))
|
||||
|
||||
if "streaks" in enabled_set:
|
||||
streak = compute_streaks(github_data, stored_streak)
|
||||
widgets["streaks"] = render_streaks_widget(streak, theme, settings=ws.get("streaks"))
|
||||
|
||||
if "achievements" in enabled_set:
|
||||
# User-authored content — no GitHub data involved.
|
||||
raw = [a for a in (achievements or []) if (a.get("title") or "").strip()]
|
||||
|
||||
@@ -6,6 +6,7 @@ from .collaborators import render_collaborators_widget
|
||||
from .focus import render_focus_widget
|
||||
from .languages import render_languages_widget
|
||||
from .achievements import render_achievements_widget
|
||||
from .streaks import render_streaks_widget
|
||||
from .composite import compose_widget
|
||||
|
||||
__all__ = [
|
||||
@@ -15,5 +16,6 @@ __all__ = [
|
||||
"render_focus_widget",
|
||||
"render_languages_widget",
|
||||
"render_achievements_widget",
|
||||
"render_streaks_widget",
|
||||
"compose_widget",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Streaks widget rendering."""
|
||||
|
||||
from datetime import date
|
||||
from ..models import StreakData
|
||||
from ..themes import THEMES
|
||||
from ..utils import escape, card_wrapper
|
||||
|
||||
|
||||
_FLAME_SVG = (
|
||||
'<path d="M12 2c1 4 5 5 5 10a5 5 0 1 1-10 0c0-2 1-3 2-4 0 1 1 2 2 2 '
|
||||
'-1-2 0-5 1-8z" fill="{color}" opacity="0.95"/>'
|
||||
)
|
||||
|
||||
_TROPHY_SVG = (
|
||||
'<path d="M6 3h12v3a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V3z" fill="none" '
|
||||
'stroke="{color}" stroke-width="1.6"/>'
|
||||
'<path d="M4 4h2v2a2 2 0 0 1-2 2H3V5a1 1 0 0 1 1-1zM20 4h-2v2a2 2 0 0 0 2 '
|
||||
'2h1V5a1 1 0 0 0-1-1z" fill="none" stroke="{color}" stroke-width="1.4"/>'
|
||||
'<rect x="9" y="11" width="6" height="3" fill="{color}"/>'
|
||||
'<rect x="7" y="14" width="10" height="2" rx="0.5" fill="{color}"/>'
|
||||
)
|
||||
|
||||
|
||||
def _fmt_date(iso: str) -> str:
|
||||
if not iso:
|
||||
return ""
|
||||
try:
|
||||
d = date.fromisoformat(iso)
|
||||
except ValueError:
|
||||
return ""
|
||||
return d.strftime("%b %d, %Y")
|
||||
|
||||
|
||||
def _fmt_range(start: str, end: str) -> str:
|
||||
s = _fmt_date(start)
|
||||
e = _fmt_date(end)
|
||||
if s and e:
|
||||
return f"{s} – {e}"
|
||||
return s or e
|
||||
|
||||
|
||||
def render_streaks_widget(
|
||||
data: StreakData,
|
||||
theme_name: str = "dark",
|
||||
settings: dict | None = None,
|
||||
) -> str:
|
||||
"""Render the streaks widget.
|
||||
|
||||
Settings:
|
||||
show_dates (bool): Show date captions below each number. Default True.
|
||||
"""
|
||||
t = THEMES[theme_name]
|
||||
s = settings or {}
|
||||
show_dates = bool(s.get("show_dates", True))
|
||||
|
||||
width = 380
|
||||
height = 170
|
||||
col_w = width / 2
|
||||
|
||||
current_color = t["accent"]
|
||||
max_color = t.get("text", "#e6e6e6")
|
||||
|
||||
current_sub = _fmt_date(data.current_start) if data.current_start else "—"
|
||||
max_sub = _fmt_range(data.max_start, data.max_end) if (data.max_start or data.max_end) else ""
|
||||
|
||||
date_lines = ""
|
||||
if show_dates:
|
||||
date_lines = f'''
|
||||
<text x="{col_w / 2}" y="130" text-anchor="middle"
|
||||
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="9" fill="{t["text_secondary"]}">{escape("since " + current_sub) if data.current > 0 else ""}</text>
|
||||
<text x="{col_w + col_w / 2}" y="130" text-anchor="middle"
|
||||
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="9" fill="{t["text_secondary"]}">{escape(max_sub)}</text>'''
|
||||
|
||||
inner = f'''
|
||||
<g transform="translate({col_w / 2 - 12}, 14)">{_FLAME_SVG.format(color=current_color)}</g>
|
||||
<text x="{col_w / 2}" y="78" text-anchor="middle"
|
||||
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="40" font-weight="800" fill="{current_color}">{data.current}</text>
|
||||
<text x="{col_w / 2}" y="108" text-anchor="middle"
|
||||
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="11" fill="{t["text_secondary"]}" letter-spacing="0.5">Current Streak</text>
|
||||
|
||||
<line x1="{col_w}" y1="24" x2="{col_w}" y2="{height - 24 - 36}" stroke="{t["grid"]}" stroke-width="1"/>
|
||||
|
||||
<g transform="translate({col_w + col_w / 2 - 12}, 14)">{_TROPHY_SVG.format(color=max_color)}</g>
|
||||
<text x="{col_w + col_w / 2}" y="78" text-anchor="middle"
|
||||
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="40" font-weight="800" fill="{max_color}">{data.max}</text>
|
||||
<text x="{col_w + col_w / 2}" y="108" text-anchor="middle"
|
||||
font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif"
|
||||
font-size="11" fill="{t["text_secondary"]}" letter-spacing="0.5">Longest Streak</text>
|
||||
{date_lines}'''
|
||||
|
||||
return card_wrapper(inner, width, height, t, "")
|
||||
+20
-3
@@ -24,16 +24,31 @@ log = logging.getLogger("generator.worker")
|
||||
MAX_ATTEMPTS = 3
|
||||
|
||||
|
||||
def _compute_widget_data(payload: dict, settings: dict) -> dict:
|
||||
"""Compute raw widget data dict for client-side rendering."""
|
||||
def _compute_widget_data(payload: dict, settings: dict, username: str) -> dict:
|
||||
"""Compute raw widget data dict for client-side rendering.
|
||||
|
||||
Also persists the user's streak state as a side effect — the longest streak
|
||||
must survive settings-hash rotations, so it lives outside widget_data.
|
||||
"""
|
||||
custom_tags = settings.get("custom_tags")
|
||||
hidden_languages = settings.get("hidden_languages")
|
||||
stored_streak = db.get_user_streak(username)
|
||||
streak = processor.compute_streaks(payload, stored_streak)
|
||||
db.put_user_streak(username, {
|
||||
"current_streak": streak.current,
|
||||
"current_start": streak.current_start,
|
||||
"last_active_date": streak.last_active_date,
|
||||
"max_streak": streak.max,
|
||||
"max_start": streak.max_start,
|
||||
"max_end": streak.max_end,
|
||||
})
|
||||
return {
|
||||
"grade": asdict(processor.compute_grade(payload, custom_tags=custom_tags)),
|
||||
"impact": [asdict(w) for w in processor.compute_impact_timeline(payload)],
|
||||
"collaborators": [asdict(c) for c in processor.compute_collaborators(payload)],
|
||||
"focus": [asdict(f) for f in processor.compute_focus(payload, hidden_languages=hidden_languages)],
|
||||
"languages": [asdict(l) for l in processor.compute_languages(payload, hidden_languages=hidden_languages)],
|
||||
"streaks": asdict(streak),
|
||||
}
|
||||
|
||||
|
||||
@@ -41,6 +56,7 @@ def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, s
|
||||
enabled = settings.get("enabled") or config.ENABLED_WIDGETS
|
||||
order = settings.get("widget_order") or config.WIDGET_ORDER
|
||||
theme = settings.get("theme", "dark")
|
||||
stored_streak = db.get_user_streak(username)
|
||||
widgets = processor.generate_widgets_from_github(
|
||||
payload,
|
||||
theme=theme,
|
||||
@@ -49,6 +65,7 @@ def _render_widgets(username: str, payload: dict, settings: dict) -> dict[str, s
|
||||
enabled=enabled,
|
||||
widget_settings=settings.get("widget_settings") or {},
|
||||
achievements=settings.get("achievements") or [],
|
||||
stored_streak=stored_streak,
|
||||
)
|
||||
ordered = [w for w in order if w in enabled and w in widgets and widgets[w]]
|
||||
composite = compose_widget(
|
||||
@@ -81,7 +98,7 @@ def process_one() -> bool:
|
||||
db.fail_job(job["id"], "settings missing", retry=False)
|
||||
return True
|
||||
|
||||
widget_data = _compute_widget_data(payload, settings_row["settings"])
|
||||
widget_data = _compute_widget_data(payload, settings_row["settings"], username)
|
||||
db.put_widget_data(username, settings_row["settings_hash"], widget_data)
|
||||
db.point_current_widget(username, settings_row["settings_hash"])
|
||||
db.set_last_fetcher_hash(username, result.get("payload_hash", ""))
|
||||
|
||||
@@ -110,3 +110,43 @@ def test_set_github_profile_round_trip(tmp_dbs):
|
||||
row = c.execute("SELECT github_id, github_avatar_url FROM users WHERE username='alice'").fetchone()
|
||||
assert row["github_id"] == 42
|
||||
assert row["github_avatar_url"] == "https://example.com/a.png"
|
||||
|
||||
|
||||
def test_get_user_streak_missing_returns_none(tmp_dbs):
|
||||
assert dbmod.get_user_streak("nobody") is None
|
||||
|
||||
|
||||
def test_put_and_get_user_streak_roundtrip(tmp_dbs):
|
||||
dbmod.put_user_streak("alice", {
|
||||
"current_streak": 12,
|
||||
"current_start": "2026-04-08",
|
||||
"last_active_date": "2026-04-19",
|
||||
"max_streak": 42,
|
||||
"max_start": "2025-11-01",
|
||||
"max_end": "2025-12-12",
|
||||
})
|
||||
row = dbmod.get_user_streak("alice")
|
||||
assert row["current_streak"] == 12
|
||||
assert row["current_start"] == "2026-04-08"
|
||||
assert row["last_active_date"] == "2026-04-19"
|
||||
assert row["max_streak"] == 42
|
||||
assert row["max_start"] == "2025-11-01"
|
||||
assert row["max_end"] == "2025-12-12"
|
||||
assert row["updated_at"] # set on write
|
||||
|
||||
|
||||
def test_put_user_streak_upserts(tmp_dbs):
|
||||
dbmod.put_user_streak("alice", {
|
||||
"current_streak": 1, "current_start": "2026-04-19",
|
||||
"last_active_date": "2026-04-19",
|
||||
"max_streak": 1, "max_start": "2026-04-19", "max_end": "2026-04-19",
|
||||
})
|
||||
dbmod.put_user_streak("alice", {
|
||||
"current_streak": 2, "current_start": "2026-04-18",
|
||||
"last_active_date": "2026-04-19",
|
||||
"max_streak": 5, "max_start": "2024-01-01", "max_end": "2024-01-05",
|
||||
})
|
||||
row = dbmod.get_user_streak("alice")
|
||||
assert row["current_streak"] == 2
|
||||
assert row["max_streak"] == 5
|
||||
assert row["max_start"] == "2024-01-01"
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
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
|
||||
|
||||
|
||||
from src.widgets import render_streaks_widget
|
||||
|
||||
|
||||
def test_render_streaks_contains_values():
|
||||
data = StreakData(
|
||||
current=7, max=42,
|
||||
current_start="2026-04-13", last_active_date="2026-04-19",
|
||||
max_start="2024-03-01", max_end="2024-04-11",
|
||||
)
|
||||
svg = render_streaks_widget(data, theme_name="dark")
|
||||
assert svg.startswith("<svg")
|
||||
assert "</svg>" in svg
|
||||
assert ">7<" in svg
|
||||
assert ">42<" in svg
|
||||
assert "Current" in svg
|
||||
assert "Longest" in svg
|
||||
|
||||
|
||||
def test_render_streaks_zero_values_render():
|
||||
data = StreakData(current=0, max=0)
|
||||
svg = render_streaks_widget(data, theme_name="dark")
|
||||
assert ">0<" in svg
|
||||
assert "Current" in svg
|
||||
assert "Longest" in svg
|
||||
|
||||
|
||||
def test_render_streaks_hides_dates_when_disabled():
|
||||
data = StreakData(
|
||||
current=7, max=42,
|
||||
current_start="2026-04-13", last_active_date="2026-04-19",
|
||||
max_start="2024-03-01", max_end="2024-04-11",
|
||||
)
|
||||
svg = render_streaks_widget(data, theme_name="dark", settings={"show_dates": False})
|
||||
assert "2026-04-13" not in svg
|
||||
assert "2024-03-01" not in svg
|
||||
|
||||
|
||||
def test_generate_widgets_includes_streaks_when_enabled(freeze_today):
|
||||
from datetime import timedelta
|
||||
dates = [freeze_today - timedelta(days=i) for i in range(4)]
|
||||
payload = {
|
||||
"user": {"login": "alice"},
|
||||
"repos": [],
|
||||
"events": [],
|
||||
"commits": _days(dates),
|
||||
"total_commits": 4, "recent_commits": 4, "total_prs": 0,
|
||||
"collaborators_data": [],
|
||||
}
|
||||
widgets = processor.generate_widgets_from_github(
|
||||
payload, theme="dark", enabled=["streaks"],
|
||||
)
|
||||
assert "streaks" in widgets
|
||||
assert ">4<" in widgets["streaks"]
|
||||
|
||||
|
||||
def test_generate_widgets_uses_stored_streak(freeze_today):
|
||||
payload = {
|
||||
"user": {"login": "alice"}, "repos": [], "events": [],
|
||||
"commits": [],
|
||||
"total_commits": 0, "recent_commits": 0, "total_prs": 0,
|
||||
"collaborators_data": [],
|
||||
}
|
||||
stored = {
|
||||
"max_streak": 99, "max_start": "2022-01-01", "max_end": "2022-04-09",
|
||||
"current_streak": 0, "current_start": "", "last_active_date": "",
|
||||
}
|
||||
widgets = processor.generate_widgets_from_github(
|
||||
payload, theme="dark", enabled=["streaks"], stored_streak=stored,
|
||||
)
|
||||
assert ">99<" in widgets["streaks"]
|
||||
@@ -79,3 +79,58 @@ def test_worker_marks_failed_after_max_attempts(tmp_dbs):
|
||||
row = c.execute("SELECT status, attempts FROM jobs WHERE username='alice'").fetchone()
|
||||
assert row["status"] == "failed"
|
||||
assert row["attempts"] >= 3
|
||||
|
||||
|
||||
def test_process_one_persists_streak(tmp_dbs):
|
||||
"""Phase 1 worker must compute and persist the user's streak so max survives
|
||||
future settings changes."""
|
||||
from datetime import date, timedelta
|
||||
|
||||
today = date.today()
|
||||
dates = [today - timedelta(days=i) for i in range(3)]
|
||||
dbmod.enroll("alice", {"theme": "dark", "enabled": ["streaks"]})
|
||||
fake_payload = {
|
||||
"user": {"login": "alice"}, "repos": [], "events": [],
|
||||
"commits": [{"date": d.isoformat(), "count": 1} for d in dates],
|
||||
"total_commits": 3, "recent_commits": 3, "total_prs": 0,
|
||||
"collaborators_data": [], "avatar_b64": "",
|
||||
}
|
||||
with patch("src.worker.fetcher_client.get_data",
|
||||
return_value={"data": fake_payload, "payload_hash": "h1"}):
|
||||
worker.process_one()
|
||||
|
||||
row = dbmod.get_user_streak("alice")
|
||||
assert row is not None
|
||||
assert row["current_streak"] == 3
|
||||
assert row["max_streak"] == 3
|
||||
assert row["last_active_date"] == today.isoformat()
|
||||
|
||||
|
||||
def test_process_one_merges_stored_max(tmp_dbs):
|
||||
"""A stored max of 50 must survive a refresh whose window max is only 2."""
|
||||
from datetime import date, timedelta
|
||||
|
||||
today = date.today()
|
||||
dbmod.enroll("alice", {"theme": "dark", "enabled": ["streaks"]})
|
||||
dbmod.put_user_streak("alice", {
|
||||
"current_streak": 0, "current_start": "",
|
||||
"last_active_date": "2023-01-15",
|
||||
"max_streak": 50,
|
||||
"max_start": "2023-01-01", "max_end": "2023-02-19",
|
||||
})
|
||||
|
||||
dates = [today - timedelta(days=i) for i in range(2)]
|
||||
fake_payload = {
|
||||
"user": {"login": "alice"}, "repos": [], "events": [],
|
||||
"commits": [{"date": d.isoformat(), "count": 1} for d in dates],
|
||||
"total_commits": 2, "recent_commits": 2, "total_prs": 0,
|
||||
"collaborators_data": [], "avatar_b64": "",
|
||||
}
|
||||
with patch("src.worker.fetcher_client.get_data",
|
||||
return_value={"data": fake_payload, "payload_hash": "h1"}):
|
||||
worker.process_one()
|
||||
|
||||
row = dbmod.get_user_streak("alice")
|
||||
assert row["max_streak"] == 50
|
||||
assert row["max_start"] == "2023-01-01"
|
||||
assert row["current_streak"] == 2
|
||||
|
||||
Reference in New Issue
Block a user