"""Fleetmesh GRASP Git Smart HTTP & Source Code Repository Store (`node.protocols.grasp.git_store`).
Provides real Git bare repository storage, Git Smart HTTP (`git clone`, `git fetch`, `git push`
via `/git/<slug>.git/info/refs`, `git-upload-pack`, `git-receive-pack`), and JSON workbench APIs
(`/api/grasp/repos`, `/push`, `/merge`) with 1,024-byte `RhioBaoTree` Merkle root commitments
and `Kind 30617` (NIP-34 / GRASP) repository state announcements.
"""
from __future__ import annotations
import hashlib
import logging
import os
import re
import subprocess
import tempfile
import threading
import time
from typing import Any, Dict, List, Mapping, MutableMapping, Optional, Tuple
from fleetmesh_core.textile.bao import bao_root_1024
from fleetmesh_core.textile.code_repo import code_repo_fibers, nostr_pubkey_of
from fleetmesh_core.textile.git_objects import (
commit_env,
commit_id as git_commit_id,
identity as git_identity,
tree_id as git_tree_id,
)
from fleetmesh_core.textile.principal import MeshAccessError, Principal, is_owner, owner_fields, require_principal
from .seeds import SEEDED_GRASP_REPOS
log = logging.getLogger(__name__)
SEED_EPOCH = 1730002000
def _commit_time(payload: Mapping[str, Any]) -> int:
"""The commit time a browser chose (so its commit id and the node's agree), within ten minutes of now."""
now = int(time.time())
try:
at = int(payload.get("created_at") or 0)
except (TypeError, ValueError):
at = 0
return at if abs(at - now) <= 600 else now
def _clean_slug(raw: str) -> str:
slug = re.sub(r"\.git$", "", str(raw or "").strip().lower())
slug = re.sub(r"[^a-z0-9._-]+", "-", slug).strip("-._")
return slug or "unnamed-repo"
GIT_TIMEOUT_SEC = 120
MAX_PUSH_BYTES = 64 * 1024 * 1024
_BRANCH_PART = r"[A-Za-z0-9_][A-Za-z0-9._-]*"
_BRANCH_RE = re.compile(rf"^{_BRANCH_PART}(?:/{_BRANCH_PART})*$")
[docs]def branch_name(raw: Any) -> str:
"""A branch name git takes as a name, never as an option (`MeshAccessError` 400 otherwise)."""
name = str(raw or "").strip()
if (
not name
or len(name) > 200
or not _BRANCH_RE.match(name)
or ".." in name
or name.endswith((".lock", "."))
or any(part.endswith(".lock") for part in name.split("/"))
):
raise MeshAccessError(400, "invalid_branch")
return name
[docs]def repo_path(raw: Any) -> str:
"""A file path inside the work tree, never into `.git` or above it (`MeshAccessError` 400 otherwise)."""
path = str(raw or "").replace("\\", "/").lstrip("/")
parts = path.split("/")
if (
not path
or "\x00" in path
or any(p in ("", ".", "..") for p in parts)
or any(p.casefold().rstrip(". ") in (".git", "git~1") for p in parts)
):
raise MeshAccessError(400, "invalid_path")
return path
def _harden_bare(bare_path: str) -> None:
"""Pushes are checked object by object and capped in size."""
for key, val in (
("http.receivepack", "true"),
("http.uploadpack", "true"),
("receive.fsckObjects", "true"),
("receive.maxInputSize", str(MAX_PUSH_BYTES)),
):
subprocess.run(["git", "--git-dir", bare_path, "config", key, val], check=False, capture_output=True)
[docs]class StandaloneGraspGitStore:
"""Manages bare Git repositories on disk and JSON metadata for `/git/*` and `/api/grasp/*`."""
# What is read back from a branch after a git push; the rest is listed in `omitted_files`.
MAX_SYNC_FILE_BYTES = 1024 * 1024
MAX_SYNC_FILES = 5000
MAX_SYNC_BYTES = 32 * 1024 * 1024
[docs] def __init__(self, base_dir: Optional[str] = None, public_base_url: str = "") -> None:
"""`public_base_url` is where this host serves `/git/`; without it no clone URL is published."""
self._lock = threading.RLock()
env_dir = (os.environ.get("FLEETMESH_GRASP_DIR") or "").strip()
if base_dir:
self.root_dir = os.path.abspath(base_dir)
elif env_dir:
self.root_dir = os.path.abspath(env_dir)
else:
self._tmp_dir = tempfile.TemporaryDirectory(prefix="fleetmesh_grasp_git_")
self.root_dir = self._tmp_dir.name
os.makedirs(self.root_dir, exist_ok=True)
self.public_base_url = public_base_url.rstrip("/")
self._repos: Dict[str, MutableMapping[str, Any]] = {}
self._hardened: set = set()
self._seed_defaults()
def _bare_repo_path(self, repo_id: str) -> str:
return os.path.join(self.root_dir, f"{_clean_slug(repo_id)}.git")
def _compute_repo_bao(self, files_map: Mapping[str, str]) -> Tuple[str, str, int, int]:
"""`(tree sha256, tree root, file bytes, file leaves)`: the repo's root is its tree fiber's."""
tree, _files, byte_len, leaves = code_repo_fibers(files_map)
return hashlib.sha256(tree).hexdigest(), bao_root_1024(tree)[0], byte_len, leaves
def _sync_files_to_bare_git(
self,
repo_id: str,
branch: str,
files_map: Mapping[str, str],
message: str,
author_handle: str,
at: Optional[int] = None,
base_branch: str = "main",
) -> str:
"""Commit `files_map` onto `branch` with `git` (as `author_handle`, at `at` when given): its real id, or `''`."""
bare_path = self._bare_repo_path(repo_id)
try:
branch, base_branch = branch_name(branch), (branch_name(base_branch) if base_branch else "")
if not os.path.isdir(bare_path):
subprocess.run(["git", "init", "--bare", bare_path], check=True, capture_output=True)
_harden_bare(bare_path)
self._hardened.add(bare_path)
with tempfile.TemporaryDirectory(prefix="grasp_work_") as work_dir:
subprocess.run(["git", "init", work_dir], check=True, capture_output=True)
# A pushed symlink is checked out as a plain file holding its target, never followed.
subprocess.run(["git", "-C", work_dir, "config", "core.symlinks", "false"], check=True, capture_output=True)
name, email = git_identity(author_handle)
subprocess.run(["git", "-C", work_dir, "config", "user.name", name], check=True, capture_output=True)
subprocess.run(["git", "-C", work_dir, "config", "user.email", email], check=True, capture_output=True)
subprocess.run(["git", "-C", work_dir, "remote", "add", "origin", bare_path], check=True, capture_output=True)
fetch_res = subprocess.run(["git", "-C", work_dir, "fetch", "origin", branch], capture_output=True)
if fetch_res.returncode == 0:
subprocess.run(
["git", "-C", work_dir, "checkout", "-B", branch, f"origin/{branch}"], check=False, capture_output=True
)
elif (
base_branch
and base_branch != branch
and subprocess.run(["git", "-C", work_dir, "fetch", "origin", base_branch], capture_output=True).returncode
== 0
):
subprocess.run(
["git", "-C", work_dir, "checkout", "-B", branch, f"origin/{base_branch}"],
check=False,
capture_output=True,
)
else:
subprocess.run(["git", "-C", work_dir, "checkout", "-B", branch], check=False, capture_output=True)
root = os.path.realpath(work_dir)
for rel_path, content in files_map.items():
full_p = os.path.join(root, repo_path(rel_path))
if not os.path.realpath(full_p).startswith(root + os.sep):
raise MeshAccessError(400, "invalid_path")
if os.path.isfile(full_p) and not os.path.islink(full_p):
with open(full_p, "rb") as f:
# Unchanged (as the record holds it): leave the bytes, binary ones included.
if f.read().decode("utf-8", errors="replace") == content:
continue
os.makedirs(os.path.dirname(full_p), exist_ok=True)
with open(full_p, "w", encoding="utf-8") as f:
f.write(content)
subprocess.run(["git", "-C", work_dir, "add", "-A"], check=True, capture_output=True)
env = {**os.environ, **(commit_env(at) if at else {})}
subprocess.run(
["git", "-C", work_dir, "commit", "--allow-empty", "-m", message],
check=True,
capture_output=True,
env=env,
)
rev = subprocess.run(
["git", "-C", work_dir, "rev-parse", "HEAD"], check=True, capture_output=True, text=True
).stdout.strip()
subprocess.run(
["git", "-C", work_dir, "push", "-f", "origin", f"HEAD:refs/heads/{branch}"],
check=True,
capture_output=True,
)
if branch == "main":
subprocess.run(
["git", "--git-dir", bare_path, "symbolic-ref", "HEAD", "refs/heads/main"],
check=False,
capture_output=True,
)
return rev
except Exception:
return ""
def _sync_from_bare_git(self, repo_id: str) -> None:
"""Read files and HEAD commit from bare git repo after an external `git push`."""
bare_path = self._bare_repo_path(repo_id)
if not os.path.isdir(bare_path):
return
try:
refs_out = subprocess.run(
["git", "--git-dir", bare_path, "for-each-ref", "--format=%(refname:short) %(objectname)", "refs/heads/"],
capture_output=True,
text=True,
check=True,
).stdout.strip()
if not refs_out:
return
rec = self._repos.get(repo_id)
if not rec:
rec = self._create_empty_record(repo_id, {"title": repo_id})
self._load_owner(repo_id, rec)
self._repos[repo_id] = rec
for line in refs_out.splitlines():
parts = line.strip().split()
if len(parts) != 2:
continue
br_name, commit_sha = parts
ls_out = subprocess.run(
["git", "--git-dir", bare_path, "ls-tree", "-r", "-l", "-z", commit_sha],
capture_output=True,
check=True,
).stdout.decode("utf-8", errors="replace")
files_map: Dict[str, str] = {}
omitted: List[str] = []
total = 0
for entry in ls_out.split("\x00"):
head, _, fpath = entry.partition("\t")
fields = head.split()
if not fpath or len(fields) != 4 or fields[1] != "blob":
continue
size = int(fields[3]) if fields[3].isdigit() else 0
if (
size > self.MAX_SYNC_FILE_BYTES
or len(files_map) >= self.MAX_SYNC_FILES
or total + size > self.MAX_SYNC_BYTES
):
omitted.append(fpath)
continue
total += size
blob = subprocess.run(
["git", "--git-dir", bare_path, "show", f"{commit_sha}:{fpath}"],
capture_output=True,
check=False,
).stdout
files_map[fpath] = blob.decode("utf-8", errors="replace")
if files_map or omitted:
rec["branches"][br_name] = {
"head_commit": commit_sha,
"files": files_map,
"omitted_files": omitted,
"updated_at": int(time.time()),
}
if br_name == rec.get("default_branch", "main") or not rec.get("files"):
rec["files"] = dict(files_map)
rec["omitted_files"] = list(omitted)
rec["head_commit"] = commit_sha
msg_out = (
subprocess.run(
["git", "--git-dir", bare_path, "log", "-1", "--format=%s", commit_sha],
capture_output=True,
text=True,
check=False,
).stdout.strip()
or "External git push"
)
if not any(c.get("commit_sha") == commit_sha for c in rec["commits"]):
sha_hex, bao_root, byte_len, leaves = self._compute_repo_bao(files_map or rec.get("files", {}))
rec["commits"].insert(
0,
{
"commit_sha": commit_sha,
"branch": br_name,
"message": msg_out,
"author_handle": "@git_pusher",
"bao_root": bao_root,
"created_at": int(time.time()),
},
)
self._refresh_repo_hashes(rec)
except Exception as exc:
log.debug("grasp git_store: sync from bare git skipped for %s (%s)", repo_id, exc)
def _ensure_bare_git_synced(self, repo_id: str) -> str:
slug = _clean_slug(repo_id)
bare_path = self._bare_repo_path(slug)
if os.path.isdir(bare_path) and bare_path not in self._hardened:
_harden_bare(bare_path)
self._hardened.add(bare_path)
if not os.path.isdir(bare_path):
rec = self._repos.get(slug)
if rec:
commit_sha = self._sync_files_to_bare_git(
slug,
"main",
rec.get("files", {}),
f"Initial GRASP seed for {rec['title']}",
str(rec.get("owner_handle") or ""),
at=int(rec.get("created_at") or 0) or None,
)
if commit_sha:
rec["head_commit"] = commit_sha
if "main" in rec["branches"]:
rec["branches"]["main"]["head_commit"] = commit_sha
else:
return ""
return bare_path
def _save_owner(self, slug: str, rec: Mapping[str, Any]) -> None:
bare_path = self._bare_repo_path(slug)
for key in ("owner_id", "owner_did", "owner_handle", "title", "description", "linked_target_id", "target_kind"):
subprocess.run(
["git", "--git-dir", bare_path, "config", f"fleetmesh.{key.replace('_', '')}", str(rec.get(key) or "")],
check=False,
capture_output=True,
)
def _load_owner(self, slug: str, rec: MutableMapping[str, Any]) -> None:
bare_path = self._bare_repo_path(slug)
for key in ("owner_id", "owner_did", "owner_handle", "title", "description", "linked_target_id", "target_kind"):
out = subprocess.run(
["git", "--git-dir", bare_path, "config", "--get", f"fleetmesh.{key.replace('_', '')}"],
capture_output=True,
text=True,
check=False,
)
if out.returncode == 0 and out.stdout.strip():
rec[key] = out.stdout.strip()
elif key in ("owner_id", "owner_did"):
rec[key] = ""
def _owned(self, slug: str, who: Mapping[str, Any]) -> MutableMapping[str, Any]:
"""The repo, if `who` owns it (`MeshAccessError` otherwise)."""
rec = self._repos.get(slug)
if rec is None and os.path.isdir(self._bare_repo_path(slug)):
self._sync_from_bare_git(slug)
rec = self._repos.get(slug)
if rec is None:
raise MeshAccessError(404, "repo_not_found")
if not is_owner(rec, who):
raise MeshAccessError(403, "not_repo_owner")
return rec
def _create_empty_record(self, slug: str, meta: Mapping[str, Any]) -> MutableMapping[str, Any]:
clean = _clean_slug(slug)
now = int(time.time())
return {
"repo_id": clean,
"title": str(meta.get("title") or clean),
"description": str(meta.get("description") or "Sovereign GRASP Git Repository"),
"linked_target_id": str(meta.get("linked_target_id") or clean),
"target_kind": str(meta.get("target_kind") or "game"),
"owner_id": str(meta.get("owner_id") or ""),
"owner_handle": str(meta.get("owner_handle") or ""),
"owner_did": str(meta.get("owner_did") or ""),
"clone_url": f"{self.public_base_url}/git/{clean}.git" if self.public_base_url else "",
"default_branch": "main",
"head_commit": "",
"bao_root": "",
"sha256_hex": "",
"size_bytes": 0,
"leaf_count_1024b": 1,
"files": {},
"branches": {},
"commits": [],
"created_at": now,
"updated_at": now,
}
def _refresh_repo_hashes(self, rec: MutableMapping[str, Any]) -> None:
sha_hex, bao_root, byte_len, leaves = self._compute_repo_bao(rec.get("files", {}))
rec["sha256_hex"] = sha_hex
rec["bao_root"] = bao_root
rec["size_bytes"] = byte_len
rec["leaf_count_1024b"] = leaves
rec["updated_at"] = int(time.time())
rec["kind_30617_event"] = {
"kind": 30617,
"pubkey": nostr_pubkey_of(str(rec.get("owner_did") or "")),
"created_at": rec["updated_at"],
"tags": [
["d", rec["repo_id"]],
["name", rec["title"]],
*([["clone", rec["clone_url"]]] if rec["clone_url"] else []),
["r", rec["head_commit"], "refs/heads/main"],
["x", bao_root],
],
"content": rec["description"],
}
def _seed_defaults(self) -> None:
with self._lock:
for idx, item in enumerate(SEEDED_GRASP_REPOS):
slug = _clean_slug(item["repo_id"])
rec = self._create_empty_record(slug, item)
rec["created_at"] = rec["updated_at"] = SEED_EPOCH + idx * 120
files_map = dict(item.get("files") or {})
rec["files"] = files_map
commit_sha = git_commit_id(
git_tree_id(files_map),
[],
rec["owner_handle"],
int(rec["created_at"]),
f"Initial GRASP seed for {rec['title']}",
)
rec["head_commit"] = commit_sha
rec["branches"]["main"] = {
"head_commit": commit_sha,
"files": dict(files_map),
"updated_at": rec["updated_at"],
}
self._refresh_repo_hashes(rec)
rec["commits"].append(
{
"commit_sha": commit_sha,
"branch": "main",
"message": f"Initial GRASP seed for {rec['title']}",
"author_handle": rec["owner_handle"],
"bao_root": rec["bao_root"],
"created_at": rec["created_at"],
}
)
self._repos[slug] = rec
if os.path.isdir(self._bare_repo_path(slug)):
self._sync_from_bare_git(slug)
if rec["head_commit"] != commit_sha:
rec["commits"] = [c for c in rec["commits"] if c.get("commit_sha") != commit_sha]
for entry in sorted(os.listdir(self.root_dir)):
if entry.endswith(".git") and os.path.isdir(os.path.join(self.root_dir, entry)):
slug = _clean_slug(entry[:-4])
if slug not in self._repos:
self._sync_from_bare_git(slug)
[docs] def list_repos(self) -> List[MutableMapping[str, Any]]:
with self._lock:
return [dict(r) for r in self._repos.values()]
[docs] def get_repo(self, repo_id: str) -> Optional[MutableMapping[str, Any]]:
slug = _clean_slug(repo_id)
with self._lock:
if slug not in self._repos and os.path.isdir(self._bare_repo_path(slug)):
self._sync_from_bare_git(slug)
rec = self._repos.get(slug)
return dict(rec) if rec else None
[docs] def create_or_update_repo(self, payload: Mapping[str, Any], principal: Principal = None) -> MutableMapping[str, Any]:
who = require_principal(principal)
slug = _clean_slug(str(payload.get("repo_id") or payload.get("title") or "custom-repo"))
with self._lock:
exists = slug in self._repos or os.path.isdir(self._bare_repo_path(slug))
rec = self._owned(slug, who) if exists else self._create_empty_record(slug, {**dict(payload), **owner_fields(who)})
if payload.get("title"):
rec["title"] = str(payload["title"])
if payload.get("description"):
rec["description"] = str(payload["description"])
if payload.get("linked_target_id"):
rec["linked_target_id"] = str(payload["linked_target_id"])
if payload.get("target_kind"):
rec["target_kind"] = str(payload["target_kind"])
in_files = payload.get("files")
if isinstance(in_files, Mapping) and in_files:
files_map = {repo_path(k): str(v) for k, v in in_files.items()}
elif not rec["files"]:
files_map = {"README.md": f"# {rec['title']}\n\n{rec['description']}\n"}
else:
files_map = dict(rec["files"])
rec["files"] = files_map
commit_sha = self._sync_files_to_bare_git(
slug,
"main",
files_map,
str(payload.get("message") or f"Initialize {rec['title']}"),
rec["owner_handle"],
at=_commit_time(payload),
)
if not commit_sha:
raise MeshAccessError(500, "git_commit_failed")
self._save_owner(slug, rec)
rec["head_commit"] = commit_sha
rec["branches"]["main"] = {"head_commit": commit_sha, "files": dict(files_map), "updated_at": int(time.time())}
self._refresh_repo_hashes(rec)
if not rec["commits"]:
rec["commits"].append(
{
"commit_sha": commit_sha,
"branch": "main",
"message": str(payload.get("message") or f"Initialize {rec['title']}"),
"author_handle": rec["owner_handle"],
"bao_root": rec["bao_root"],
"created_at": rec["updated_at"],
}
)
self._repos[slug] = rec
return dict(rec)
[docs] def push_commit(self, repo_id: str, payload: Mapping[str, Any], principal: Principal = None) -> MutableMapping[str, Any]:
who = require_principal(principal)
slug = _clean_slug(repo_id)
branch_name(re.sub(r"[^a-zA-Z0-9._/-]+", "-", str(payload.get("branch") or "main").strip()) or "main")
if payload.get("base_branch"):
branch_name(payload["base_branch"])
with self._lock:
if slug not in self._repos and not os.path.isdir(self._bare_repo_path(slug)):
self.create_or_update_repo({"repo_id": slug, **dict(payload)}, who)
rec = self._owned(slug, who)
branch = branch_name(re.sub(r"[^a-zA-Z0-9._/-]+", "-", str(payload.get("branch") or "main").strip()) or "main")
base_branch = branch_name(payload.get("base_branch") or rec.get("default_branch") or "main")
br_obj = rec["branches"].get(branch) or rec["branches"].get(base_branch) or {"files": dict(rec["files"])}
merged_files = dict(br_obj.get("files") or rec["files"])
if isinstance(payload.get("files"), Mapping):
for fpath, content in payload["files"].items():
merged_files[repo_path(fpath)] = str(content)
elif isinstance(payload.get("files"), list):
for entry in payload["files"]:
if isinstance(entry, Mapping) and entry.get("path"):
merged_files[repo_path(entry["path"])] = str(entry.get("content") or "")
elif payload.get("file_path"):
merged_files[repo_path(payload["file_path"])] = str(payload.get("content") or "")
msg = str(payload.get("message") or f"Update files on {branch}").strip()
author = str(who.get("handle") or rec.get("owner_handle") or who.get("identity_id") or "")
commit_sha = self._sync_files_to_bare_git(
slug, branch, merged_files, msg, author, at=_commit_time(payload), base_branch=base_branch
)
if not commit_sha:
raise MeshAccessError(500, "git_commit_failed")
now = int(time.time())
rec["branches"][branch] = {"head_commit": commit_sha, "files": dict(merged_files), "updated_at": now}
if branch == rec.get("default_branch", "main"):
rec["files"] = dict(merged_files)
rec["head_commit"] = commit_sha
_, br_bao_root, _, _ = self._compute_repo_bao(merged_files)
self._refresh_repo_hashes(rec)
commit_entry = {
"commit_sha": commit_sha,
"branch": branch,
"message": msg,
"author_handle": author,
"bao_root": br_bao_root,
"created_at": now,
}
rec["commits"].insert(0, commit_entry)
return {"ok": True, "repo": dict(rec), "commit": commit_entry, "branch": branch}
[docs] def merge_branch(self, repo_id: str, payload: Mapping[str, Any], principal: Principal = None) -> MutableMapping[str, Any]:
who = require_principal(principal)
slug = _clean_slug(repo_id)
with self._lock:
rec = self._owned(slug, who)
source_branch = branch_name(payload.get("source_branch"))
target_branch = branch_name(str(payload.get("target_branch") or "main").strip() or "main")
if not source_branch or source_branch not in rec["branches"]:
return {"ok": False, "error": "source_branch_not_found", "source_branch": source_branch}
src_files = dict(rec["branches"][source_branch].get("files") or {})
tgt_files = dict((rec["branches"].get(target_branch) or {}).get("files") or rec["files"])
merged_files = {**tgt_files, **src_files}
author = str(who.get("handle") or rec.get("owner_handle") or who.get("identity_id") or "")
msg = str(payload.get("message") or f"Merge branch '{source_branch}' into {target_branch}")
commit_sha = self._sync_files_to_bare_git(
slug, target_branch, merged_files, msg, author, at=_commit_time(payload)
)
if not commit_sha:
raise MeshAccessError(500, "git_commit_failed")
now = int(time.time())
rec["branches"][target_branch] = {"head_commit": commit_sha, "files": dict(merged_files), "updated_at": now}
if target_branch == rec.get("default_branch", "main"):
rec["files"] = dict(merged_files)
rec["head_commit"] = commit_sha
self._refresh_repo_hashes(rec)
commit_entry = {
"commit_sha": commit_sha,
"branch": target_branch,
"merged_from": source_branch,
"message": msg,
"author_handle": author,
"bao_root": rec["bao_root"],
"created_at": now,
}
rec["commits"].insert(0, commit_entry)
return {"ok": True, "repo": dict(rec), "commit": commit_entry, "merged_into": target_branch}
[docs]def handle_grasp_api_http(
store: StandaloneGraspGitStore,
method: str,
route: str,
body: Optional[Mapping[str, Any]] = None,
principal: Principal = None,
) -> Optional[Tuple[int, MutableMapping[str, Any]]]:
"""Dispatch `/api/grasp/*` JSON requests; writes as `principal` (the server's own session resolution)."""
try:
return _grasp_api_http(store, method, route, body or {}, principal)
except MeshAccessError as exc:
return exc.status, {"ok": False, "error": exc.error}
def _grasp_api_http(
store: StandaloneGraspGitStore, method: str, route: str, body: Mapping[str, Any], principal: Principal
) -> Optional[Tuple[int, MutableMapping[str, Any]]]:
if route == "/api/grasp/repos" and method == "GET":
repos = store.list_repos()
return (
200,
{"ok": True, "grasp_base_url": f"{store.public_base_url}/git", "repos_count": len(repos), "repos": repos},
)
if route == "/api/grasp/repos" and method == "POST":
repo = store.create_or_update_repo(body, principal)
return 200, {"ok": True, "repo": repo}
if route.startswith("/api/grasp/repos/"):
parts = [p for p in route[len("/api/grasp/repos/") :].split("/") if p]
if not parts:
return None
repo_id = parts[0]
action = parts[1] if len(parts) > 1 else ""
if method == "GET" and not action:
found_repo = store.get_repo(repo_id)
return (200, {"ok": True, "repo": found_repo}) if found_repo else (404, {"ok": False, "error": "repo_not_found"})
if method == "POST" and action == "push":
res = store.push_commit(repo_id, body, principal)
return (200 if res.get("ok") else 400), res
if method == "POST" and action == "merge":
res = store.merge_branch(repo_id, body, principal)
return (200 if res.get("ok") else 400), res
return None