d964104 997da40 d964104 19e7c78 a29919a 2b8fce2 ae1889a 7947ec5 d964104 65ca31f 215041e d964104 a29919a 85b8192 dfe0870 d964104 26f0919 997da40 65ca31f 267233d 997da40 de79289 997da40 bb40e9d 997da40 1c90f78 85b8192 fbd311b 60679ee e6c6972 85b8192 608d8b2 dfe0870 0b3610d a2948bf fbd311b a2948bf 1e48deb a2948bf 69644d2 26f0919 dfe0870 4401744 e6c6972 521172d 997da40 8c60507 ccd8854 2b8fce2 275a710 997da40 69644d2 ae1889a a2948bf d964104 dfe0870 65ca31f dfe0870 19e7c78 ae1889a 19e7c78 2b8fce2 521172d 2b8fce2 ae1889a 19e7c78 521172d 2b8fce2 19e7c78 8c60507 ae1889a b4f548a 9ad78c1 fb2fe5d 997da40 b4f548a 997da40 19e7c78 fb2fe5d 57230a6 b2267f4 57230a6 d964104 997da40 d964104 85b8192 ccd8854 3ee2226 4401744 275a710 ccd8854 d964104 997da40 0b3610d 997da40 6208a28 997da40 d964104 521172d 11b5ebf 521172d 11b5ebf 367a341 11b5ebf 69644d2 367a341 11b5ebf d964104 997da40 fbd311b 65ca31f 997da40 65ca31f d964104 997da40 fbd311b 997da40 26f0919 997da40 fbd311b 997da40 fbd311b 997da40 259cf17 997da40 26f0919 997da40 69644d2 997da40 69644d2 fbd311b d964104 fbd311b 997da40 d964104 997da40 fbd311b 997da40 d964104 7947ec5 fbd311b 7947ec5 fbd311b 7947ec5 2a40553 69644d2 7947ec5 69644d2 0b3610d 2a40553 69644d2 2a40553 69644d2 2a40553 7947ec5 215041e 7947ec5 215041e 7947ec5 69644d2 7947ec5 d964104 fbd311b 997da40 fbd311b 997da40 69644d2 997da40 d964104 9af949c dc408b2 a2948bf 9af949c 259cf17 997da40 a2948bf 997da40 a2948bf 997da40 9af949c a29919a 239aaa8 a29919a 60679ee e6c6972 60679ee e6c6972 215041e a2948bf 997da40 a2948bf 997da40 a2948bf 997da40 a29919a 60679ee 997da40 60679ee 608d8b2 60679ee 997da40 26f0919 997da40 1c90f78 60679ee 1c90f78 997da40 a29919a e6c6972 997da40 239aaa8 a29919a e6c6972 997da40 a2948bf 997da40 26f0919 997da40 1c90f78 997da40 1c90f78 997da40 6208a28 997da40 6208a28 997da40 a29919a d964104 9af949c fbd311b 997da40 9af949c 997da40 69644d2 26f0919 997da40 9af949c bb40e9d fbd311b bb40e9d fbd311b bb40e9d de79289 fbd311b de79289 11b5ebf 521172d fbd311b 11b5ebf 521172d 11b5ebf 69644d2 11b5ebf 0b3610d 11b5ebf 69644d2 11b5ebf 69644d2 11b5ebf dfe0870 fbd311b dfe0870 85b8192 65ca31f dfe0870 85b8192 e6c6972 dfe0870 fbd311b dfe0870 1e48deb dfe0870 df79f94 dfe0870 997da40 fbd311b 997da40 dfe0870 215041e 65ca31f 215041e 827512a d964104 997da40 521172d 997da40 dfe0870 19e7c78 dfe0870 19e7c78 521172d 367a341 997da40 521172d 997da40 267233d 997da40 827512a 997da40 de79289 215041e 997da40 69644d2 b4792a4 d964104 997da40
"""
FastAPI app and routes: gitweb actions as path operations.
Ported from gitweb/gitweb.perl dispatch and action handlers.
"""

from __future__ import annotations

import asyncio
import os
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
from datetime import UTC, datetime
from pathlib import Path
from typing import Annotated, Literal
from urllib.parse import quote, urlencode

import pygit2
from fastapi import Depends, FastAPI, File, Form, HTTPException, Query, Request, UploadFile
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles

from pygitweb import __meta__
from pygitweb.actions import (
	SearchFlagQuery,
	SearchSortQuery,
	git_blame,
	git_blame_raw,
	git_blob,
	git_blobdiff,
	git_blobpatch,
	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,
	summary_ref_options,
	summary_ref_state,
)
from pygitweb.api.plugins.project_zip import ProjectZip
from pygitweb.api.project import Project
from pygitweb.auth import (
	access_token_from_request,
	auth_router,
	can_read_project,
	decode_access_token,
	ensure_permission,
	require_permission,
)
from pygitweb.auth_config import auth_config, is_auth_configured
from pygitweb.change_queue import CHANGE_QUEUE
from pygitweb.config import ACTIONS, get_loadavg, settings
from pygitweb.dependencies import (
	ValidatedBoardCreateProject,
	ValidatedNotifyProject,
	ValidatedReadableProject,
	filter_projects_by_read_access,
	project_visible_in_list,
	require_loopback_client,
)
from pygitweb.formatting import age_string
from pygitweb.git_helpers import git_get_references, git_get_type
from pygitweb.hooks_install import (
	HookStatus,
	bundle_status,
	get_bundle,
	get_sample,
	list_bundles,
	list_samples,
)
from pygitweb.hooks_install import (
	install as install_hook,
)
from pygitweb.hooks_install import (
	install_bundle as install_hook_bundle,
)
from pygitweb.hooks_install import (
	remove as remove_hook,
)
from pygitweb.hooks_install import (
	remove_bundle as remove_hook_bundle,
)
from pygitweb.hooks_install import (
	status as hook_status,
)
from pygitweb.merge_requests import merge_router
from pygitweb.permissions import Permission
from pygitweb.plugin_registry import PluginRegistry
from pygitweb.projects import git_get_project_owner, git_get_projects_list
from pygitweb.sessions import clear_all_sessions
from pygitweb.settings import router as settings_router
from pygitweb.shutdown import begin_shutdown, install_graceful_shutdown_wakeup
from pygitweb.smart_http import http_router
from pygitweb.tasks import (
	board_router,
	comment_router,
	create_board_for_project,
	get_board_tasks_grouped,
	task_router,
)
from pygitweb.templates_env import POSTAMBLE, PREAMBLE, env, jinja_escape
from pygitweb.timeline_cache import clear_timeline_cache_async, get_all_timeline_events, warm_timeline_cache_async
from pygitweb.validation import is_valid_pathname

UPDATES_SUPPORTED_ACTIONS: frozenset[str] = frozenset({"history", "log", "shortlog", "heads", "tags"})

ProjectListAction = Literal["project_list"]
ProjectListOrder = Literal["none", "project", "descr", "owner", "age"]
HookInstallOp = Literal["add", "remove", "check"]


def _parse_updates_flag(value: str | None) -> bool:
	if value is None:
		return False
	return value.strip().lower() in ("1", "true", "yes", "on")


def _resolve_subscribed_projects(project: str, project_filter: str | None) -> list[str]:
	"""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]


def _updates_idle_response() -> Response:
	return Response(status_code=200, content=b"")


@asynccontextmanager
async def app_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
	app.state.shutting_down = False
	app.state.shutdown_event = asyncio.Event()
	app.state.can_signal_shutdown = False
	plugins = PluginRegistry()
	plugins.load_all()
	app.state.plugins = plugins
	install_graceful_shutdown_wakeup(app)
	warm_timeline_cache_async()
	try:
		yield
	finally:
		plugins.unload_all()
		begin_shutdown(app)
		clear_timeline_cache_async()
		clear_all_sessions()


with open("pygitweb/README.md", encoding="utf-8") as _readme_file:
	_app_description = _readme_file.read()

app = FastAPI(
	debug=(settings.AUTH is False),
	title="PyGitWeb",
	summary="FastAPI + Pygit2 Repo Browser",
	description=_app_description,
	version=__meta__.__version__,
	lifespan=app_lifespan,
	openapi_tags=[
		{
			"name": "auth",
			"description": """Session status, account pages, and sign-out.
Sessions are opaque ids (cookie or Bearer), not IdP JWTs.""",
		},
		{
			"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).
Ends with the same session cookie as local login.""",
		},
	],
)

# Todo handle with nginx route
_static_dir = Path(__file__).parent / "static"
if _static_dir.is_dir():
	app.mount("/static", StaticFiles(directory=str(_static_dir)), name="static")


app.include_router(auth_router)
app.include_router(settings_router)
app.include_router(board_router, prefix="/board")
app.include_router(task_router, prefix="/tasks")
app.include_router(comment_router, prefix="/comments")
app.include_router(merge_router, prefix="/mr")
app.include_router(http_router)


@app.middleware("http")
async def loadavg_middleware(request: Request, call_next):
	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)


def _project_subpage_rows(project: str, plugins: PluginRegistry) -> list[list[str]]:
	project_enc = quote(project, safe="/")
	rows: list[list[str]] = []
	for subpage in plugins.subpages:
		link_label = subpage.link_name(project)
		if not link_label:
			continue
		subpage_name = subpage.subpage_name()
		view = f'<a href="/project/{project_enc}/subpage/{quote(subpage_name, safe="")}">view</a>'
		suffix = subpage.summary_value_suffix_html(project, project_enc)
		value = f"{view}{suffix}" if suffix else view
		rows.append([
			jinja_escape(link_label) or "",
			value,
		])
	return rows


# ---------- Routes (no project) ----------


@app.get("/", response_class=HTMLResponse)
def git_project_list(
	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,
):
	"""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)
	visibility_notice = ""
	if not list_:
		if all_projects and settings.AUTH:
			visibility_notice = (
				'<p class="text-warning">No projects are visible with your current authentication '
				"and permissions. Sign in or ask an administrator for repository access.</p>"
			)
		elif not all_projects:
			visibility_notice = "<p>No projects found.</p>"

	def board_cell(pr: dict) -> str:
		path = pr.get("path", "")
		path_enc = quote(path, safe="/")
		try:
			board_refs = git_get_references(path, "refs/tags/boards")
			has_boards = len(board_refs) > 0
		except Exception:
			has_boards = False
		if has_boards:
			return f'<a href="/project/{path_enc}/board/">project board</a>'
		grey_style = ' style="color: #999; cursor: not-allowed;"' if settings.AUTH else ""
		proj_q = quote(path, safe="")
		return f'<a href="/board/create?project={proj_q}"{grey_style}>create board</a>'

	# We need better escaping logic here but can wait until we harden the templates
	table = env.get_template("table.html").render(
		cols=["Project", "Description", "Board"],
		rows=[
			[
				f"<a href='/project/{quote(pr.get('path', ''), safe='/')}'>{jinja_escape(pr.get('path', ''))}</a>",
				jinja_escape(pr.get("descr") or pr.get("path", "")),
				board_cell(pr),
			]
			for pr in list_[:50]
		],
	)
	pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - Projects", site_name=settings.SITE_NAME)
	return HTMLResponse(f"{pre}<h1>Project List</h1>{visibility_notice}{table}{POSTAMBLE}")


@app.get("/index", response_class=PlainTextResponse)
def git_project_index(
	token: Annotated[str | None, Depends(access_token_from_request)],
	pf: Annotated[str | None, Query(alias="pf")] = None,
):
	"""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")


@app.get("/activity", response_class=HTMLResponse)
def activity_page(
	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,
) -> HTMLResponse:
	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]
	rows: list[list[str]] = []
	for item in events_page:
		project_name = item["project"]
		event = item["event"]
		oid = event["oid"]
		if event["kind"] == "commit":
			event_label = f"<a href='/project/{quote(project_name, safe='/')}"
			event_label += f"?a=commit&h={quote(oid, safe='')}'>{jinja_escape(oid[:7])}</a>"
		else:
			event_label = jinja_escape(event["kind"]) or ""
		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 = ""
		rows.append([
			jinja_escape(activity_time) or "",
			f"<a href='/project/{quote(project_name, safe='/')}'>{jinja_escape(project_name)}</a>",
			event_label,
			jinja_escape(description) or "",
		])
	table = env.get_template("table.html").render(
		cols=["Time", "Project Name", "Event", "Description"],
		rows=rows,
	)
	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)})}"
	pagination_html = env.get_template("pagination.html").render(
		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,
	)
	pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - Activity", site_name=settings.SITE_NAME)
	return HTMLResponse(f"{pre}<h1>Activity</h1>{table}{pagination_html}{POSTAMBLE}")


@app.get("/opml", response_class=PlainTextResponse)
def git_opml(token: Annotated[str | None, Depends(access_token_from_request)]):
	"""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")


@app.get("/board/create", response_class=RedirectResponse)
def board_create_page(
	_: Annotated[None, Depends(require_permission(Permission.BOARDS, project_from_query=True))],
	project: ValidatedBoardCreateProject,
) -> RedirectResponse:
	"""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)


# ---------- Add project ----------

_OPTIONAL_REPO_ZIP = File(default=None)


@app.get("/projectnamevalid", response_class=HTMLResponse)
def addproject_namevalid(
	_: Annotated[None, Depends(require_permission(Permission.ADD_PROJECTS))],
	name: Annotated[str | None, Query()] = None,
):
	"""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")


@app.get("/addproject", response_class=HTMLResponse)
def addproject_page(
	token: Annotated[str | None, Depends(access_token_from_request)],
):
	"""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)
	)
	pre = PREAMBLE.render(
		title=f"{settings.SITE_NAME} - Add Project",
		site_name=settings.SITE_NAME,
	)
	tpl = env.get_template("addproject.html")
	body = tpl.render(
		site_name=settings.SITE_NAME,
		show_sign_in_notice=show_sign_in_notice,
		empty_repo_form_content=Project.form_content(),
		upload_zip_form_content=ProjectZip.form_content(),
	)
	return HTMLResponse(status_code=200, content=f"{pre}{body}{POSTAMBLE}")


@app.post("/addproject", response_class=HTMLResponse)
async def addproject_submit(
	_: 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,
):
	"""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)


# ---------- Routes (project required) ----------


@app.get("/project/{project:path}/board/", response_class=HTMLResponse)
def project_board(
	project: ValidatedReadableProject,
	board: Annotated[str, Query(alias="b")] = "Tasks",
) -> HTMLResponse:
	"""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='')}"
	pre = PREAMBLE.render(
		title=f"{jinja_escape(project)} - Board",
		site_name=settings.SITE_NAME,
	)
	body = env.get_template("board.html").render(
		project=project,
		project_url=project_url,
		board_name=board_name,
		board_url=board_url,
		columns=columns,
	)
	return HTMLResponse(f"{pre}{body}{POSTAMBLE}")


@app.get("/project/{project:path}/summary-refs")
def project_summary_refs(project: ValidatedReadableProject) -> dict[str, list[dict[str, str]]]:
	return {"options": summary_ref_options(project)}


@app.get("/project/{project:path}/summary-ref-state")
def project_summary_ref_state(
	project: ValidatedReadableProject,
	ref: Annotated[str | None, Query(alias="ref")] = None,
) -> dict[str, str]:
	return summary_ref_state(project, ref)


@app.get("/project/{project:path}/search", response_class=HTMLResponse)
def project_search_page(project: ValidatedReadableProject) -> HTMLResponse:
	"""Per-project search page (UI only; results fetched from /project/{project}?a=search)."""
	return git_search_page(project)


@app.get("/project/{project:path}/subpage/{subpage_name}", response_class=HTMLResponse)
def project_subpage(
	request: Request,
	project: ValidatedReadableProject,
	subpage_name: str,
	raw: Annotated[bool, Query()] = False,
) -> HTMLResponse:
	for subpage in request.app.state.plugins.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()
		pre = PREAMBLE.render(
			title=f"{jinja_escape(subpage.link_name(project) or subpage_name)} - {jinja_escape(project)}",
			site_name=settings.SITE_NAME,
		)
		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="")
			iframe_src = f"/project/{project_enc}/subpage/{subpage_enc}?raw=true"
			return HTMLResponse(
				f"{pre}<h1>{jinja_escape(project)}</h1>"
				f'<iframe class="subpage-frame" src="{iframe_src}" title="{jinja_escape(subpage_name)}"></iframe>'
				f"{POSTAMBLE}"
			)
		return HTMLResponse(f"{pre}<h1>{jinja_escape(project)}</h1>{content}{POSTAMBLE}")
	raise HTTPException(status_code=404, detail="Unknown subpage")


@app.post("/project/{project:path}/hook", response_class=JSONResponse)
def project_hook(
	project: ValidatedReadableProject,
	name: Annotated[str, Query(alias="name")],
	token: Annotated[str | None, Depends(access_token_from_request)],
	op: Annotated[HookInstallOp, Query(alias="op")] = "check",
) -> JSONResponse:
	"""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)


@app.get("/project/{project:path}/hooks", response_class=JSONResponse)
def project_hooks_list(project: ValidatedReadableProject) -> JSONResponse:
	"""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})


@app.post("/_internal/notify", response_class=JSONResponse)
async def internal_notify(
	_: Annotated[None, Depends(require_loopback_client)],
	project: ValidatedNotifyProject,
) -> JSONResponse:
	"""Notify long-polling subscribers that a project's refs changed.

	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})


@app.get("/project/{project:path}", response_class=HTMLResponse)
async def dispatch(
	request: Request,
	project: ValidatedReadableProject,
	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,
):
	"""
	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"
	plugins: PluginRegistry = request.app.state.plugins
	if action not in plugins.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 plugins.actions:
		plugin = plugins.actions[action]
		result = plugin.action(project, request)
		if result is not None:
			return result
		pre = PREAMBLE.render(title=f"{plugin.action_name()} - {project}", site_name=settings.SITE_NAME)
		return HTMLResponse(f"{pre}<p>Action completed.</p>{POSTAMBLE}")
	if action == "summary":
		return git_summary(project, extra_rows=_project_subpage_rows(project, plugins))
	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
	pre = PREAMBLE.render(title=f"{action} - {project}", site_name=settings.SITE_NAME)
	return HTMLResponse(f"{pre}<p>Action: {jinja_escape(action)}</p><p>Project: {jinja_escape(project)}</p>{POSTAMBLE}")


if __name__ == "__main__":
	import uvicorn

	uvicorn.run(app, host="0.0.0.0", port=8000)