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
"""
Settings routes: PyGitWeb global options, PyGit2 library settings, and per-project git config.
Forms are generated from type() and docstrings; project config shows only LOCAL/WORKTREE entries.
"""
from __future__ import annotations
import os
from contextlib import suppress
from typing import Any
from urllib.parse import quote
import pygit2
from fastapi import APIRouter, Depends, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from pygitweb.auth import require_permission
from pygitweb.config import settings
from pygitweb.dependencies import ValidatedSettingsProject
from pygitweb.permissions import Permission
from pygitweb.templates_env import POSTAMBLE, PREAMBLE, env, jinja_escape
def _quote_path(path: str) -> str:
"""Quote path segment for URL (e.g. project name with slashes)."""
return quote(path, safe="/")
# libgit2 config levels: only local (5) and worktree (6) for per-repo editing
GIT_CONFIG_LEVEL_LOCAL = 5
GIT_CONFIG_LEVEL_WORKTREE = 6
router = APIRouter(
prefix="/settings",
tags=["settings"],
dependencies=[Depends(require_permission(Permission.SETTINGS))],
)
# ---------- PyGitWeb settings schema ----------
# Name, type, docstring for form generation. Must match Settings field names.
PYGITWEB_SETTINGS: list[tuple[str, type, str]] = [
("PROJECTROOT", str, "Root filesystem path under which git repositories live."),
("PROJECTS_LIST", str, "Path used for listing projects (often same as PROJECTROOT)."),
("SITE_NAME", str, "Site name shown in the web interface."),
("EXPORT_OK", str, "If set, only repos with this file (or matching path) are listed."),
("LIST_ALL", bool, "When true, list all directories under project root without export_ok checks."),
("STRICT_EXPORT", bool, "When true, require export_ok (or path match) to list projects."),
("GIT", str, "Path to the git executable (e.g. for maintenance)."),
("MAXLOAD", float, "Max load average; 503 when exceeded. Empty to disable."),
]
def _get_pygitweb_values() -> list[tuple[str, Any, type, str]]:
"""Return (name, current_value, type, docstring) for each PyGitWeb setting."""
return [(name, getattr(settings, name), expected_type, doc) for name, expected_type, doc in PYGITWEB_SETTINGS]
def _render_form_field(name: str, value: Any, value_type: type, docstring: str, name_prefix: str = "") -> str:
"""Generate HTML for a single form field based on type."""
field_name = f"{name_prefix}{name}" if name_prefix else name
safe_name = field_name.replace(".", "_")
tpl = env.get_template("settings_form_field.html")
if value_type is bool:
return tpl.render(
kind="bool",
safe_name=safe_name,
field_name=field_name,
name=name,
checked=bool(value),
hint_text=docstring,
)
if value_type in (int, float):
raw = "" if value is None else str(value)
return tpl.render(
kind="number",
safe_name=safe_name,
field_name=field_name,
name=name,
str_val=raw,
hint_text=docstring,
number_step="any",
)
raw = "" if value is None else str(value)
return tpl.render(
kind="text",
safe_name=safe_name,
field_name=field_name,
name=name,
str_val=raw,
hint_text=docstring,
)
# ---------- PyGit2 Settings schema ----------
# List of (attr_name, docstring, value_kind: 'bool'|'int'|'str'|'readonly').
# Based on https://www.pygit2.org/settings.html
PYGIT2_SETTINGS = [
(
"cache_max_size",
"Maximum total data size (bytes) cached in memory across all repositories. Default 256MB.",
"int",
),
(
"cache_object_limit",
"Max size per object type for caching (use cache_object_limit_commit etc. for fine-grained).",
"skip",
), # multi-param
(
"cached_memory",
"Current bytes in cache and maximum allowed (read-only).",
"readonly",
),
(
"disable_pack_keep_file_checks",
"Skip .keep file checks when accessing packfiles; can help on remote filesystems.",
"bool",
),
("enable_caching", "Enable or disable caching completely.", "bool"),
(
"enable_fsync_gitdir",
"Enable or disable fsync for git directory operations.",
"bool",
),
(
"enable_http_expect_continue",
"Enable or disable HTTP Expect/Continue for large pushes.",
"bool",
),
("enable_ofs_delta", "Enable or disable offset delta encoding.", "bool"),
(
"enable_strict_hash_verification",
"Enable or disable strict hash verification.",
"bool",
),
(
"enable_strict_object_creation",
"Enable or disable strict object creation validation.",
"bool",
),
(
"enable_strict_symbolic_ref_creation",
"Enable or disable strict symbolic reference creation validation.",
"bool",
),
(
"enable_unsaved_index_safety",
"Enable or disable unsaved index safety checks.",
"bool",
),
("extensions", "List of enabled extensions (read-only).", "readonly"),
("homedir", "Home directory for config lookup.", "str"),
("mwindow_file_limit", "Maximum number of files to be mapped at any time.", "int"),
(
"mwindow_mapped_limit",
"Maximum memory that will be mapped in total by the library.",
"int",
),
("mwindow_size", "Maximum mmap window size.", "int"),
(
"owner_validation",
"Validate that repository directories are owned by the current user.",
"bool",
),
("pack_max_objects", "Maximum number of objects in a pack.", "int"),
("search_path", "Configuration file search path (read-only).", "readonly"),
("server_connect_timeout", "Server connection timeout in milliseconds.", "int"),
("server_timeout", "Server timeout in milliseconds.", "int"),
("ssl_cert_dir", "TLS certificates lookup directory path.", "str"),
("ssl_cert_file", "TLS certificate file path.", "str"),
("template_path", "Default template path for new repositories.", "str"),
("user_agent", "User agent string for network operations.", "str"),
("user_agent_product", "User agent product name.", "str"),
("windows_sharemode", "Windows share mode for opening files.", "int"),
]
def _get_pygit2_values() -> list[tuple[str, Any, str, str]]:
"""Return (name, value, kind, docstring) for each PyGit2 setting we can show."""
st = pygit2.Settings
instance = pygit2.Settings() # need instance to read property values
out = []
for attr, docstring, kind in PYGIT2_SETTINGS:
if kind == "skip":
continue
if not hasattr(st, attr):
continue
try:
prop = getattr(st, attr)
if callable(prop) and not isinstance(prop, property):
continue
val = getattr(instance, attr)
if isinstance(val, (list, tuple)):
val = ", ".join(str(x) for x in val) if val else ""
elif val is None:
val = ""
out.append((attr, val, kind, docstring))
except (TypeError, AttributeError):
continue
return out
def _render_pygit2_field(name: str, value: Any, kind: str, docstring: str, name_prefix: str = "pygit2_") -> str:
"""Generate HTML for a PyGit2 form field."""
field_name = f"{name_prefix}{name}"
safe_name = field_name.replace(".", "_")
tpl = env.get_template("settings_form_field.html")
if kind == "readonly":
raw = str(value) if value != "" else "(not set)"
return tpl.render(
kind="readonly",
safe_name=safe_name,
field_name=field_name,
name=name,
str_val=raw,
hint_text=docstring,
)
if kind == "bool":
checked_attr = (
" checked"
if (value is True or (isinstance(value, str) and value.lower() in ("true", "1", "on", "yes")))
else ""
)
return tpl.render(
kind="bool",
safe_name=safe_name,
field_name=field_name,
name=name,
checked=(checked_attr != ""),
hint_text=docstring,
)
if kind == "int":
raw = str(value) if value != "" and value is not None else ""
return tpl.render(
kind="number",
safe_name=safe_name,
field_name=field_name,
name=name,
str_val=raw,
hint_text=docstring,
)
raw = str(value) if value is not None else ""
return tpl.render(
kind="text",
safe_name=safe_name,
field_name=field_name,
name=name,
str_val=raw,
hint_text=docstring,
)
# ---------- Project config (local/worktree only) ----------
def _get_project_config_entries(project: str) -> list[tuple[str, str]]:
"""
Return list of (name, value) for repo config, only from LOCAL (5) or WORKTREE (6).
For each name we keep the last value (highest priority when iterating).
"""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
cfg = repo.config
# Iterate; for level in (5, 6) keep last value per name
by_name: dict[str, str] = {}
for entry in cfg:
if entry.level not in (GIT_CONFIG_LEVEL_LOCAL, GIT_CONFIG_LEVEL_WORKTREE):
continue
by_name[entry.name] = entry.value or ""
return [(k, v) for k, v in sorted(by_name.items())]
def _project_config_table_row(key: str, value: str, index: int) -> list[str]:
"""One table row as [key_cell_html, value_cell_html] for project config form."""
key_name = f"config_key_{index}"
val_name = f"config_value_{index}"
key_cell = (
'<input type="text" class="form-control form-control-sm" '
f'id="{key_name}" name="{key_name}" '
f'value="{jinja_escape(key)}" placeholder="e.g. user.name">'
)
val_cell = (
'<input type="text" class="form-control form-control-sm" '
f'id="{val_name}" name="{val_name}" '
f'value="{jinja_escape(value)}" placeholder="value">'
)
return [key_cell, val_cell]
# ---------- Routes: PyGitWeb ----------
@router.get("/pygitweb", response_class=HTMLResponse)
def settings_pygitweb_page(request: Request):
"""PyGitWeb global settings form."""
fields_html = []
for name, val, value_type, doc in _get_pygitweb_values():
fields_html.append(_render_form_field(name, val, value_type, doc))
form_body = "\n".join(fields_html)
pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - PyGitWeb settings", site_name=settings.SITE_NAME)
body = env.get_template("pygitweb_settings.html").render(form_body=form_body)
return HTMLResponse(f"{pre}{body}{POSTAMBLE}")
@router.post("/pygitweb/submit", response_class=HTMLResponse)
async def settings_pygitweb_submit(request: Request):
"""Apply PyGitWeb settings (in-memory for current process)."""
form = await request.form()
def _get(k: str) -> str:
return str(form.get(k) or "").strip()
_TRUTHY = {"on", "1", "true", "yes"}
for name, expected_type, _doc in PYGITWEB_SETTINGS:
raw = _get(name)
if expected_type is bool:
setattr(settings, name, raw.lower() in _TRUTHY)
elif expected_type is float:
with suppress(ValueError):
setattr(settings, name, float(raw) if raw else None)
elif raw:
setattr(settings, name, raw)
return RedirectResponse(url="/settings/pygitweb", status_code=303)
# ---------- Routes: PyGit2 ----------
@router.get("/pygit2", response_class=HTMLResponse)
def settings_pygit2_page(request: Request):
"""PyGit2 library settings form."""
fields_html = []
for name, val, kind, doc in _get_pygit2_values():
fields_html.append(_render_pygit2_field(name, val, kind, doc))
form_body = "\n".join(fields_html)
pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - PyGit2 settings", site_name=settings.SITE_NAME)
body = env.get_template("pygit2_settings.html").render(form_body=form_body)
return HTMLResponse(f"{pre}{body}{POSTAMBLE}")
@router.post("/pygit2/submit", response_class=HTMLResponse)
async def settings_pygit2_submit(request: Request):
"""Apply PyGit2 settings from form (all pygit2_* fields)."""
form = await request.form()
st = pygit2.Settings
for key, form_value in form.items():
if not key.startswith("pygit2_"):
continue
attr = key[7:] # strip pygit2_
if attr not in [x[0] for x in PYGIT2_SETTINGS]:
continue
kind = next((k[2] for k in PYGIT2_SETTINGS if k[0] == attr), "str")
if kind in ("readonly", "skip"):
continue
try:
if kind == "bool":
_ = str(form_value or "").strip().lower() in ("on", "1", "true", "yes")
setattr(st, attr, _)
elif kind == "int":
s = str(form_value or "").strip()
_ = int(s) if s else 0
setattr(st, attr, _)
else:
setattr(st, attr, str(form_value).strip() if form_value else None)
except (TypeError, AttributeError, ValueError):
continue
return RedirectResponse(url="/settings/pygit2", status_code=303)
# ---------- Routes: Project ----------
@router.get("/project/{name:path}", response_class=HTMLResponse)
def settings_project_page(request: Request, name: ValidatedSettingsProject):
"""Project-specific git config form (local/worktree only)."""
entries = _get_project_config_entries(name)
rows = [_project_config_table_row(k, v, i) for i, (k, v) in enumerate(entries)]
# One empty row for adding new
rows.append(_project_config_table_row("", "", len(entries)))
table_html = env.get_template("table.html").render(cols=["Key", "Value"], rows=rows)
pre = PREAMBLE.render(
title=f"{settings.SITE_NAME} - Project settings: {name}",
site_name=settings.SITE_NAME,
)
submit_url = f"/settings/project/{_quote_path(name)}/submit"
cancel_url = f"/project/{_quote_path(name)}"
body = env.get_template("project_settings.html").render(
project_title=name,
submit_url=submit_url,
cancel_url=cancel_url,
table_html=table_html,
)
return HTMLResponse(f"{pre}{body}{POSTAMBLE}")
@router.post("/project/{name:path}/submit", response_class=HTMLResponse)
async def settings_project_submit(request: Request, name: ValidatedSettingsProject):
"""Apply project config from form."""
form = await request.form()
# Collect key/value pairs; keys are config_key_0, config_value_0, ...
indices = set()
for form_key in form:
if form_key.startswith("config_key_"):
with suppress(ValueError):
indices.add(int(form_key.split("_")[-1]))
pairs = []
for i in sorted(indices):
k = str(form.get(f"config_key_{i}") or "").strip() or ""
v = str(form.get(f"config_value_{i}") or "").strip() or ""
if k:
pairs.append((k, v))
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, name))
cfg = repo.config
for config_key, config_value in pairs:
try:
cfg[config_key] = config_value
except (pygit2.GitError, ValueError, KeyError):
continue
return RedirectResponse(url=f"/settings/project/{_quote_path(name)}", status_code=303)