Project: pygitweb

d964104 """
FastAPI app and routes: gitweb actions as path operations.
Ported from gitweb/gitweb.perl dispatch and action handlers.
"""
d964104 from __future__ import annotations
19e7c78 import asyncio
a29919a import os
4614448 from collections.abc import AsyncGenerator, Awaitable, Callable
ae1889a from contextlib import asynccontextmanager
7947ec5 from datetime import UTC, datetime
d964104 from pathlib import Path
65ca31f from typing import Annotated, Literal
215041e from urllib.parse import quote, urlencode
d964104
a29919a import pygit2
85b8192 from fastapi import Depends, FastAPI, File, Form, HTTPException, Query, Request, UploadFile
dfe0870 from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse, Response
d964104 from fastapi.staticfiles import StaticFiles
3558586 from pygittools.validation import is_valid_pathname
d964104
26f0919 from pygitweb import __meta__
997da40 from pygitweb.actions import (
73c9c30 BLOG_MANIFEST_PATH,
SearchFlagQuery,
SearchSortQuery,
SummaryRefsPayload,
SummaryRefState,
board_link_spec,
create_board_link,
git_blame,
git_blame_raw,
git_blob,
git_blobdiff,
git_blobpatch,
git_blog_raw,
git_commit,
git_commitdiff,
git_heads,
git_history,
git_log,
git_object,
git_patch,
git_patches,
git_remotes,
git_search,
git_search_page,
git_shortlog,
git_summary,
git_tag,
git_tags,
git_tree,
parse_pagination,
project_has_blog,
summary_ref_options,
summary_ref_state,
997da40 )
1c90f78 from pygitweb.api.plugins.project_zip import ProjectZip
from pygitweb.api.project import Project
85b8192 from pygitweb.auth import (
73c9c30 access_token_from_request,
auth_router,
can_read_project,
decode_access_token,
ensure_permission,
85b8192 )
b96c6f3 from pygitweb.auth_config import is_auth_configured
8dc22a4 from pygitweb.board_refs import BoardRefManifest, board_ref_manifest
dfe0870 from pygitweb.change_queue import CHANGE_QUEUE
0e30bdd from pygitweb.config import auth_config, get_loadavg, settings
a2948bf from pygitweb.dependencies import (
ded5e8b RequirePermission,
73c9c30 ValidatedBoardCreateProject,
ValidatedNotifyProject,
ValidatedReadableProject,
filter_projects_by_read_access,
project_visible_in_list,
require_loopback_client,
ded5e8b require_permission,
a2948bf )
69644d2 from pygitweb.formatting import age_string
760fe33 from pygitweb.git_helpers import git_get_type
dfe0870 from pygitweb.hooks_install import (
73c9c30 HookStatus,
bundle_status,
get_bundle,
get_sample,
list_bundles,
list_samples,
dfe0870 )
from pygitweb.hooks_install import (
73c9c30 install as install_hook,
dfe0870 )
from pygitweb.hooks_install import (
73c9c30 install_bundle as install_hook_bundle,
dfe0870 )
from pygitweb.hooks_install import (
73c9c30 remove as remove_hook,
dfe0870 )
from pygitweb.hooks_install import (
73c9c30 remove_bundle as remove_hook_bundle,
dfe0870 )
from pygitweb.hooks_install import (
73c9c30 status as hook_status,
dfe0870 )
4401744 from pygitweb.merge_requests import merge_router
e6c6972 from pygitweb.permissions import Permission
c06f565 from pygitweb.plugin_loader import (
73c9c30 DISPATCH_ACTIONS,
PLUGIN_ACTIONS,
SUBPAGES,
apply_plugin_reload,
c06f565 )
997da40 from pygitweb.projects import git_get_project_owner, git_get_projects_list
ccd8854 from pygitweb.settings import router as settings_router
2b8fce2 from pygitweb.shutdown import begin_shutdown, install_graceful_shutdown_wakeup
275a710 from pygitweb.smart_http import http_router
997da40 from pygitweb.tasks import (
73c9c30 board_router,
comment_router,
create_board_for_project,
get_all_project_tasks,
get_board_tasks_grouped,
list_project_boards,
task_router,
997da40 )
52026a0 from pygitweb.team import team_router
00e5b5b from pygitweb.templates_env import Cell, html_join, html_link, jinja_escape, render_page, trusted_html
ae1889a from pygitweb.timeline_cache import clear_timeline_cache_async, get_all_timeline_events, warm_timeline_cache_async
d964104
dfe0870 UPDATES_SUPPORTED_ACTIONS: frozenset[str] = frozenset({"history", "log", "shortlog", "heads", "tags"})
65ca31f ProjectListAction = Literal["project_list"]
ProjectListOrder = Literal["none", "project", "descr", "owner", "age"]
HookInstallOp = Literal["add", "remove", "check"]
dfe0870
def _parse_updates_flag(value: str | None) -> bool:
73c9c30 if value is None:
return False
return value.strip().lower() in ("1", "true", "yes", "on")
dfe0870
def _resolve_subscribed_projects(project: str, project_filter: str | None) -> list[str]:
73c9c30 """Pick the project set to long-poll. Uses pf prefix if provided, else the URL project."""
if not project_filter:
return [project]
pf = project_filter.strip().strip("/")
if not pf:
return [project]
matches = git_get_projects_list(
filter_path=pf,
paranoid=settings.STRICT_EXPORT,
export_ok=settings.EXPORT_OK,
)
names: list[str] = [m.get("path", "") for m in matches if m.get("path")]
return names or [project]
dfe0870
19e7c78 def _updates_idle_response() -> Response:
73c9c30 return Response(status_code=200, content=b"")
19e7c78
ae1889a @asynccontextmanager
19e7c78 async def app_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
73c9c30 app.state.shutting_down = False
app.state.shutdown_event = asyncio.Event()
app.state.can_signal_shutdown = False
install_graceful_shutdown_wakeup(app)
warm_timeline_cache_async()
try:
yield
finally:
begin_shutdown(app)
clear_timeline_cache_async()
ae1889a
9ad78c1 app = FastAPI(
73c9c30 debug=(settings.AUTH is False),
title="PyGitWeb",
summary="FastAPI + Pygit2 Repo Browser",
version=__meta__.__version__,
lifespan=app_lifespan,
openapi_tags=[
{
"name": "auth",
"description": """Session status, account pages, and sign-out.
fb2fe5d Sessions are opaque ids (cookie or Bearer), not IdP JWTs.""",
73c9c30 },
{
"name": "auth - local",
"description": "Local username/password sign-in via HTML form or POST /token.",
},
{
"name": "auth - OAuth",
"description": """Browser OAuth2 authorization-code flow (Google/GitHub).
fb2fe5d Ends with the same session cookie as local login.""",
73c9c30 },
],
57230a6 )
b2267f4
c06f565 apply_plugin_reload()
11b5ebf
57230a6 # Todo handle with nginx route
d964104 _static_dir = Path(__file__).parent / "static"
if _static_dir.is_dir():
73c9c30 app.mount("/static", StaticFiles(directory=str(_static_dir)), name="static")
d964104
85b8192 app.include_router(auth_router)
ccd8854 app.include_router(settings_router)
3ee2226 app.include_router(board_router, prefix="/board")
app.include_router(task_router, prefix="/tasks")
52026a0 app.include_router(team_router, prefix="/team")
3ee2226 app.include_router(comment_router, prefix="/comments")
4401744 app.include_router(merge_router, prefix="/mr")
275a710 app.include_router(http_router)
ccd8854
d964104 @app.middleware("http")
4614448 async def loadavg_middleware(
73c9c30 request: Request,
call_next: Callable[[Request], Awaitable[Response]],
4614448 ) -> Response:
73c9c30 try:
if settings.MAXLOAD is not None and get_loadavg() > settings.MAXLOAD:
raise RuntimeError("503:The load average on the server is too high")
except RuntimeError as e:
msg = str(e)
if msg.startswith("503:"):
raise HTTPException(status_code=503, detail=msg[4:]) from e
raise
return await call_next(request)
d964104
760fe33 def _project_subpage_rows(project: str) -> list[list[Cell]]:
73c9c30 project_enc = quote(project, safe="/")
rows: list[list[Cell]] = []
for subpage in SUBPAGES:
link_label = subpage.link_name(project)
if not link_label:
continue
subpage_name = subpage.subpage_name()
view = html_link(f"/project/{project_enc}/subpage/{quote(subpage_name, safe='')}", "view")
suffix = subpage.summary_value_suffix_html(project, project_enc)
value = html_join([view, trusted_html(suffix)]) if suffix else view
rows.append([link_label, value])
return rows
11b5ebf
d964104 # ---------- Routes (no project) ----------
147709a _OPEN_TASK_STATUSES = frozenset({"TODO", "IN_PROGRESS", "IN_REVIEW"})
def _home_stats(projects: list[dict[str, object]]) -> dict[str, int]:
73c9c30 """Counts for the project-list dashboard cards."""
from pygitweb.capacity_config import current_iso_week, get_user_week_capacity
visible = {str(pr.get("path") or "") for pr in projects if pr.get("path")}
points_by_assignee: dict[str, int] = {}
open_tasks = 0
for path in visible:
try:
tasks = get_all_project_tasks(path)
except Exception:
continue
for task in tasks:
if task.get("status") not in _OPEN_TASK_STATUSES:
continue
open_tasks += 1
assignee = str(task.get("assignee") or "").strip()
if not assignee:
continue
points = task.get("points") or 0
points_by_assignee[assignee] = points_by_assignee.get(assignee, 0) + int(points)
week = current_iso_week()
over_capacity = 0
for assignee, points in points_by_assignee.items():
capacity = get_user_week_capacity(assignee, week)
if capacity is not None and points > capacity:
over_capacity += 1
recent_commits = sum(
1 for item in get_all_timeline_events() if item["project"] in visible and item["event"]["kind"] == "commit"
)
return {
"projects": len(visible),
"open_tasks": open_tasks,
"over_capacity": over_capacity,
"recent_commits": recent_commits,
}
147709a
d964104
@app.get("/", response_class=HTMLResponse)
def git_project_list(
73c9c30 request: Request,
token: Annotated[str | None, Depends(access_token_from_request)],
_action: Annotated[ProjectListAction | None, Query(alias="a")] = None,
pf: Annotated[str | None, Query(alias="pf")] = None,
_order: Annotated[ProjectListOrder | None, Query(alias="o")] = None,
7377412 ) -> HTMLResponse:
73c9c30 """Project list page. Port of git_project_list."""
project_filter = pf or ""
all_projects = git_get_projects_list(
filter_path=project_filter,
paranoid=settings.STRICT_EXPORT,
export_ok=settings.EXPORT_OK,
)
list_ = filter_projects_by_read_access(all_projects, token)
notice = ""
if not list_:
if all_projects and settings.AUTH:
notice = "hidden"
elif not all_projects:
notice = "empty"
projects = []
for pr in list_[:50]:
path = pr.get("path", "") or ""
board = board_link_spec(path)
projects.append({
"href": f"/project/{quote(path, safe='/')}",
"path": path,
"descr": pr.get("descr") or path,
"board_href": board["href"],
"board_text": board["text"],
"board_style": board["style"],
})
return render_page(
"project_list.html",
title=f"{settings.SITE_NAME} - Projects",
notice=notice,
projects=projects,
stats=_home_stats(list_),
nav="projects",
)
d964104
@app.get("/index", response_class=PlainTextResponse)
def git_project_index(
73c9c30 token: Annotated[str | None, Depends(access_token_from_request)],
pf: Annotated[str | None, Query(alias="pf")] = None,
7377412 ) -> PlainTextResponse:
73c9c30 """Plain text project index (path owner). Port of git_project_index."""
from urllib.parse import quote_plus
projects = filter_projects_by_read_access(
git_get_projects_list(
filter_path=pf or "",
paranoid=settings.STRICT_EXPORT,
export_ok=settings.EXPORT_OK,
),
token,
)
if not projects:
raise HTTPException(status_code=404, detail="No projects found")
lines = []
for pr in projects:
path = pr.get("path", "")
owner = pr.get("owner") or git_get_project_owner(path) or ""
path_enc = quote_plus(path, safe="/")
owner_enc = quote_plus(owner, safe="/")
lines.append(f"{path_enc} {owner_enc}")
return PlainTextResponse("\n".join(lines), media_type="text/plain; charset=utf-8")
d964104
7947ec5 @app.get("/activity", response_class=HTMLResponse)
def activity_page(
73c9c30 token: Annotated[str | None, Depends(access_token_from_request)],
page: Annotated[str | None, Query(alias="page")] = None,
pagecount: Annotated[str | None, Query(alias="pagecount")] = None,
7947ec5 ) -> HTMLResponse:
73c9c30 p, pc = parse_pagination(page, pagecount)
all_events = [item for item in get_all_timeline_events() if can_read_project(item["project"], token)]
skip = (p - 1) * pc
events_page = all_events[skip : skip + pc + 1]
has_next = len(events_page) > pc
if has_next:
events_page = events_page[:pc]
events: list[dict[str, str]] = []
for item in events_page:
project_name = item["project"]
event = item["event"]
oid = event["oid"]
kind = event["kind"] or ""
event_href = ""
label: Literal["commit", "ref"] | str = kind
if kind == "commit":
label = oid[:7]
event_href = f"/project/{quote(project_name, safe='/')}?a=commit&h={quote(oid, safe='')}"
description_raw = event.get("description")
if not description_raw:
description = ""
elif "\n" in description_raw:
description = description_raw.splitlines()[0][:80].rstrip() + "..."
elif len(description_raw) > 80:
description = description_raw[:80].rstrip() + "..."
else:
description = description_raw
try:
age_seconds = datetime.now(UTC).timestamp() - float(event["timestamp"])
activity_time = "right now" if age_seconds <= 0 else age_string(age_seconds)
except (ValueError, OSError):
activity_time = ""
events.append({
"time": activity_time,
"project": project_name,
"project_href": f"/project/{quote(project_name, safe='/')}",
"label": label,
"event_href": event_href,
"description": description,
})
prev_url = ""
next_url = ""
if p > 1:
prev_url = f"/activity?{urlencode({'page': str(p - 1), 'pagecount': str(pc)})}"
if has_next:
next_url = f"/activity?{urlencode({'page': str(p + 1), 'pagecount': str(pc)})}"
return render_page(
"activity.html",
title=f"{settings.SITE_NAME} - Activity",
events=events,
nav="activity",
pagination={
"current_page": p,
"pagecount": pc,
"has_prev": p > 1,
"has_next": has_next,
"prev_url": prev_url,
"next_url": next_url,
"total_pages": None,
"page_links": None,
},
)
7947ec5
52026a0 @app.get("/boards", response_class=HTMLResponse)
def boards_overview_page(
73c9c30 token: Annotated[str | None, Depends(access_token_from_request)],
52026a0 ) -> HTMLResponse:
73c9c30 """Cross-project index of boards, so users can jump straight to any project's board."""
projects = filter_projects_by_read_access(
git_get_projects_list(paranoid=settings.STRICT_EXPORT, export_ok=settings.EXPORT_OK),
token,
)
rows: list[list[Cell]] = []
for pr in projects:
project = pr.get("path", "")
if not project:
continue
project_url = f"/project/{quote(project, safe='/')}"
boards = list_project_boards(project)
if not boards:
rows.append([
html_link(project_url, project),
create_board_link(project),
"",
])
continue
for b in boards:
board_url = f"{project_url}/board/?b={quote(b['name'], safe='')}"
rows.append([
html_link(project_url, project),
html_link(board_url, b["name"]),
str(b.get("task_count", 0)),
])
return render_page(
"table_page.html",
title=f"{settings.SITE_NAME} - Boards",
heading="Boards",
cols=["Project", "Board", "Tasks"],
rows=rows,
empty_message="No projects found." if not rows else None,
empty_muted=True,
nav="boards",
)
52026a0
d964104 @app.get("/opml", response_class=PlainTextResponse)
7377412 def git_opml(token: Annotated[str | None, Depends(access_token_from_request)]) -> PlainTextResponse:
73c9c30 """OPML feed list. Port of git_opml (stub)."""
projects = filter_projects_by_read_access(
git_get_projects_list(export_ok=settings.EXPORT_OK),
token,
)
# Minimal OPML
lines = ['<?xml version="1.0"?><opml version="1.0"><head><title>Git</title></head><body>']
for pr in projects[:100]:
path = pr.get("path", "")
lines.append(f'<outline text="{jinja_escape(path)}" />')
lines.append("</body></opml>")
return PlainTextResponse("\n".join(lines), media_type="text/xml; charset=utf-8")
d964104
9af949c @app.get("/board/create", response_class=RedirectResponse)
def board_create_page(
ded5e8b _: Annotated[None, Depends(RequirePermission(Permission.BOARDS))],
73c9c30 project: ValidatedBoardCreateProject,
9af949c ) -> RedirectResponse:
73c9c30 """Create a board named 'Tasks' (refs/tags/boards/Tasks) and redirect to the project summary."""
try:
create_board_for_project(project, name="Tasks", description="")
except HTTPException as e:
if e.status_code == 409:
pass
else:
raise
p_url = quote(project, safe="/")
return RedirectResponse(url=f"/project/{p_url}", status_code=303)
9af949c
a29919a # ---------- Add project ----------
239aaa8 _OPTIONAL_REPO_ZIP = File(default=None)
a29919a
@app.get("/projectnamevalid", response_class=HTMLResponse)
60679ee def addproject_namevalid(
73c9c30 _: Annotated[None, Depends(require_permission(Permission.ADD_PROJECTS))],
name: Annotated[str | None, Query()] = None,
4614448 ) -> HTMLResponse:
73c9c30 """Check if project name is valid (requires pgw.addprojects when auth is enabled)."""
if not name:
raise HTTPException(status_code=400, detail="Param 'name' required")
if not is_valid_pathname(name):
raise HTTPException(status_code=400, detail="Invalid project name (no path segments)")
if project_visible_in_list(name):
raise HTTPException(status_code=409, detail="Project already exists")
return HTMLResponse(status_code=200, content=f"Project name '{name}' is valid")
997da40
a29919a
@app.get("/addproject", response_class=HTMLResponse)
60679ee def addproject_page(
73c9c30 token: Annotated[str | None, Depends(access_token_from_request)],
7377412 ) -> HTMLResponse:
73c9c30 """Add project form page."""
show_sign_in_notice = (
settings.AUTH and is_auth_configured(auth_config) and (not token or decode_access_token(token) is None)
)
return render_page(
"addproject.html",
title=f"{settings.SITE_NAME} - Add Project",
show_sign_in_notice=show_sign_in_notice,
empty_repo_form_content=Project.form_content(),
upload_zip_form_content=ProjectZip.form_content(),
nav="add",
)
a29919a
@app.post("/addproject", response_class=HTMLResponse)
async def addproject_submit(
73c9c30 _: Annotated[None, Depends(require_permission(Permission.ADD_PROJECTS))],
request: Request,
project_name: Annotated[str, Form()] = "",
pull_from_remote: Annotated[str, Form()] = "",
perform_maintenance: Annotated[str, Form()] = "off",
create_task_board: Annotated[str, Form()] = "off",
repo_zip: UploadFile | None = _OPTIONAL_REPO_ZIP,
7377412 ) -> RedirectResponse:
73c9c30 """Create a new project (requires pgw.addprojects when auth is enabled)."""
project_name = (project_name or "").strip()
if not project_name:
raise HTTPException(status_code=400, detail="Project name is required")
if not is_valid_pathname(project_name):
raise HTTPException(status_code=400, detail="Invalid project name")
if project_visible_in_list(project_name):
raise HTTPException(status_code=409, detail="Project already exists")
remote_url = (pull_from_remote or "").strip()
do_maintenance = perform_maintenance.lower() in ("on", "1", "true", "yes")
do_task_board = create_task_board.lower() in ("on", "1", "true", "yes")
dest_path = os.path.join(settings.PROJECTROOT, project_name)
os.makedirs(settings.PROJECTROOT, exist_ok=True)
try:
if repo_zip and repo_zip.filename and repo_zip.filename.lower().endswith(".zip"):
content = await repo_zip.read()
with ProjectZip(
path=dest_path,
zip_content=content,
create_task_board=do_task_board,
do_maintenance=do_maintenance,
):
pass
else:
with Project(
path=dest_path,
remote_url=remote_url or None,
create_task_board=do_task_board,
do_maintenance=do_maintenance,
):
pass
except pygit2.GitError as e:
raise HTTPException(status_code=400, detail=f"Git error: {e}") from e
except HTTPException:
raise
except OSError as e:
raise HTTPException(status_code=500, detail=str(e)) from e
return RedirectResponse(url=f"/project/{project_name}", status_code=303)
a29919a
d964104 # ---------- Routes (project required) ----------
9af949c @app.get("/project/{project:path}/board/", response_class=HTMLResponse)
def project_board(
73c9c30 project: ValidatedReadableProject,
board: Annotated[str, Query(alias="b")] = "Tasks",
9af949c ) -> HTMLResponse:
73c9c30 """Board view: columns (dropzones) and task cards."""
board_name = board
project_url = f"/project/{quote(project, safe='/')}"
board_url = f"{project_url}/board/"
columns = get_board_tasks_grouped(project, board_name)
for col in columns:
for t in col["tasks"]:
t["task_url"] = f"{board_url}?task={quote(t['ref'], safe='')}"
return render_page(
"board.html",
title=f"{project} - Board",
project=project,
project_url=project_url,
board_name=board_name,
nav="boards",
board_url=board_url,
columns=columns,
)
9af949c
83f6159 @app.get("/project/{project:path}/blog/", response_class=HTMLResponse)
def project_blog(project: ValidatedReadableProject) -> HTMLResponse:
73c9c30 """Markdown blog viewer for repos with articles/manifest.json at HEAD."""
if not project_has_blog(project):
raise HTTPException(status_code=404, detail="Blog not found")
project_enc = quote(project, safe="/")
project_url = f"/project/{project_enc}"
blog_url = f"{project_url}/blog/"
return render_page(
"blog.html",
title=f"{project} - Blog",
project=project,
project_url=project_url,
blog_url=blog_url,
content_base=f"{blog_url}raw/",
manifest_path=BLOG_MANIFEST_PATH,
nav="projects",
)
83f6159
@app.get("/project/{project:path}/blog/raw/{path:path}")
def project_blog_raw(project: ValidatedReadableProject, path: str) -> Response:
73c9c30 """Raw blob from HEAD for the blog viewer (markdown, manifest, assets)."""
return git_blog_raw(project, path)
83f6159
8dc22a4 @app.get("/project/{project:path}/board-ref-manifest")
def project_board_ref_manifest(
73c9c30 project: ValidatedReadableProject,
board: Annotated[str, Query(alias="b")] = "Tasks",
8dc22a4 ) -> BoardRefManifest:
73c9c30 """JSON manifest of recent commits and board/MR refs for @ / # autocomplete."""
return board_ref_manifest(project, board)
8dc22a4
bb40e9d @app.get("/project/{project:path}/summary-refs")
7377412 def project_summary_refs(project: ValidatedReadableProject) -> SummaryRefsPayload:
73c9c30 return {"options": summary_ref_options(project)}
bb40e9d
@app.get("/project/{project:path}/summary-ref-state")
def project_summary_ref_state(
73c9c30 project: ValidatedReadableProject,
ref: Annotated[str | None, Query(alias="ref")] = None,
7377412 ) -> SummaryRefState:
73c9c30 return summary_ref_state(project, ref)
bb40e9d
de79289 @app.get("/project/{project:path}/search", response_class=HTMLResponse)
fbd311b def project_search_page(project: ValidatedReadableProject) -> HTMLResponse:
73c9c30 """Per-project search page (UI only; results fetched from /project/{project}?a=search)."""
return git_search_page(project)
de79289
11b5ebf @app.get("/project/{project:path}/subpage/{subpage_name}", response_class=HTMLResponse)
def project_subpage(
73c9c30 project: ValidatedReadableProject,
subpage_name: str,
raw: Annotated[bool, Query()] = False,
11b5ebf ) -> HTMLResponse:
73c9c30 for subpage in SUBPAGES:
if subpage.subpage_name() != subpage_name:
continue
content = subpage.subpage_html(project)
if content is None:
raise HTTPException(status_code=404, detail="No content for subpage")
content_lc = content.lstrip().lower()
title = f"{subpage.link_name(project) or subpage_name} - {project}"
if content_lc.startswith("<!doctype html") or "<html" in content_lc:
if raw:
stylesheet_href = "/static/main.css"
link_tag = f'<link rel="stylesheet" href="{stylesheet_href}">'
if "<head" in content.lower():
return HTMLResponse(content.replace("</head>", f"{link_tag}</head>", 1))
return HTMLResponse(f"{link_tag}{content}")
project_enc = quote(project, safe="/")
subpage_enc = quote(subpage_name, safe="")
return render_page(
"subpage.html",
title=title,
project=project,
subpage_name=subpage_name,
iframe_src=f"/project/{project_enc}/subpage/{subpage_enc}?raw=true",
)
return render_page(
"subpage.html",
title=title,
project=project,
subpage_name=subpage_name,
content=trusted_html(content),
)
raise HTTPException(status_code=404, detail="Unknown subpage")
11b5ebf
9f381bb @app.post("/project/{project:path}/hook")
dfe0870 def project_hook(
73c9c30 project: ValidatedReadableProject,
name: Annotated[str, Query(alias="name")],
token: Annotated[str | None, Depends(access_token_from_request)],
op: Annotated[HookInstallOp, Query(alias="op")] = "check",
dfe0870 ) -> JSONResponse:
73c9c30 """Add, remove, or check a pygittools hook sample (or bundle of samples) for a project.
`name` may be a sample filename (e.g. `post-receive.notify`) or a bundle name
(e.g. `update`, which installs both `post-commit.notify` and `post-receive.notify`).
`op` is `add`, `remove`, or `check`.
"""
if op != "check":
ensure_permission(Permission.HOOKS, project, token=token)
bundle = get_bundle(name)
sample = get_sample(name) if bundle is None else None
if bundle is None and sample is None:
raise HTTPException(status_code=404, detail=f"Unknown hook sample or bundle: {name}")
try:
if bundle is not None:
if op == "add":
result_status: HookStatus = install_hook_bundle(project, name)
if result_status == HookStatus.DIFFERENT:
raise HTTPException(
status_code=409,
detail="One or more custom hooks installed; refusing to add",
)
elif op == "remove":
result_status = remove_hook_bundle(project, name)
if result_status == HookStatus.DIFFERENT:
raise HTTPException(
status_code=409,
detail="One or more custom hooks installed; refusing to remove",
)
else:
result_status = bundle_status(project, name)
else:
assert sample is not None
if op == "add":
result_status = install_hook(project, name)
if result_status == HookStatus.DIFFERENT:
raise HTTPException(
status_code=409,
detail="A different hook is already installed at this path; refusing to overwrite",
)
elif op == "remove":
result_status = remove_hook(project, name)
if result_status == HookStatus.DIFFERENT:
raise HTTPException(
status_code=409,
detail="Installed hook content differs from the sample; refusing to remove",
)
else:
result_status = hook_status(project, name)
except OSError as e:
raise HTTPException(status_code=500, detail=str(e)) from e
if bundle is not None:
body: dict[str, object] = {
"project": project,
"kind": "bundle",
"name": name,
"label": bundle["label"],
"members": [m["name"] for m in bundle["members"]],
"op": op,
"status": result_status.value,
"installed": result_status == HookStatus.INSTALLED,
}
else:
assert sample is not None
body = {
"project": project,
"kind": "sample",
"name": name,
"target": sample["target"],
"label": sample["label"],
"op": op,
"status": result_status.value,
"installed": result_status == HookStatus.INSTALLED,
}
return JSONResponse(body)
dfe0870
9f381bb @app.get("/project/{project:path}/hooks")
fbd311b def project_hooks_list(project: ValidatedReadableProject) -> JSONResponse:
73c9c30 """List all hook samples and bundles with current status in this project's hooks dir."""
samples_out: list[dict[str, object]] = []
for sample in list_samples():
try:
st: HookStatus = hook_status(project, sample["name"])
except KeyError:
continue
samples_out.append({
"name": sample["name"],
"target": sample["target"],
"label": sample["label"],
"status": st.value,
"installed": st == HookStatus.INSTALLED,
})
bundles_out: list[dict[str, object]] = []
for bundle in list_bundles():
try:
bst: HookStatus = bundle_status(project, bundle["name"])
except KeyError:
continue
bundles_out.append({
"name": bundle["name"],
"label": bundle["label"],
"members": [m["name"] for m in bundle["members"]],
"status": bst.value,
"installed": bst == HookStatus.INSTALLED,
})
return JSONResponse({"project": project, "hooks": samples_out, "bundles": bundles_out})
dfe0870
9f381bb @app.post("/_internal/notify")
1e48deb async def internal_notify(
73c9c30 _: Annotated[None, Depends(require_loopback_client)],
project: ValidatedNotifyProject,
1e48deb ) -> JSONResponse:
73c9c30 """Notify long-polling subscribers that a project's refs changed.
dfe0870
73c9c30 Intended for server-side hooks (pre-receive / post-receive) running on the same host.
"""
woken = await CHANGE_QUEUE.notify(project)
return JSONResponse({"project": project, "waiters_woken": woken})
dfe0870
df79f94 @app.get("/project/{project:path}", response_class=HTMLResponse)
dfe0870 async def dispatch(
73c9c30 request: Request,
project: ValidatedReadableProject,
token: Annotated[str | None, Depends(access_token_from_request)],
a: Annotated[str | None, Query(alias="a")] = None,
h: Annotated[str | None, Query(alias="h")] = None,
hb: Annotated[str | None, Query(alias="hb")] = None,
f: Annotated[str | None, Query(alias="f")] = None,
fp: Annotated[str | None, Query(alias="fp")] = None,
page: Annotated[str | None, Query(alias="page")] = None,
pagecount: Annotated[str | None, Query(alias="pagecount")] = None,
updates: Annotated[str | None, Query(alias="updates")] = None,
pf: Annotated[str | None, Query(alias="pf")] = None,
search_patterns: Annotated[str | None, Query(alias="patterns")] = None,
search_paths: Annotated[str | None, Query(alias="paths")] = None,
search_globs: Annotated[str | None, Query(alias="globs")] = None,
search_heading: Annotated[SearchFlagQuery | None, Query(alias="heading")] = None,
search_multiline: Annotated[SearchFlagQuery | None, Query(alias="multiline")] = None,
search_sort: Annotated[SearchSortQuery | None, Query(alias="sort")] = None,
search_max_count: Annotated[str | None, Query(alias="max_count")] = None,
notice: Annotated[str | None, Query(alias="notice")] = None,
4614448 ) -> Response:
73c9c30 """
Dispatch by path: /project/{project} -> summary; /project/{project}/action/... -> action.
Port of dispatch + run_request path handling.
"""
action = a
hash_param = h or hb
file_name = f
file_parent = fp
# If no action, infer: hash only -> object type; project only -> summary
if not action:
if hash_param and file_name:
obj_type = git_get_type(project, f"{hash_param}:{file_name}")
if not obj_type:
raise HTTPException(status_code=404, detail="File or directory does not exist")
action = "tree" if obj_type == "tree" else "blob_plain"
elif hash_param:
obj_type = git_get_type(project, hash_param)
if not obj_type:
raise HTTPException(status_code=404, detail="Object does not exist")
action = {
"commit": "commit",
"tree": "tree",
"blob": "blob",
"tag": "tag",
}.get(obj_type, "object")
else:
action = "summary"
if action not in DISPATCH_ACTIONS:
raise HTTPException(status_code=400, detail="Unknown action")
if action in ("opml", "project_list", "project_index"):
raise HTTPException(status_code=400, detail="Project not needed for this action")
if _parse_updates_flag(updates):
if action not in UPDATES_SUPPORTED_ACTIONS:
raise HTTPException(status_code=400, detail="updates not supported for this action")
subscribed = _resolve_subscribed_projects(project, pf)
if getattr(request.app.state, "shutting_down", False):
return _updates_idle_response()
shutdown_ev: asyncio.Event | None = getattr(request.app.state, "shutdown_event", None)
notified = await CHANGE_QUEUE.wait_for_changes(
subscribed,
timeout=CHANGE_QUEUE.DEFAULT_TIMEOUT_SECONDS,
shutdown_event=shutdown_ev,
)
if notified is None:
return _updates_idle_response()
if action in PLUGIN_ACTIONS:
plugin = PLUGIN_ACTIONS[action]
result = plugin.action(project, request)
if result is not None:
return result
return render_page(
"message.html",
title=f"{plugin.action_name()} - {project}",
paragraphs=["Action completed."],
)
if action == "summary":
return git_summary(project, extra_rows=_project_subpage_rows(project))
if action == "tree":
return git_tree(project, hash_param, file_name)
if action in ("blob", "blob_plain"):
return git_blob(project, hash_param, file_name, raw=(action == "blob_plain"))
if action == "blame":
return git_blame(project, hash_param, file_name)
if action == "blame_raw":
return git_blame_raw(project, hash_param, file_name)
if action == "blobdiff":
return git_blobdiff(project, h, hb, file_name, file_parent)
if action == "blobpatch":
return git_blobpatch(project, h, hb, file_name, file_parent)
if action == "log":
p, pc = parse_pagination(page, pagecount)
return git_log(project, hash_param, request, p, pc)
if action == "shortlog":
p, pc = parse_pagination(page, pagecount)
return git_shortlog(project, hash_param, request, p, pc)
if action == "history":
p, pc = parse_pagination(page, pagecount)
return git_history(project, hash_param, file_name, request, p, pc)
if action == "heads":
return git_heads(project)
if action == "tags":
p, pc = parse_pagination(page, pagecount)
return git_tags(project, request, p, pc)
if action == "tag":
return git_tag(project, hash_param, notice=notice)
if action == "commit":
return git_commit(project, hash_param)
if action == "patch":
return git_patch(project, h)
if action == "patches":
return git_patches(project, h, hb)
if action == "commitdiff":
return git_commitdiff(project, hash_param)
if action == "remotes":
return git_remotes(project)
if action == "object":
return git_object(project, hash_param)
if action == "search":
return git_search(
project,
search_patterns,
search_paths,
search_globs,
search_heading,
search_multiline,
search_sort,
search_max_count,
)
# Stub others with minimal response
return render_page(
"message.html",
title=f"{action} - {project}",
paragraphs=[f"Action: {action}", f"Project: {project}"],
)
b4792a4
d964104 if __name__ == "__main__":
73c9c30 import uvicorn
997da40
73c9c30 uvicorn.run(app, host="0.0.0.0", port=8000)