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
"""
FastAPI app and routes: gitweb actions as path operations.
Ported from gitweb/gitweb.perl dispatch and action handlers.
"""
from __future__ import annotations
import mimetypes
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Annotated
from fastapi import FastAPI, HTTPException, Query, Request
from fastapi.responses import HTMLResponse, PlainTextResponse, Response
from fastapi.staticfiles import StaticFiles
from jinja2 import Template, Environment, PackageLoader
from pygitweb import config
from pygitweb.config import (
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_commit_history,
get_tree_at_ref_path,
git_get_head_hash,
git_get_project_description,
parse_commit,
)
from pygitweb.projects import (
filter_forks_from_projects_list,
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
# Allowed actions (from %actions in gitweb.perl)
ACTIONS = {
"blame",
"blame_incremental",
"blame_data",
"blobdiff",
"blobdiff_plain",
"blob",
"blob_plain",
"commitdiff",
"commitdiff_plain",
"commit",
"forks",
"heads",
"history",
"log",
"patch",
"patches",
"remotes",
"rss",
"atom",
"search",
"search_help",
"shortlog",
"summary",
"tag",
"tags",
"tree",
"snapshot",
"object",
"opml",
"project_list",
"project_index",
}
app = FastAPI(title="pygitweb", description="FastAPI + Pygit2 Repo Browser")
env = Environment(
loader=PackageLoader("pygitweb", "templates"),
# autoescape=True,
trim_blocks=True,
lstrip_blocks=True,
)
PREAMBLE = env.get_template("preamble.html")
POSTAMBLE = "</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(
project_filter="",
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)
@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")
# todo
# list_ = filter_forks_from_projects_list(list_)
# 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', theme="dark")
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")
# ---------- Routes (project required) ----------
@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,
):
"""
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
# 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 == "forks":
return git_forks(proj, request)
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 == "log":
return git_log(proj, hash_param)
if action == "shortlog":
return git_shortlog(proj, hash_param)
if action == "history":
return git_history(proj, hash_param, file_name)
# Stub others with minimal response
pre = PREAMBLE.render(title=f"{esc_html(action)} - {esc_html(proj)}", theme="dark")
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)
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=[],
rows=[
["Description", esc_html(descr)],
["Owner", esc_html(owner)],
[esc_html("HEAD"), f"<a href='/{project}/commit/{head or ''}'>{head_short or 'N/A'}</a>"],
[esc_html("tree"), f"<a href='/{project}?a=tree&h={head or ''}'>browse</a>"],
]
)
pre = PREAMBLE.render(title=f"{esc_html(config.SITE_NAME)} - {project}", theme="dark")
return HTMLResponse(f"{pre}<h1>{esc_html(project)}</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
text = to_utf8(data) or ""
body = sanitize(text) or ""
pre = PREAMBLE.render(title=f"{esc_html(f)} - {esc_html(project)}", theme="dark")
return HTMLResponse(
f"{pre}<pre class='blob-content'>{body}</pre>{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", theme="dark")
table = env.get_template("table.html").render(
cols=["Name", "Type"],
rows=rows
)
return HTMLResponse(
f"{pre}<p class='breadcrumb'>{breadcrumb_html}</p><h1>Tree{esc_html(title_path)}</h1>{table}{POSTAMBLE}"
)
def git_forks(project: str, request: Request) -> HTMLResponse:
"""Forks of project. Port of git_forks."""
filter_path = project.replace(".git", "")
list_ = git_get_projects_list(filter_path=filter_path, export_ok=EXPORT_OK)
if not list_:
raise HTTPException(status_code=404, detail="No forks found")
list_ = filter_forks_from_projects_list(list_)
rows = []
for pr in list_:
path = pr.get("path", "")
rows.append(f"<tr><td><a href='/{path}'>{esc_html(path)}</a></td></tr>")
pre = PREAMBLE.render(title=f"{esc_html(project)} - Forks", theme="dark")
return HTMLResponse(
f"{pre}<h1>Forks of {esc_html(project)}</h1><table>{"".join(rows)}</table>{POSTAMBLE}"
)
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='')}"
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)
]
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)
]
def git_log(project: str, h: str | None) -> HTMLResponse:
"""Commit log page. Port of git_log."""
commits = get_commit_history(project, ref=h, max_count=100)
if not commits:
raise HTTPException(status_code=404, detail="No commits found")
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, theme="dark")
table = env.get_template("table.html").render(
cols=["Commit", "Subject", "Author", "Date", "Age"],
rows=rows
)
return HTMLResponse(
f"{pre}<h1>{title}</h1>{table}{POSTAMBLE}"
)
def git_shortlog(project: str, h: str | None) -> HTMLResponse:
"""Shortlog page. Port of git_shortlog."""
commits = get_commit_history(project, ref=h, max_count=100)
if not commits:
raise HTTPException(status_code=404, detail="No commits found")
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, theme="dark")
table = env.get_template("table.html").render(
cols=["Commit", "Subject", "Author", "Age"],
rows=rows
)
return HTMLResponse(
f"{pre}<h1>{title}</h1>{table}{POSTAMBLE}"
)
def git_history(project: str, h: str | None, f: str | None) -> 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")
commits = get_commit_history(project, ref=h, path=f, max_count=100)
if not commits:
raise HTTPException(status_code=404, detail="No history found for this path")
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, theme="dark")
table = env.get_template("table.html").render(
cols=["Commit", "Subject", "Author", "Date", "Age"],
rows=rows
)
return HTMLResponse(
f"{pre}<h1>{title}</h1><p>Project: <a href='/{project}'>{esc_html(project)}</a></p>{table}{POSTAMBLE}"
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)