Commit 1c92c50334
Unsigned
Layout: unified · split
lib/checks/check-project.py +17 −87
| @@ -7,9 +7,11 @@ import re | |||
| 7 | import sys | 7 | import sys |
| 8 | from datetime import datetime, timedelta, timezone | 8 | from datetime import datetime, timedelta, timezone |
| 9 | 9 | ||
| 10 | import requests | ||
| 11 | import yaml | 10 | import yaml |
| 12 | 11 | ||
| 12 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | ||
| 13 | import utils | ||
| 14 | |||
| 13 | logging.basicConfig( | 15 | logging.basicConfig( |
| 14 | level=logging.INFO, | 16 | level=logging.INFO, |
| 15 | format="%(levelname)s [%(filename)s] %(message)s", | 17 | format="%(levelname)s [%(filename)s] %(message)s", |
| @@ -27,17 +29,13 @@ MIN_STARS = 100 | |||
| 27 | INACTIVE_DAYS = 90 | 29 | INACTIVE_DAYS = 90 |
| 28 | MIN_AGE_DAYS = 120 | 30 | MIN_AGE_DAYS = 120 |
| 29 | AI_COMMIT_RATIO = 0.2 | 31 | AI_COMMIT_RATIO = 0.2 |
| 30 | AI_BOT_AUTHORS = [ | ||
| 31 | "noreply@anthropic.com", | ||
| 32 | "devin-ai-integration[bot]", | ||
| 33 | "copilot-swe-agent.github.com", | ||
| 34 | "noreply@cursor.com", | ||
| 35 | ] | ||
| 36 | SPAM_AWESOME_THRESHOLD = 3 | 32 | SPAM_AWESOME_THRESHOLD = 3 |
| 37 | SPAM_DISTINCT_REPO_THRESHOLD = 7 | 33 | SPAM_DISTINCT_REPO_THRESHOLD = 7 |
| 38 | SPAM_WINDOW_DAYS = 2 | 34 | SPAM_WINDOW_DAYS = 2 |
| 39 | NEW_ACCOUNT_DAYS = 14 | 35 | NEW_ACCOUNT_DAYS = 14 |
| 40 | 36 | ||
| 37 | SESSION = utils.make_session(user_agent=USER_AGENT) | ||
| 38 | |||
| 41 | LINK_MSG = ( | 39 | LINK_MSG = ( |
| 42 | "The link(s) you included seem to be returning a 404." | 40 | "The link(s) you included seem to be returning a 404." |
| 43 | " Please double check all URLs listed are valid and publicly accessible" | 41 | " Please double check all URLs listed are valid and publicly accessible" |
| @@ -107,71 +105,18 @@ def load_diff(path): | |||
| 107 | 105 | ||
| 108 | 106 | ||
| 109 | def check_url(url): | 107 | def check_url(url): |
| 110 | """Return True if the URL is reachable, True on any error (no false positives).""" | 108 | """Return True if the URL is reachable. Transport errors are treated as reachable.""" |
| 111 | try: | 109 | ok, status = utils.check_url(url, SESSION, TIMEOUT) |
| 112 | resp = requests.head( | 110 | if not ok: |
| 113 | url, timeout=TIMEOUT, allow_redirects=True, | 111 | logging.warning("URL check failed for %s (HTTP %d)", url, status) |
| 114 | headers={"User-Agent": USER_AGENT}, | 112 | elif status is None: |
| 115 | ) | 113 | logging.warning("URL check error for %s (unreachable)", url) |
| 116 | if resp.status_code >= 400: | 114 | return ok |
| 117 | resp = requests.get( | ||
| 118 | url, timeout=TIMEOUT, allow_redirects=True, | ||
| 119 | headers={"User-Agent": USER_AGENT}, stream=True, | ||
| 120 | ) | ||
| 121 | resp.close() | ||
| 122 | if resp.status_code >= 400: | ||
| 123 | logging.warning("URL check failed for %s (HTTP %d)", url, resp.status_code) | ||
| 124 | return resp.status_code < 400 | ||
| 125 | except Exception as exc: | ||
| 126 | logging.warning("URL check error for %s: %s", url, exc) | ||
| 127 | return True | ||
| 128 | |||
| 129 | |||
| 130 | def parse_github_field(value): | ||
| 131 | """Parse a github field into (owner, repo), or (None, None) on failure.""" | ||
| 132 | if not value: | ||
| 133 | return None, None | ||
| 134 | if value.startswith("https://github.com/"): | ||
| 135 | parts = value.removeprefix("https://github.com/").strip("/").split("/") | ||
| 136 | if len(parts) >= 2: | ||
| 137 | return parts[0], parts[1] | ||
| 138 | return None, None | ||
| 139 | if "/" in value: | ||
| 140 | parts = value.split("/") | ||
| 141 | if len(parts) == 2: | ||
| 142 | return parts[0], parts[1] | ||
| 143 | return None, None | ||
| 144 | 115 | ||
| 145 | 116 | ||
| 146 | def _gh_get(path, token, params=None, label=""): | 117 | def _gh_get(path, token, params=None, label=""): |
| 147 | """GET a GitHub API endpoint. Returns parsed JSON on 200, None otherwise.""" | 118 | """GET a GitHub API endpoint. Returns parsed JSON on 200, None otherwise.""" |
| 148 | headers = {"Accept": "application/vnd.github.v3+json", "User-Agent": USER_AGENT} | 119 | return utils.gh_get(path, token, session=SESSION, params=params, timeout=TIMEOUT, label=label) |
| 149 | if token: | ||
| 150 | headers["Authorization"] = f"token {token}" | ||
| 151 | try: | ||
| 152 | resp = requests.get( | ||
| 153 | f"https://api.github.com{path}", | ||
| 154 | headers=headers, timeout=TIMEOUT, params=params, | ||
| 155 | ) | ||
| 156 | remaining = resp.headers.get("X-RateLimit-Remaining") | ||
| 157 | if remaining is not None: | ||
| 158 | try: | ||
| 159 | if int(remaining) < 100: | ||
| 160 | logging.warning("[%s] GitHub rate limit low: %s/%s remaining", | ||
| 161 | label, remaining, resp.headers.get("X-RateLimit-Limit")) | ||
| 162 | except ValueError: | ||
| 163 | pass | ||
| 164 | if resp.status_code == 200: | ||
| 165 | return resp.json() | ||
| 166 | logging.warning("[%s] HTTP %d from %s", label, resp.status_code, path) | ||
| 167 | except Exception as exc: | ||
| 168 | logging.warning("[%s] request error for %s: %s", label, path, exc) | ||
| 169 | return None | ||
| 170 | |||
| 171 | |||
| 172 | def fetch_repo(owner, repo, token): | ||
| 173 | """Fetch GitHub repo metadata, returning None on any error.""" | ||
| 174 | return _gh_get(f"/repos/{owner}/{repo}", token, label="repos") | ||
| 175 | 120 | ||
| 176 | 121 | ||
| 177 | def load_yaml_data(): | 122 | def load_yaml_data(): |
| @@ -231,29 +176,14 @@ def check_links(diff, head): | |||
| 231 | return None | 176 | return None |
| 232 | 177 | ||
| 233 | 178 | ||
| 234 | def _commit_has_bot(commit, bot_set): | ||
| 235 | """Check if a commit was authored or co-authored by a known AI bot.""" | ||
| 236 | author = commit.get("commit", {}).get("author", {}) | ||
| 237 | email = (author.get("email") or "").lower() | ||
| 238 | name = (author.get("name") or "").lower() | ||
| 239 | if email in bot_set or name in bot_set: | ||
| 240 | return True | ||
| 241 | message = (commit.get("commit", {}).get("message") or "").lower() | ||
| 242 | for line in message.splitlines(): | ||
| 243 | if line.strip().startswith("co-authored-by:"): | ||
| 244 | if any(bot in line for bot in bot_set): | ||
| 245 | return True | ||
| 246 | return False | ||
| 247 | |||
| 248 | |||
| 249 | def check_ai_commits(owner, repo, token): | 179 | def check_ai_commits(owner, repo, token): |
| 250 | """Return AI_CODE_MSG if recent commits contain significant AI bot activity.""" | 180 | """Return AI_CODE_MSG if recent commits contain significant AI bot activity.""" |
| 251 | commits = _gh_get(f"/repos/{owner}/{repo}/commits", token, | 181 | commits = _gh_get(f"/repos/{owner}/{repo}/commits", token, |
| 252 | params={"per_page": 100}, label="commits") | 182 | params={"per_page": 100}, label="commits") |
| 253 | if not commits: | 183 | if not commits: |
| 254 | return None | 184 | return None |
| 255 | bot_set = {a.lower() for a in AI_BOT_AUTHORS} | 185 | bot_set = {a.lower() for a in utils.AI_BOT_AUTHORS} |
| 256 | count = sum(1 for c in commits if _commit_has_bot(c, bot_set)) | 186 | count = sum(1 for c in commits if utils.commit_has_bot(c, bot_set)) |
| 257 | if count / len(commits) >= AI_COMMIT_RATIO: | 187 | if count / len(commits) >= AI_COMMIT_RATIO: |
| 258 | return AI_CODE_MSG | 188 | return AI_CODE_MSG |
| 259 | return None | 189 | return None |
| @@ -369,12 +299,12 @@ def check_repo_signals(diff, pr_user, token, pr_body=""): | |||
| 369 | cache = {} | 299 | cache = {} |
| 370 | for svc in get_services(diff, "added"): | 300 | for svc in get_services(diff, "added"): |
| 371 | gh = svc.get("fields", {}).get("github") | 301 | gh = svc.get("fields", {}).get("github") |
| 372 | owner, repo = parse_github_field(gh) | 302 | owner, repo = utils.parse_github_field(gh) |
| 373 | if not owner: | 303 | if not owner: |
| 374 | continue | 304 | continue |
| 375 | cache_key = f"{owner}/{repo}" | 305 | cache_key = f"{owner}/{repo}" |
| 376 | if cache_key not in cache: | 306 | if cache_key not in cache: |
| 377 | cache[cache_key] = fetch_repo(owner, repo, token) | 307 | cache[cache_key] = utils.fetch_repo(owner, repo, token, session=SESSION) |
| 378 | data = cache[cache_key] | 308 | data = cache[cache_key] |
| 379 | if not data: | 309 | if not data: |
| 380 | continue | 310 | continue |
lib/review-listings.py +7 −19
| @@ -46,7 +46,6 @@ import signal | |||
| 46 | import sys | 46 | import sys |
| 47 | from concurrent.futures import ThreadPoolExecutor, as_completed | 47 | from concurrent.futures import ThreadPoolExecutor, as_completed |
| 48 | from dataclasses import asdict, dataclass, field | 48 | from dataclasses import asdict, dataclass, field |
| 49 | from datetime import datetime, timezone | ||
| 50 | from threading import Lock | 49 | from threading import Lock |
| 51 | from time import monotonic | 50 | from time import monotonic |
| 52 | from typing import Callable, Iterable | 51 | from typing import Callable, Iterable |
| @@ -140,10 +139,7 @@ def _get_repo(entry: Entry, ctx: Context): | |||
| 140 | with ctx.repo_lock: | 139 | with ctx.repo_lock: |
| 141 | if key in ctx.repo_cache: | 140 | if key in ctx.repo_cache: |
| 142 | return ctx.repo_cache[key] | 141 | return ctx.repo_cache[key] |
| 143 | data = utils.gh_get( | 142 | data = utils.fetch_repo(owner, repo, ctx.token, session=ctx.session) |
| 144 | f"/repos/{owner}/{repo}", ctx.token, ctx.session, | ||
| 145 | timeout=ctx.timeout, label="repos", | ||
| 146 | ) | ||
| 147 | with ctx.repo_lock: | 143 | with ctx.repo_lock: |
| 148 | ctx.repo_cache[key] = data | 144 | ctx.repo_cache[key] = data |
| 149 | return data | 145 | return data |
| @@ -293,8 +289,7 @@ def _github_exists(entry: Entry, ctx: Context) -> Iterable[Finding]: | |||
| 293 | @check("github-archived", needs_github=True) | 289 | @check("github-archived", needs_github=True) |
| 294 | def _github_archived(entry: Entry, ctx: Context) -> Iterable[Finding]: | 290 | def _github_archived(entry: Entry, ctx: Context) -> Iterable[Finding]: |
| 295 | """GitHub repo must not be archived.""" | 291 | """GitHub repo must not be archived.""" |
| 296 | data = _get_repo(entry, ctx) | 292 | if utils.repo_is_archived(_get_repo(entry, ctx)): |
| 297 | if data and data.get("archived"): | ||
| 298 | yield _finding(entry, "github-archived", "error", "repository is archived on GitHub") | 293 | yield _finding(entry, "github-archived", "error", "repository is archived on GitHub") |
| 299 | 294 | ||
| 300 | 295 | ||
| @@ -302,7 +297,7 @@ def _github_archived(entry: Entry, ctx: Context) -> Iterable[Finding]: | |||
| 302 | def _github_fork(entry: Entry, ctx: Context) -> Iterable[Finding]: | 297 | def _github_fork(entry: Entry, ctx: Context) -> Iterable[Finding]: |
| 303 | """GitHub repo should not be a fork.""" | 298 | """GitHub repo should not be a fork.""" |
| 304 | data = _get_repo(entry, ctx) | 299 | data = _get_repo(entry, ctx) |
| 305 | if data and data.get("fork"): | 300 | if utils.repo_is_fork(data): |
| 306 | parent = (data.get("parent") or {}).get("full_name") | 301 | parent = (data.get("parent") or {}).get("full_name") |
| 307 | suffix = f" of {parent}" if parent else "" | 302 | suffix = f" of {parent}" if parent else "" |
| 308 | yield _finding(entry, "github-fork", "warn", f"repository is a fork{suffix}") | 303 | yield _finding(entry, "github-fork", "warn", f"repository is a fork{suffix}") |
| @@ -311,17 +306,10 @@ def _github_fork(entry: Entry, ctx: Context) -> Iterable[Finding]: | |||
| 311 | @check("github-activity", needs_github=True) | 306 | @check("github-activity", needs_github=True) |
| 312 | def _github_activity(entry: Entry, ctx: Context) -> Iterable[Finding]: | 307 | def _github_activity(entry: Entry, ctx: Context) -> Iterable[Finding]: |
| 313 | """GitHub repo has been pushed to recently.""" | 308 | """GitHub repo has been pushed to recently.""" |
| 314 | data = _get_repo(entry, ctx) | 309 | age = utils.repo_pushed_days_ago(_get_repo(entry, ctx)) |
| 315 | pushed = data.get("pushed_at") if data else None | 310 | if age is None: |
| 316 | if not pushed: | ||
| 317 | return | ||
| 318 | try: | ||
| 319 | pushed_dt = datetime.fromisoformat(pushed.replace("Z", "+00:00")) | ||
| 320 | except ValueError: | ||
| 321 | return | 311 | return |
| 322 | age = (datetime.now(timezone.utc) - pushed_dt).days | 312 | if age > ctx.inactive_days * 2: |
| 323 | warn_days = ctx.inactive_days * 2 | ||
| 324 | if age > warn_days: | ||
| 325 | sev = "warn" | 313 | sev = "warn" |
| 326 | elif age > ctx.inactive_days: | 314 | elif age > ctx.inactive_days: |
| 327 | sev = "info" | 315 | sev = "info" |
| @@ -334,7 +322,7 @@ def _github_activity(entry: Entry, ctx: Context) -> Iterable[Finding]: | |||
| 334 | def _github_license(entry: Entry, ctx: Context) -> Iterable[Finding]: | 322 | def _github_license(entry: Entry, ctx: Context) -> Iterable[Finding]: |
| 335 | """GitHub repo must have a declared license.""" | 323 | """GitHub repo must have a declared license.""" |
| 336 | data = _get_repo(entry, ctx) | 324 | data = _get_repo(entry, ctx) |
| 337 | if data and not data.get("license"): | 325 | if data and not utils.repo_has_license(data): |
| 338 | yield _finding(entry, "github-license", "warn", "repository has no declared license") | 326 | yield _finding(entry, "github-license", "warn", "repository has no declared license") |
| 339 | 327 | ||
| 340 | 328 | ||
lib/utils.py deleted −121
| @@ -1,121 +0,0 @@ | |||
| 1 | """Shared helpers for lib/ scripts: YAML loading, HTTP, GitHub API, ANSI colors.""" | ||
| 2 | |||
| 3 | import logging | ||
| 4 | import os | ||
| 5 | import re | ||
| 6 | import sys | ||
| 7 | |||
| 8 | import requests | ||
| 9 | import yaml | ||
| 10 | |||
| 11 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 12 | DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") | ||
| 13 | |||
| 14 | DEFAULT_TIMEOUT = 10 | ||
| 15 | DEFAULT_USER_AGENT = ( | ||
| 16 | "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0" | ||
| 17 | ) | ||
| 18 | |||
| 19 | _COLOR_CODES = {"red": 31, "green": 32, "yellow": 33, "cyan": 36, "bold": 1, "dim": 2} | ||
| 20 | |||
| 21 | |||
| 22 | def setup_logging(level="INFO"): | ||
| 23 | logging.basicConfig( | ||
| 24 | level=getattr(logging, str(level).upper(), logging.INFO), | ||
| 25 | format="%(levelname)s [%(filename)s] %(message)s", | ||
| 26 | stream=sys.stderr, | ||
| 27 | ) | ||
| 28 | |||
| 29 | |||
| 30 | def make_colors(enabled=None): | ||
| 31 | """Return {name: callable(str) -> str}; no-ops when colors disabled.""" | ||
| 32 | if enabled is None: | ||
| 33 | enabled = sys.stderr.isatty() and not os.environ.get("NO_COLOR") | ||
| 34 | if not enabled: | ||
| 35 | return {name: (lambda s: s) for name in _COLOR_CODES} | ||
| 36 | return {name: (lambda s, c=code: f"\033[{c}m{s}\033[0m") for name, code in _COLOR_CODES.items()} | ||
| 37 | |||
| 38 | |||
| 39 | def load_yaml(path=DATA_PATH): | ||
| 40 | with open(path) as f: | ||
| 41 | return yaml.safe_load(f) | ||
| 42 | |||
| 43 | |||
| 44 | def iter_services(data): | ||
| 45 | """Yield (category_name, section_name, service_dict) for every service.""" | ||
| 46 | for cat in data.get("categories", []) or []: | ||
| 47 | cat_name = cat.get("name", "") | ||
| 48 | for sec in cat.get("sections", []) or []: | ||
| 49 | sec_name = sec.get("name", "") | ||
| 50 | for svc in sec.get("services", []) or []: | ||
| 51 | yield cat_name, sec_name, svc | ||
| 52 | |||
| 53 | |||
| 54 | def slugify(title): | ||
| 55 | """Match the slug format used by awesome-privacy.xyz and the README generator.""" | ||
| 56 | if not title: | ||
| 57 | return "" | ||
| 58 | title = re.sub(r"[+&]", "and", title.lower()) | ||
| 59 | title = re.sub(r"\s+", "-", title) | ||
| 60 | return re.sub(r"[^a-z0-9-]", "", title) | ||
| 61 | |||
| 62 | |||
| 63 | def parse_github_field(value): | ||
| 64 | """Parse a `github` field into (owner, repo), or (None, None) on failure.""" | ||
| 65 | if not value: | ||
| 66 | return None, None | ||
| 67 | if value.startswith(("https://github.com/", "http://github.com/")): | ||
| 68 | value = value.split("github.com/", 1)[1] | ||
| 69 | parts = value.strip("/").split("/") | ||
| 70 | if len(parts) >= 2 and parts[0] and parts[1]: | ||
| 71 | return parts[0], parts[1] | ||
| 72 | return None, None | ||
| 73 | |||
| 74 | |||
| 75 | def make_session(user_agent=DEFAULT_USER_AGENT): | ||
| 76 | session = requests.Session() | ||
| 77 | session.headers.update({"User-Agent": user_agent}) | ||
| 78 | return session | ||
| 79 | |||
| 80 | |||
| 81 | def check_url(url, session=None, timeout=DEFAULT_TIMEOUT): | ||
| 82 | """Return (ok, status_code). ok=True for 2xx/3xx; on transport error returns (True, None).""" | ||
| 83 | session = session or make_session() | ||
| 84 | try: | ||
| 85 | resp = session.head(url, timeout=timeout, allow_redirects=True) | ||
| 86 | if resp.status_code >= 400: | ||
| 87 | resp = session.get(url, timeout=timeout, allow_redirects=True, stream=True) | ||
| 88 | resp.close() | ||
| 89 | return resp.status_code < 400, resp.status_code | ||
| 90 | except requests.RequestException as exc: | ||
| 91 | logging.debug("URL check error for %s: %s", url, exc) | ||
| 92 | return True, None | ||
| 93 | |||
| 94 | |||
| 95 | def gh_get(path, token, session=None, params=None, timeout=DEFAULT_TIMEOUT, label=""): | ||
| 96 | """GET https://api.github.com{path}. Returns parsed JSON on 200, else None.""" | ||
| 97 | session = session or make_session() | ||
| 98 | headers = {"Accept": "application/vnd.github.v3+json"} | ||
| 99 | if token: | ||
| 100 | headers["Authorization"] = f"token {token}" | ||
| 101 | try: | ||
| 102 | resp = session.get( | ||
| 103 | f"https://api.github.com{path}", | ||
| 104 | headers=headers, params=params, timeout=timeout, | ||
| 105 | ) | ||
| 106 | except requests.RequestException as exc: | ||
| 107 | logging.warning("[%s] request error for %s: %s", label, path, exc) | ||
| 108 | return None | ||
| 109 | remaining = resp.headers.get("X-RateLimit-Remaining") | ||
| 110 | if remaining is not None: | ||
| 111 | try: | ||
| 112 | if int(remaining) < 50: | ||
| 113 | logging.warning("[%s] GitHub rate limit low: %s/%s remaining", | ||
| 114 | label, remaining, resp.headers.get("X-RateLimit-Limit")) | ||
| 115 | except ValueError: | ||
| 116 | pass | ||
| 117 | if resp.status_code == 200: | ||
| 118 | return resp.json() | ||
| 119 | if resp.status_code != 404: | ||
| 120 | logging.warning("[%s] HTTP %d from %s", label, resp.status_code, path) | ||
| 121 | return None | ||
lib/utils/__init__.py added +41
| @@ -0,0 +1,41 @@ | |||
| 1 | """Shared helpers for lib/ scripts. Re-exports the public API of each submodule.""" | ||
| 2 | |||
| 3 | from .data import DATA_PATH, PROJECT_ROOT, iter_services, load_yaml, slugify | ||
| 4 | from .github import ( | ||
| 5 | AI_BOT_AUTHORS, | ||
| 6 | commit_has_bot, | ||
| 7 | fetch_repo, | ||
| 8 | gh_get, | ||
| 9 | parse_github_field, | ||
| 10 | repo_age_days, | ||
| 11 | repo_has_license, | ||
| 12 | repo_is_archived, | ||
| 13 | repo_is_fork, | ||
| 14 | repo_pushed_days_ago, | ||
| 15 | ) | ||
| 16 | from .http import DEFAULT_TIMEOUT, DEFAULT_USER_AGENT, check_url, make_session | ||
| 17 | from .term import make_colors, setup_logging | ||
| 18 | |||
| 19 | __all__ = [ | ||
| 20 | "AI_BOT_AUTHORS", | ||
| 21 | "DATA_PATH", | ||
| 22 | "DEFAULT_TIMEOUT", | ||
| 23 | "DEFAULT_USER_AGENT", | ||
| 24 | "PROJECT_ROOT", | ||
| 25 | "check_url", | ||
| 26 | "commit_has_bot", | ||
| 27 | "fetch_repo", | ||
| 28 | "gh_get", | ||
| 29 | "iter_services", | ||
| 30 | "load_yaml", | ||
| 31 | "make_colors", | ||
| 32 | "make_session", | ||
| 33 | "parse_github_field", | ||
| 34 | "repo_age_days", | ||
| 35 | "repo_has_license", | ||
| 36 | "repo_is_archived", | ||
| 37 | "repo_is_fork", | ||
| 38 | "repo_pushed_days_ago", | ||
| 39 | "setup_logging", | ||
| 40 | "slugify", | ||
| 41 | ] | ||
lib/utils/data.py added +35
| @@ -0,0 +1,35 @@ | |||
| 1 | """YAML loading, service iteration, slug generation.""" | ||
| 2 | |||
| 3 | import os | ||
| 4 | import re | ||
| 5 | |||
| 6 | import yaml | ||
| 7 | |||
| 8 | PROJECT_ROOT = os.path.dirname( | ||
| 9 | os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | ||
| 10 | ) | ||
| 11 | DATA_PATH = os.path.join(PROJECT_ROOT, "awesome-privacy.yml") | ||
| 12 | |||
| 13 | |||
| 14 | def load_yaml(path=DATA_PATH): | ||
| 15 | with open(path) as f: | ||
| 16 | return yaml.safe_load(f) | ||
| 17 | |||
| 18 | |||
| 19 | def iter_services(data): | ||
| 20 | """Yield (category_name, section_name, service_dict) for every service.""" | ||
| 21 | for cat in data.get("categories", []) or []: | ||
| 22 | cat_name = cat.get("name", "") | ||
| 23 | for sec in cat.get("sections", []) or []: | ||
| 24 | sec_name = sec.get("name", "") | ||
| 25 | for svc in sec.get("services", []) or []: | ||
| 26 | yield cat_name, sec_name, svc | ||
| 27 | |||
| 28 | |||
| 29 | def slugify(title): | ||
| 30 | """Match the slug format used by awesome-privacy.xyz and the README generator.""" | ||
| 31 | if not title: | ||
| 32 | return "" | ||
| 33 | title = re.sub(r"[+&]", "and", title.lower()) | ||
| 34 | title = re.sub(r"\s+", "-", title) | ||
| 35 | return re.sub(r"[^a-z0-9-]", "", title) | ||
lib/utils/github.py added +114
| @@ -0,0 +1,114 @@ | |||
| 1 | """GitHub API helpers and read-only accessors for repo metadata.""" | ||
| 2 | |||
| 3 | import logging | ||
| 4 | from datetime import datetime, timezone | ||
| 5 | |||
| 6 | import requests | ||
| 7 | |||
| 8 | from .http import DEFAULT_TIMEOUT, make_session | ||
| 9 | |||
| 10 | AI_BOT_AUTHORS = [ | ||
| 11 | "noreply@anthropic.com", | ||
| 12 | "devin-ai-integration[bot]", | ||
| 13 | "copilot-swe-agent.github.com", | ||
| 14 | "noreply@cursor.com", | ||
| 15 | ] | ||
| 16 | |||
| 17 | |||
| 18 | def parse_github_field(value): | ||
| 19 | """Parse a `github` field into (owner, repo), or (None, None) on failure.""" | ||
| 20 | if not value: | ||
| 21 | return None, None | ||
| 22 | if value.startswith("https://github.com/"): | ||
| 23 | parts = value.removeprefix("https://github.com/").strip("/").split("/") | ||
| 24 | if len(parts) >= 2 and parts[0] and parts[1]: | ||
| 25 | return parts[0], parts[1] | ||
| 26 | return None, None | ||
| 27 | if "/" in value: | ||
| 28 | parts = value.split("/") | ||
| 29 | if len(parts) == 2 and parts[0] and parts[1]: | ||
| 30 | return parts[0], parts[1] | ||
| 31 | return None, None | ||
| 32 | |||
| 33 | |||
| 34 | def gh_get(path, token, session=None, params=None, timeout=DEFAULT_TIMEOUT, label=""): | ||
| 35 | """GET https://api.github.com{path}. Returns parsed JSON on 200, else None. | ||
| 36 | |||
| 37 | Catches any exception raised during the request or JSON decode, so callers | ||
| 38 | can treat None as a generic failure signal without needing their own guard. | ||
| 39 | """ | ||
| 40 | session = session or make_session() | ||
| 41 | headers = {"Accept": "application/vnd.github.v3+json"} | ||
| 42 | if token: | ||
| 43 | headers["Authorization"] = f"token {token}" | ||
| 44 | try: | ||
| 45 | resp = session.get( | ||
| 46 | f"https://api.github.com{path}", | ||
| 47 | headers=headers, params=params, timeout=timeout, | ||
| 48 | ) | ||
| 49 | remaining = resp.headers.get("X-RateLimit-Remaining") | ||
| 50 | if remaining is not None: | ||
| 51 | try: | ||
| 52 | if int(remaining) < 100: | ||
| 53 | logging.warning("[%s] GitHub rate limit low: %s/%s remaining", | ||
| 54 | label, remaining, resp.headers.get("X-RateLimit-Limit")) | ||
| 55 | except ValueError: | ||
| 56 | pass | ||
| 57 | if resp.status_code == 200: | ||
| 58 | return resp.json() | ||
| 59 | logging.warning("[%s] HTTP %d from %s", label, resp.status_code, path) | ||
| 60 | except Exception as exc: | ||
| 61 | logging.warning("[%s] request error for %s: %s", label, path, exc) | ||
| 62 | return None | ||
| 63 | |||
| 64 | |||
| 65 | def fetch_repo(owner, repo, token, session=None): | ||
| 66 | """Fetch GitHub repo metadata, returning None on any error.""" | ||
| 67 | return gh_get(f"/repos/{owner}/{repo}", token, session=session, label="repos") | ||
| 68 | |||
| 69 | |||
| 70 | def commit_has_bot(commit, bot_set): | ||
| 71 | """Return True if a commit was authored or co-authored by a known AI bot.""" | ||
| 72 | author = commit.get("commit", {}).get("author", {}) | ||
| 73 | email = (author.get("email") or "").lower() | ||
| 74 | name = (author.get("name") or "").lower() | ||
| 75 | if email in bot_set or name in bot_set: | ||
| 76 | return True | ||
| 77 | message = (commit.get("commit", {}).get("message") or "").lower() | ||
| 78 | for line in message.splitlines(): | ||
| 79 | if line.strip().startswith("co-authored-by:"): | ||
| 80 | if any(bot in line for bot in bot_set): | ||
| 81 | return True | ||
| 82 | return False | ||
| 83 | |||
| 84 | |||
| 85 | def _days_since(iso_str): | ||
| 86 | if not iso_str: | ||
| 87 | return None | ||
| 88 | try: | ||
| 89 | dt = datetime.fromisoformat(iso_str.replace("Z", "+00:00")) | ||
| 90 | except (ValueError, AttributeError): | ||
| 91 | return None | ||
| 92 | return (datetime.now(timezone.utc) - dt).days | ||
| 93 | |||
| 94 | |||
| 95 | def repo_is_fork(data): | ||
| 96 | return bool(data and data.get("fork")) | ||
| 97 | |||
| 98 | |||
| 99 | def repo_is_archived(data): | ||
| 100 | return bool(data and data.get("archived")) | ||
| 101 | |||
| 102 | |||
| 103 | def repo_has_license(data): | ||
| 104 | return bool(data and data.get("license")) | ||
| 105 | |||
| 106 | |||
| 107 | def repo_pushed_days_ago(data): | ||
| 108 | """Days since last push, or None if unknown.""" | ||
| 109 | return _days_since(data.get("pushed_at")) if data else None | ||
| 110 | |||
| 111 | |||
| 112 | def repo_age_days(data): | ||
| 113 | """Days since repo creation, or None if unknown.""" | ||
| 114 | return _days_since(data.get("created_at")) if data else None | ||
lib/utils/http.py added +30
| @@ -0,0 +1,30 @@ | |||
| 1 | """HTTP session and URL reachability helpers.""" | ||
| 2 | |||
| 3 | import logging | ||
| 4 | |||
| 5 | import requests | ||
| 6 | |||
| 7 | DEFAULT_TIMEOUT = 10 | ||
| 8 | DEFAULT_USER_AGENT = ( | ||
| 9 | "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0" | ||
| 10 | ) | ||
| 11 | |||
| 12 | |||
| 13 | def make_session(user_agent=DEFAULT_USER_AGENT): | ||
| 14 | session = requests.Session() | ||
| 15 | session.headers.update({"User-Agent": user_agent}) | ||
| 16 | return session | ||
| 17 | |||
| 18 | |||
| 19 | def check_url(url, session=None, timeout=DEFAULT_TIMEOUT): | ||
| 20 | """Return (ok, status_code). ok=True for 2xx/3xx; returns (True, None) on transport error.""" | ||
| 21 | session = session or make_session() | ||
| 22 | try: | ||
| 23 | resp = session.head(url, timeout=timeout, allow_redirects=True) | ||
| 24 | if resp.status_code >= 400: | ||
| 25 | resp = session.get(url, timeout=timeout, allow_redirects=True, stream=True) | ||
| 26 | resp.close() | ||
| 27 | return resp.status_code < 400, resp.status_code | ||
| 28 | except requests.RequestException as exc: | ||
| 29 | logging.debug("URL check error for %s: %s", url, exc) | ||
| 30 | return True, None | ||
lib/utils/term.py added +24
| @@ -0,0 +1,24 @@ | |||
| 1 | """ANSI colors and logging configuration.""" | ||
| 2 | |||
| 3 | import logging | ||
| 4 | import os | ||
| 5 | import sys | ||
| 6 | |||
| 7 | _COLOR_CODES = {"red": 31, "green": 32, "yellow": 33, "cyan": 36, "bold": 1, "dim": 2} | ||
| 8 | |||
| 9 | |||
| 10 | def setup_logging(level="INFO"): | ||
| 11 | logging.basicConfig( | ||
| 12 | level=getattr(logging, str(level).upper(), logging.INFO), | ||
| 13 | format="%(levelname)s [%(filename)s] %(message)s", | ||
| 14 | stream=sys.stderr, | ||
| 15 | ) | ||
| 16 | |||
| 17 | |||
| 18 | def make_colors(enabled=None): | ||
| 19 | """Return {name: callable(str) -> str}; no-ops when colors disabled.""" | ||
| 20 | if enabled is None: | ||
| 21 | enabled = sys.stderr.isatty() and not os.environ.get("NO_COLOR") | ||
| 22 | if not enabled: | ||
| 23 | return {name: (lambda s: s) for name in _COLOR_CODES} | ||
| 24 | return {name: (lambda s, c=code: f"\033[{c}m{s}\033[0m") for name, code in _COLOR_CODES.items()} | ||