1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
"""
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)