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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
"""
FastAPI app and routes: gitweb actions as path operations.
Ported from gitweb/gitweb.perl dispatch and action handlers.
"""
from __future__ import annotations
import base64
import mimetypes
import os
import subprocess
import tempfile
import zipfile
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Annotated, Any
import pygit2
from fastapi import FastAPI, File, Form, HTTPException, Query, Request, UploadFile
from fastapi.responses import HTMLResponse, PlainTextResponse, RedirectResponse, Response
from fastapi.staticfiles import StaticFiles
from jinja2 import Template, Environment, PackageLoader
from pygitweb import config, __meta__
from pygitweb.config import (
ACTIONS,
BLOB_LANG,
DISTGIT_AUTH,
DISTGIT_ADMIN_USER,
DISTGIT_ADMIN_PASSWORD,
DISTGIT_SESSION_TIMEOUT,
EXPORT_OK,
PROJECTROOT,
PROJECTS_LIST,
STRICT_EXPORT,
check_loadavg,
configure_gitweb_features,
evaluate_gitweb_config,
get_snapshot_fmts,
)
from pygitweb.formatting import age_string, esc_html, sanitize, to_utf8
from pygitweb.git_helpers import (
get_blob_at_ref_path,
get_blob_unified_diff,
get_commit_history,
get_commits_in_range,
get_tree_at_ref_path,
git_get_head_hash,
git_get_heads_list,
git_get_project_description,
git_get_remotes_info,
git_get_tags_list,
parse_commit,
parse_tag,
)
from pygitweb.projects import (
git_get_projects_list,
git_get_project_list_from_file,
git_get_project_owner,
project_in_list,
)
from pygitweb.validation import (
check_export_ok,
is_valid_action,
is_valid_pathname,
is_valid_project,
is_valid_ref_format,
)
from urllib.parse import quote, urlencode
app = FastAPI(
debug=(DISTGIT_AUTH == "None"),
title="PyGitWeb",
summary="FastAPI + Pygit2 Repo Browser",
description=open("pygitweb/README.md", "r", encoding="utf-8").read(),
version = __meta__.__version__
)
env = Environment(
loader=PackageLoader("pygitweb", "templates"),
# autoescape=True,
trim_blocks=True,
lstrip_blocks=True,
)
PREAMBLE = env.get_template("preamble.html")
POSTAMBLE = """</div></div></div></body></html>"""
# 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")
def _project_in_list(project: str) -> bool:
lst = git_get_projects_list(
filter_path="",
paranoid=STRICT_EXPORT,
export_ok=EXPORT_OK,
)
return any(p.get("path") == project for p in lst)
def _get_project_config(project: str, key: str):
from pygitweb.git_helpers import git_get_project_config
return git_get_project_config(project, key)
_auth_provider = None
def _get_auth_provider():
"""Return auth provider instance if DISTGIT_AUTH is set; None if auth disabled."""
global _auth_provider
if DISTGIT_AUTH == "None":
return None
if _auth_provider is not None:
return _auth_provider
try:
mod_name, _, cls_name = DISTGIT_AUTH.rpartition(".")
mod = __import__(mod_name, fromlist=[cls_name])
cls = getattr(mod, cls_name)
# RootAuthProvider accepts admin_user, admin_password, session_timeout from env
admin_user = DISTGIT_ADMIN_USER.encode("utf-8") or None
admin_password = DISTGIT_ADMIN_PASSWORD.encode("utf-8") or None
timeout = DISTGIT_SESSION_TIMEOUT
_auth_provider = cls(
admin_user=admin_user,
admin_password=admin_password,
session_timeout=timeout,
)
except Exception:
_auth_provider = None
return _auth_provider
def _request_can_add_project(request: Request) -> bool:
"""True if auth is disabled or request has a valid session (header X-Session-Token or param/cookie session)."""
if DISTGIT_AUTH == "None":
return True
provider = _get_auth_provider()
if provider is None:
return False
token = (
request.headers.get("X-Session-Token")
or request.query_params.get("session")
or request.cookies.get("session")
)
if not token:
return False
return getattr(provider, "validate_session", lambda _: False)(token)
@app.on_event("startup")
def startup():
evaluate_gitweb_config()
configure_gitweb_features(
get_project_config=_get_project_config,
git_dir=None,
is_valid_ref_format=is_valid_ref_format,
)
@app.middleware("http")
async def loadavg_middleware(request: Request, call_next):
try:
check_loadavg()
except RuntimeError as e:
msg = str(e)
if msg.startswith("503:"):
raise HTTPException(status_code=503, detail=msg[4:])
raise
return await call_next(request)
def _validate_project(project: str | None) -> str:
if not project:
raise HTTPException(status_code=400, detail="Project needed")
if not is_valid_project(
project,
PROJECTROOT,
EXPORT_OK,
STRICT_EXPORT,
_project_in_list,
):
raise HTTPException(status_code=404, detail="No such project")
return project
# ---------- Routes (no project) ----------
@app.get("/", response_class=HTMLResponse)
def git_project_list(
request: Request,
a: Annotated[str | None, Query(alias="a")] = None,
pf: Annotated[str | None, Query(alias="pf")] = None,
o: Annotated[str | None, Query(alias="o")] = None,
):
"""Project list page. Port of git_project_list."""
if a and a != "project_list":
raise HTTPException(status_code=400, detail="Unknown action")
if o and o not in ("none", "project", "descr", "owner", "age"):
raise HTTPException(status_code=400, detail="Unknown order parameter")
project_filter = pf or ""
list_ = git_get_projects_list(
filter_path=project_filter,
paranoid=STRICT_EXPORT,
export_ok=EXPORT_OK,
)
if not list_:
raise HTTPException(status_code=404, detail="No projects found")
# We need better escaping logic here but can wait until we harden the templates
table = env.get_template("table.html").render(
cols=["Project", "Description"],
rows=[
[f"<a href='/{pr.get('path', "")}'>{pr.get('path', "")}</a>",
pr.get('descr') or pr.get('path', "")]
for pr in list_[:50]]
)
pre = PREAMBLE.render(title=f'{esc_html(config.SITE_NAME)} - Projects', site_name=config.SITE_NAME)
return HTMLResponse(f"{pre}<h1>Project List</h1>{table}{POSTAMBLE}")
@app.get("/index", response_class=PlainTextResponse)
def git_project_index(
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 = git_get_projects_list(
filter_path=pf or "",
paranoid=STRICT_EXPORT,
export_ok=EXPORT_OK,
)
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("/opml", response_class=PlainTextResponse)
def git_opml():
"""OPML feed list. Port of git_opml (stub)."""
projects = git_get_projects_list(export_ok=EXPORT_OK)
# 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="{esc_html(path)}" />')
lines.append("</body></opml>")
return PlainTextResponse("\n".join(lines), media_type="text/xml; charset=utf-8")
# ---------- Add project ----------
@app.get("/projectnamevalid", response_class=HTMLResponse)
def addproject_namevalid(request: Request):
"""Check if project name is valid."""
project_name = request.query_params.get("name")
if not project_name:
raise HTTPException(status_code=400, detail="Param 'name' required")
if not is_valid_pathname(project_name):
raise HTTPException(status_code=400, detail="Invalid project name (no path segments)")
if _project_in_list(project_name):
raise HTTPException(status_code=409, detail="Project already exists")
return HTMLResponse(status_code=200, content=f"Project name '{project_name}' is valid")
@app.get("/addproject", response_class=HTMLResponse)
def addproject_page(request: Request):
"""Add project form page."""
pre = PREAMBLE.render(
title=f"{config.SITE_NAME} - Add Project",
site_name=config.SITE_NAME,
)
tpl = env.get_template("addproject.html")
body = tpl.render(site_name=config.SITE_NAME)
return HTMLResponse(status_code=200, content=f"{pre}{body}{POSTAMBLE}")
@app.post("/addproject", response_class=HTMLResponse)
async def addproject_submit(
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 = File(default=None),
):
"""
Create a new project. Allowed only if project name does not exist,
and valid session in headers / session param (or auth is disabled).
"""
if not _request_can_add_project(request):
raise HTTPException(status_code=401, detail="Authentication required to add projects")
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_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(PROJECTROOT, project_name)
os.makedirs(PROJECTROOT, exist_ok=True)
try:
if remote_url and remote_url != "":
pygit2.clone_repository(remote_url, dest_path, bare=True)
elif repo_zip and repo_zip.filename and repo_zip.filename.lower().endswith(".zip"):
with tempfile.TemporaryDirectory() as tmpdir:
zip_path = os.path.join(tmpdir, "repo.zip")
content = await repo_zip.read()
with open(zip_path, "wb") as f:
f.write(content)
with zipfile.ZipFile(zip_path, "r") as zf:
zf.extractall(tmpdir)
# Find .git: either at root or inside a single top-level dir
repo_root = None
for name in os.listdir(tmpdir):
if name == "repo.zip":
continue
p = os.path.join(tmpdir, name)
if os.path.isdir(p):
if os.path.isdir(os.path.join(p, ".git")):
repo_root = p
break
if name == ".git":
repo_root = tmpdir
break
if repo_root is None:
if os.path.isdir(os.path.join(tmpdir, ".git")):
repo_root = tmpdir
else:
# Single subdir that might be the repo
subs = [x for x in os.listdir(tmpdir) if x != "repo.zip" and os.path.isdir(os.path.join(tmpdir, x))]
if len(subs) == 1:
repo_root = os.path.join(tmpdir, subs[0])
if repo_root is None or not pygit2.discover_repository(repo_root):
raise HTTPException(
status_code=400,
detail="ZIP must contain a git repository (directory with .git)",
)
pygit2.clone_repository(repo_root, dest_path, bare=True)
else:
pygit2.init_repository(dest_path, bare=True)
if do_maintenance:
try:
subprocess.run(
[config.GIT, "-C", dest_path, "maintenance", "start"],
capture_output=True,
timeout=60,
)
except (subprocess.SubprocessError, FileNotFoundError):
pass # best-effort
if do_task_board:
pass # stub
except pygit2.GitError as e:
raise HTTPException(status_code=400, detail=f"Git error: {e}")
except HTTPException:
raise
except OSError as e:
raise HTTPException(status_code=500, detail=str(e))
return RedirectResponse(url=f"/{project_name}", status_code=303)
# ---------- Routes (project required) ----------
def _pagination_url(request: Request, page: int, pagecount: int) -> str:
"""Build URL for a pagination page, preserving path and other query params."""
params = dict(request.query_params)
params["page"] = str(page)
params["pagecount"] = str(pagecount)
return f"{request.url.path}?{urlencode(params)}"
def _parse_pagination(
page: str | None,
pagecount: str | None,
) -> tuple[int, int]:
"""Parse page and pagecount; default 1 and 25; raise if pagecount > 50."""
p = 1
pc = 25
if page is not None:
try:
p = int(page)
except ValueError:
raise HTTPException(status_code=400, detail="page must be an integer")
if p < 1:
raise HTTPException(status_code=400, detail="page must be at least 1")
if pagecount is not None:
try:
pc = int(pagecount)
except ValueError:
raise HTTPException(status_code=400, detail="pagecount must be an integer")
if pc < 1:
raise HTTPException(status_code=400, detail="pagecount must be at least 1")
if pc > 50:
raise HTTPException(status_code=400, detail="pagecount must not exceed 50")
return p, pc
@app.get("/{project:path}", response_class=HTMLResponse)
def dispatch(
request: Request,
project: str,
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,
):
"""
Dispatch by path: /project -> summary; /project/action/... -> action.
Port of dispatch + run_request path handling.
"""
# Normalize project: first path segment that is a valid repo
segments = [s for s in project.split("/") if s]
if not segments:
raise HTTPException(status_code=400, detail="Project needed")
proj = segments[0]
_validate_project(proj)
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 = _object_type(proj, 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 = _object_type(proj, 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 not is_valid_action(action, 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")
# Route to handler
if action == "summary":
return git_summary(proj)
if action == "tree":
return git_tree(proj, hash_param, file_name)
if action in ("blob", "blob_plain"):
return git_blob(proj, hash_param, file_name, raw=(action == "blob_plain"))
if action == "blobdiff":
return git_blobdiff(proj, h, hb, file_name, file_parent)
if action == "blobpatch":
return git_blobpatch(proj, h, hb, file_name, file_parent)
if action == "log":
p, pc = _parse_pagination(page, pagecount)
return git_log(proj, hash_param, request, p, pc)
if action == "shortlog":
p, pc = _parse_pagination(page, pagecount)
return git_shortlog(proj, hash_param, request, p, pc)
if action == "history":
p, pc = _parse_pagination(page, pagecount)
return git_history(proj, hash_param, file_name, request, p, pc)
if action == "heads":
return git_heads(proj)
if action == "tags":
p, pc = _parse_pagination(page, pagecount)
return git_tags(proj, request, p, pc)
if action == "tag":
return git_tag(proj, hash_param)
if action == "commit":
return git_commit(proj, hash_param)
if action == "patch":
return git_patch(proj, h)
if action == "patches":
return git_patches(proj, h, hb)
if action == "commitdiff":
return git_commitdiff(proj, hash_param)
if action == "remotes":
return git_remotes(proj)
# Stub others with minimal response
pre = PREAMBLE.render(title=f"{esc_html(action)} - {esc_html(proj)}", site_name=config.SITE_NAME)
return HTMLResponse(
f"{pre}<p>Action: {esc_html(action)}</p><p>Project: {esc_html(proj)}</p>{POSTAMBLE}"
)
def _object_type(project: str, ref: str) -> str | None:
from pygitweb.git_helpers import git_get_type
return git_get_type(project, ref)
# Common README filenames to look for (order matters: prefer README.md)
README_CANDIDATES = ["README.md", "README", "readme.md", "readme", "Readme.md"]
def _get_readme_at_ref_path(
project: str, ref: str | None, dir_path: str | None
) -> tuple[str, str] | None:
"""If a README exists at ref in the given tree (dir_path), return (filename, utf8_content). Otherwise None.
dir_path is the tree path (e.g. '' for root, 'docs' for docs/)."""
if not ref:
return None
for name in README_CANDIDATES:
path = f"{dir_path.strip('/')}/{name}".strip("/") if dir_path else name
result = get_blob_at_ref_path(project, ref, path)
if result:
blob, _ = result
text = to_utf8(blob.data) or ""
return (name, text)
return None
def _render_readme_card(
project: str,
ref_oid: str,
readme_filename: str,
readme_content: str,
blob_dir: str = "",
) -> str:
"""Return HTML for the README card (and script for markdown). blob_dir is the current tree path for relative links."""
is_markdown = readme_filename.lower().endswith(".md")
blob_base = f"/{project}?a=blob&h={quote(ref_oid, safe='')}&f="
blob_base_attr = blob_base.replace("&", "&").replace('"', """)
blob_dir_attr = blob_dir.replace("&", "&").replace('"', """) if blob_dir else ""
if is_markdown:
readme_b64 = base64.b64encode(readme_content.encode("utf-8")).decode("ascii")
card = (
'<div class="card mt-3"><div class="card-header"><h2 class="card-title">README</h2></div>'
'<div class="card-body"><div id="readme-container" class="markdown-body" data-readme-b64="'
+ readme_b64
+ '" data-blob-base="'
+ blob_base_attr
+ '"'
)
if blob_dir_attr:
card += ' data-blob-dir="' + blob_dir_attr + '"'
card += '></div></div></div><script src="/static/readme-render.js"></script>'
return card
return (
'<div class="card mt-3"><div class="card-header"><h2 class="card-title">README</h2></div>'
'<div class="card-body"><pre class="readme-plain"><code>'
+ esc_html(sanitize(readme_content) or "")
+ "</code></pre></div></div>"
)
def git_summary(project: str) -> HTMLResponse:
"""Project summary page. Port of git_summary."""
descr = git_get_project_description(project) or "none"
owner = git_get_project_owner(project) or ""
head = git_get_head_hash(project)
co = parse_commit(project, head) if head else {}
head_short = head[:7] if head else ""
table = env.get_template("table.html").render(
cols=["Field", "Value"],
rows=[
["Description", esc_html(descr)],
["Owner", esc_html(owner)],
[esc_html("HEAD"), f"<a href='/{project}?a=commit&h={quote(head or '', safe='')}'>{head_short or 'N/A'}</a>"],
[esc_html("tree"), f"<a href='/{project}?a=tree&h={head or ''}'>browse</a>"],
["Log", f"<a href='/{project}?a=log&h={head or ''}'>view log</a>"],
["Shortlog", f"<a href='/{project}?a=shortlog&h={head or ''}'>view shortlog</a>"],
["Heads", f"<a href='/{project}?a=heads'>view heads</a>"],
["Tags", f"<a href='/{project}?a=tags'>view tags</a>"],
["Remotes", f"<a href='/{project}?a=remotes'>view remotes</a>"],
]
)
pre = PREAMBLE.render(title=f"{esc_html(config.SITE_NAME)} - {project}", site_name=config.SITE_NAME)
body_parts = [f"{pre}<h1>{esc_html(project)}</h1>{table}"]
readme = _get_readme_at_ref_path(project, head, "")
if readme:
readme_filename, readme_content = readme
body_parts.append(_render_readme_card(project, head or "", readme_filename, readme_content, ""))
body_parts.append(POSTAMBLE)
return HTMLResponse("".join(body_parts))
def git_remotes(project: str) -> HTMLResponse:
"""Remotes page: list configured remotes (name, url, push_url)."""
remotes = git_get_remotes_info(project)
if not remotes:
pre = PREAMBLE.render(title=f"Remotes - {esc_html(project)}", site_name=config.SITE_NAME)
return HTMLResponse(
f"{pre}<h1>Remotes</h1><p>No remotes configured.</p>{POSTAMBLE}"
)
rows = []
for r in remotes:
name = esc_html(r["name"])
url = esc_html(r["url"] or "—")
push_url = esc_html(r["push_url"] or "—")
rows.append([name, url, push_url])
table = env.get_template("table.html").render(
cols=["Name", "URL", "Push URL"],
rows=rows,
)
pre = PREAMBLE.render(title=f"Remotes - {esc_html(project)}", site_name=config.SITE_NAME)
return HTMLResponse(f"{pre}<h1>Remotes</h1>{table}{POSTAMBLE}")
def _tree_url(project: str, h: str, f: str | None, a: str = "tree") -> str:
"""Build URL for tree or blob: /project?a=a&h=h&f=f with f quoted."""
q = f"a={a}&h={quote(h, safe='')}"
if f:
q += f"&f={quote(f, safe='/')}"
return f"/{project}?{q}"
def git_blob(project: str, h: str | None, f: str | None, *, raw: bool = False) -> Response:
"""Return blob content when f points to a file. Raw = bytes; else HTML with escaped content."""
if not f:
raise HTTPException(status_code=400, detail="File path (f) required")
if not is_valid_pathname(f):
raise HTTPException(status_code=400, detail="Invalid path")
result = get_blob_at_ref_path(project, h, f)
if not result:
raise HTTPException(status_code=404, detail="File not found")
blob, _ = result
data = blob.data
if raw:
media_type, _ = mimetypes.guess_type(f.split("/")[-1])
if media_type is None:
try:
data.decode("utf-8")
media_type = "text/plain; charset=utf-8"
except UnicodeDecodeError:
media_type = "application/octet-stream"
return Response(content=data, media_type=media_type)
# HTML view: raw content, escaped for safe display (so HTML/XML/SVG are not parsed as DOM)
text = to_utf8(data) or ""
body = esc_html(sanitize(text) or "") or ""
lines = text.split("\n")
num_lines = max(1, len(lines))
line_nums = "\n".join(str(i) for i in range(1, num_lines + 1))
ext = os.path.splitext(f.split("/")[-1])[1].lstrip(".").lower()
lang = BLOB_LANG.get(ext, "")
lang_attr = f" language-{lang}" if lang else ""
blob_html = (
f"<div class=\"blob-view\">"
f"<div class=\"blob-line-nums\" aria-hidden=\"true\">{esc_html(line_nums)}</div>"
f"<pre class=\"blob-content\"><code class=\"hljs{lang_attr}\">{body}</code></pre>"
f"</div>"
)
blob_script = '<script src="static/blob-view.js"></script>'
pre = PREAMBLE.render(title=f"{esc_html(f)} - {esc_html(project)}", site_name=config.SITE_NAME)
return HTMLResponse(f"{pre}{blob_html}{blob_script}{POSTAMBLE}")
def git_tree(project: str, h: str | None, f: str | None) -> HTMLResponse:
"""Tree page: list files and directories; directories link to tree with f=path."""
if f is not None and not is_valid_pathname(f):
raise HTTPException(status_code=400, detail="Invalid path")
result = get_tree_at_ref_path(project, h, f)
if not result:
raise HTTPException(status_code=404, detail="Tree or path not found")
tree, ref_oid = result
# Breadcrumb: project -> path segments
base = f"/{project}"
breadcrumbs = [f'<a href="{base}">{esc_html(project)}</a>']
if f:
parts = f.strip("/").split("/")
for i, seg in enumerate(parts):
prefix = "/".join(parts[: i + 1])
breadcrumbs.append(
f' / <a href="{_tree_url(project, ref_oid, prefix)}">{esc_html(seg)}</a>'
)
breadcrumb_html = "".join(breadcrumbs)
# List entries: dirs first then files, sorted by name
entries = [(obj.name, obj.type_str, str(obj.id)) for obj in tree]
dirs = sorted((n, t, o) for n, t, o in entries if t == "tree")
blobs = sorted((n, t, o) for n, t, o in entries if t == "blob")
rows = []
for name, typ, _ in dirs:
sub_path = f"{f.strip('/')}/{name}".strip("/") if f else name
link = _tree_url(project, ref_oid, sub_path)
rows.append(
[f'<a href="{link}">{esc_html(name)}/</a>', "tree"]
)
for name, typ, _ in blobs:
sub_path = f"{f.strip('/')}/{name}".strip("/") if f else name
link = _tree_url(project, ref_oid, sub_path, a="blob")
rows.append(
[f'<a href="{link}">{esc_html(name)}</a>', "blob"]
)
title_path = f" / {f}" if f else ""
pre = PREAMBLE.render(title=f"{esc_html(project)}{esc_html(title_path)} - Tree", site_name=config.SITE_NAME)
table = env.get_template("table.html").render(
cols=["Name", "Type"],
rows=rows
)
body_parts = [
f"{pre}<p class='breadcrumb'>{breadcrumb_html}</p><h1>Tree{esc_html(title_path)}</h1>{table}"
]
readme = _get_readme_at_ref_path(project, ref_oid, f or "")
if readme:
readme_filename, readme_content = readme
body_parts.append(_render_readme_card(project, ref_oid, readme_filename, readme_content, f or ""))
body_parts.append(POSTAMBLE)
return HTMLResponse("".join(body_parts))
def _format_date(epoch: int | None, tz_offset: int | None = None) -> str:
"""Format epoch timestamp to readable date string.
tz_offset is in minutes (as returned by pygit2).
"""
if epoch is None:
return ""
try:
# Create timezone-aware datetime
if tz_offset is not None:
# pygit2 offset is in minutes, convert to seconds for timedelta
tz = timezone(timedelta(seconds=tz_offset * 60))
else:
tz = timezone.utc
dt = datetime.fromtimestamp(epoch, tz=tz)
return dt.strftime("%Y-%m-%d %H:%M:%S")
except (ValueError, OSError):
return ""
def _format_commit_table_row(project: str, commit: dict[str, Any], short: bool = False) -> str:
"""Format a single commit as a table row."""
oid = commit.get("oid", "")
oid_short = oid[:7] if oid else ""
subject = commit.get("subject", "")
author = commit.get("author", "")
author_email = commit.get("author_email", "")
committer_epoch = commit.get("committer_epoch")
author_epoch = commit.get("author_epoch")
# Format date
date_str = _format_date(author_epoch, commit.get("author_tz"))
age_sec = None
if author_epoch:
age_sec = datetime.now(timezone.utc).timestamp() - author_epoch
age_str = age_string(age_sec) if age_sec > 0 else "right now"
else:
age_str = ""
commit_link = f"/{project}?a=commit&h={quote(oid, safe='')}"
diff_link = f"/{project}?a=commitdiff&h={quote(oid, safe='')}"
author_display = esc_html(author) or "unknown"
if short:
# Shortlog: simpler format
return [
f'<a href="{commit_link}">{esc_html(oid_short)}</a>',
esc_html(subject),
author_display,
esc_html(age_str),
f'<a href="{diff_link}">diff</a>',
]
else:
# Full log: more details
return [
f'<a href="{commit_link}">{esc_html(oid_short)}</a>',
esc_html(subject),
author_display,
esc_html(date_str),
esc_html(age_str),
f'<a href="{diff_link}">diff</a>',
]
def _render_pagination(
request: Request,
page: int,
pagecount: int,
has_prev: bool,
has_next: bool,
total_pages: int | None = None,
) -> str:
"""Render Tabler pagination HTML."""
prev_url = _pagination_url(request, page - 1, pagecount) if has_prev else ""
next_url = _pagination_url(request, page + 1, pagecount) if has_next else ""
page_links = None
if total_pages is not None and total_pages <= 20:
page_links = [(p, _pagination_url(request, p, pagecount)) for p in range(1, total_pages + 1)]
elif total_pages is not None:
start = max(1, page - 2)
end = min(total_pages, page + 2)
page_links = [(p, _pagination_url(request, p, pagecount)) for p in range(start, end + 1)]
if start > 1:
page_links = [(1, _pagination_url(request, 1, pagecount))] + [(-1, "")] + page_links
if end < total_pages:
page_links = page_links + [(-1, "")] + [(total_pages, _pagination_url(request, total_pages, pagecount))]
return env.get_template("pagination.html").render(
current_page=page,
pagecount=pagecount,
has_prev=has_prev,
has_next=has_next,
prev_url=prev_url,
next_url=next_url,
total_pages=total_pages,
page_links=page_links,
)
def git_log(project: str, h: str | None, request: Request, page: int, pagecount: int) -> HTMLResponse:
"""Commit log page. Port of git_log."""
skip = (page - 1) * pagecount
commits = get_commit_history(project, ref=h, max_count=pagecount + 1, skip=skip)
if not commits:
raise HTTPException(status_code=404, detail="No commits found")
has_next = len(commits) > pagecount
if has_next:
commits = commits[:pagecount]
rows = []
for commit in commits:
rows.append(_format_commit_table_row(project, commit, short=False))
ref_display = h[:7] if h else "HEAD"
title = f"Log - {esc_html(project)} @ {esc_html(ref_display)}"
pre = PREAMBLE.render(title=title, site_name=config.SITE_NAME)
table = env.get_template("table.html").render(
cols=["Commit", "Subject", "Author", "Date", "Age", "Diff"],
rows=rows
)
pagination_html = _render_pagination(request, page, pagecount, page > 1, has_next)
return HTMLResponse(
f"{pre}<h1>{title}</h1>{table}{pagination_html}{POSTAMBLE}"
)
def git_shortlog(project: str, h: str | None, request: Request, page: int, pagecount: int) -> HTMLResponse:
"""Shortlog page. Port of git_shortlog."""
skip = (page - 1) * pagecount
commits = get_commit_history(project, ref=h, max_count=pagecount + 1, skip=skip)
if not commits:
raise HTTPException(status_code=404, detail="No commits found")
has_next = len(commits) > pagecount
if has_next:
commits = commits[:pagecount]
rows = []
for commit in commits:
rows.append(_format_commit_table_row(project, commit, short=True))
ref_display = h[:7] if h else "HEAD"
title = f"Shortlog - {esc_html(project)} @ {esc_html(ref_display)}"
pre = PREAMBLE.render(title=title, site_name=config.SITE_NAME)
table = env.get_template("table.html").render(
cols=["Commit", "Subject", "Author", "Age", "Diff"],
rows=rows
)
pagination_html = _render_pagination(request, page, pagecount, page > 1, has_next)
return HTMLResponse(
f"{pre}<h1>{title}</h1>{table}{pagination_html}{POSTAMBLE}"
)
def git_history(project: str, h: str | None, f: str | None, request: Request, page: int, pagecount: int) -> HTMLResponse:
"""History page for a file or directory. Port of git_history."""
if not f:
raise HTTPException(status_code=400, detail="File path (f) required for history")
if not is_valid_pathname(f):
raise HTTPException(status_code=400, detail="Invalid path")
skip = (page - 1) * pagecount
commits = get_commit_history(project, ref=h, path=f, max_count=pagecount + 1, skip=skip)
if not commits:
raise HTTPException(status_code=404, detail="No history found for this path")
has_next = len(commits) > pagecount
if has_next:
commits = commits[:pagecount]
rows = []
for commit in commits:
rows.append(_format_commit_table_row(project, commit, short=False))
ref_display = h[:7] if h else "HEAD"
title = f"History - {esc_html(f)} - {esc_html(project)} @ {esc_html(ref_display)}"
pre = PREAMBLE.render(title=title, site_name=config.SITE_NAME)
table = env.get_template("table.html").render(
cols=["Commit", "Subject", "Author", "Date", "Age", "Patch"],
rows=rows
)
pagination_html = _render_pagination(request, page, pagecount, page > 1, has_next)
return HTMLResponse(
f"{pre}<h1>{title}</h1><p>Project: <a href='/{project}'>{esc_html(project)}</a></p>{table}{pagination_html}{POSTAMBLE}"
)
def git_heads(project: str) -> HTMLResponse:
"""Heads (branches) list page. Port of git_heads."""
heads_list = git_get_heads_list(project)
if not heads_list:
raise HTTPException(status_code=404, detail="No heads found")
rows = []
for name, _ref, oid in heads_list:
oid_short = oid[:7] if oid else ""
commit_link = f"/{project}?a=commit&h={quote(oid, safe='')}"
tree_link = f"/{project}?a=tree&h={quote(oid, safe='')}"
rows.append([
f'<a href="{commit_link}">{esc_html(name)}</a>',
f'<a href="{commit_link}">{esc_html(oid_short)}</a>',
f'<a href="{tree_link}">tree</a>',
])
title = f"Heads - {esc_html(project)}"
pre = PREAMBLE.render(title=title, site_name=config.SITE_NAME)
table = env.get_template("table.html").render(
cols=["Head", "Commit", ""],
rows=rows,
)
return HTMLResponse(
f"{pre}<h1>{title}</h1><p>Project: <a href='/{project}'>{esc_html(project)}</a></p>{table}{POSTAMBLE}"
)
def git_tags(project: str, request: Request, page: int, pagecount: int) -> HTMLResponse:
"""Tags list page. Port of git_tags."""
tags_list = git_get_tags_list(project)
if not tags_list:
raise HTTPException(status_code=404, detail="No tags found")
total = len(tags_list)
total_pages = (total + pagecount - 1) // pagecount if pagecount else 1
if page > total_pages and total > 0:
raise HTTPException(status_code=404, detail="Page does not exist")
skip = (page - 1) * pagecount
tags_page = tags_list[skip : skip + pagecount]
try:
from pygitweb.git_helpers import open_repo
repo = open_repo(project)
except Exception:
raise HTTPException(status_code=404, detail="Repository not found")
rows = []
for name, _ref, oid in tags_page:
tag_link = f"/{project}?a=tag&h={quote(oid, safe='')}"
target_oid = oid
target_type = "commit"
try:
obj = repo.revparse_single(oid)
if isinstance(obj, pygit2.Tag):
target_oid = str(obj.target)
target_type = obj.type_str
except (KeyError, pygit2.GitError):
pass
target_short = target_oid[:7] if target_oid else ""
if target_type == "commit":
target_link = f"/{project}?a=commit&h={quote(target_oid, safe='')}"
elif target_type == "tree":
target_link = f"/{project}?a=tree&h={quote(target_oid, safe='')}"
else:
target_link = None
obj_cell = f'<a href="{target_link}">{esc_html(target_short)}</a>' if target_link else esc_html(target_short)
rows.append([
f'<a href="{tag_link}">{esc_html(name)}</a>',
obj_cell,
])
title = f"Tags - {esc_html(project)}"
pre = PREAMBLE.render(title=title, site_name=config.SITE_NAME)
table = env.get_template("table.html").render(
cols=["Tag", "Object"],
rows=rows,
)
pagination_html = _render_pagination(
request, page, pagecount, page > 1, page < total_pages, total_pages=total_pages
)
return HTMLResponse(
f"{pre}<h1>{title}</h1><p>Project: <a href='/{project}'>{esc_html(project)}</a></p>{table}{pagination_html}{POSTAMBLE}"
)
def git_tag(project: str, h: str | None) -> HTMLResponse:
"""Single tag view. Port of git_tag."""
if not h:
raise HTTPException(status_code=400, detail="Tag ref or hash (h) required")
if not is_valid_ref_format(h):
raise HTTPException(status_code=400, detail="Invalid ref or hash")
try:
from pygitweb.git_helpers import open_repo
repo = open_repo(project)
obj = repo.revparse_single(h)
except (KeyError, pygit2.GitError, OSError):
raise HTTPException(status_code=404, detail="Tag or object not found")
if not isinstance(obj, pygit2.Tag):
raise HTTPException(status_code=404, detail="Not a tag object")
tag_oid = str(obj.id)
tag_data = parse_tag(project, tag_oid)
if not tag_data:
raise HTTPException(status_code=404, detail="Tag not found")
target_oid = tag_data.get("object", "")
target_type = tag_data.get("type", "commit")
tagger = tag_data.get("tagger", "")
tagger_epoch = tag_data.get("tagger_epoch")
tagger_tz = tag_data.get("tagger_tz")
message = (tag_data.get("message") or "").strip()
tag_name = None
for name, _ref, oid in git_get_tags_list(project):
if oid == tag_oid:
tag_name = name
break
if tag_name is None:
tag_name = tag_oid[:7]
target_short = target_oid[:7] if target_oid else ""
if target_type == "commit":
object_link = f'<a href="/{project}?a=commit&h={quote(target_oid, safe="")}">{esc_html(target_short)}</a>'
elif target_type == "tree":
object_link = f'<a href="/{project}?a=tree&h={quote(target_oid, safe="")}">{esc_html(target_short)}</a>'
else:
object_link = esc_html(target_short)
table_rows = [
["Tag", esc_html(tag_name)],
["Object", f"{object_link} ({esc_html(target_type)})"],
["Tagger", esc_html(tagger)],
["Date", esc_html(_format_date(tagger_epoch, tagger_tz))],
]
if message:
table_rows.append(["Message", f"<pre class='tag-message'>{esc_html(message)}</pre>"])
table = env.get_template("table.html").render(cols=["Field", "Value"], rows=table_rows)
title = f"Tag {esc_html(tag_name)} - {esc_html(project)}"
pre = PREAMBLE.render(title=title, site_name=config.SITE_NAME)
return HTMLResponse(
f"{pre}<h1>Tag {esc_html(tag_name)}</h1><p>Project: <a href='/{project}'>{esc_html(project)}</a></p>{table}{POSTAMBLE}"
)
# Well-known empty tree OID (Git standard)
_EMPTY_TREE_OID = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
def git_commit(project: str, h: str | None) -> HTMLResponse:
"""Single commit view. Port of git_commit (git show)."""
if not h:
raise HTTPException(status_code=400, detail="Commit hash (h) required")
if not is_valid_ref_format(h):
raise HTTPException(status_code=400, detail="Invalid ref or hash")
try:
from pygitweb.git_helpers import open_repo
repo = open_repo(project)
obj = repo.revparse_single(h)
except (KeyError, pygit2.GitError, OSError):
raise HTTPException(status_code=404, detail="Commit not found")
if not isinstance(obj, pygit2.Commit):
raise HTTPException(status_code=404, detail="Not a commit object")
commit = obj
oid = str(commit.id)
oid_short = oid[:7]
data = parse_commit(project, oid)
author = data.get("author", "")
author_email = data.get("author_email", "")
author_date = _format_date(data.get("author_epoch"), data.get("author_tz"))
tree_oid = data.get("tree", "")
message = (data.get("body") or "").strip()
commit_link = f"/{project}?a=commit&h={quote(oid, safe='')}"
tree_link = f"/{project}?a=tree&h={quote(oid, safe='')}"
diff_link = f"/{project}?a=commitdiff&h={quote(oid, safe='')}"
patch_link = f"/{project}?a=patch&h={quote(oid, safe='')}"
table_rows = [
["commit", f'<a href="{commit_link}">{esc_html(oid)}</a>'],
["Author", f"{esc_html(author)} <{esc_html(author_email)}>"],
["Date", esc_html(author_date)],
["tree", f'<a href="{tree_link}">{esc_html(tree_oid[:7])}</a>'],
]
if message:
table_rows.append(["", f"<pre class='commit-message'>{esc_html(message)}</pre>"])
table_rows.append(["", f'<a href="{diff_link}">diff</a> · <a href="{patch_link}">patch</a>'])
table = env.get_template("table.html").render(cols=["Field", "Value"], rows=table_rows)
title = f"Commit {esc_html(oid_short)} - {esc_html(project)}"
pre = PREAMBLE.render(title=title, site_name=config.SITE_NAME)
return HTMLResponse(
f"{pre}<h1>Commit {esc_html(oid_short)}</h1><p>Project: <a href='/{project}'>{esc_html(project)}</a></p>{table}{POSTAMBLE}"
)
def _get_commit_unified_diff(project: str, h: str) -> tuple[str, str]:
"""Return (unified_diff_text, oid_short) for commit h. Raises HTTPException on error."""
if not h:
raise HTTPException(status_code=400, detail="Commit hash (h) required")
if not is_valid_ref_format(h):
raise HTTPException(status_code=400, detail="Invalid ref or hash")
try:
from pygitweb.git_helpers import open_repo
repo = open_repo(project)
commit = repo.revparse_single(h)
except (KeyError, pygit2.GitError, OSError):
raise HTTPException(status_code=404, detail="Commit not found")
if not isinstance(commit, pygit2.Commit):
raise HTTPException(status_code=404, detail="Not a commit object")
if commit.parents:
diff = repo.diff(commit.parents[0], commit)
else:
empty_tree = repo.revparse_single(_EMPTY_TREE_OID)
diff = repo.diff(empty_tree, commit.tree)
parts: list[str] = []
for patch in diff:
if patch.text:
parts.append(patch.text)
body = "".join(parts) if parts else ""
oid_short = str(commit.id)[:7]
return body, oid_short
def git_commitdiff(project: str, h: str | None) -> HTMLResponse:
"""Commit diff page: unified diff rendered with diff2html (script id diff2html-script)."""
diff_text, oid_short = _get_commit_unified_diff(project, h or "")
# Base64-encode diff so we can embed safely in HTML without breaking script tags
diff_b64 = base64.b64encode(diff_text.encode("utf-8")).decode("ascii")
title = f"Commit diff {oid_short} - {project}"
pre = PREAMBLE.render(title=title, site_name=config.SITE_NAME)
body = env.get_template("commitdiff.html").render(
project=project,
oid_short=oid_short,
diff_b64=diff_b64,
commit_link=f"/{project}?a=commit&h={quote(h or '', safe='')}",
)
return HTMLResponse(f"{pre}{body}{POSTAMBLE}")
def git_patch(project: str, h: str | None) -> PlainTextResponse:
"""Single-commit patch (plain text unified diff)."""
if not h:
raise HTTPException(status_code=400, detail="Commit hash (h) required")
body, oid_short = _get_commit_unified_diff(project, h)
filename = f"{project}-{oid_short}.patch"
return PlainTextResponse(
body,
media_type="text/x-diff; charset=utf-8",
headers={"Content-Disposition": f'inline; filename="{filename}"'},
)
def git_patches(project: str, h: str | None, hb: str | None) -> PlainTextResponse:
"""Multi-commit patches (plain text). Range hb..h if hb given, else single commit."""
if not h:
raise HTTPException(status_code=400, detail="Commit hash (h) required")
if hb:
oids = get_commits_in_range(project, h, hb)
if not oids:
raise HTTPException(status_code=404, detail="No commits in range")
parts = []
for oid in oids:
diff, _ = _get_commit_unified_diff(project, oid)
if diff:
parts.append(diff)
body = "\n".join(parts)
filename = f"{project}-{h[:7]}-patches.patch"
else:
body, oid_short = _get_commit_unified_diff(project, h)
filename = f"{project}-{oid_short}.patch"
return PlainTextResponse(
body,
media_type="text/x-diff; charset=utf-8",
headers={"Content-Disposition": f'inline; filename="{filename}"'},
)
def git_blobdiff(
project: str,
h: str | None,
hb: str | None,
f: str | None,
fp: str | None,
) -> HTMLResponse:
"""Blob diff page: diff between two blob versions, rendered with diff2html."""
if not h or not hb:
raise HTTPException(status_code=400, detail="Both h and hb (refs) required for blob diff")
if not f:
raise HTTPException(status_code=400, detail="File path (f) required for blob diff")
if not is_valid_ref_format(h) or not is_valid_ref_format(hb):
raise HTTPException(status_code=400, detail="Invalid ref or hash")
path_new = f or ""
path_old = fp if fp is not None else path_new
if not is_valid_pathname(path_old) or not is_valid_pathname(path_new):
raise HTTPException(status_code=400, detail="Invalid path")
diff_text = get_blob_unified_diff(project, hb, path_old, h, path_new)
if diff_text is None:
raise HTTPException(status_code=404, detail="Blob not found")
diff_b64 = base64.b64encode(diff_text.encode("utf-8")).decode("ascii")
blob_link = f"/{project}?a=blob&h={quote(h or '', safe='')}&f={quote(path_new, safe='/')}"
pre = PREAMBLE.render(
title=f"Blob diff - {esc_html(path_new)} - {esc_html(project)}",
site_name=config.SITE_NAME,
)
body = env.get_template("blobdiff.html").render(
project=project,
path_new=path_new,
diff_b64=diff_b64,
blob_link=blob_link,
)
return HTMLResponse(f"{pre}{body}{POSTAMBLE}")
def git_blobpatch(
project: str,
h: str | None,
hb: str | None,
f: str | None,
fp: str | None,
) -> PlainTextResponse:
"""Blob diff as plain unified diff."""
if not h or not hb:
raise HTTPException(status_code=400, detail="Both h and hb (refs) required for blob diff")
if not f:
raise HTTPException(status_code=400, detail="File path (f) required for blob diff")
if not is_valid_ref_format(h) or not is_valid_ref_format(hb):
raise HTTPException(status_code=400, detail="Invalid ref or hash")
path_new = f or ""
path_old = fp if fp is not None else path_new
if not is_valid_pathname(path_old) or not is_valid_pathname(path_new):
raise HTTPException(status_code=400, detail="Invalid path")
body = get_blob_unified_diff(project, hb, path_old, h, path_new)
if body is None:
raise HTTPException(status_code=404, detail="Blob not found")
filename = f"{path_new.split('/')[-1] or 'blob'}.patch"
return PlainTextResponse(
body,
media_type="text/x-diff; charset=utf-8",
headers={"Content-Disposition": f'inline; filename="{filename}"'},
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)