pygitweb 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pygitweb/__init__.py +22 -0
- pygitweb/__meta__.py +9 -0
- pygitweb/actions.py +1303 -0
- pygitweb/addproject_permissions_test.py +114 -0
- pygitweb/api/__init__.py +0 -0
- pygitweb/api/action.py +20 -0
- pygitweb/api/plugins/__init__.py +0 -0
- pygitweb/api/plugins/project_zip.py +71 -0
- pygitweb/api/project.py +67 -0
- pygitweb/api/subpage.py +22 -0
- pygitweb/auth.py +387 -0
- pygitweb/auth.schema.json +106 -0
- pygitweb/auth_config.py +243 -0
- pygitweb/auth_oauth.py +343 -0
- pygitweb/auth_test.py +390 -0
- pygitweb/boards_permissions_test.py +113 -0
- pygitweb/change_queue.py +110 -0
- pygitweb/change_queue_routes_test.py +146 -0
- pygitweb/change_queue_test.py +91 -0
- pygitweb/comments_permissions_test.py +140 -0
- pygitweb/config.py +185 -0
- pygitweb/conftest.py +43 -0
- pygitweb/dependencies.py +87 -0
- pygitweb/formatting.py +182 -0
- pygitweb/formatting_test.py +68 -0
- pygitweb/git_helpers.py +454 -0
- pygitweb/git_helpers_test.py +223 -0
- pygitweb/gravatar.py +16 -0
- pygitweb/gravatar_test.py +10 -0
- pygitweb/hooks_install.py +278 -0
- pygitweb/hooks_install_test.py +363 -0
- pygitweb/hooks_permissions_test.py +116 -0
- pygitweb/main.py +887 -0
- pygitweb/merge_requests.py +230 -0
- pygitweb/merge_requests_test.py +85 -0
- pygitweb/mr_permissions_test.py +148 -0
- pygitweb/password_hash.py +74 -0
- pygitweb/password_hash_test.py +20 -0
- pygitweb/permissions.py +209 -0
- pygitweb/permissions_test.py +86 -0
- pygitweb/plugin_loader.py +83 -0
- pygitweb/projects.py +213 -0
- pygitweb/projects_test.py +186 -0
- pygitweb/sessions.py +73 -0
- pygitweb/settings.py +412 -0
- pygitweb/settings.schema.json +73 -0
- pygitweb/settings_config.py +122 -0
- pygitweb/settings_config_test.py +101 -0
- pygitweb/settings_permissions_test.py +76 -0
- pygitweb/static/blob-view.js +133 -0
- pygitweb/static/board.js +839 -0
- pygitweb/static/hook-install.js +53 -0
- pygitweb/static/icons/cloud-down.svg +1 -0
- pygitweb/static/icons/cloud-exclamation.svg +1 -0
- pygitweb/static/icons/cloud-filled.svg +1 -0
- pygitweb/static/icons/cloud-storm.svg +1 -0
- pygitweb/static/icons/cloud-up.svg +1 -0
- pygitweb/static/icons/cloud.svg +1 -0
- pygitweb/static/logo.svg +44 -0
- pygitweb/static/main.css +1210 -0
- pygitweb/static/navbar-auth.js +82 -0
- pygitweb/static/readme-render.js +174 -0
- pygitweb/static/search-page.js +139 -0
- pygitweb/static/summary-ref-switcher.js +130 -0
- pygitweb/static/themes/solarized.css +34 -0
- pygitweb/tasks.py +595 -0
- pygitweb/tasks_permissions_test.py +137 -0
- pygitweb/tasks_routes_test.py +430 -0
- pygitweb/templates/addproject.html +174 -0
- pygitweb/templates/blobdiff.html +57 -0
- pygitweb/templates/board.html +31 -0
- pygitweb/templates/board_card.html +44 -0
- pygitweb/templates/commitdiff.html +57 -0
- pygitweb/templates/hooks_summary_cell.html +37 -0
- pygitweb/templates/login.html +37 -0
- pygitweb/templates/merge_request_summary_cell.html +18 -0
- pygitweb/templates/merge_request_tag.html +90 -0
- pygitweb/templates/pagination.html +44 -0
- pygitweb/templates/preamble.html +89 -0
- pygitweb/templates/project_settings.html +13 -0
- pygitweb/templates/pygit2_settings.html +12 -0
- pygitweb/templates/pygitweb_settings.html +12 -0
- pygitweb/templates/search.html +77 -0
- pygitweb/templates/settings_form_field.html +27 -0
- pygitweb/templates/table.html +15 -0
- pygitweb/templates/user_profile.html +10 -0
- pygitweb/templates_env.py +21 -0
- pygitweb/timeline_cache.py +243 -0
- pygitweb/validation.py +75 -0
- pygitweb/validation_test.py +167 -0
- pygitweb-0.1.0.dist-info/METADATA +165 -0
- pygitweb-0.1.0.dist-info/RECORD +95 -0
- pygitweb-0.1.0.dist-info/WHEEL +5 -0
- pygitweb-0.1.0.dist-info/licenses/LICENSE +21 -0
- pygitweb-0.1.0.dist-info/top_level.txt +1 -0
pygitweb/main.py
ADDED
|
@@ -0,0 +1,887 @@
|
|
|
1
|
+
"""
|
|
2
|
+
FastAPI app and routes: gitweb actions as path operations.
|
|
3
|
+
Ported from gitweb/gitweb.perl dispatch and action handlers.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import os
|
|
10
|
+
import signal
|
|
11
|
+
import sys
|
|
12
|
+
import threading
|
|
13
|
+
from collections.abc import AsyncGenerator, Callable
|
|
14
|
+
from contextlib import asynccontextmanager
|
|
15
|
+
from datetime import UTC, datetime
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Annotated, Literal
|
|
18
|
+
from urllib.parse import quote, urlencode
|
|
19
|
+
|
|
20
|
+
import pygit2
|
|
21
|
+
from fastapi import Depends, FastAPI, File, Form, HTTPException, Query, Request, UploadFile
|
|
22
|
+
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, RedirectResponse, Response
|
|
23
|
+
from fastapi.staticfiles import StaticFiles
|
|
24
|
+
|
|
25
|
+
from pygitweb import __meta__
|
|
26
|
+
from pygitweb.actions import (
|
|
27
|
+
SearchFlagQuery,
|
|
28
|
+
SearchSortQuery,
|
|
29
|
+
git_blame,
|
|
30
|
+
git_blame_raw,
|
|
31
|
+
git_blob,
|
|
32
|
+
git_blobdiff,
|
|
33
|
+
git_blobpatch,
|
|
34
|
+
git_commit,
|
|
35
|
+
git_commitdiff,
|
|
36
|
+
git_heads,
|
|
37
|
+
git_history,
|
|
38
|
+
git_log,
|
|
39
|
+
git_object,
|
|
40
|
+
git_patch,
|
|
41
|
+
git_patches,
|
|
42
|
+
git_remotes,
|
|
43
|
+
git_search,
|
|
44
|
+
git_search_page,
|
|
45
|
+
git_shortlog,
|
|
46
|
+
git_summary,
|
|
47
|
+
git_tag,
|
|
48
|
+
git_tags,
|
|
49
|
+
git_tree,
|
|
50
|
+
parse_pagination,
|
|
51
|
+
summary_ref_options,
|
|
52
|
+
summary_ref_state,
|
|
53
|
+
)
|
|
54
|
+
from pygitweb.api.plugins.project_zip import ProjectZip
|
|
55
|
+
from pygitweb.api.project import Project
|
|
56
|
+
from pygitweb.api.subpage import Subpage
|
|
57
|
+
from pygitweb.auth import (
|
|
58
|
+
access_token_from_request,
|
|
59
|
+
auth_router,
|
|
60
|
+
decode_access_token,
|
|
61
|
+
ensure_permission,
|
|
62
|
+
require_active_user_if_auth_enabled,
|
|
63
|
+
require_permission,
|
|
64
|
+
)
|
|
65
|
+
from pygitweb.auth_config import auth_config, is_auth_configured
|
|
66
|
+
from pygitweb.change_queue import CHANGE_QUEUE
|
|
67
|
+
from pygitweb.config import ACTIONS, get_loadavg, settings
|
|
68
|
+
from pygitweb.dependencies import (
|
|
69
|
+
ValidatedBoardCreateProject,
|
|
70
|
+
ValidatedNotifyProject,
|
|
71
|
+
ValidatedPathProject,
|
|
72
|
+
project_visible_in_list,
|
|
73
|
+
)
|
|
74
|
+
from pygitweb.formatting import age_string
|
|
75
|
+
from pygitweb.git_helpers import git_get_references, git_get_type
|
|
76
|
+
from pygitweb.hooks_install import (
|
|
77
|
+
HookStatus,
|
|
78
|
+
bundle_status,
|
|
79
|
+
get_bundle,
|
|
80
|
+
get_sample,
|
|
81
|
+
list_bundles,
|
|
82
|
+
list_samples,
|
|
83
|
+
)
|
|
84
|
+
from pygitweb.hooks_install import (
|
|
85
|
+
install as install_hook,
|
|
86
|
+
)
|
|
87
|
+
from pygitweb.hooks_install import (
|
|
88
|
+
install_bundle as install_hook_bundle,
|
|
89
|
+
)
|
|
90
|
+
from pygitweb.hooks_install import (
|
|
91
|
+
remove as remove_hook,
|
|
92
|
+
)
|
|
93
|
+
from pygitweb.hooks_install import (
|
|
94
|
+
remove_bundle as remove_hook_bundle,
|
|
95
|
+
)
|
|
96
|
+
from pygitweb.hooks_install import (
|
|
97
|
+
status as hook_status,
|
|
98
|
+
)
|
|
99
|
+
from pygitweb.merge_requests import merge_router
|
|
100
|
+
from pygitweb.permissions import Permission
|
|
101
|
+
from pygitweb.plugin_loader import load_plugin_actions, load_subpages
|
|
102
|
+
from pygitweb.projects import git_get_project_owner, git_get_projects_list
|
|
103
|
+
from pygitweb.sessions import clear_all_sessions
|
|
104
|
+
from pygitweb.settings import router as settings_router
|
|
105
|
+
from pygitweb.tasks import (
|
|
106
|
+
board_router,
|
|
107
|
+
comment_router,
|
|
108
|
+
create_board_for_project,
|
|
109
|
+
get_board_tasks_grouped,
|
|
110
|
+
task_router,
|
|
111
|
+
)
|
|
112
|
+
from pygitweb.templates_env import POSTAMBLE, PREAMBLE, env, jinja_escape
|
|
113
|
+
from pygitweb.timeline_cache import clear_timeline_cache_async, get_all_timeline_events, warm_timeline_cache_async
|
|
114
|
+
from pygitweb.validation import is_valid_pathname
|
|
115
|
+
|
|
116
|
+
UPDATES_SUPPORTED_ACTIONS: frozenset[str] = frozenset({"history", "log", "shortlog", "heads", "tags"})
|
|
117
|
+
|
|
118
|
+
ProjectListAction = Literal["project_list"]
|
|
119
|
+
ProjectListOrder = Literal["none", "project", "descr", "owner", "age"]
|
|
120
|
+
HookInstallOp = Literal["add", "remove", "check"]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _parse_updates_flag(value: str | None) -> bool:
|
|
124
|
+
if value is None:
|
|
125
|
+
return False
|
|
126
|
+
return value.strip().lower() in ("1", "true", "yes", "on")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _resolve_subscribed_projects(project: str, project_filter: str | None) -> list[str]:
|
|
130
|
+
"""Pick the project set to long-poll. Uses pf prefix if provided, else the URL project."""
|
|
131
|
+
if not project_filter:
|
|
132
|
+
return [project]
|
|
133
|
+
pf = project_filter.strip().strip("/")
|
|
134
|
+
if not pf:
|
|
135
|
+
return [project]
|
|
136
|
+
matches = git_get_projects_list(
|
|
137
|
+
filter_path=pf,
|
|
138
|
+
paranoid=settings.STRICT_EXPORT,
|
|
139
|
+
export_ok=settings.EXPORT_OK,
|
|
140
|
+
)
|
|
141
|
+
names: list[str] = [m.get("path", "") for m in matches if m.get("path")]
|
|
142
|
+
return names or [project]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _updates_idle_response() -> Response:
|
|
146
|
+
return Response(status_code=200, content=b"")
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _install_graceful_shutdown_wakeup(app: FastAPI) -> None:
|
|
150
|
+
"""Wake ``updates=true`` waiters as soon as shutdown is requested.
|
|
151
|
+
|
|
152
|
+
Uvicorn waits for open connections to finish before running ASGI lifespan shutdown,
|
|
153
|
+
so toggling ``shutdown_event`` only from lifespan would deadlock with long polls.
|
|
154
|
+
We chain OS signals (same ones uvicorn uses) and notify waiters before uvicorn's
|
|
155
|
+
handler runs.
|
|
156
|
+
|
|
157
|
+
Skipped when not running on the main thread (e.g. Starlette ``TestClient`` lifespan).
|
|
158
|
+
"""
|
|
159
|
+
if threading.current_thread() is not threading.main_thread():
|
|
160
|
+
return
|
|
161
|
+
signals: tuple[int, ...] = (signal.SIGINT, signal.SIGTERM)
|
|
162
|
+
if sys.platform == "win32":
|
|
163
|
+
signals = signals + (signal.SIGBREAK,)
|
|
164
|
+
for sig in signals:
|
|
165
|
+
|
|
166
|
+
def make_chain(
|
|
167
|
+
previous: Callable[[int, object | None], object] | int | None,
|
|
168
|
+
) -> Callable[[int, object | None], None]:
|
|
169
|
+
def handler(signum: int, frame: object | None) -> None:
|
|
170
|
+
app.state.shutting_down = True
|
|
171
|
+
app.state.shutdown_event.set()
|
|
172
|
+
if callable(previous) and previous not in (signal.SIG_DFL, signal.SIG_IGN):
|
|
173
|
+
previous(signum, frame)
|
|
174
|
+
|
|
175
|
+
return handler
|
|
176
|
+
|
|
177
|
+
try:
|
|
178
|
+
prev = signal.getsignal(sig)
|
|
179
|
+
signal.signal(sig, make_chain(prev))
|
|
180
|
+
except ValueError:
|
|
181
|
+
continue
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@asynccontextmanager
|
|
185
|
+
async def app_lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
|
186
|
+
app.state.shutting_down = False
|
|
187
|
+
app.state.shutdown_event = asyncio.Event()
|
|
188
|
+
_install_graceful_shutdown_wakeup(app)
|
|
189
|
+
warm_timeline_cache_async()
|
|
190
|
+
try:
|
|
191
|
+
yield
|
|
192
|
+
finally:
|
|
193
|
+
app.state.shutting_down = True
|
|
194
|
+
app.state.shutdown_event.set()
|
|
195
|
+
clear_timeline_cache_async()
|
|
196
|
+
clear_all_sessions()
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
with open("pygitweb/README.md", encoding="utf-8") as _readme_file:
|
|
200
|
+
_app_description = _readme_file.read()
|
|
201
|
+
|
|
202
|
+
app = FastAPI(
|
|
203
|
+
debug=(settings.AUTH is False),
|
|
204
|
+
title="PyGitWeb",
|
|
205
|
+
summary="FastAPI + Pygit2 Repo Browser",
|
|
206
|
+
description=_app_description,
|
|
207
|
+
version=__meta__.__version__,
|
|
208
|
+
lifespan=app_lifespan,
|
|
209
|
+
openapi_tags=[
|
|
210
|
+
{
|
|
211
|
+
"name": "auth",
|
|
212
|
+
"description": """Session status, account pages, and sign-out.
|
|
213
|
+
Sessions are opaque ids (cookie or Bearer), not IdP JWTs.""",
|
|
214
|
+
},
|
|
215
|
+
{
|
|
216
|
+
"name": "auth - local",
|
|
217
|
+
"description": "Local username/password sign-in via HTML form or POST /token.",
|
|
218
|
+
},
|
|
219
|
+
{
|
|
220
|
+
"name": "auth - OAuth",
|
|
221
|
+
"description": """Browser OAuth2 authorization-code flow (Google/GitHub).
|
|
222
|
+
Ends with the same session cookie as local login.""",
|
|
223
|
+
},
|
|
224
|
+
],
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
PLUGIN_ACTIONS = load_plugin_actions()
|
|
228
|
+
SUBPAGES: list[Subpage] = load_subpages()
|
|
229
|
+
DISPATCH_ACTIONS: frozenset[str] = frozenset(ACTIONS) | frozenset(PLUGIN_ACTIONS.keys())
|
|
230
|
+
|
|
231
|
+
# Todo handle with nginx route
|
|
232
|
+
_static_dir = Path(__file__).parent / "static"
|
|
233
|
+
if _static_dir.is_dir():
|
|
234
|
+
app.mount("/static", StaticFiles(directory=str(_static_dir)), name="static")
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
app.include_router(auth_router)
|
|
238
|
+
app.include_router(settings_router)
|
|
239
|
+
app.include_router(board_router, prefix="/board")
|
|
240
|
+
app.include_router(task_router, prefix="/tasks")
|
|
241
|
+
app.include_router(comment_router, prefix="/comments")
|
|
242
|
+
app.include_router(merge_router, prefix="/mr")
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
@app.middleware("http")
|
|
246
|
+
async def loadavg_middleware(request: Request, call_next):
|
|
247
|
+
try:
|
|
248
|
+
if settings.MAXLOAD is not None and get_loadavg() > settings.MAXLOAD:
|
|
249
|
+
raise RuntimeError("503:The load average on the server is too high")
|
|
250
|
+
except RuntimeError as e:
|
|
251
|
+
msg = str(e)
|
|
252
|
+
if msg.startswith("503:"):
|
|
253
|
+
raise HTTPException(status_code=503, detail=msg[4:]) from e
|
|
254
|
+
raise
|
|
255
|
+
return await call_next(request)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _project_subpage_rows(project: str) -> list[list[str]]:
|
|
259
|
+
project_enc = quote(project, safe="/")
|
|
260
|
+
rows: list[list[str]] = []
|
|
261
|
+
for subpage in SUBPAGES:
|
|
262
|
+
link_label = subpage.link_name(project)
|
|
263
|
+
if not link_label:
|
|
264
|
+
continue
|
|
265
|
+
subpage_name = subpage.subpage_name()
|
|
266
|
+
view = f'<a href="/project/{project_enc}/subpage/{quote(subpage_name, safe="")}">view</a>'
|
|
267
|
+
suffix = subpage.summary_value_suffix_html(project, project_enc)
|
|
268
|
+
value = f"{view}{suffix}" if suffix else view
|
|
269
|
+
rows.append([
|
|
270
|
+
jinja_escape(link_label) or "",
|
|
271
|
+
value,
|
|
272
|
+
])
|
|
273
|
+
return rows
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
# ---------- Routes (no project) ----------
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
@app.get("/", response_class=HTMLResponse)
|
|
280
|
+
def git_project_list(
|
|
281
|
+
request: Request,
|
|
282
|
+
_action: Annotated[ProjectListAction | None, Query(alias="a")] = None,
|
|
283
|
+
pf: Annotated[str | None, Query(alias="pf")] = None,
|
|
284
|
+
_order: Annotated[ProjectListOrder | None, Query(alias="o")] = None,
|
|
285
|
+
):
|
|
286
|
+
"""Project list page. Port of git_project_list."""
|
|
287
|
+
project_filter = pf or ""
|
|
288
|
+
list_ = git_get_projects_list(
|
|
289
|
+
filter_path=project_filter,
|
|
290
|
+
paranoid=settings.STRICT_EXPORT,
|
|
291
|
+
export_ok=settings.EXPORT_OK,
|
|
292
|
+
)
|
|
293
|
+
if not list_:
|
|
294
|
+
raise HTTPException(status_code=404, detail="No projects found")
|
|
295
|
+
|
|
296
|
+
def board_cell(pr: dict) -> str:
|
|
297
|
+
path = pr.get("path", "")
|
|
298
|
+
path_enc = quote(path, safe="/")
|
|
299
|
+
try:
|
|
300
|
+
board_refs = git_get_references(path, "refs/tags/boards")
|
|
301
|
+
has_boards = len(board_refs) > 0
|
|
302
|
+
except Exception:
|
|
303
|
+
has_boards = False
|
|
304
|
+
if has_boards:
|
|
305
|
+
return f'<a href="/project/{path_enc}/board/">project board</a>'
|
|
306
|
+
grey_style = ' style="color: #999; cursor: not-allowed;"' if settings.AUTH else ""
|
|
307
|
+
proj_q = quote(path, safe="")
|
|
308
|
+
return f'<a href="/board/create?project={proj_q}"{grey_style}>create board</a>'
|
|
309
|
+
|
|
310
|
+
# We need better escaping logic here but can wait until we harden the templates
|
|
311
|
+
table = env.get_template("table.html").render(
|
|
312
|
+
cols=["Project", "Description", "Board"],
|
|
313
|
+
rows=[
|
|
314
|
+
[
|
|
315
|
+
f"<a href='/project/{quote(pr.get('path', ''), safe='/')}'>{jinja_escape(pr.get('path', ''))}</a>",
|
|
316
|
+
jinja_escape(pr.get("descr") or pr.get("path", "")),
|
|
317
|
+
board_cell(pr),
|
|
318
|
+
]
|
|
319
|
+
for pr in list_[:50]
|
|
320
|
+
],
|
|
321
|
+
)
|
|
322
|
+
pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - Projects", site_name=settings.SITE_NAME)
|
|
323
|
+
return HTMLResponse(f"{pre}<h1>Project List</h1>{table}{POSTAMBLE}")
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
@app.get("/index", response_class=PlainTextResponse)
|
|
327
|
+
def git_project_index(
|
|
328
|
+
pf: Annotated[str | None, Query(alias="pf")] = None,
|
|
329
|
+
):
|
|
330
|
+
"""Plain text project index (path owner). Port of git_project_index."""
|
|
331
|
+
from urllib.parse import quote_plus
|
|
332
|
+
|
|
333
|
+
projects = git_get_projects_list(
|
|
334
|
+
filter_path=pf or "",
|
|
335
|
+
paranoid=settings.STRICT_EXPORT,
|
|
336
|
+
export_ok=settings.EXPORT_OK,
|
|
337
|
+
)
|
|
338
|
+
if not projects:
|
|
339
|
+
raise HTTPException(status_code=404, detail="No projects found")
|
|
340
|
+
lines = []
|
|
341
|
+
for pr in projects:
|
|
342
|
+
path = pr.get("path", "")
|
|
343
|
+
owner = pr.get("owner") or git_get_project_owner(path) or ""
|
|
344
|
+
path_enc = quote_plus(path, safe="/")
|
|
345
|
+
owner_enc = quote_plus(owner, safe="/")
|
|
346
|
+
lines.append(f"{path_enc} {owner_enc}")
|
|
347
|
+
return PlainTextResponse("\n".join(lines), media_type="text/plain; charset=utf-8")
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
@app.get("/activity", response_class=HTMLResponse)
|
|
351
|
+
def activity_page(
|
|
352
|
+
page: Annotated[str | None, Query(alias="page")] = None,
|
|
353
|
+
pagecount: Annotated[str | None, Query(alias="pagecount")] = None,
|
|
354
|
+
) -> HTMLResponse:
|
|
355
|
+
p, pc = parse_pagination(page, pagecount)
|
|
356
|
+
all_events = get_all_timeline_events()
|
|
357
|
+
skip = (p - 1) * pc
|
|
358
|
+
events_page = all_events[skip : skip + pc + 1]
|
|
359
|
+
has_next = len(events_page) > pc
|
|
360
|
+
if has_next:
|
|
361
|
+
events_page = events_page[:pc]
|
|
362
|
+
rows: list[list[str]] = []
|
|
363
|
+
for item in events_page:
|
|
364
|
+
project_name = item["project"]
|
|
365
|
+
event = item["event"]
|
|
366
|
+
oid = event["oid"]
|
|
367
|
+
if event["kind"] == "commit":
|
|
368
|
+
event_label = f"<a href='/project/{quote(project_name, safe='/')}"
|
|
369
|
+
event_label += f"?a=commit&h={quote(oid, safe='')}'>{jinja_escape(oid[:7])}</a>"
|
|
370
|
+
else:
|
|
371
|
+
event_label = jinja_escape(event["kind"]) or ""
|
|
372
|
+
description_raw = event.get("description")
|
|
373
|
+
if not description_raw:
|
|
374
|
+
description = ""
|
|
375
|
+
elif "\n" in description_raw:
|
|
376
|
+
description = description_raw.splitlines()[0][:80].rstrip() + "..."
|
|
377
|
+
elif len(description_raw) > 80:
|
|
378
|
+
description = description_raw[:80].rstrip() + "..."
|
|
379
|
+
else:
|
|
380
|
+
description = description_raw
|
|
381
|
+
try:
|
|
382
|
+
age_seconds = datetime.now(UTC).timestamp() - float(event["timestamp"])
|
|
383
|
+
activity_time = "right now" if age_seconds <= 0 else age_string(age_seconds)
|
|
384
|
+
except (ValueError, OSError):
|
|
385
|
+
activity_time = ""
|
|
386
|
+
rows.append([
|
|
387
|
+
jinja_escape(activity_time) or "",
|
|
388
|
+
f"<a href='/project/{quote(project_name, safe='/')}'>{jinja_escape(project_name)}</a>",
|
|
389
|
+
event_label,
|
|
390
|
+
jinja_escape(description) or "",
|
|
391
|
+
])
|
|
392
|
+
table = env.get_template("table.html").render(
|
|
393
|
+
cols=["Time", "Project Name", "Event", "Description"],
|
|
394
|
+
rows=rows,
|
|
395
|
+
)
|
|
396
|
+
prev_url = ""
|
|
397
|
+
next_url = ""
|
|
398
|
+
if p > 1:
|
|
399
|
+
prev_url = f"/activity?{urlencode({'page': str(p - 1), 'pagecount': str(pc)})}"
|
|
400
|
+
if has_next:
|
|
401
|
+
next_url = f"/activity?{urlencode({'page': str(p + 1), 'pagecount': str(pc)})}"
|
|
402
|
+
pagination_html = env.get_template("pagination.html").render(
|
|
403
|
+
current_page=p,
|
|
404
|
+
pagecount=pc,
|
|
405
|
+
has_prev=p > 1,
|
|
406
|
+
has_next=has_next,
|
|
407
|
+
prev_url=prev_url,
|
|
408
|
+
next_url=next_url,
|
|
409
|
+
total_pages=None,
|
|
410
|
+
page_links=None,
|
|
411
|
+
)
|
|
412
|
+
pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - Activity", site_name=settings.SITE_NAME)
|
|
413
|
+
return HTMLResponse(f"{pre}<h1>Activity</h1>{table}{pagination_html}{POSTAMBLE}")
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
@app.get("/opml", response_class=PlainTextResponse)
|
|
417
|
+
def git_opml():
|
|
418
|
+
"""OPML feed list. Port of git_opml (stub)."""
|
|
419
|
+
projects = git_get_projects_list(export_ok=settings.EXPORT_OK)
|
|
420
|
+
# Minimal OPML
|
|
421
|
+
lines = ['<?xml version="1.0"?><opml version="1.0"><head><title>Git</title></head><body>']
|
|
422
|
+
for pr in projects[:100]:
|
|
423
|
+
path = pr.get("path", "")
|
|
424
|
+
lines.append(f'<outline text="{jinja_escape(path)}" />')
|
|
425
|
+
lines.append("</body></opml>")
|
|
426
|
+
return PlainTextResponse("\n".join(lines), media_type="text/xml; charset=utf-8")
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
@app.get("/board/create", response_class=RedirectResponse)
|
|
430
|
+
def board_create_page(
|
|
431
|
+
_: Annotated[None, Depends(require_active_user_if_auth_enabled)],
|
|
432
|
+
project: ValidatedBoardCreateProject,
|
|
433
|
+
) -> RedirectResponse:
|
|
434
|
+
"""Create a board named 'Tasks' (refs/tags/boards/Tasks) and redirect to the project summary."""
|
|
435
|
+
try:
|
|
436
|
+
create_board_for_project(project, name="Tasks", description="")
|
|
437
|
+
except HTTPException as e:
|
|
438
|
+
if e.status_code == 409:
|
|
439
|
+
pass
|
|
440
|
+
else:
|
|
441
|
+
raise
|
|
442
|
+
p_url = quote(project, safe="/")
|
|
443
|
+
return RedirectResponse(url=f"/project/{p_url}", status_code=303)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
# ---------- Add project ----------
|
|
447
|
+
|
|
448
|
+
_OPTIONAL_REPO_ZIP = File(default=None)
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
@app.get("/projectnamevalid", response_class=HTMLResponse)
|
|
452
|
+
def addproject_namevalid(
|
|
453
|
+
_: Annotated[None, Depends(require_permission(Permission.ADD_PROJECTS))],
|
|
454
|
+
name: Annotated[str | None, Query()] = None,
|
|
455
|
+
):
|
|
456
|
+
"""Check if project name is valid (requires pgw.addprojects when auth is enabled)."""
|
|
457
|
+
if not name:
|
|
458
|
+
raise HTTPException(status_code=400, detail="Param 'name' required")
|
|
459
|
+
if not is_valid_pathname(name):
|
|
460
|
+
raise HTTPException(status_code=400, detail="Invalid project name (no path segments)")
|
|
461
|
+
if project_visible_in_list(name):
|
|
462
|
+
raise HTTPException(status_code=409, detail="Project already exists")
|
|
463
|
+
return HTMLResponse(status_code=200, content=f"Project name '{name}' is valid")
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
@app.get("/addproject", response_class=HTMLResponse)
|
|
467
|
+
def addproject_page(
|
|
468
|
+
token: Annotated[str | None, Depends(access_token_from_request)],
|
|
469
|
+
):
|
|
470
|
+
"""Add project form page."""
|
|
471
|
+
show_sign_in_notice = (
|
|
472
|
+
settings.AUTH and is_auth_configured(auth_config) and (not token or decode_access_token(token) is None)
|
|
473
|
+
)
|
|
474
|
+
pre = PREAMBLE.render(
|
|
475
|
+
title=f"{settings.SITE_NAME} - Add Project",
|
|
476
|
+
site_name=settings.SITE_NAME,
|
|
477
|
+
)
|
|
478
|
+
tpl = env.get_template("addproject.html")
|
|
479
|
+
body = tpl.render(
|
|
480
|
+
site_name=settings.SITE_NAME,
|
|
481
|
+
show_sign_in_notice=show_sign_in_notice,
|
|
482
|
+
empty_repo_form_content=Project.form_content(),
|
|
483
|
+
upload_zip_form_content=ProjectZip.form_content(),
|
|
484
|
+
)
|
|
485
|
+
return HTMLResponse(status_code=200, content=f"{pre}{body}{POSTAMBLE}")
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
@app.post("/addproject", response_class=HTMLResponse)
|
|
489
|
+
async def addproject_submit(
|
|
490
|
+
_: Annotated[None, Depends(require_permission(Permission.ADD_PROJECTS))],
|
|
491
|
+
request: Request,
|
|
492
|
+
project_name: Annotated[str, Form()] = "",
|
|
493
|
+
pull_from_remote: Annotated[str, Form()] = "",
|
|
494
|
+
perform_maintenance: Annotated[str, Form()] = "off",
|
|
495
|
+
create_task_board: Annotated[str, Form()] = "off",
|
|
496
|
+
repo_zip: UploadFile | None = _OPTIONAL_REPO_ZIP,
|
|
497
|
+
):
|
|
498
|
+
"""Create a new project (requires pgw.addprojects when auth is enabled)."""
|
|
499
|
+
project_name = (project_name or "").strip()
|
|
500
|
+
if not project_name:
|
|
501
|
+
raise HTTPException(status_code=400, detail="Project name is required")
|
|
502
|
+
if not is_valid_pathname(project_name):
|
|
503
|
+
raise HTTPException(status_code=400, detail="Invalid project name")
|
|
504
|
+
if project_visible_in_list(project_name):
|
|
505
|
+
raise HTTPException(status_code=409, detail="Project already exists")
|
|
506
|
+
|
|
507
|
+
remote_url = (pull_from_remote or "").strip()
|
|
508
|
+
do_maintenance = perform_maintenance.lower() in ("on", "1", "true", "yes")
|
|
509
|
+
do_task_board = create_task_board.lower() in ("on", "1", "true", "yes")
|
|
510
|
+
|
|
511
|
+
dest_path = os.path.join(settings.PROJECTROOT, project_name)
|
|
512
|
+
os.makedirs(settings.PROJECTROOT, exist_ok=True)
|
|
513
|
+
|
|
514
|
+
try:
|
|
515
|
+
if repo_zip and repo_zip.filename and repo_zip.filename.lower().endswith(".zip"):
|
|
516
|
+
content = await repo_zip.read()
|
|
517
|
+
with ProjectZip(
|
|
518
|
+
path=dest_path,
|
|
519
|
+
zip_content=content,
|
|
520
|
+
create_task_board=do_task_board,
|
|
521
|
+
do_maintenance=do_maintenance,
|
|
522
|
+
):
|
|
523
|
+
pass
|
|
524
|
+
else:
|
|
525
|
+
with Project(
|
|
526
|
+
path=dest_path,
|
|
527
|
+
remote_url=remote_url or None,
|
|
528
|
+
create_task_board=do_task_board,
|
|
529
|
+
do_maintenance=do_maintenance,
|
|
530
|
+
):
|
|
531
|
+
pass
|
|
532
|
+
|
|
533
|
+
except pygit2.GitError as e:
|
|
534
|
+
raise HTTPException(status_code=400, detail=f"Git error: {e}") from e
|
|
535
|
+
except HTTPException:
|
|
536
|
+
raise
|
|
537
|
+
except OSError as e:
|
|
538
|
+
raise HTTPException(status_code=500, detail=str(e)) from e
|
|
539
|
+
|
|
540
|
+
return RedirectResponse(url=f"/project/{project_name}", status_code=303)
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
# ---------- Routes (project required) ----------
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
@app.get("/project/{project:path}/board/", response_class=HTMLResponse)
|
|
547
|
+
def project_board(
|
|
548
|
+
project: ValidatedPathProject,
|
|
549
|
+
board: Annotated[str, Query(alias="b")] = "Tasks",
|
|
550
|
+
) -> HTMLResponse:
|
|
551
|
+
"""Board view: columns (dropzones) and task cards."""
|
|
552
|
+
board_name = board
|
|
553
|
+
project_url = f"/project/{quote(project, safe='/')}"
|
|
554
|
+
board_url = f"{project_url}/board/"
|
|
555
|
+
columns = get_board_tasks_grouped(project, board_name)
|
|
556
|
+
for col in columns:
|
|
557
|
+
for t in col["tasks"]:
|
|
558
|
+
t["task_url"] = f"{board_url}?task={quote(t['ref'], safe='')}"
|
|
559
|
+
pre = PREAMBLE.render(
|
|
560
|
+
title=f"{jinja_escape(project)} - Board",
|
|
561
|
+
site_name=settings.SITE_NAME,
|
|
562
|
+
)
|
|
563
|
+
body = env.get_template("board.html").render(
|
|
564
|
+
project=project,
|
|
565
|
+
project_url=project_url,
|
|
566
|
+
board_name=board_name,
|
|
567
|
+
board_url=board_url,
|
|
568
|
+
columns=columns,
|
|
569
|
+
)
|
|
570
|
+
return HTMLResponse(f"{pre}{body}{POSTAMBLE}")
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
@app.get("/project/{project:path}/summary-refs")
|
|
574
|
+
def project_summary_refs(project: ValidatedPathProject) -> dict[str, list[dict[str, str]]]:
|
|
575
|
+
return {"options": summary_ref_options(project)}
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
@app.get("/project/{project:path}/summary-ref-state")
|
|
579
|
+
def project_summary_ref_state(
|
|
580
|
+
project: ValidatedPathProject,
|
|
581
|
+
ref: Annotated[str | None, Query(alias="ref")] = None,
|
|
582
|
+
) -> dict[str, str]:
|
|
583
|
+
return summary_ref_state(project, ref)
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
@app.get("/project/{project:path}/search", response_class=HTMLResponse)
|
|
587
|
+
def project_search_page(project: ValidatedPathProject) -> HTMLResponse:
|
|
588
|
+
"""Per-project search page (UI only; results fetched from /project/{project}?a=search)."""
|
|
589
|
+
return git_search_page(project)
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
@app.get("/project/{project:path}/subpage/{subpage_name}", response_class=HTMLResponse)
|
|
593
|
+
def project_subpage(
|
|
594
|
+
project: ValidatedPathProject,
|
|
595
|
+
subpage_name: str,
|
|
596
|
+
raw: Annotated[bool, Query()] = False,
|
|
597
|
+
) -> HTMLResponse:
|
|
598
|
+
for subpage in SUBPAGES:
|
|
599
|
+
if subpage.subpage_name() != subpage_name:
|
|
600
|
+
continue
|
|
601
|
+
content = subpage.subpage_html(project)
|
|
602
|
+
if content is None:
|
|
603
|
+
raise HTTPException(status_code=404, detail="No content for subpage")
|
|
604
|
+
content_lc = content.lstrip().lower()
|
|
605
|
+
pre = PREAMBLE.render(
|
|
606
|
+
title=f"{jinja_escape(subpage.link_name(project) or subpage_name)} - {jinja_escape(project)}",
|
|
607
|
+
site_name=settings.SITE_NAME,
|
|
608
|
+
)
|
|
609
|
+
if content_lc.startswith("<!doctype html") or "<html" in content_lc:
|
|
610
|
+
if raw:
|
|
611
|
+
stylesheet_href = "/static/main.css"
|
|
612
|
+
link_tag = f'<link rel="stylesheet" href="{stylesheet_href}">'
|
|
613
|
+
if "<head" in content.lower():
|
|
614
|
+
return HTMLResponse(content.replace("</head>", f"{link_tag}</head>", 1))
|
|
615
|
+
return HTMLResponse(f"{link_tag}{content}")
|
|
616
|
+
project_enc = quote(project, safe="/")
|
|
617
|
+
subpage_enc = quote(subpage_name, safe="")
|
|
618
|
+
iframe_src = f"/project/{project_enc}/subpage/{subpage_enc}?raw=true"
|
|
619
|
+
return HTMLResponse(
|
|
620
|
+
f"{pre}<h1>{jinja_escape(project)}</h1>"
|
|
621
|
+
f'<iframe class="subpage-frame" src="{iframe_src}" title="{jinja_escape(subpage_name)}"></iframe>'
|
|
622
|
+
f"{POSTAMBLE}"
|
|
623
|
+
)
|
|
624
|
+
return HTMLResponse(f"{pre}<h1>{jinja_escape(project)}</h1>{content}{POSTAMBLE}")
|
|
625
|
+
raise HTTPException(status_code=404, detail="Unknown subpage")
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
@app.post("/project/{project:path}/hook", response_class=JSONResponse)
|
|
629
|
+
def project_hook(
|
|
630
|
+
project: ValidatedPathProject,
|
|
631
|
+
name: Annotated[str, Query(alias="name")],
|
|
632
|
+
token: Annotated[str | None, Depends(access_token_from_request)],
|
|
633
|
+
op: Annotated[HookInstallOp, Query(alias="op")] = "check",
|
|
634
|
+
) -> JSONResponse:
|
|
635
|
+
"""Add, remove, or check a pygittools hook sample (or bundle of samples) for a project.
|
|
636
|
+
|
|
637
|
+
`name` may be a sample filename (e.g. `post-receive.notify`) or a bundle name
|
|
638
|
+
(e.g. `update`, which installs both `post-commit.notify` and `post-receive.notify`).
|
|
639
|
+
`op` is `add`, `remove`, or `check`.
|
|
640
|
+
"""
|
|
641
|
+
if op != "check":
|
|
642
|
+
ensure_permission(Permission.HOOKS, project, token=token)
|
|
643
|
+
bundle = get_bundle(name)
|
|
644
|
+
sample = get_sample(name) if bundle is None else None
|
|
645
|
+
if bundle is None and sample is None:
|
|
646
|
+
raise HTTPException(status_code=404, detail=f"Unknown hook sample or bundle: {name}")
|
|
647
|
+
try:
|
|
648
|
+
if bundle is not None:
|
|
649
|
+
if op == "add":
|
|
650
|
+
result_status: HookStatus = install_hook_bundle(project, name)
|
|
651
|
+
if result_status == HookStatus.DIFFERENT:
|
|
652
|
+
raise HTTPException(
|
|
653
|
+
status_code=409,
|
|
654
|
+
detail="One or more custom hooks installed; refusing to add",
|
|
655
|
+
)
|
|
656
|
+
elif op == "remove":
|
|
657
|
+
result_status = remove_hook_bundle(project, name)
|
|
658
|
+
if result_status == HookStatus.DIFFERENT:
|
|
659
|
+
raise HTTPException(
|
|
660
|
+
status_code=409,
|
|
661
|
+
detail="One or more custom hooks installed; refusing to remove",
|
|
662
|
+
)
|
|
663
|
+
else:
|
|
664
|
+
result_status = bundle_status(project, name)
|
|
665
|
+
else:
|
|
666
|
+
assert sample is not None
|
|
667
|
+
if op == "add":
|
|
668
|
+
result_status = install_hook(project, name)
|
|
669
|
+
if result_status == HookStatus.DIFFERENT:
|
|
670
|
+
raise HTTPException(
|
|
671
|
+
status_code=409,
|
|
672
|
+
detail="A different hook is already installed at this path; refusing to overwrite",
|
|
673
|
+
)
|
|
674
|
+
elif op == "remove":
|
|
675
|
+
result_status = remove_hook(project, name)
|
|
676
|
+
if result_status == HookStatus.DIFFERENT:
|
|
677
|
+
raise HTTPException(
|
|
678
|
+
status_code=409,
|
|
679
|
+
detail="Installed hook content differs from the sample; refusing to remove",
|
|
680
|
+
)
|
|
681
|
+
else:
|
|
682
|
+
result_status = hook_status(project, name)
|
|
683
|
+
except OSError as e:
|
|
684
|
+
raise HTTPException(status_code=500, detail=str(e)) from e
|
|
685
|
+
if bundle is not None:
|
|
686
|
+
body: dict[str, object] = {
|
|
687
|
+
"project": project,
|
|
688
|
+
"kind": "bundle",
|
|
689
|
+
"name": name,
|
|
690
|
+
"label": bundle["label"],
|
|
691
|
+
"members": [m["name"] for m in bundle["members"]],
|
|
692
|
+
"op": op,
|
|
693
|
+
"status": result_status.value,
|
|
694
|
+
"installed": result_status == HookStatus.INSTALLED,
|
|
695
|
+
}
|
|
696
|
+
else:
|
|
697
|
+
assert sample is not None
|
|
698
|
+
body = {
|
|
699
|
+
"project": project,
|
|
700
|
+
"kind": "sample",
|
|
701
|
+
"name": name,
|
|
702
|
+
"target": sample["target"],
|
|
703
|
+
"label": sample["label"],
|
|
704
|
+
"op": op,
|
|
705
|
+
"status": result_status.value,
|
|
706
|
+
"installed": result_status == HookStatus.INSTALLED,
|
|
707
|
+
}
|
|
708
|
+
return JSONResponse(body)
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
@app.get("/project/{project:path}/hooks", response_class=JSONResponse)
|
|
712
|
+
def project_hooks_list(project: ValidatedPathProject) -> JSONResponse:
|
|
713
|
+
"""List all hook samples and bundles with current status in this project's hooks dir."""
|
|
714
|
+
samples_out: list[dict[str, object]] = []
|
|
715
|
+
for sample in list_samples():
|
|
716
|
+
try:
|
|
717
|
+
st: HookStatus = hook_status(project, sample["name"])
|
|
718
|
+
except KeyError:
|
|
719
|
+
continue
|
|
720
|
+
samples_out.append({
|
|
721
|
+
"name": sample["name"],
|
|
722
|
+
"target": sample["target"],
|
|
723
|
+
"label": sample["label"],
|
|
724
|
+
"status": st.value,
|
|
725
|
+
"installed": st == HookStatus.INSTALLED,
|
|
726
|
+
})
|
|
727
|
+
bundles_out: list[dict[str, object]] = []
|
|
728
|
+
for bundle in list_bundles():
|
|
729
|
+
try:
|
|
730
|
+
bst: HookStatus = bundle_status(project, bundle["name"])
|
|
731
|
+
except KeyError:
|
|
732
|
+
continue
|
|
733
|
+
bundles_out.append({
|
|
734
|
+
"name": bundle["name"],
|
|
735
|
+
"label": bundle["label"],
|
|
736
|
+
"members": [m["name"] for m in bundle["members"]],
|
|
737
|
+
"status": bst.value,
|
|
738
|
+
"installed": bst == HookStatus.INSTALLED,
|
|
739
|
+
})
|
|
740
|
+
return JSONResponse({"project": project, "hooks": samples_out, "bundles": bundles_out})
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
@app.post("/_internal/notify", response_class=JSONResponse)
|
|
744
|
+
async def internal_notify(project: ValidatedNotifyProject) -> JSONResponse:
|
|
745
|
+
"""Notify long-polling subscribers that a project's refs changed.
|
|
746
|
+
|
|
747
|
+
Intended for server-side hooks (pre-receive / post-receive) running on the same host.
|
|
748
|
+
"""
|
|
749
|
+
woken = await CHANGE_QUEUE.notify(project)
|
|
750
|
+
return JSONResponse({"project": project, "waiters_woken": woken})
|
|
751
|
+
|
|
752
|
+
|
|
753
|
+
@app.get("/project/{project:path}", response_class=HTMLResponse)
|
|
754
|
+
async def dispatch(
|
|
755
|
+
request: Request,
|
|
756
|
+
project: ValidatedPathProject,
|
|
757
|
+
a: Annotated[str | None, Query(alias="a")] = None,
|
|
758
|
+
h: Annotated[str | None, Query(alias="h")] = None,
|
|
759
|
+
hb: Annotated[str | None, Query(alias="hb")] = None,
|
|
760
|
+
f: Annotated[str | None, Query(alias="f")] = None,
|
|
761
|
+
fp: Annotated[str | None, Query(alias="fp")] = None,
|
|
762
|
+
page: Annotated[str | None, Query(alias="page")] = None,
|
|
763
|
+
pagecount: Annotated[str | None, Query(alias="pagecount")] = None,
|
|
764
|
+
updates: Annotated[str | None, Query(alias="updates")] = None,
|
|
765
|
+
pf: Annotated[str | None, Query(alias="pf")] = None,
|
|
766
|
+
search_patterns: Annotated[str | None, Query(alias="patterns")] = None,
|
|
767
|
+
search_paths: Annotated[str | None, Query(alias="paths")] = None,
|
|
768
|
+
search_globs: Annotated[str | None, Query(alias="globs")] = None,
|
|
769
|
+
search_heading: Annotated[SearchFlagQuery | None, Query(alias="heading")] = None,
|
|
770
|
+
search_multiline: Annotated[SearchFlagQuery | None, Query(alias="multiline")] = None,
|
|
771
|
+
search_sort: Annotated[SearchSortQuery | None, Query(alias="sort")] = None,
|
|
772
|
+
search_max_count: Annotated[str | None, Query(alias="max_count")] = None,
|
|
773
|
+
):
|
|
774
|
+
"""
|
|
775
|
+
Dispatch by path: /project/{project} -> summary; /project/{project}/action/... -> action.
|
|
776
|
+
Port of dispatch + run_request path handling.
|
|
777
|
+
"""
|
|
778
|
+
action = a
|
|
779
|
+
hash_param = h or hb
|
|
780
|
+
file_name = f
|
|
781
|
+
file_parent = fp
|
|
782
|
+
# If no action, infer: hash only -> object type; project only -> summary
|
|
783
|
+
if not action:
|
|
784
|
+
if hash_param and file_name:
|
|
785
|
+
obj_type = git_get_type(project, f"{hash_param}:{file_name}")
|
|
786
|
+
if not obj_type:
|
|
787
|
+
raise HTTPException(status_code=404, detail="File or directory does not exist")
|
|
788
|
+
action = "tree" if obj_type == "tree" else "blob_plain"
|
|
789
|
+
elif hash_param:
|
|
790
|
+
obj_type = git_get_type(project, hash_param)
|
|
791
|
+
if not obj_type:
|
|
792
|
+
raise HTTPException(status_code=404, detail="Object does not exist")
|
|
793
|
+
action = {
|
|
794
|
+
"commit": "commit",
|
|
795
|
+
"tree": "tree",
|
|
796
|
+
"blob": "blob",
|
|
797
|
+
"tag": "tag",
|
|
798
|
+
}.get(obj_type, "object")
|
|
799
|
+
else:
|
|
800
|
+
action = "summary"
|
|
801
|
+
if action not in DISPATCH_ACTIONS:
|
|
802
|
+
raise HTTPException(status_code=400, detail="Unknown action")
|
|
803
|
+
if action in ("opml", "project_list", "project_index"):
|
|
804
|
+
raise HTTPException(status_code=400, detail="Project not needed for this action")
|
|
805
|
+
if _parse_updates_flag(updates):
|
|
806
|
+
if action not in UPDATES_SUPPORTED_ACTIONS:
|
|
807
|
+
raise HTTPException(status_code=400, detail="updates not supported for this action")
|
|
808
|
+
subscribed = _resolve_subscribed_projects(project, pf)
|
|
809
|
+
if getattr(request.app.state, "shutting_down", False):
|
|
810
|
+
return _updates_idle_response()
|
|
811
|
+
shutdown_ev: asyncio.Event | None = getattr(request.app.state, "shutdown_event", None)
|
|
812
|
+
notified = await CHANGE_QUEUE.wait_for_changes(
|
|
813
|
+
subscribed,
|
|
814
|
+
timeout=CHANGE_QUEUE.DEFAULT_TIMEOUT_SECONDS,
|
|
815
|
+
shutdown_event=shutdown_ev,
|
|
816
|
+
)
|
|
817
|
+
if notified is None:
|
|
818
|
+
return _updates_idle_response()
|
|
819
|
+
if action in PLUGIN_ACTIONS:
|
|
820
|
+
plugin = PLUGIN_ACTIONS[action]
|
|
821
|
+
result = plugin.action(project, request)
|
|
822
|
+
if result is not None:
|
|
823
|
+
return result
|
|
824
|
+
pre = PREAMBLE.render(title=f"{plugin.action_name()} - {project}", site_name=settings.SITE_NAME)
|
|
825
|
+
return HTMLResponse(f"{pre}<p>Action completed.</p>{POSTAMBLE}")
|
|
826
|
+
if action == "summary":
|
|
827
|
+
return git_summary(project, extra_rows=_project_subpage_rows(project))
|
|
828
|
+
if action == "tree":
|
|
829
|
+
return git_tree(project, hash_param, file_name)
|
|
830
|
+
if action in ("blob", "blob_plain"):
|
|
831
|
+
return git_blob(project, hash_param, file_name, raw=(action == "blob_plain"))
|
|
832
|
+
if action == "blame":
|
|
833
|
+
return git_blame(project, hash_param, file_name)
|
|
834
|
+
if action == "blame_raw":
|
|
835
|
+
return git_blame_raw(project, hash_param, file_name)
|
|
836
|
+
if action == "blobdiff":
|
|
837
|
+
return git_blobdiff(project, h, hb, file_name, file_parent)
|
|
838
|
+
if action == "blobpatch":
|
|
839
|
+
return git_blobpatch(project, h, hb, file_name, file_parent)
|
|
840
|
+
if action == "log":
|
|
841
|
+
p, pc = parse_pagination(page, pagecount)
|
|
842
|
+
return git_log(project, hash_param, request, p, pc)
|
|
843
|
+
if action == "shortlog":
|
|
844
|
+
p, pc = parse_pagination(page, pagecount)
|
|
845
|
+
return git_shortlog(project, hash_param, request, p, pc)
|
|
846
|
+
if action == "history":
|
|
847
|
+
p, pc = parse_pagination(page, pagecount)
|
|
848
|
+
return git_history(project, hash_param, file_name, request, p, pc)
|
|
849
|
+
if action == "heads":
|
|
850
|
+
return git_heads(project)
|
|
851
|
+
if action == "tags":
|
|
852
|
+
p, pc = parse_pagination(page, pagecount)
|
|
853
|
+
return git_tags(project, request, p, pc)
|
|
854
|
+
if action == "tag":
|
|
855
|
+
return git_tag(project, hash_param)
|
|
856
|
+
if action == "commit":
|
|
857
|
+
return git_commit(project, hash_param)
|
|
858
|
+
if action == "patch":
|
|
859
|
+
return git_patch(project, h)
|
|
860
|
+
if action == "patches":
|
|
861
|
+
return git_patches(project, h, hb)
|
|
862
|
+
if action == "commitdiff":
|
|
863
|
+
return git_commitdiff(project, hash_param)
|
|
864
|
+
if action == "remotes":
|
|
865
|
+
return git_remotes(project)
|
|
866
|
+
if action == "object":
|
|
867
|
+
return git_object(project, hash_param)
|
|
868
|
+
if action == "search":
|
|
869
|
+
return git_search(
|
|
870
|
+
project,
|
|
871
|
+
search_patterns,
|
|
872
|
+
search_paths,
|
|
873
|
+
search_globs,
|
|
874
|
+
search_heading,
|
|
875
|
+
search_multiline,
|
|
876
|
+
search_sort,
|
|
877
|
+
search_max_count,
|
|
878
|
+
)
|
|
879
|
+
# Stub others with minimal response
|
|
880
|
+
pre = PREAMBLE.render(title=f"{action} - {project}", site_name=settings.SITE_NAME)
|
|
881
|
+
return HTMLResponse(f"{pre}<p>Action: {jinja_escape(action)}</p><p>Project: {jinja_escape(project)}</p>{POSTAMBLE}")
|
|
882
|
+
|
|
883
|
+
|
|
884
|
+
if __name__ == "__main__":
|
|
885
|
+
import uvicorn
|
|
886
|
+
|
|
887
|
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|