1"""GitHub Repository Search & Scraper — Apify Actor.
2
3Uses the official GitHub REST API v3 search endpoint:
4 https://api.github.com/search/repositories
5
6Field shape verified against a live API response. Relevant per-item fields:
7 full_name, name, description, html_url, stargazers_count, forks_count,
8 open_issues_count, language, topics, license{spdx_id,name},
9 owner{login,type,html_url}, created_at, updated_at, pushed_at, homepage,
10 archived, fork, default_branch, size
11NOTE: the search endpoint's watchers_count is an alias of stargazers_count; the
12real subscriber count (subscribers_count) is NOT in search results, so no
13watchers field is emitted.
14
15Paging: GitHub numbers pages by per_page, so every request asks for a full page of
16100 and the last page is cut locally. (Asking for a smaller last page, as earlier
17versions did, made GitHub return rows that were already delivered: maxItems=250
18gave 50 repeated repositories and missed 50.) Rows are also de-duplicated by
19full name, because results can shift between pages while a search runs.
20
21Auth: optional GitHub token. Unauthenticated search is limited to ~10 req/min;
22authenticated is ~30 req/min. When GitHub rate limits the run, the actor waits for
23the reset GitHub announces and carries on. A token GitHub rejects (401) is dropped
24and the run continues unauthenticated. The token is only ever sent to GitHub.
25
26Billing: pay per event, one 'apify-default-dataset-item' per repository pushed
27(charged by the platform). The run stops cleanly at the user's maximum charge, and
28after a restart (the platform moving the run to another server) repositories that
29are already in the dataset are not pushed or charged again.
30"""
31
32from __future__ import annotations
33
34import asyncio
35import calendar
36import re
37import time
38from datetime import date, datetime, timedelta, timezone
39
40import httpx
41try:
42 from . import _tier_prices
43except ImportError:
44 import _tier_prices
45from apify import Actor, Event
46
47SEARCH_URL = "https://api.github.com/search/repositories"
48GITHUB_MAX_RESULTS = 1000
49PAGE_SIZE = 100
50MAX_PAGES = GITHUB_MAX_RESULTS // PAGE_SIZE
51DATASET_EVENT = "apify-default-dataset-item"
52FETCH_ATTEMPTS = 6
53MAX_RATE_WAIT_SECS = 65
54_DATE_RE = re.compile(r"\d{4}-\d{2}-\d{2}")
55
56
57
58
59
60
61def as_text(value, joiner: str = " ") -> str:
62 """A string field that may arrive as None, a number or a list (API and AI-agent callers)."""
63 if value is None or isinstance(value, bool):
64 return ""
65 if isinstance(value, (list, tuple)):
66 parts = [as_text(v, joiner) for v in value]
67 return joiner.join(p for p in parts if p)
68 return str(value).strip()
69
70
71def as_int(value) -> int | None:
72 """An integer field that may arrive as a float or a numeric string."""
73 if value is None or isinstance(value, bool):
74 return None
75 try:
76 return int(float(str(value).strip()))
77 except (TypeError, ValueError):
78 return None
79
80
81_MONTH_RE = re.compile(r"(\d{4})-(\d{1,2})")
82_YEAR_RE = re.compile(r"\d{4}")
83_PERIOD_RE = re.compile(
84 r"[+-]?\s*(?:(?:last|past)\s+)?(\d+)\s*(days?|d|weeks?|w|months?|years?|y)(?:\s+ago)?",
85 re.IGNORECASE,
86)
87
88
89def _months_back(day: date, months: int) -> date:
90 """The same day `months` calendar months earlier, clamped to the end of a shorter month."""
91 index = day.year * 12 + (day.month - 1) - months
92 year, month = divmod(index, 12)
93 month += 1
94 return date(year, month, min(day.day, calendar.monthrange(year, month)[1]))
95
96
97def as_date(value, today: date | None = None) -> str:
98 """YYYY-MM-DD from a date, ISO date-time, YYYY-MM, YYYY or a period like '7 days'; '' if unreadable."""
99 text = as_text(value)
100 match = _DATE_RE.search(text)
101 if match:
102 return match.group(0)
103 text = text.strip().lower()
104 if not text:
105 return ""
106 month = _MONTH_RE.fullmatch(text)
107 if month and 1 <= int(month.group(2)) <= 12:
108 return f"{month.group(1)}-{int(month.group(2)):02d}-01"
109 if _YEAR_RE.fullmatch(text):
110 return f"{text}-01-01"
111 today = today or datetime.now(timezone.utc).date()
112 if text == "today":
113 return today.isoformat()
114 if text == "yesterday":
115 return (today - timedelta(days=1)).isoformat()
116 period = _PERIOD_RE.fullmatch(text)
117 if not period:
118 return ""
119 n, unit = int(period.group(1)), period.group(2)
120 try:
121 if unit.startswith("d"):
122 result = today - timedelta(days=n)
123 elif unit.startswith("w"):
124 result = today - timedelta(weeks=n)
125 elif unit.startswith("m"):
126 result = _months_back(today, n)
127 else:
128 result = _months_back(today, 12 * n)
129 except (ValueError, OverflowError):
130 return ""
131 return result.isoformat()
132
133
134def build_search_q(actor_input: dict) -> str:
135 """Assemble the GitHub search `q` string from structured inputs.
136
137 GitHub uses qualifiers like `language:python stars:>100 topic:cli`.
138 """
139 parts: list[str] = []
140
141 query = as_text(actor_input.get("query"))
142 if query:
143 parts.append(query)
144
145 language = as_text(actor_input.get("language"))
146 if language:
147 parts.append(f"language:{language}" if " " not in language else f'language:"{language}"')
148
149 topic = as_text(actor_input.get("topic"), ",")
150 if topic:
151
152 for t in (x.strip() for x in topic.split(",") if x.strip()):
153 parts.append(f"topic:{t}")
154
155 min_stars = as_int(actor_input.get("minStars"))
156 if min_stars is not None and min_stars > 0:
157 parts.append(f"stars:>={min_stars}")
158
159 user = as_text(actor_input.get("user"))
160 if user:
161
162 user = re.sub(r"^(https?://)?(www\.)?github\.com/", "", user).strip("/@ ").split("/")[0]
163 if user:
164 parts.append(f"user:{user}")
165
166 pushed_after = as_date(actor_input.get("pushedAfter"))
167 if pushed_after:
168 parts.append(f"pushed:>={pushed_after}")
169
170 created_after = as_date(actor_input.get("createdAfter"))
171 if created_after:
172 parts.append(f"created:>={created_after}")
173
174 if actor_input.get("excludeForks"):
175 parts.append("fork:false")
176 if actor_input.get("excludeArchived"):
177 parts.append("archived:false")
178
179 return " ".join(parts).strip()
180
181
182def transform_repo(repo: dict) -> dict:
183 """Convert a raw GitHub repo object into a clean, stable output record."""
184 owner = repo.get("owner") or {}
185 license_info = repo.get("license") or {}
186 return {
187 "fullName": repo.get("full_name"),
188 "name": repo.get("name"),
189 "description": repo.get("description"),
190 "url": repo.get("html_url"),
191 "homepage": repo.get("homepage"),
192 "owner": owner.get("login"),
193 "ownerType": owner.get("type"),
194 "ownerUrl": owner.get("html_url"),
195 "stars": repo.get("stargazers_count"),
196 "forks": repo.get("forks_count"),
197 "openIssues": repo.get("open_issues_count"),
198 "language": repo.get("language"),
199 "topics": repo.get("topics") or [],
200 "license": license_info.get("spdx_id"),
201 "licenseName": license_info.get("name"),
202 "isFork": repo.get("fork"),
203 "isArchived": repo.get("archived"),
204 "defaultBranch": repo.get("default_branch"),
205 "sizeKb": repo.get("size"),
206 "createdAt": repo.get("created_at"),
207 "updatedAt": repo.get("updated_at"),
208 "pushedAt": repo.get("pushed_at"),
209 }
210
211
212
213
214
215
216class QueryRejected(Exception):
217 """GitHub refused the search itself (bad qualifiers and the like). Retrying won't help."""
218
219
220def github_message(resp: httpx.Response) -> str:
221 try:
222 data = resp.json()
223 except ValueError:
224 return resp.text[:300]
225 message = str(data.get("message") or "").strip()
226 details = "; ".join(str(e.get("message") or e) for e in (data.get("errors") or []) if e)
227 return f"{message} ({details})" if details else message
228
229
230def is_rate_limited(resp: httpx.Response) -> bool:
231 if resp.status_code == 429:
232 return True
233 if resp.status_code != 403:
234 return False
235 return (
236 resp.headers.get("x-ratelimit-remaining") == "0"
237 or "retry-after" in resp.headers
238 or "rate limit" in resp.text.lower()
239 )
240
241
242def rate_limit_wait(resp: httpx.Response, attempt: int) -> int:
243 """Seconds to wait, from the headers GitHub sends with a rate-limit response."""
244 wait = None
245 retry_after = as_int(resp.headers.get("retry-after"))
246 reset = as_int(resp.headers.get("x-ratelimit-reset"))
247 if retry_after is not None:
248 wait = retry_after
249 elif reset is not None:
250 wait = reset - int(time.time()) + 1
251 if wait is None or wait <= 0:
252 wait = 10 * attempt
253 return max(1, min(wait, MAX_RATE_WAIT_SECS))
254
255
256class GitHub:
257 def __init__(self, client: httpx.AsyncClient, token: str) -> None:
258 self._client = client
259 self._token = token
260 self.rate_limited = 0
261
262 @property
263 def headers(self) -> dict:
264 return {"Authorization": f"Bearer {self._token}"} if self._token else {}
265
266 async def search(self, params: dict) -> dict | None:
267 """One search page. None when GitHub stays unreachable or rate limited."""
268 for attempt in range(1, FETCH_ATTEMPTS + 1):
269 try:
270 resp = await self._client.get(SEARCH_URL, params=params, headers=self.headers)
271 except httpx.HTTPError as exc:
272 Actor.log.warning(f"Request attempt {attempt} failed: {exc!r}")
273 await asyncio.sleep(min(3 * attempt, 15))
274 continue
275 if resp.status_code == 401 and self._token:
276 Actor.log.warning(
277 "GitHub rejected the token in the input (401 Bad credentials), so the run continues "
278 "without it, at the lower unauthenticated rate limit. Check the token for next time."
279 )
280 self._token = ""
281 continue
282 if is_rate_limited(resp):
283 self.rate_limited += 1
284 wait = rate_limit_wait(resp, attempt)
285 hint = "" if self._token else " Add a free GitHub token in the input to raise the limit."
286 Actor.log.warning(f"GitHub rate limit reached, waiting {wait}s before trying again.{hint}")
287 await asyncio.sleep(wait)
288 continue
289 if resp.status_code == 422:
290 raise QueryRejected(github_message(resp))
291 if resp.status_code >= 500 or resp.status_code in (403, 429):
292 Actor.log.warning(f"GitHub answered HTTP {resp.status_code} on attempt {attempt}, retrying.")
293 await asyncio.sleep(min(3 * attempt, 15))
294 continue
295 if resp.status_code != 200:
296 raise QueryRejected(f"HTTP {resp.status_code}: {github_message(resp)}")
297 try:
298 return resp.json()
299 except ValueError:
300 Actor.log.warning(f"GitHub sent a page that isn't JSON on attempt {attempt}, retrying.")
301 await asyncio.sleep(min(3 * attempt, 15))
302 return None
303
304
305
306
307
308
309def budget_left(pushed_this_run: int) -> int | None:
310 """How many more repositories the user's maximum charge allows; None = no limit.
311 The platform charges the dataset-item event itself and the SDK doesn't count those
312 charges while the run is going, so the items pushed in this run are subtracted."""
313 try:
314 charging = Actor.get_charging_manager()
315 if not charging.get_pricing_info().is_pay_per_event:
316 return None
317 n = charging.calculate_max_event_charge_count_within_limit(DATASET_EVENT)
318 except Exception:
319 return None
320 return None if n is None else max(0, n - pushed_this_run)
321
322
323async def read_delivered() -> set[str]:
324 """Repositories already in this run's dataset (only after a restart)."""
325 names: set[str] = set()
326 dataset = await Actor.open_dataset()
327 offset = 0
328 while True:
329 page = await dataset.get_data(offset=offset, limit=1000)
330 items = page.items or []
331 if not items:
332 break
333 names.update(str(item.get("fullName")) for item in items if item.get("fullName"))
334 offset += len(items)
335 return names
336
337
338
339
340
341
342def startup_info() -> str:
343 """SDK version and whether the Store-discount patch hooked in. Never raises."""
344 try:
345 from importlib.metadata import version
346 sdk = version("apify")
347 except Exception:
348 sdk = "unknown"
349 patched = getattr(_tier_prices, "INSTALLED", None)
350 return f"Startup: apify SDK {sdk}, tier price patch {'hooked in' if patched else 'NOT hooked in' if patched is False else 'unknown'}."
351
352
353async def main() -> None:
354 async with Actor:
355 try:
356 Actor.log.info(startup_info())
357 except Exception:
358 pass
359 try:
360 await run()
361 except Exception as exc:
362 name = type(exc).__name__
363 Actor.log.exception(f"Unexpected error: {name}: {exc}")
364 try:
365 await Actor.set_status_message(
366 f"The run stopped on an unexpected error ({name}). "
367 f"Please report it in the Issues tab with the run link."
368 )
369 except Exception:
370 pass
371 raise
372
373
374async def run() -> None:
375 actor_input = await Actor.get_input() or {}
376
377 sort = as_text(actor_input.get("sort")) or "stars"
378 if sort not in ("stars", "forks", "updated", "best-match"):
379 Actor.log.warning(f"Unknown sort '{sort}', using stars.")
380 sort = "stars"
381 order = as_text(actor_input.get("order")) or "desc"
382 if order not in ("asc", "desc"):
383 order = "desc"
384 max_items = as_int(actor_input.get("maxItems"))
385 if max_items is None or max_items < 1:
386 max_items = 100
387 token = as_text(actor_input.get("githubToken"))
388 token = re.sub(r"^(bearer|token)\s+", "", token, flags=re.I).strip()
389
390 for field in ("pushedAfter", "createdAfter"):
391 raw = as_text(actor_input.get(field))
392 if not raw:
393 continue
394 resolved = as_date(raw)
395 if not resolved:
396 message = (f'Could not read {field} "{raw}". '
397 f"Use a date like 2025-01-31 or a period like 7 days.")
398 Actor.log.error(message)
399 await Actor.set_status_message(message)
400 return
401 Actor.log.info(f'{field} "{raw}" means on or after {resolved}.')
402
403 q = build_search_q(actor_input)
404 if not q:
405 message = "Nothing to search: add a query, language, topic, user or another filter."
406 Actor.log.error(message)
407 await Actor.set_status_message(message)
408 return
409
410 if token:
411 Actor.log.info("Using authenticated GitHub requests (higher rate limit).")
412 else:
413 Actor.log.info(
414 "Running unauthenticated (low rate limit ~10 req/min). "
415 "Add a free GitHub token in the input for a higher limit."
416 )
417
418
419 target = min(max_items, GITHUB_MAX_RESULTS)
420 if max_items > GITHUB_MAX_RESULTS:
421 Actor.log.warning(
422 f"GitHub returns at most {GITHUB_MAX_RESULTS:,} repositories per search, so this run stops "
423 f"there. Narrow the search (language, stars, dates) and run it in parts for more."
424 )
425 Actor.log.info(f"GitHub search q={q!r} sort={sort} order={order} maxItems={target}")
426
427 seen = await read_delivered()
428 if seen:
429 Actor.log.info(
430 f"Continuing this run after a restart: {len(seen):,} repositories are already in the "
431 f"dataset and will not be pushed or charged again."
432 )
433 delivered = len(seen)
434 pushed = 0
435 total_count: int | None = None
436 stop = None
437 progress = {"aborting": False}
438
439 async def on_aborting(_event_data=None):
440 progress["aborting"] = True
441
442 Actor.on(Event.ABORTING, on_aborting)
443
444 headers = {
445 "Accept": "application/vnd.github+json",
446 "User-Agent": "scrapeworks-github-search/0.2",
447 "X-GitHub-Api-Version": "2022-11-28",
448 }
449 async with httpx.AsyncClient(timeout=30.0, headers=headers) as client:
450 github = GitHub(client, token)
451 for page in range(1, MAX_PAGES + 1):
452 if delivered >= target:
453 break
454 if progress["aborting"]:
455 stop = "aborted"
456 break
457 params = {"q": q, "per_page": PAGE_SIZE, "page": page}
458
459 if sort != "best-match":
460 params.update(sort=sort, order=order)
461 try:
462 data = await github.search(params)
463 except QueryRejected as exc:
464 stop = f"rejected: {exc}"
465 break
466 if data is None:
467 stop = "unreachable"
468 break
469
470 if total_count is None:
471 total_count = as_int(data.get("total_count")) or 0
472 Actor.log.info(f"GitHub reports {total_count:,} matching repositories.")
473 if data.get("incomplete_results"):
474 Actor.log.warning(f"GitHub timed out on part of the search for page {page}; it may be incomplete.")
475
476 items = data.get("items") or []
477 rows = []
478 for repo in items:
479 name = repo.get("full_name")
480 if not name or name in seen:
481 continue
482 seen.add(name)
483 rows.append(transform_repo(repo))
484 rows = rows[: target - delivered]
485 left = budget_left(pushed)
486 if left is not None and len(rows) > left:
487 rows = rows[:left]
488 stop = "budget"
489 if rows:
490 await Actor.push_data(rows)
491 pushed += len(rows)
492 delivered += len(rows)
493 Actor.log.info(f"Pushed {delivered}/{target} repositories (page {page}).")
494 await Actor.set_status_message(f"{delivered:,} of {target:,} repositories so far.")
495 if stop:
496 break
497 if len(items) < PAGE_SIZE:
498 break
499 if total_count is not None and page * PAGE_SIZE >= total_count:
500 break
501
502 if stop == "budget":
503 message = (f"Stopped at the maximum charge you set for this run, after {delivered:,} repositories. "
504 f"Raise the maximum charge to get more.")
505 elif stop == "aborted":
506 message = f"Run aborted after {delivered:,} repositories."
507 elif stop and stop.startswith("rejected: "):
508 message = f"GitHub rejected the search, so nothing was charged. GitHub said: {stop[10:]}"
509 elif stop == "unreachable":
510 message = f"GitHub kept refusing requests, so the run stopped after {delivered:,} repositories."
511 if not token:
512 message += " Add a free GitHub token in the input to raise the rate limit."
513 else:
514 message = f"Done: {delivered:,} repositories."
515 if total_count is not None and total_count > delivered and delivered >= GITHUB_MAX_RESULTS:
516 message += (f" GitHub found {total_count:,} matches but returns at most "
517 f"{GITHUB_MAX_RESULTS:,} per search. Narrow the search to get the rest.")
518 elif total_count == 0:
519 message = "Done: GitHub found no repositories for this search."
520 Actor.log.info(message)
521 await Actor.set_status_message(message)