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
"""
FastAPI app and routes: gitweb actions as path operations.
Ported from gitweb/gitweb.perl dispatch and action handlers.
"""
from __future__ import annotations
import os
import subprocess
import tempfile
import zipfile
from pathlib import Path
from typing import Annotated
from urllib.parse import quote
import pygit2
from fastapi import FastAPI, File, Form, HTTPException, Query, Request, UploadFile
from fastapi.responses import HTMLResponse, PlainTextResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from pygitweb import __meta__, config
from pygitweb.actions import (
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_shortlog,
git_summary,
git_tag,
git_tags,
git_tree,
parse_pagination,
)
from pygitweb.config import (
ACTIONS,
DISTGIT_ADMIN_PASSWORD,
DISTGIT_ADMIN_USER,
DISTGIT_AUTH,
DISTGIT_SESSION_TIMEOUT,
EXPORT_OK,
PROJECTROOT,
STRICT_EXPORT,
check_loadavg,
configure_gitweb_features,
evaluate_gitweb_config,
)
from pygitweb.formatting import esc_html
from pygitweb.git_helpers import (
git_get_project_config,
git_get_references,
git_get_type,
)
from pygitweb.projects import git_get_project_owner, git_get_projects_list
from pygitweb.settings import router as settings_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
from pygitweb.validation import (
is_valid_action,
is_valid_pathname,
is_valid_project,
is_valid_ref_format,
)
app = FastAPI(
debug=(DISTGIT_AUTH == "None"),
title="PyGitWeb",
summary="FastAPI + Pygit2 Repo Browser",
description=open("pygitweb/README.md", encoding="utf-8").read(),
version=__meta__.__version__,
)
# 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)
_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.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.on_event("startup")
def startup():
evaluate_gitweb_config()
configure_gitweb_features(
get_project_config=git_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")
auth_disabled = DISTGIT_AUTH == "None"
def board_cell(pr: dict) -> str:
path = pr.get("path", "")
path_enc = quote(path, safe="/")
try:
board_refs = git_get_references(path, "refs/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 not auth_disabled 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='/')}'>{esc_html(pr.get('path', ''))}</a>",
esc_html(pr.get("descr") or pr.get("path", "")),
board_cell(pr),
]
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")
@app.get("/board/create", response_class=RedirectResponse)
def board_create_page(
request: Request,
project: Annotated[str | None, Query(alias="p")] = None,
) -> RedirectResponse:
"""Create a board named 'Tasks' (refs/boards/Tasks) and redirect to the project summary."""
if DISTGIT_AUTH != "None":
raise HTTPException(status_code=401, detail="Authentication required")
p = project or request.query_params.get("project")
if not p:
raise HTTPException(status_code=400, detail="Project needed (use ?project= or ?p=)")
_validate_project(p)
try:
create_board_for_project(p, name="Tasks", description="")
except HTTPException as e:
if e.status_code == 409:
pass
else:
raise
p_url = quote(p, safe="/")
return RedirectResponse(url=f"/project/{p_url}", status_code=303)
# ---------- 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/{project_name}", status_code=303)
# ---------- Routes (project required) ----------
@app.get("/project/{project:path}/board/", response_class=HTMLResponse)
def project_board(
project: str,
board: Annotated[str, Query(alias="b")] = "Tasks",
) -> HTMLResponse:
"""Board view: columns (dropzones) and task cards."""
_validate_project(project)
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"{esc_html(project)} - Board",
site_name=config.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}", 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/{project} -> summary; /project/{project}/action/... -> action.
Port of dispatch + run_request path handling.
"""
if not project or project == "":
raise HTTPException(status_code=400, detail="Project needed")
_validate_project(project)
action = a
hash_param = h or hb
file_name = f
file_parent = fp
# If no action, infer: hash only -> object type; project only -> summary
if not action:
if hash_param and file_name:
obj_type = git_get_type(project, f"{hash_param}:{file_name}")
if not obj_type:
raise HTTPException(status_code=404, detail="File or directory does not exist")
action = "tree" if obj_type == "tree" else "blob_plain"
elif hash_param:
obj_type = git_get_type(project, hash_param)
if not obj_type:
raise HTTPException(status_code=404, detail="Object does not exist")
action = {
"commit": "commit",
"tree": "tree",
"blob": "blob",
"tag": "tag",
}.get(obj_type, "object")
else:
action = "summary"
if 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(project)
if action == "tree":
return git_tree(project, hash_param, file_name)
if action in ("blob", "blob_plain"):
return git_blob(project, hash_param, file_name, raw=(action == "blob_plain"))
if action == "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)
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)
# Stub others with minimal response
pre = PREAMBLE.render(title=f"{esc_html(action)} - {esc_html(project)}", site_name=config.SITE_NAME)
return HTMLResponse(f"{pre}<p>Action: {esc_html(action)}</p><p>Project: {esc_html(project)}</p>{POSTAMBLE}")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)