Skip to content

The definitive list of the best of (consumer facing) open source.

Switched to graphql github api

Lucas31472210b260
diff --git a/core/source/maintenance/backlog_updator.py b/core/source/maintenance/backlog_updator.py
index 09c6c2b..6d637b3 100644
--- a/core/source/maintenance/backlog_updator.py
+++ b/core/source/maintenance/backlog_updator.py
@@ -9,6 +9,8 @@ if str(CORE_DIR) not in sys.path:
from source.utils.github_utils import ( # noqa: E402
extract_repo_path,
fetch_repo_summary,
+ fetch_repos_batch,
+ format_commit_date,
get_github_headers,
get_github_token,
)
@@ -44,6 +46,14 @@ def generate_backlog(
applications = data.get("applications", [])
total = len(applications)
+
+ repo_paths = [
+ extract_repo_path(app.get("repo_url", ""))
+ for app in applications
+ if extract_repo_path(app.get("repo_url", ""))
+ ]
+ batch_results = fetch_repos_batch(repo_paths, token=token, headers=headers)
+
generated_apps = []
for idx, app in enumerate(applications, 1):
@@ -55,8 +65,11 @@ def generate_backlog(
stars = 0
repo_path = extract_repo_path(repo_url)
- if repo_path:
- print(f"[{idx}/{total}] Fetching {name} ({repo_path})...")
+ if repo_path and repo_path in batch_results and batch_results[repo_path]:
+ repo_data = batch_results[repo_path]
+ stars = repo_data.get("stargazers_count", 0)
+ last_commit = format_commit_date(repo_data.get("pushed_at"))
+ elif repo_path:
last_commit, stars = fetch_repo_summary(repo_path, headers)
else:
print(
diff --git a/core/source/maintenance/stats_updator.py b/core/source/maintenance/stats_updator.py
index be80f09..1ee79f9 100644
--- a/core/source/maintenance/stats_updator.py
+++ b/core/source/maintenance/stats_updator.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import json
from pathlib import Path
import sys
@@ -9,21 +11,28 @@ if str(CORE_DIR) not in sys.path:
from source.utils.github_utils import ( # noqa: E402
extract_repo_path,
fetch_repo_data,
+ fetch_repos_batch,
format_commit_date,
get_github_headers,
get_github_token,
)
-def update_application_data(app: dict, headers: dict) -> dict:
+def update_application_data(
+ app: dict,
+ headers: dict | None = None,
+ repo_data: dict | None = None,
+ fallback_app: dict | None = None,
+) -> dict:
repo_url = app.get("repo_url", "")
repo_name = extract_repo_path(repo_url)
if not repo_name:
print(f"Skipping {app.get('name', 'Unknown')}: Invalid GitHub URL ({repo_url})")
return app
- print(f"Updating: {repo_name}")
- repo_data = fetch_repo_data(repo_name, headers=headers)
+ if repo_data is None and headers is not None:
+ print(f"Updating: {repo_name}")
+ repo_data = fetch_repo_data(repo_name, headers=headers)
if repo_data is not None:
app["stars"] = repo_data.get("stargazers_count", app.get("stars", 0))
@@ -54,12 +63,25 @@ def update_application_data(app: dict, headers: dict) -> dict:
return app
else:
+ # If fetch failed but fallback_app exists, preserve previous dynamic values
+ if fallback_app:
+ for field in [
+ "stars",
+ "language",
+ "homepage_url",
+ "description",
+ "license",
+ "last_commit",
+ ]:
+ if (field not in app or not app.get(field)) and fallback_app.get(field):
+ app[field] = fallback_app[field]
return app
def update_all_applications(
input_file: Path | str | None = None,
output_file: Path | str | None = None,
+ batch_size: int = 100,
) -> dict:
if input_file is None:
input_path = Path("data/static/applications.json")
@@ -83,12 +105,52 @@ def update_all_applications(
)
headers = get_github_headers(token)
+ # Load fallback cache from existing generated file to avoid data loss on failures
+ existing_lookup: dict[str, dict] = {}
+ if output_path.exists():
+ try:
+ with open(output_path, "r", encoding="utf-8") as f:
+ existing_data = json.load(f)
+ for existing_app in existing_data.get("applications", []):
+ if existing_app.get("repo_url"):
+ existing_lookup[existing_app["repo_url"]] = existing_app
+ if existing_app.get("name"):
+ existing_lookup[existing_app["name"]] = existing_app
+ except Exception as e:
+ print(f"Notice: Could not load existing generated data for fallback: {e}")
+
with open(input_path, "r", encoding="utf-8") as f:
data = json.load(f)
+ applications = data.get("applications", [])
+ repo_paths: list[str] = []
+ for app in applications:
+ repo_path = extract_repo_path(app.get("repo_url", ""))
+ if repo_path:
+ repo_paths.append(repo_path)
+
+ # Batch fetch all repositories via GraphQL (or threaded REST fallback)
+ batch_results = fetch_repos_batch(
+ repo_paths,
+ token=token,
+ headers=headers,
+ batch_size=batch_size,
+ )
+
generated_apps = []
- for app in data.get("applications", []):
- updated_app = update_application_data(app.copy(), headers)
+ for app in applications:
+ repo_path = extract_repo_path(app.get("repo_url", ""))
+ repo_data = batch_results.get(repo_path) if repo_path else None
+ fallback_app = (
+ existing_lookup.get(app.get("repo_url", ""))
+ or existing_lookup.get(app.get("name", ""))
+ )
+ updated_app = update_application_data(
+ app.copy(),
+ headers=headers,
+ repo_data=repo_data,
+ fallback_app=fallback_app,
+ )
generated_apps.append(updated_app)
generated_data = {"applications": generated_apps}
@@ -104,3 +166,4 @@ def update_all_applications(
if __name__ == "__main__":
update_all_applications()
+
diff --git a/core/source/utils/__init__.py b/core/source/utils/__init__.py
index 2056b10..c4760a1 100644
--- a/core/source/utils/__init__.py
+++ b/core/source/utils/__init__.py
@@ -1,11 +1,16 @@
from .github_utils import (
+ build_graphql_repos_query,
extract_repo_path,
fetch_repo_data,
fetch_repo_summary,
+ fetch_repos_batch,
+ fetch_repos_batch_graphql,
+ fetch_repos_batch_rest,
format_commit_date,
format_time_ago,
get_github_headers,
get_github_token,
+ normalize_graphql_repo,
)
from .markdown_utils import (
format_stars,
@@ -28,6 +33,11 @@ __all__ = [
"extract_repo_path",
"fetch_repo_data",
"fetch_repo_summary",
+ "fetch_repos_batch",
+ "fetch_repos_batch_graphql",
+ "fetch_repos_batch_rest",
+ "build_graphql_repos_query",
+ "normalize_graphql_repo",
"format_commit_date",
"format_time_ago",
"get_github_headers",
@@ -45,3 +55,4 @@ __all__ = [
"READMES_DIR",
"MAINTENANCE_DIR",
]
+
diff --git a/core/source/utils/github_utils.py b/core/source/utils/github_utils.py
index 61f611f..4ae72cb 100644
--- a/core/source/utils/github_utils.py
+++ b/core/source/utils/github_utils.py
@@ -1,6 +1,12 @@
+from __future__ import annotations
+
+from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
+import json
import os
import subprocess
+from typing import Any
+
import requests
@@ -101,12 +107,14 @@ def fetch_repo_data(
repo_path: str,
headers: dict | None = None,
timeout: int = 15,
+ session: requests.Session | None = None,
) -> dict | None:
if headers is None:
headers = get_github_headers()
api_url = f"https://api.github.com/repos/{repo_path}"
+ client = session or requests
try:
- response = requests.get(api_url, headers=headers, timeout=timeout)
+ response = client.get(api_url, headers=headers, timeout=timeout)
if response.status_code == 200:
return response.json()
else:
@@ -130,3 +138,255 @@ def fetch_repo_summary(
stars = repo_data.get("stargazers_count", 0)
last_commit = format_commit_date(repo_data.get("pushed_at"))
return last_commit, stars
+
+
+def build_graphql_repos_query(repo_pairs: list[tuple[str, str]]) -> str:
+ """Construct a GraphQL query batching multiple repository lookups using aliases."""
+ fields = """
+ nameWithOwner
+ description
+ homepageUrl
+ stargazerCount
+ pushedAt
+ isArchived
+ primaryLanguage {
+ name
+ }
+ licenseInfo {
+ spdxId
+ }
+ """
+ query_parts = ["query {"]
+ for i, (owner, name) in enumerate(repo_pairs):
+ owner_json = json.dumps(owner)
+ name_json = json.dumps(name)
+ query_parts.append(
+ f" repo_{i}: repository(owner: {owner_json}, name: {name_json}) {{{fields}}}"
+ )
+ query_parts.append("}")
+ return "\n".join(query_parts)
+
+
+def normalize_graphql_repo(raw_node: dict[str, Any] | None) -> dict[str, Any] | None:
+ """Normalize a GitHub GraphQL Repository node to match REST API schema expectations."""
+ if not raw_node:
+ return None
+ license_info = raw_node.get("licenseInfo")
+ primary_language = raw_node.get("primaryLanguage")
+ return {
+ "stargazers_count": raw_node.get("stargazerCount", 0),
+ "language": primary_language.get("name") if primary_language else None,
+ "homepage": raw_node.get("homepageUrl") or "",
+ "description": raw_node.get("description") or "",
+ "license": (
+ {"spdx_id": license_info.get("spdxId") or ""}
+ if license_info and license_info.get("spdxId")
+ else None
+ ),
+ "pushed_at": raw_node.get("pushedAt"),
+ "archived": raw_node.get("isArchived", False),
+ "full_name": raw_node.get("nameWithOwner", ""),
+ }
+
+
+def fetch_repos_batch_graphql(
+ repo_paths: list[str],
+ token: str | None = None,
+ batch_size: int = 100,
+ timeout: int = 30,
+) -> dict[str, dict[str, Any] | None]:
+ """
+ Fetch repository data in bulk using the GitHub GraphQL API in batches.
+ Batches lookups using aliases (up to batch_size repos per HTTP request).
+ """
+ if token is None:
+ token = get_github_token()
+ if not token:
+ raise ValueError("GitHub token required for GraphQL API batch requests.")
+
+ results: dict[str, dict[str, Any] | None] = {}
+ graphql_url = "https://api.github.com/graphql"
+ headers = {
+ "Authorization": f"Bearer {token}",
+ "Accept": "application/vnd.github.v4+json",
+ "User-Agent": "definitive-opensource",
+ }
+
+ for i in range(0, len(repo_paths), batch_size):
+ batch = repo_paths[i : i + batch_size]
+ batch_pairs: list[tuple[str, str]] = []
+ valid_indices: list[int] = []
+
+ for idx, path in enumerate(batch):
+ parts = path.split("/")
+ if len(parts) == 2 and parts[0] and parts[1]:
+ batch_pairs.append((parts[0], parts[1]))
+ valid_indices.append(idx)
+ else:
+ results[path] = None
+
+ if not batch_pairs:
+ continue
+
+ query = build_graphql_repos_query(batch_pairs)
+ batch_num = (i // batch_size) + 1
+ total_batches = (len(repo_paths) + batch_size - 1) // batch_size
+ print(
+ f"Fetching GraphQL batch {batch_num}/{total_batches} ({len(batch_pairs)} repos)..."
+ )
+
+ try:
+ response = requests.post(
+ graphql_url,
+ json={"query": query},
+ headers=headers,
+ timeout=timeout,
+ )
+ if response.status_code != 200:
+ print(
+ f"Warning: GraphQL request failed (Status {response.status_code}): {response.text[:200]}"
+ )
+ for path in batch:
+ if path not in results:
+ results[path] = None
+ continue
+
+ res_json = response.json()
+ data = res_json.get("data") or {}
+
+ for query_idx, orig_idx in enumerate(valid_indices):
+ orig_path = batch[orig_idx]
+ raw_node = data.get(f"repo_{query_idx}")
+ results[orig_path] = normalize_graphql_repo(raw_node)
+
+ except Exception as e:
+ print(f"Error executing GraphQL query for batch {batch_num}: {e}")
+ for path in batch:
+ if path not in results:
+ results[path] = None
+
+ return results
+
+
+def fetch_repos_batch_rest(
+ repo_paths: list[str],
+ headers: dict | None = None,
+ max_workers: int = 8,
+ timeout: int = 15,
+) -> dict[str, dict[str, Any] | None]:
+ """Fetch repository data concurrently using ThreadPoolExecutor and GitHub REST API."""
+ if headers is None:
+ headers = get_github_headers()
+
+ results: dict[str, dict[str, Any] | None] = {}
+ total = len(repo_paths)
+ if total == 0:
+ return results
+
+ print(
+ f"Fetching {total} repos concurrently via REST (max_workers={max_workers})..."
+ )
+
+ with requests.Session() as session:
+ adapter = requests.adapters.HTTPAdapter(
+ pool_connections=max_workers,
+ pool_maxsize=max_workers,
+ max_retries=2,
+ )
+ session.mount("https://", adapter)
+ session.mount("http://", adapter)
+
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
+ future_to_repo = {
+ executor.submit(
+ fetch_repo_data,
+ path,
+ headers=headers,
+ timeout=timeout,
+ session=session,
+ ): path
+ for path in repo_paths
+ }
+ completed = 0
+ for future in as_completed(future_to_repo):
+ repo_path = future_to_repo[future]
+ completed += 1
+ try:
+ results[repo_path] = future.result()
+ except Exception as e:
+ print(f"Error fetching {repo_path} via REST: {e}")
+ results[repo_path] = None
+
+ if completed % 100 == 0 or completed == total:
+ print(f"REST progress: {completed}/{total} completed.")
+
+ return results
+
+
+def fetch_repos_batch(
+ repo_paths: list[str],
+ token: str | None = None,
+ headers: dict | None = None,
+ batch_size: int = 100,
+ max_workers: int = 8,
+ timeout: int = 30,
+) -> dict[str, dict[str, Any] | None]:
+ """
+ Fetch repository metadata in bulk.
+ Uses GitHub GraphQL API (batched in chunks of batch_size) if a token is available.
+ Falls back to REST for any unresolvable repos (e.g. renamed repos following redirects)
+ or falls back to concurrent REST if GraphQL is unavailable or unauthenticated.
+ """
+ unique_paths = list(dict.fromkeys(repo_paths))
+ if not unique_paths:
+ return {}
+
+ if token is None:
+ token = get_github_token()
+
+ if headers is None:
+ headers = get_github_headers(token)
+
+ results: dict[str, dict[str, Any] | None] = {}
+
+ if token:
+ try:
+ print(
+ f"Batch fetching metadata for {len(unique_paths)} repositories via GitHub GraphQL API..."
+ )
+ results = fetch_repos_batch_graphql(
+ unique_paths, token=token, batch_size=batch_size, timeout=timeout
+ )
+ except Exception as e:
+ print(
+ f"GraphQL batch fetch failed ({e}). Falling back to threaded REST API..."
+ )
+ results = {}
+
+ # Check for repositories that were not resolved via GraphQL (e.g. renamed or moved repos)
+ unresolved = [p for p in unique_paths if results.get(p) is None]
+ if unresolved and len(unresolved) < len(unique_paths):
+ print(
+ f"{len(unresolved)} repos not resolved via GraphQL. Falling back to REST for these repos..."
+ )
+ rest_fallback = fetch_repos_batch_rest(
+ unresolved, headers=headers, max_workers=max_workers, timeout=timeout
+ )
+ results.update(rest_fallback)
+ elif unresolved and len(unresolved) == len(unique_paths):
+ # All repos failed via GraphQL; retry via REST
+ print("All repos unresolved via GraphQL. Retrying via threaded REST API...")
+ results = fetch_repos_batch_rest(
+ unique_paths, headers=headers, max_workers=max_workers, timeout=timeout
+ )
+ else:
+ print(
+ "Warning: GITHUB_TOKEN not found. GraphQL batching requires authentication. "
+ "Falling back to threaded REST API (requests may be rate-limited)."
+ )
+ results = fetch_repos_batch_rest(
+ unique_paths, headers=headers, max_workers=max_workers, timeout=timeout
+ )
+
+ return results
+
diff --git a/core/source/utils/markdown_utils.py b/core/source/utils/markdown_utils.py
index dba77c5..13ea725 100644
--- a/core/source/utils/markdown_utils.py
+++ b/core/source/utils/markdown_utils.py
@@ -1,3 +1,6 @@
+from __future__ import annotations
+
+
def slugify(name: str) -> str:
"""Generate a markdown anchor-friendly slug from a heading or section name."""
return name.lower().replace(" ", "-").replace("(", "").replace(")", "")
diff --git a/core/tests/test_batch_github.py b/core/tests/test_batch_github.py
new file mode 100644
index 0000000..0e18e07
--- /dev/null
+++ b/core/tests/test_batch_github.py
@@ -0,0 +1,319 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+import sys
+import unittest
+from unittest.mock import MagicMock, patch
+
+# Ensure core is on sys.path
+CORE_DIR = Path(__file__).resolve().parents[1]
+if str(CORE_DIR) not in sys.path:
+ sys.path.insert(0, str(CORE_DIR))
+
+from source.maintenance.stats_updator import ( # noqa: E402
+ update_all_applications,
+ update_application_data,
+)
+from source.utils.github_utils import ( # noqa: E402
+ build_graphql_repos_query,
+ extract_repo_path,
+ fetch_repos_batch,
+ fetch_repos_batch_graphql,
+ fetch_repos_batch_rest,
+ normalize_graphql_repo,
+)
+
+
+class TestBatchGitHubUtils(unittest.TestCase):
+ def test_extract_repo_path(self):
+ self.assertEqual(
+ extract_repo_path("https://github.com/openinterpreter/openinterpreter"),
+ "openinterpreter/openinterpreter",
+ )
+ self.assertEqual(
+ extract_repo_path("https://github.com/screenpipe/screenpipe.git"),
+ "screenpipe/screenpipe",
+ )
+ self.assertEqual(
+ extract_repo_path("https://github.com/owner/repo/"),
+ "owner/repo",
+ )
+ self.assertIsNone(extract_repo_path("https://gitlab.com/owner/repo"))
+ self.assertIsNone(extract_repo_path(""))
+
+ def test_build_graphql_repos_query(self):
+ pairs = [("owner1", "repo1"), ("owner2", 'repo"with"quote')]
+ query = build_graphql_repos_query(pairs)
+ self.assertIn('repo_0: repository(owner: "owner1", name: "repo1")', query)
+ self.assertIn(
+ 'repo_1: repository(owner: "owner2", name: "repo\\"with\\"quote")', query
+ )
+ self.assertIn("stargazerCount", query)
+ self.assertIn("primaryLanguage", query)
+ self.assertIn("licenseInfo", query)
+
+ def test_normalize_graphql_repo(self):
+ raw_node = {
+ "nameWithOwner": "foo/bar",
+ "stargazerCount": 1234,
+ "description": "A cool repo",
+ "homepageUrl": "https://foo.bar",
+ "pushedAt": "2026-09-27T10:00:00Z",
+ "isArchived": False,
+ "primaryLanguage": {"name": "Rust"},
+ "licenseInfo": {"spdxId": "MIT"},
+ }
+ normalized = normalize_graphql_repo(raw_node)
+ self.assertEqual(normalized["stargazers_count"], 1234)
+ self.assertEqual(normalized["language"], "Rust")
+ self.assertEqual(normalized["homepage"], "https://foo.bar")
+ self.assertEqual(normalized["description"], "A cool repo")
+ self.assertEqual(normalized["license"], {"spdx_id": "MIT"})
+ self.assertEqual(normalized["pushed_at"], "2026-09-27T10:00:00Z")
+ self.assertFalse(normalized["archived"])
+ self.assertEqual(normalized["full_name"], "foo/bar")
+
+ def test_normalize_graphql_repo_null_license_and_language(self):
+ raw_node = {
+ "nameWithOwner": "foo/bar",
+ "stargazerCount": 0,
+ "description": None,
+ "homepageUrl": None,
+ "pushedAt": None,
+ "isArchived": True,
+ "primaryLanguage": None,
+ "licenseInfo": None,
+ }
+ normalized = normalize_graphql_repo(raw_node)
+ self.assertEqual(normalized["stargazers_count"], 0)
+ self.assertIsNone(normalized["language"])
+ self.assertEqual(normalized["homepage"], "")
+ self.assertEqual(normalized["description"], "")
+ self.assertIsNone(normalized["license"])
+ self.assertTrue(normalized["archived"])
+
+ @patch("source.utils.github_utils.requests.post")
+ def test_fetch_repos_batch_graphql_success(self, mock_post):
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "data": {
+ "repo_0": {
+ "nameWithOwner": "owner1/repo1",
+ "stargazerCount": 100,
+ "description": "Desc 1",
+ "homepageUrl": "https://example.com",
+ "pushedAt": "2026-09-01T00:00:00Z",
+ "isArchived": False,
+ "primaryLanguage": {"name": "Python"},
+ "licenseInfo": {"spdxId": "Apache-2.0"},
+ },
+ "repo_1": None, # Not found
+ }
+ }
+ mock_post.return_value = mock_response
+
+ results = fetch_repos_batch_graphql(
+ ["owner1/repo1", "owner2/notfound"],
+ token="fake-token",
+ batch_size=10,
+ )
+
+ self.assertEqual(len(results), 2)
+ self.assertEqual(results["owner1/repo1"]["stargazers_count"], 100)
+ self.assertEqual(results["owner1/repo1"]["language"], "Python")
+ self.assertIsNone(results["owner2/notfound"])
+
+ @patch("source.utils.github_utils.fetch_repo_data")
+ def test_fetch_repos_batch_rest(self, mock_fetch_repo_data):
+ mock_fetch_repo_data.side_effect = lambda path, **kwargs: {
+ "stargazers_count": 50,
+ "language": "Go",
+ "full_name": path,
+ }
+
+ results = fetch_repos_batch_rest(["owner/repoA", "owner/repoB"], max_workers=2)
+ self.assertEqual(len(results), 2)
+ self.assertEqual(results["owner/repoA"]["stargazers_count"], 50)
+ self.assertEqual(results["owner/repoB"]["language"], "Go")
+
+ @patch("source.utils.github_utils.fetch_repos_batch_graphql")
+ @patch("source.utils.github_utils.fetch_repos_batch_rest")
+ def test_fetch_repos_batch_with_token_and_partial_fallback(
+ self, mock_rest, mock_graphql
+ ):
+ mock_graphql.return_value = {
+ "owner/good": {"stargazers_count": 200},
+ "owner/renamed": None,
+ }
+ mock_rest.return_value = {
+ "owner/renamed": {"stargazers_count": 300, "full_name": "owner/newname"},
+ }
+
+ results = fetch_repos_batch(
+ ["owner/good", "owner/renamed"],
+ token="token123",
+ )
+
+ mock_graphql.assert_called_once()
+ mock_rest.assert_called_once_with(
+ ["owner/renamed"], headers=mock_rest.call_args[1]["headers"], max_workers=8, timeout=30
+ )
+ self.assertEqual(results["owner/good"]["stargazers_count"], 200)
+ self.assertEqual(results["owner/renamed"]["stargazers_count"], 300)
+
+ @patch("source.utils.github_utils.fetch_repos_batch_rest")
+ @patch("source.utils.github_utils.get_github_token", return_value=None)
+ def test_fetch_repos_batch_without_token_falls_back_to_rest(
+ self, mock_token, mock_rest
+ ):
+ mock_rest.return_value = {"owner/repo": {"stargazers_count": 10}}
+ results = fetch_repos_batch(["owner/repo"], token=None)
+ mock_rest.assert_called_once()
+ self.assertEqual(results["owner/repo"]["stargazers_count"], 10)
+
+
+class TestStatsUpdator(unittest.TestCase):
+ def test_update_application_data_with_batch_result(self):
+ app = {
+ "name": "Test App",
+ "repo_url": "https://github.com/foo/bar",
+ "category": "ai",
+ "flags": [],
+ }
+ repo_data = {
+ "stargazers_count": 4200,
+ "language": "TypeScript",
+ "homepage": "https://testapp.dev",
+ "description": "Batch updated description",
+ "license": {"spdx_id": "MIT"},
+ "pushed_at": "2026-09-28T12:00:00Z",
+ }
+
+ updated = update_application_data(app.copy(), repo_data=repo_data)
+ self.assertEqual(updated["stars"], 4200)
+ self.assertEqual(updated["language"], "TypeScript")
+ self.assertEqual(updated["homepage_url"], "https://testapp.dev")
+ self.assertEqual(updated["description"], "Batch updated description")
+ self.assertEqual(updated["license"], "MIT")
+ self.assertEqual(updated["last_commit"], "09/28/2026")
+
+ def test_update_application_data_respects_custom_flags(self):
+ app = {
+ "name": "Custom App",
+ "repo_url": "https://github.com/foo/bar",
+ "category": "ai",
+ "flags": ["custom-homepage", "custom-description", "custom-license"],
+ "homepage_url": "https://custom.org",
+ "description": "Custom curated description",
+ "license": "Custom Commercial",
+ }
+ repo_data = {
+ "stargazers_count": 999,
+ "language": "Python",
+ "homepage": "https://overwritten.org",
+ "description": "Overwritten description",
+ "license": {"spdx_id": "GPL-3.0"},
+ "pushed_at": "2026-09-28T12:00:00Z",
+ }
+
+ updated = update_application_data(app.copy(), repo_data=repo_data)
+ self.assertEqual(updated["stars"], 999)
+ self.assertEqual(updated["language"], "Python")
+ self.assertEqual(updated["homepage_url"], "https://custom.org")
+ self.assertEqual(updated["description"], "Custom curated description")
+ self.assertEqual(updated["license"], "Custom Commercial")
+
+ def test_update_application_data_uses_fallback_cache_on_fetch_failure(self):
+ app = {
+ "name": "Failing App",
+ "repo_url": "https://github.com/broken/repo",
+ "category": "ai",
+ "flags": [],
+ }
+ fallback_app = {
+ "name": "Failing App",
+ "repo_url": "https://github.com/broken/repo",
+ "stars": 1500,
+ "language": "Rust",
+ "homepage_url": "https://cached.org",
+ "description": "Cached description",
+ "license": "MIT",
+ "last_commit": "09/20/2026",
+ }
+
+ # repo_data is None (fetch failed)
+ updated = update_application_data(
+ app.copy(),
+ repo_data=None,
+ fallback_app=fallback_app,
+ )
+ self.assertEqual(updated["stars"], 1500)
+ self.assertEqual(updated["language"], "Rust")
+ self.assertEqual(updated["homepage_url"], "https://cached.org")
+ self.assertEqual(updated["description"], "Cached description")
+ self.assertEqual(updated["license"], "MIT")
+ self.assertEqual(updated["last_commit"], "09/20/2026")
+
+ @patch("source.maintenance.stats_updator.fetch_repos_batch")
+ def test_update_all_applications_flow(self, mock_batch):
+ mock_batch.return_value = {
+ "foo/bar": {
+ "stargazers_count": 888,
+ "language": "C++",
+ "homepage": "https://foo.bar",
+ "description": "Great C++ repo",
+ "license": {"spdx_id": "Apache-2.0"},
+ "pushed_at": "2026-09-25T00:00:00Z",
+ }
+ }
+
+ test_input = CORE_DIR / "tests" / "test_input.json"
+ test_output = CORE_DIR / "tests" / "test_output.json"
+
+ input_data = {
+ "applications": [
+ {
+ "name": "FooBar",
+ "repo_url": "https://github.com/foo/bar",
+ "category": "tools",
+ "flags": [],
+ }
+ ]
+ }
+ with open(test_input, "w", encoding="utf-8") as f:
+ json.dump(input_data, f)
+
+ try:
+ result = update_all_applications(
+ input_file=test_input,
+ output_file=test_output,
+ batch_size=50,
+ )
+ mock_batch.assert_called_once_with(
+ ["foo/bar"],
+ token=mock_batch.call_args[1]["token"],
+ headers=mock_batch.call_args[1]["headers"],
+ batch_size=50,
+ )
+ self.assertEqual(len(result["applications"]), 1)
+ app = result["applications"][0]
+ self.assertEqual(app["stars"], 888)
+ self.assertEqual(app["language"], "C++")
+ self.assertEqual(app["license"], "Apache-2.0")
+
+ # Check that file was written
+ self.assertTrue(test_output.exists())
+ with open(test_output, "r", encoding="utf-8") as f:
+ saved = json.load(f)
+ self.assertEqual(saved["applications"][0]["stars"], 888)
+ finally:
+ if test_input.exists():
+ test_input.unlink()
+ if test_output.exists():
+ test_output.unlink()
+
+
+if __name__ == "__main__":
+ unittest.main()