Skip to content

Commit 90d55a9

Browse files
ci: daily Hacktoberfest 2026 prep tracker refresh (cron 11:50 UTC)
Adds .github/workflows/hacktoberfest_prep.yml (schedule: 50 11 * * *) and scripts/hacktoberfest_prep_update.py. Each run: - ticks tracked PR rows in docs/hacktober_2026_prep.md that are now merged/closed (`[ ]` -> `[x]`), - rewrites an 'Automated statistics' section with the current open issue and open PR counts plus the top three directories with the most open 'awaiting reviews' PRs, - exits non-zero once Hacktoberfest 2026 has begun (>= 2026-10-01), so the prep window closing is loud and the job gets retired. Standard library only; uses the Actions GITHUB_TOKEN. Refs #15081.
1 parent 2067ce6 commit 90d55a9

2 files changed

Lines changed: 259 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Daily refresh of the Hacktoberfest 2026 open-PR cleanup tracker.
2+
# Ticks off any tracked pull request that has since been merged/closed, and
3+
# rewrites the "Automated statistics" section (open issue/PR counts + the top
4+
# three `awaiting reviews` directories). The job fails on purpose once
5+
# Hacktoberfest 2026 has begun (>= 2026-10-01), which is the signal to retire it.
6+
name: hacktoberfest_prep
7+
8+
on:
9+
schedule:
10+
- cron: "50 11 * * *" # 11:50 UTC every day
11+
workflow_dispatch: # allow a manual run while testing
12+
13+
permissions:
14+
contents: write
15+
16+
jobs:
17+
hacktoberfest-prep:
18+
# No point running on forks — this pushes to the repo's own docs file.
19+
if: github.repository == 'TheAlgorithms/Python'
20+
runs-on: ubuntu-latest
21+
steps:
22+
- uses: actions/checkout@v7
23+
- uses: actions/setup-python@v7
24+
with:
25+
python-version-file: .python-version
26+
allow-prereleases: true
27+
- name: Update the tracker
28+
id: update
29+
env:
30+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
31+
GITHUB_REPOSITORY: ${{ github.repository }}
32+
# Don't let the intentional post-Oct-1 failure stop the commit step;
33+
# capture the exit code and re-raise it after pushing any changes.
34+
run: |
35+
set +e
36+
python scripts/hacktoberfest_prep_update.py
37+
echo "exit_code=$?" >> "$GITHUB_OUTPUT"
38+
- name: Commit any changes
39+
run: |
40+
git config --global user.name "$GITHUB_ACTOR"
41+
git config --global user.email "$GITHUB_ACTOR@users.noreply.github.com"
42+
git add docs/hacktober_2026_prep.md
43+
git commit -m "chore: refresh Hacktoberfest 2026 prep tracker" || echo "No changes to commit"
44+
git push || echo "Nothing to push"
45+
- name: Propagate the script's exit code
46+
run: exit ${{ steps.update.outputs.exit_code }}
Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
#!/usr/bin/env python3
2+
"""Refresh the Hacktoberfest 2026 open-PR cleanup tracker.
3+
4+
This script is run once a day by the ``hacktoberfest_prep`` GitHub Actions
5+
workflow (see ``.github/workflows/hacktoberfest_prep.yml``). It:
6+
7+
1. Reads ``docs/hacktober_2026_prep.md`` and, for every tracked pull request
8+
that is still an unchecked ``[ ]`` box, checks whether the PR has since
9+
been merged or closed. Resolved rows are ticked (``[ ]`` -> ``[x]``) and
10+
annotated with ``merged`` / ``closed``.
11+
2. Rewrites a machine-generated ``## Automated statistics`` section at the end
12+
of the file with the current number of open issues and open pull requests
13+
and the top three algorithm directories that have the most open pull
14+
requests labelled ``awaiting reviews``.
15+
3. Exits non-zero once Hacktoberfest 2026 has begun (on or after
16+
2026-10-01, UTC), so the prep window closing is loud rather than silent.
17+
18+
It only uses the standard library and the ``GITHUB_TOKEN`` provided by the
19+
Actions runner, so there is nothing to install.
20+
"""
21+
22+
from __future__ import annotations
23+
24+
import datetime as dt
25+
import json
26+
import os
27+
import re
28+
import sys
29+
import time
30+
import urllib.error
31+
import urllib.parse
32+
import urllib.request
33+
34+
REPO = os.environ.get("GITHUB_REPOSITORY", "TheAlgorithms/Python")
35+
TOKEN = os.environ.get("GITHUB_TOKEN", "")
36+
API = "https://api.github.com"
37+
TRACKER = "docs/hacktober_2026_prep.md"
38+
AWAITING_LABEL = "awaiting reviews"
39+
HACKTOBERFEST_START = dt.date(2026, 10, 1)
40+
41+
# A tracked row looks like: ``12. [ ] #15144 awaiting reviews``
42+
ROW_RE = re.compile(
43+
r"^(?P<idx>\d+)\.\s+\[(?P<mark>[ x])\]\s+#(?P<pr>\d+)\b(?P<rest>.*)$"
44+
)
45+
STATS_HEADER = "## Automated statistics"
46+
47+
48+
def _request(url: str) -> tuple[dict | list, dict]:
49+
"""GET ``url`` and return ``(json_body, headers)``, retrying on 403/rate limit."""
50+
headers = {
51+
"Accept": "application/vnd.github+json",
52+
"X-GitHub-Api-Version": "2022-11-28",
53+
"User-Agent": "hacktoberfest-prep-bot",
54+
}
55+
if TOKEN:
56+
headers["Authorization"] = f"Bearer {TOKEN}"
57+
for attempt in range(4):
58+
req = urllib.request.Request(url, headers=headers) # noqa: S310
59+
try:
60+
with urllib.request.urlopen(req, timeout=30) as resp: # noqa: S310
61+
return json.load(resp), dict(resp.headers)
62+
except urllib.error.HTTPError as exc:
63+
remaining = exc.headers.get("X-RateLimit-Remaining")
64+
if exc.code in (403, 429) and remaining == "0":
65+
reset = int(exc.headers.get("X-RateLimit-Reset", "0"))
66+
wait = max(1, reset - int(time.time())) + 1
67+
print(f"Rate limited; sleeping {wait}s", file=sys.stderr)
68+
time.sleep(min(wait, 90))
69+
continue
70+
if exc.code >= 500 and attempt < 3:
71+
time.sleep(2 * (attempt + 1))
72+
continue
73+
raise
74+
msg = f"giving up on {url}"
75+
raise RuntimeError(msg)
76+
77+
78+
def _search_count(query: str) -> int:
79+
url = f"{API}/search/issues?q={urllib.parse.quote(query)}&per_page=1"
80+
body, _ = _request(url)
81+
return int(body.get("total_count", 0)) # type: ignore[union-attr]
82+
83+
84+
def pr_state(number: int) -> str | None:
85+
"""Return ``"merged"`` / ``"closed"`` for a resolved PR, else ``None``."""
86+
body, _ = _request(f"{API}/repos/{REPO}/pulls/{number}")
87+
if body.get("state") == "open": # type: ignore[union-attr]
88+
return None
89+
return "merged" if body.get("merged_at") else "closed" # type: ignore[union-attr]
90+
91+
92+
def top_awaiting_directories(
93+
limit: int = 3, max_prs: int = 400
94+
) -> list[tuple[str, int]]:
95+
"""Count open ``awaiting reviews`` PRs by the top-level directory they touch."""
96+
query = f'repo:{REPO} is:pr is:open label:"{AWAITING_LABEL}"'
97+
counts: dict[str, int] = {}
98+
page = 1
99+
scanned = 0
100+
while scanned < max_prs:
101+
url = (
102+
f"{API}/search/issues?q={urllib.parse.quote(query)}"
103+
f"&per_page=100&page={page}"
104+
)
105+
body, _ = _request(url)
106+
items = body.get("items", []) # type: ignore[union-attr]
107+
if not items:
108+
break
109+
for item in items:
110+
number = item["number"]
111+
files, _ = _request(f"{API}/repos/{REPO}/pulls/{number}/files?per_page=100")
112+
dirs = set()
113+
for changed in files: # type: ignore[union-attr]
114+
parts = changed["filename"].split("/")
115+
if len(parts) > 1 and not parts[0].startswith("."):
116+
dirs.add(parts[0])
117+
for directory in dirs:
118+
counts[directory] = counts.get(directory, 0) + 1
119+
scanned += 1
120+
if scanned >= max_prs:
121+
break
122+
if len(items) < 100:
123+
break
124+
page += 1
125+
ranked = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
126+
return ranked[:limit]
127+
128+
129+
def refresh_checkboxes(lines: list[str]) -> tuple[list[str], int]:
130+
"""Tick rows whose PR is now merged/closed. Returns (new_lines, n_updated)."""
131+
updated = 0
132+
out: list[str] = []
133+
for line in lines:
134+
match = ROW_RE.match(line)
135+
if not match or match.group("mark") == "x":
136+
out.append(line)
137+
continue
138+
state = pr_state(int(match.group("pr")))
139+
if state is None:
140+
out.append(line)
141+
continue
142+
out.append(f"{match.group('idx')}. [x] #{match.group('pr')} {state}")
143+
updated += 1
144+
return out, updated
145+
146+
147+
def build_stats_block() -> str:
148+
open_issues = _search_count(f"repo:{REPO} is:issue is:open")
149+
open_prs = _search_count(f"repo:{REPO} is:pr is:open")
150+
awaiting = _search_count(f'repo:{REPO} is:pr is:open label:"{AWAITING_LABEL}"')
151+
today = dt.datetime.now(dt.UTC).date().isoformat()
152+
top_dirs = top_awaiting_directories()
153+
154+
lines = [
155+
STATS_HEADER,
156+
"",
157+
f"_Generated automatically by "
158+
f"`scripts/hacktoberfest_prep_update.py` on {today} (UTC)._",
159+
"",
160+
f"- **Open issues:** {open_issues}",
161+
f"- **Open pull requests:** {open_prs}",
162+
f"- **Open PRs labelled `{AWAITING_LABEL}`:** {awaiting}",
163+
"",
164+
"**Top three directories to work on** (most open pull requests labelled "
165+
f"`{AWAITING_LABEL}`):",
166+
"",
167+
]
168+
if top_dirs:
169+
for rank, (directory, count) in enumerate(top_dirs, start=1):
170+
plural = "PR" if count == 1 else "PRs"
171+
lines.append(f"{rank}. `{directory}/` — {count} awaiting-reviews {plural}")
172+
else:
173+
lines.append("_No open `awaiting reviews` pull requests found._")
174+
lines.append("")
175+
return "\n".join(lines)
176+
177+
178+
def splice_stats(text: str, stats_block: str) -> str:
179+
idx = text.find(STATS_HEADER)
180+
head = text[:idx].rstrip("\n") if idx != -1 else text.rstrip("\n")
181+
return f"{head}\n\n{stats_block}\n"
182+
183+
184+
def main() -> int:
185+
with open(TRACKER, encoding="utf-8") as handle:
186+
text = handle.read()
187+
188+
body_before_stats = text.split(STATS_HEADER, 1)[0]
189+
lines = body_before_stats.splitlines()
190+
lines, n_updated = refresh_checkboxes(lines)
191+
body = "\n".join(lines)
192+
193+
stats_block = build_stats_block()
194+
new_text = splice_stats(body, stats_block)
195+
196+
with open(TRACKER, "w", encoding="utf-8") as handle:
197+
handle.write(new_text)
198+
199+
print(f"Checked off {n_updated} newly-resolved pull request(s).")
200+
201+
today = dt.datetime.now(dt.UTC).date()
202+
if today >= HACKTOBERFEST_START:
203+
print(
204+
f"Hacktoberfest 2026 has begun ({today} >= {HACKTOBERFEST_START}); "
205+
"the prep window is over — failing on purpose so this job is retired.",
206+
file=sys.stderr,
207+
)
208+
return 1
209+
return 0
210+
211+
212+
if __name__ == "__main__":
213+
raise SystemExit(main())

0 commit comments

Comments
 (0)