import re
import httpx
import base64
import asyncio
MAX_FILE_CHARS = 50000
MAX_README_CHARS = 6000
GITHUB_API = "https://api.github.com"
GITHUB_PATTERN = re.compile(
r"github\.com/([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+)(?:/(?:blob|tree)/([^/]+)(?:/(.+))?)?"
)
GITHUB_USER_PATTERN = re.compile(
r"github\.com/([A-Za-z0-9_.-]+)/?$"
)
CODE_EXTENSIONS = {
".py", ".js", ".ts", ".jsx", ".tsx", ".java", ".cpp", ".c", ".h",
".cs", ".go", ".rs", ".rb", ".php", ".swift", ".kt", ".scala",
".html", ".css", ".scss", ".json", ".yaml", ".yml", ".toml",
".sh", ".bash", ".zsh", ".sql", ".r", ".m", ".dart", ".vue",
".svelte", ".ex", ".exs", ".clj", ".hs", ".lua", ".pl", ".md",
".env.example", ".gitignore", ".dockerfile", "dockerfile",
}
KEY_FILES = [
"package.json", "requirements.txt", "pyproject.toml", "Pipfile",
"main.py", "app.py", "index.js", "index.ts", "server.js", "server.ts",
"app.js", "app.ts", "src/index.js", "src/index.ts", "src/main.py",
"src/app.py", "src/app.js", "src/server.js", "manage.py",
"Makefile", "docker-compose.yml", "docker-compose.yaml",
".env.example", "config.py", "config.js", "settings.py",
]
def _make_headers(token: str | None = None) -> dict:
h = {
"Accept": "application/vnd.github+json",
"User-Agent": "Riaz-AI-Agent/1.0",
"X-GitHub-Api-Version": "2022-11-28",
}
if token:
h["Authorization"] = f"Bearer {token}"
return h
def parse_github_url(url: str) -> dict | None:
m = GITHUB_PATTERN.search(url)
if not m:
return None
return {
"owner": m.group(1),
"repo": m.group(2).removesuffix(".git"),
"ref": m.group(3),
"path": m.group(4),
}
def is_github_user_url(url: str) -> str | None:
"""Returns username if this is a pure profile URL, None otherwise."""
clean = url.strip().rstrip("/")
m = GITHUB_USER_PATTERN.search(clean)
if m:
parsed_repo = parse_github_url(clean)
if not parsed_repo:
return m.group(1)
return None
async def _gh_get(client: httpx.AsyncClient, path: str, token: str | None = None):
try:
r = await client.get(
f"{GITHUB_API}{path}",
headers=_make_headers(token),
follow_redirects=True,
)
if r.status_code == 404:
return None
r.raise_for_status()
return r.json()
except Exception:
return None
# ─────────────────────────────────────────────────────────────────────────────
# WRITE OPERATIONS
# ─────────────────────────────────────────────────────────────────────────────
async def github_create_repo(
token: str,
name: str,
description: str = "",
private: bool = False,
auto_init: bool = True,
) -> dict:
"""Create a new GitHub repository for the authenticated user."""
async with httpx.AsyncClient(timeout=30) as client:
try:
r = await client.post(
f"{GITHUB_API}/user/repos",
headers=_make_headers(token),
json={
"name": name,
"description": description,
"private": private,
"auto_init": auto_init,
},
)
if r.status_code in (200, 201):
data = r.json()
return {
"success": True,
"url": data.get("html_url", ""),
"name": data.get("full_name", name),
"private": data.get("private", private),
"clone_url": data.get("clone_url", ""),
"default_branch": data.get("default_branch", "main"),
}
else:
try:
err = r.json().get("message", r.text)
except Exception:
err = r.text
return {"success": False, "error": err}
except Exception as e:
return {"success": False, "error": str(e)}
async def github_create_or_update_file(
token: str,
owner: str,
repo: str,
path: str,
content: str,
message: str = "Update via Riaz AI",
branch: str = "main",
) -> dict:
"""Create or update a single file in a GitHub repository.
Auto-retries once on SHA conflict (409) with a fresh SHA fetch."""
encoded = base64.b64encode(content.encode()).decode()
async def _attempt(client: httpx.AsyncClient, retry: bool = False) -> dict:
existing = await _gh_get(client, f"/repos/{owner}/{repo}/contents/{path}?ref={branch}", token)
sha = existing.get("sha") if existing else None
payload: dict = {
"message": message,
"content": encoded,
"branch": branch,
}
if sha:
payload["sha"] = sha
try:
r = await client.put(
f"{GITHUB_API}/repos/{owner}/{repo}/contents/{path}",
headers=_make_headers(token),
json=payload,
)
if r.status_code in (200, 201):
data = r.json()
file_url = data.get("content", {}).get("html_url", "")
return {"success": True, "url": file_url, "path": path}
elif r.status_code == 409 and not retry:
# SHA conflict — wait briefly and retry with fresh SHA
await asyncio.sleep(1.5)
return await _attempt(client, retry=True)
else:
try:
err = r.json().get("message", r.text)
except Exception:
err = r.text
return {"success": False, "error": err, "path": path}
except Exception as e:
return {"success": False, "error": str(e), "path": path}
async with httpx.AsyncClient(timeout=30) as client:
return await _attempt(client)
async def github_create_website(
token: str,
owner: str,
repo_name: str,
site_description: str = "Simple website",
) -> dict:
"""
Create a new GitHub repo (or use existing) and push a minimal
index.html + style.css website to it.
Returns a summary dict with success status and URLs.
"""
# 1 — Create the repo (auto_init=True so default branch exists immediately)
repo_result = await github_create_repo(
token, repo_name,
description=site_description,
private=False,
auto_init=True,
)
default_branch = "main"
repo_already_existed = False
if not repo_result.get("success"):
err_msg = repo_result.get("error", "")
if "already exists" in err_msg.lower() or "name already exists" in err_msg.lower():
# Repo exists — fetch its default branch
repo_already_existed = True
async with httpx.AsyncClient(timeout=15) as client:
rb = await _gh_get(client, f"/repos/{owner}/{repo_name}", token)
if rb:
default_branch = rb.get("default_branch", "main")
else:
return {
"success": False,
"error": f"Could not create repo: {err_msg}",
"content": f"❌ Repo create nahi hua: {err_msg}",
}
else:
default_branch = repo_result.get("default_branch", "main")
# Small wait so GitHub initialises the branch before we push
if not repo_already_existed:
await asyncio.sleep(2)
html_content = f"""
{repo_name}
Welcome to {repo_name}
{site_description}
About
This website was created by Riaz Ali Shahani using Riaz AI.
Contact
Feel free to reach out via GitHub.
"""
css_content = """/* Simple clean website styles */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: #0d1117;
color: #c9d1d9;
line-height: 1.7;
}
header {
background: linear-gradient(135deg, #161b22, #21262d);
padding: 60px 20px;
text-align: center;
border-bottom: 1px solid #30363d;
}
header h1 { font-size: 2.4rem; color: #58a6ff; margin-bottom: 10px; }
header p { font-size: 1.1rem; color: #8b949e; }
main {
max-width: 900px;
margin: 40px auto;
padding: 0 20px;
display: grid;
gap: 30px;
}
section {
background: #161b22;
border: 1px solid #30363d;
border-radius: 10px;
padding: 30px;
}
section h2 { color: #58a6ff; margin-bottom: 12px; font-size: 1.3rem; }
section p { color: #8b949e; }
footer {
text-align: center;
padding: 30px;
color: #8b949e;
border-top: 1px solid #30363d;
font-size: 0.9rem;
margin-top: 40px;
}"""
# 2 — Push index.html then style.css — sequential to avoid SHA conflicts
html_r = await github_create_or_update_file(
token, owner, repo_name, "index.html", html_content,
message="Add index.html via Riaz AI", branch=default_branch,
)
if not html_r.get("success"):
return {
"success": False,
"error": f"index.html push failed: {html_r.get('error')}",
"content": f"❌ index.html push nahi hua: {html_r.get('error')}",
}
css_r = await github_create_or_update_file(
token, owner, repo_name, "style.css", css_content,
message="Add style.css via Riaz AI", branch=default_branch,
)
if html_r.get("success") and css_r.get("success"):
repo_url = f"https://github.com/{owner}/{repo_name}"
pages_url = f"https://{owner}.github.io/{repo_name}/"
action = "Updated" if repo_already_existed else "Created"
# 3 — Auto-enable GitHub Pages via API
await asyncio.sleep(2)
pages_result = await github_enable_pages(token, owner, repo_name, default_branch)
pages_auto = pages_result.get("success", False)
pages_already = pages_result.get("already_enabled", False)
if pages_auto:
pages_url = pages_result.get("url", pages_url)
if pages_auto:
pages_status = (
f"**🌐 GitHub Pages:** {'Already enabled ✅' if pages_already else 'Auto-enabled ✅'}\n"
f"**Live URL:** [{pages_url}]({pages_url})\n"
f"*(2-3 minutes mein fully live ho jayega — GitHub deploy kar raha hai)*"
)
else:
pages_status = (
f"**GitHub Pages URL:** `{pages_url}`\n\n"
f"**Pages enable karne ke liye (1 minute):**\n"
f"1. Repo open karo → **Settings** → **Pages**\n"
f"2. Source: **Deploy from branch** → `{default_branch}` → **/ (root)**\n"
f"3. Save → 2-3 min mein live\n"
f"> _(Note: Pages auto-enable ke liye token ko `repo` scope chahiye)_"
)
return {
"success": True,
"repo_url": repo_url,
"pages_url": pages_url,
"pages_auto_enabled": pages_auto,
"content": (
f"## ✅ Website Successfully {action}!\n\n"
f"**📁 Repo:** [{owner}/{repo_name}]({repo_url})\n"
f"**🌿 Branch:** `{default_branch}`\n"
f"**index.html:** ✅ pushed\n"
f"**style.css:** ✅ pushed\n\n"
f"{pages_status}\n\n"
f"### Files Created:\n"
f"- `index.html` — clean dark-themed homepage\n"
f"- `style.css` — modern responsive styles"
),
}
else:
errors = []
if not html_r.get("success"):
errors.append(f"index.html: {html_r.get('error')}")
if not css_r.get("success"):
errors.append(f"style.css: {css_r.get('error')}")
return {
"success": False,
"error": "\n".join(errors),
"content": "❌ Files push nahi hue:\n" + "\n".join(errors),
}
async def github_enable_pages(
token: str,
owner: str,
repo: str,
branch: str = "main",
) -> dict:
"""Enable GitHub Pages for a repository (deploy from branch root)."""
async with httpx.AsyncClient(timeout=30) as client:
try:
r = await client.post(
f"{GITHUB_API}/repos/{owner}/{repo}/pages",
headers=_make_headers(token),
json={"source": {"branch": branch, "path": "/"}},
)
if r.status_code in (200, 201):
data = r.json()
return {
"success": True,
"url": data.get("html_url", f"https://{owner}.github.io/{repo}/"),
}
elif r.status_code == 409:
return {
"success": True,
"url": f"https://{owner}.github.io/{repo}/",
"already_enabled": True,
}
else:
try:
err = r.json().get("message", r.text)
except Exception:
err = r.text
return {"success": False, "error": err}
except Exception as e:
return {"success": False, "error": str(e)}
async def github_update_repo(
token: str,
owner: str,
repo: str,
private: bool | None = None,
description: str | None = None,
new_name: str | None = None,
) -> dict:
"""Update a repository's visibility, description, or name."""
payload: dict = {}
if private is not None:
payload["private"] = private
if description is not None:
payload["description"] = description
if new_name is not None:
payload["name"] = new_name
if not payload:
return {"success": False, "error": "Kuch bhi change specify nahi kiya"}
async with httpx.AsyncClient(timeout=30) as client:
try:
r = await client.patch(
f"{GITHUB_API}/repos/{owner}/{repo}",
headers=_make_headers(token),
json=payload,
)
if r.status_code == 200:
data = r.json()
return {
"success": True,
"repo_url": data.get("html_url", ""),
"name": data.get("full_name", f"{owner}/{repo}"),
"private": data.get("private", False),
"description": data.get("description", ""),
}
else:
try:
err = r.json().get("message", r.text)
except Exception:
err = r.text
return {"success": False, "error": err}
except Exception as e:
return {"success": False, "error": str(e)}
async def github_delete_repo(
token: str,
owner: str,
repo: str,
) -> dict:
"""Permanently delete a GitHub repository. Requires delete_repo scope on token."""
async with httpx.AsyncClient(timeout=30) as client:
try:
r = await client.delete(
f"{GITHUB_API}/repos/{owner}/{repo}",
headers=_make_headers(token),
)
if r.status_code == 204:
return {"success": True, "repo": repo, "owner": owner}
else:
try:
err = r.json().get("message", r.text)
except Exception:
err = r.text
return {"success": False, "error": err, "status": r.status_code}
except Exception as e:
return {"success": False, "error": str(e)}
async def github_update_profile(
token: str,
bio: str | None = None,
name: str | None = None,
company: str | None = None,
location: str | None = None,
blog: str | None = None,
twitter_username: str | None = None,
) -> dict:
"""Update the authenticated user's GitHub profile fields."""
payload: dict = {}
if bio is not None:
payload["bio"] = bio
if name is not None:
payload["name"] = name
if company is not None:
payload["company"] = company
if location is not None:
payload["location"] = location
if blog is not None:
payload["blog"] = blog
if twitter_username is not None:
payload["twitter_username"] = twitter_username
if not payload:
return {"success": False, "error": "Kuch bhi change specify nahi kiya"}
async with httpx.AsyncClient(timeout=30) as client:
try:
r = await client.patch(
f"{GITHUB_API}/user",
headers=_make_headers(token),
json=payload,
)
if r.status_code == 200:
data = r.json()
return {
"success": True,
"profile_url": data.get("html_url", ""),
"login": data.get("login", ""),
"name": data.get("name", ""),
"bio": data.get("bio", ""),
}
else:
try:
err = r.json().get("message", r.text)
except Exception:
err = r.text
return {"success": False, "error": err}
except Exception as e:
return {"success": False, "error": str(e)}
async def github_delete_file(
token: str,
owner: str,
repo: str,
path: str,
message: str = "Delete via Riaz AI",
branch: str = "main",
) -> dict:
"""Delete a file from a GitHub repository."""
async with httpx.AsyncClient(timeout=30) as client:
existing = await _gh_get(client, f"/repos/{owner}/{repo}/contents/{path}?ref={branch}", token)
if not existing:
return {"success": False, "error": f"File `{path}` not found"}
sha = existing.get("sha")
try:
r = await client.delete(
f"{GITHUB_API}/repos/{owner}/{repo}/contents/{path}",
headers=_make_headers(token),
json={"message": message, "sha": sha, "branch": branch},
)
if r.status_code in (200, 204):
return {"success": True, "path": path}
else:
return {"success": False, "error": r.json().get("message", r.text), "path": path}
except Exception as e:
return {"success": False, "error": str(e), "path": path}
async def _read_raw_file(client: httpx.AsyncClient, owner: str, repo: str,
path: str, ref: str, token: str | None = None) -> str:
"""Read a file directly from raw.githubusercontent.com — fast, no API quota."""
try:
r = await client.get(
f"https://raw.githubusercontent.com/{owner}/{repo}/{ref}/{path}",
headers=_make_headers(token),
follow_redirects=True,
timeout=15.0,
)
if r.status_code == 200:
text = r.text
return text[:MAX_FILE_CHARS] if len(text) > MAX_FILE_CHARS else text
except Exception:
pass
return ""
# ─── Public profile ───────────────────────────────────────────────────────────
async def fetch_github_public_profile(username: str, token: str | None = None) -> dict:
"""Fetch a public GitHub user's profile and their repositories with language stats."""
async with httpx.AsyncClient(timeout=25.0) as client:
user_data, repos_data = await asyncio.gather(
_gh_get(client, f"/users/{username}", token),
_gh_get(client, f"/users/{username}/repos?per_page=100&sort=updated&type=public", token),
)
if not user_data:
return {"error": f"GitHub user '{username}' not found."}
name = user_data.get("name") or username
bio = user_data.get("bio") or ""
location = user_data.get("location") or ""
company = user_data.get("company") or ""
blog = user_data.get("blog") or ""
followers = user_data.get("followers", 0)
following = user_data.get("following", 0)
pub_repos = user_data.get("public_repos", 0)
repos = []
lang_count: dict[str, int] = {}
if repos_data:
for r in repos_data:
lang = r.get("language") or "Unknown"
lang_count[lang] = lang_count.get(lang, 0) + 1
repos.append({
"name": r.get("name"),
"full_name": r.get("full_name"),
"description": r.get("description") or "",
"language": lang,
"stars": r.get("stargazers_count", 0),
"forks": r.get("forks_count", 0),
"size_kb": r.get("size", 0),
"updated": (r.get("updated_at") or "")[:10],
"open_issues": r.get("open_issues_count", 0),
})
# language breakdown sorted by count
lang_lines = ", ".join(
f"{lang} ({cnt} repo{'s' if cnt>1 else ''})"
for lang, cnt in sorted(lang_count.items(), key=lambda x: -x[1])
if lang != "Unknown"
)
repo_lines = []
for r in sorted(repos, key=lambda x: x["stars"], reverse=True):
desc = f" — {r['description']}" if r["description"] else ""
stars = f" ⭐{r['stars']}" if r["stars"] > 0 else ""
issues = f" ⚠️{r['open_issues']} issues" if r["open_issues"] > 0 else ""
repo_lines.append(f"📂 **{r['name']}** [{r['language']}]{stars}{issues}{desc}")
parts = [f"## GitHub Profile: {name} (@{username})"]
if bio: parts.append(f"**Bio:** {bio}")
if location: parts.append(f"**Location:** {location}")
if company: parts.append(f"**Company:** {company}")
if blog: parts.append(f"**Website:** {blog}")
parts.append(
f"**Followers:** {followers:,} | **Following:** {following:,} | **Public Repos:** {pub_repos}"
)
if lang_lines:
parts.append(f"**Languages used:** {lang_lines}")
if repo_lines:
parts.append(f"\n### Repositories ({len(repos)} total):\n" + "\n".join(repo_lines))
return {
"type": "github_profile",
"title": f"{name} (@{username}) — GitHub",
"content": "\n".join(parts),
"username": username,
"repo_count": len(repos),
}
async def fetch_github_user_repos(token: str) -> dict:
"""Fetch repos for the authenticated user (token required)."""
async with httpx.AsyncClient(timeout=25.0) as client:
user_data, repos_data = await asyncio.gather(
_gh_get(client, "/user", token),
_gh_get(client, "/user/repos?per_page=100&sort=updated&affiliation=owner,collaborator", token),
)
username = (user_data or {}).get("login", "Your Account")
name = (user_data or {}).get("name") or username
bio = (user_data or {}).get("bio") or ""
pub = (user_data or {}).get("public_repos", 0)
priv = (user_data or {}).get("total_private_repos", 0)
followers= (user_data or {}).get("followers", 0)
following= (user_data or {}).get("following", 0)
if not repos_data:
return {"error": "Could not fetch repositories. Check your token."}
repos = []
lang_count: dict[str, int] = {}
for r in repos_data:
lang = r.get("language") or "Unknown"
lang_count[lang] = lang_count.get(lang, 0) + 1
repos.append({
"name": r.get("full_name"),
"description": r.get("description") or "",
"language": lang,
"stars": r.get("stargazers_count", 0),
"private": r.get("private", False),
"updated": (r.get("updated_at") or "")[:10],
"open_issues": r.get("open_issues_count", 0),
"default_branch": r.get("default_branch", "main"),
})
lang_lines = ", ".join(
f"{lang} ({cnt})"
for lang, cnt in sorted(lang_count.items(), key=lambda x: -x[1])
if lang != "Unknown"
)
lines = []
for r in repos:
icon = "🔒" if r["private"] else "📂"
issues = f" ⚠️{r['open_issues']} issues" if r["open_issues"] > 0 else ""
desc = f" — {r['description']}" if r["description"] else ""
lines.append(f"{icon} **{r['name']}** [{r['language']}]{issues}{desc}")
header = (
f"## GitHub Account: {name} (@{username})\n"
f"**Bio:** {bio}\n"
f"**Followers:** {followers:,} | **Following:** {following:,} | "
f"**Public:** {pub} | **Private:** {priv}\n"
f"**Languages:** {lang_lines}\n\n"
f"### Repositories ({len(repos)} total):\n"
)
return {
"type": "github_user_repos",
"content": header + "\n".join(lines),
"repo_count": len(repos),
"repos": repos,
"username": username,
}
# ─── Single file ──────────────────────────────────────────────────────────────
async def fetch_github_file(owner: str, repo: str, file_path: str,
ref: str, token: str | None = None) -> dict:
"""Fetch the complete content of a single file."""
async with httpx.AsyncClient(timeout=30.0) as client:
ref_to_use = ref or "HEAD"
# Try raw URL first (faster, no base64)
raw = await _read_raw_file(client, owner, repo, file_path, ref_to_use, token)
if raw:
return {
"type": "github_file",
"title": f"{file_path} — {owner}/{repo}",
"file_path": file_path,
"content": raw,
"truncated": len(raw) >= MAX_FILE_CHARS,
"total_chars": len(raw),
}
# Fallback: GitHub contents API
file_data = await _gh_get(
client, f"/repos/{owner}/{repo}/contents/{file_path}?ref={ref_to_use}", token
)
if not file_data:
return {"error": f"File not found: {file_path}"}
if isinstance(file_data, list):
entries = [
f"{'📁' if e['type']=='dir' else '📄'} {e['name']}"
for e in file_data
]
return {
"type": "github_dir",
"title": f"{file_path}/ — {owner}/{repo}",
"content": f"Directory listing of `{file_path}/`:\n\n" + "\n".join(entries),
}
if file_data.get("encoding") == "base64":
try:
decoded = base64.b64decode(file_data["content"]).decode("utf-8", errors="replace")
except Exception:
return {"error": f"Cannot decode file: {file_path}"}
truncated = len(decoded) > MAX_FILE_CHARS
content = decoded[:MAX_FILE_CHARS] + "\n\n[… truncated]" if truncated else decoded
return {
"type": "github_file",
"title": f"{file_path} — {owner}/{repo}",
"file_path": file_path,
"content": content,
"truncated": truncated,
"total_chars": len(decoded),
"size_bytes": file_data.get("size", 0),
}
return {"error": f"Could not read file: {file_path}"}
# ─── Full repo view ───────────────────────────────────────────────────────────
async def fetch_github(url: str, token: str | None = None) -> dict:
parsed = parse_github_url(url)
# Pure user-profile URL?
if not parsed:
username = is_github_user_url(url)
if username:
return await fetch_github_public_profile(username, token)
return {"error": f"Could not parse GitHub URL: {url}"}
owner, repo, ref, file_path = (
parsed["owner"], parsed["repo"], parsed["ref"], parsed["path"]
)
# Specific file URL?
if file_path:
result = await fetch_github_file(owner, repo, file_path, ref or "HEAD", token)
result.setdefault("repo", f"{owner}/{repo}")
return result
# Full repo view
async with httpx.AsyncClient(timeout=35.0) as client:
repo_info, lang_data = await asyncio.gather(
_gh_get(client, f"/repos/{owner}/{repo}", token),
_gh_get(client, f"/repos/{owner}/{repo}/languages", token),
)
if not repo_info or "id" not in repo_info:
return {"error": (
f"Repository `{owner}/{repo}` not found or is private. "
"Share your GitHub token to access private repos."
)}
default_branch = repo_info.get("default_branch", "main")
tree_data, readme_data = await asyncio.gather(
_gh_get(client, f"/repos/{owner}/{repo}/git/trees/{default_branch}?recursive=1", token),
_gh_get(client, f"/repos/{owner}/{repo}/readme", token),
)
# ── File tree ────────────────────────────────────────────────────────
all_files: list[dict] = []
if tree_data and "tree" in tree_data:
for item in tree_data["tree"]:
if item["type"] == "blob":
all_files.append({
"path": item["path"],
"size": item.get("size", 0),
})
file_count = len(all_files)
file_tree_lines = [f["path"] for f in all_files[:300]]
# ── Auto-read key entry-point files ──────────────────────────────────
existing_paths = {f["path"] for f in all_files}
to_read = [p for p in KEY_FILES if p in existing_paths][:8]
key_file_contents = {}
if to_read:
results = await asyncio.gather(*[
_read_raw_file(client, owner, repo, p, default_branch, token)
for p in to_read
])
for path, content in zip(to_read, results):
if content:
key_file_contents[path] = content[:3000] # first 3000 chars per key file
# ── README ───────────────────────────────────────────────────────────
readme_text = ""
if readme_data and readme_data.get("encoding") == "base64":
raw_readme = base64.b64decode(readme_data["content"]).decode("utf-8", errors="replace")
readme_text = (
raw_readme[:MAX_README_CHARS] + "\n\n[… truncated]"
if len(raw_readme) > MAX_README_CHARS else raw_readme
)
# ── Language breakdown ────────────────────────────────────────────────
lang_str = ""
if lang_data and isinstance(lang_data, dict):
total_bytes = sum(lang_data.values()) or 1
lang_parts = [
f"{lang} {round(bytes_/total_bytes*100)}%"
for lang, bytes_ in sorted(lang_data.items(), key=lambda x: -x[1])
]
lang_str = " | ".join(lang_parts[:6])
# ── Assemble content ─────────────────────────────────────────────────
content_parts = []
if repo_info.get("description"):
content_parts.append(f"**Description:** {repo_info['description']}")
content_parts.append(
f"**Primary language:** {repo_info.get('language','unknown')} | "
f"⭐ {repo_info.get('stargazers_count',0)} | "
f"🍴 {repo_info.get('forks_count',0)} | "
f"⚠️ {repo_info.get('open_issues_count',0)} open issues | "
f"📄 {file_count} files"
)
if lang_str:
content_parts.append(f"**Language breakdown:** {lang_str}")
topics = repo_info.get("topics", [])
if topics:
content_parts.append(f"**Topics:** {', '.join(topics)}")
content_parts.append(
f"**Branch:** `{default_branch}` | "
f"**Size:** {repo_info.get('size',0)} KB | "
f"**License:** {(repo_info.get('license') or {}).get('name','None')}"
)
# Full file tree
content_parts.append(
f"\n### File Tree ({file_count} total files):\n" +
"\n".join(f" {p}" for p in file_tree_lines)
)
# Key files content
if key_file_contents:
content_parts.append("\n### Key File Contents (auto-read):")
for path, code in key_file_contents.items():
ext = path.rsplit(".", 1)[-1] if "." in path else ""
content_parts.append(f"\n**{path}:**\n```{ext}\n{code}\n```")
if readme_text:
content_parts.append(f"\n### README:\n{readme_text}")
full_content = "\n".join(content_parts)
return {
"type": "github",
"source": url,
"repo": f"{owner}/{repo}",
"title": f"{owner}/{repo}",
"description": repo_info.get("description") or "",
"content": full_content,
"file_count": file_count,
"all_files": [f["path"] for f in all_files], # full list for file lookup
"owner": owner,
"repo_name": repo,
"default_branch": default_branch,
}
# ─── Scan repo for errors ─────────────────────────────────────────────────────
async def scan_repo_for_errors(owner: str, repo: str, token: str,
branch: str | None = None) -> dict:
"""
Deep scan: read every code file, find issues, and provide concrete fix suggestions.
"""
async with httpx.AsyncClient(timeout=60.0) as client:
repo_info = await _gh_get(client, f"/repos/{owner}/{repo}", token)
if not repo_info:
return {"error": f"Repository `{owner}/{repo}` not found or no access."}
default_branch = branch or repo_info.get("default_branch", "main")
tree_data = await _gh_get(
client,
f"/repos/{owner}/{repo}/git/trees/{default_branch}?recursive=1",
token,
)
if not tree_data or "tree" not in tree_data:
return {"error": "Could not read file tree."}
code_files = [
item for item in tree_data["tree"]
if item["type"] == "blob"
and any(item["path"].lower().endswith(ext) for ext in CODE_EXTENSIONS)
and item.get("size", 0) < 150_000
][:40]
file_reports: list[str] = []
files_scanned = 0
async def scan_one(item):
nonlocal files_scanned
path = item["path"]
content = await _read_raw_file(client, owner, repo, path, default_branch, token)
if not content:
return
files_scanned += 1
lines = content.split("\n")
issues = []
for i, line in enumerate(lines, 1):
ll = line.lower()
# Missing module / import errors
if any(p in ll for p in ["modulenotfounderror", "importerror", "cannot find module", "no module named"]):
issues.append(
f" ⚠️ Line {i}: Missing import/module\n"
f" `{line.strip()}`\n"
f" → **Fix:** Install the missing package (e.g., `pip install ` or `npm install `)"
)
# Syntax errors (Python)
elif any(p in ll for p in ["syntaxerror", "indentationerror", "unexpected indent"]):
issues.append(
f" ⚠️ Line {i}: Syntax/indentation error\n"
f" `{line.strip()}`\n"
f" → **Fix:** Check indentation and syntax around this line"
)
# Undefined variable / attribute
elif any(p in ll for p in ["nameerror", "attributeerror", "is not defined", "has no attribute"]):
issues.append(
f" ⚠️ Line {i}: Undefined variable or attribute\n"
f" `{line.strip()}`\n"
f" → **Fix:** Check variable name spelling or ensure it's defined before use"
)
# Type errors
elif any(p in ll for p in ["typeerror", "cannot read properties", "is not a function"]):
issues.append(
f" ⚠️ Line {i}: Type error\n"
f" `{line.strip()}`\n"
f" → **Fix:** Check data type — a variable may be null/undefined or wrong type"
)
# Connection / network errors
elif any(p in ll for p in ["connection refused", "connection error", "econnrefused"]):
issues.append(
f" ⚠️ Line {i}: Connection error\n"
f" `{line.strip()}`\n"
f" → **Fix:** Check that the server/database is running and host/port are correct"
)
# TODO / FIXME markers (left by developer)
elif any(p in ll for p in ["todo:", "fixme:", "hack:", "xxx:"]):
issues.append(
f" 📌 Line {i}: Developer note left unresolved\n"
f" `{line.strip()}`"
)
if issues:
file_reports.append(f"\n**📄 {path}:**\n" + "\n".join(issues[:5])) # max 5 per file
await asyncio.gather(*[scan_one(item) for item in code_files])
if not file_reports:
summary = (
f"## 🔍 Code Scan — {owner}/{repo}\n"
f"Branch: `{default_branch}` | Files scanned: **{files_scanned}**\n\n"
"✅ **No obvious errors found!** The code looks clean.\n\n"
"This scan checks for: missing imports, syntax errors, undefined variables, "
"type errors, and connection issues."
)
else:
summary = (
f"## 🔍 Code Scan — {owner}/{repo}\n"
f"Branch: `{default_branch}` | Files scanned: **{files_scanned}** | "
f"Issues found in **{len(file_reports)}** file(s)\n\n"
"### Issues Found:\n" + "\n".join(file_reports) +
"\n\n---\n"
"### How to fix:\n"
"Share your GitHub token and say **\"fix karo\"** — "
"I will rewrite the broken parts and give you corrected code for each file."
)
return {
"type": "github_scan",
"title": f"Code Scan — {owner}/{repo}",
"content": summary,
"files_scanned": files_scanned,
"issues_count": len(file_reports),
"owner": owner,
"repo_name": repo,
"branch": default_branch,
}