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.
Files changed (95) hide show
  1. pygitweb/__init__.py +22 -0
  2. pygitweb/__meta__.py +9 -0
  3. pygitweb/actions.py +1303 -0
  4. pygitweb/addproject_permissions_test.py +114 -0
  5. pygitweb/api/__init__.py +0 -0
  6. pygitweb/api/action.py +20 -0
  7. pygitweb/api/plugins/__init__.py +0 -0
  8. pygitweb/api/plugins/project_zip.py +71 -0
  9. pygitweb/api/project.py +67 -0
  10. pygitweb/api/subpage.py +22 -0
  11. pygitweb/auth.py +387 -0
  12. pygitweb/auth.schema.json +106 -0
  13. pygitweb/auth_config.py +243 -0
  14. pygitweb/auth_oauth.py +343 -0
  15. pygitweb/auth_test.py +390 -0
  16. pygitweb/boards_permissions_test.py +113 -0
  17. pygitweb/change_queue.py +110 -0
  18. pygitweb/change_queue_routes_test.py +146 -0
  19. pygitweb/change_queue_test.py +91 -0
  20. pygitweb/comments_permissions_test.py +140 -0
  21. pygitweb/config.py +185 -0
  22. pygitweb/conftest.py +43 -0
  23. pygitweb/dependencies.py +87 -0
  24. pygitweb/formatting.py +182 -0
  25. pygitweb/formatting_test.py +68 -0
  26. pygitweb/git_helpers.py +454 -0
  27. pygitweb/git_helpers_test.py +223 -0
  28. pygitweb/gravatar.py +16 -0
  29. pygitweb/gravatar_test.py +10 -0
  30. pygitweb/hooks_install.py +278 -0
  31. pygitweb/hooks_install_test.py +363 -0
  32. pygitweb/hooks_permissions_test.py +116 -0
  33. pygitweb/main.py +887 -0
  34. pygitweb/merge_requests.py +230 -0
  35. pygitweb/merge_requests_test.py +85 -0
  36. pygitweb/mr_permissions_test.py +148 -0
  37. pygitweb/password_hash.py +74 -0
  38. pygitweb/password_hash_test.py +20 -0
  39. pygitweb/permissions.py +209 -0
  40. pygitweb/permissions_test.py +86 -0
  41. pygitweb/plugin_loader.py +83 -0
  42. pygitweb/projects.py +213 -0
  43. pygitweb/projects_test.py +186 -0
  44. pygitweb/sessions.py +73 -0
  45. pygitweb/settings.py +412 -0
  46. pygitweb/settings.schema.json +73 -0
  47. pygitweb/settings_config.py +122 -0
  48. pygitweb/settings_config_test.py +101 -0
  49. pygitweb/settings_permissions_test.py +76 -0
  50. pygitweb/static/blob-view.js +133 -0
  51. pygitweb/static/board.js +839 -0
  52. pygitweb/static/hook-install.js +53 -0
  53. pygitweb/static/icons/cloud-down.svg +1 -0
  54. pygitweb/static/icons/cloud-exclamation.svg +1 -0
  55. pygitweb/static/icons/cloud-filled.svg +1 -0
  56. pygitweb/static/icons/cloud-storm.svg +1 -0
  57. pygitweb/static/icons/cloud-up.svg +1 -0
  58. pygitweb/static/icons/cloud.svg +1 -0
  59. pygitweb/static/logo.svg +44 -0
  60. pygitweb/static/main.css +1210 -0
  61. pygitweb/static/navbar-auth.js +82 -0
  62. pygitweb/static/readme-render.js +174 -0
  63. pygitweb/static/search-page.js +139 -0
  64. pygitweb/static/summary-ref-switcher.js +130 -0
  65. pygitweb/static/themes/solarized.css +34 -0
  66. pygitweb/tasks.py +595 -0
  67. pygitweb/tasks_permissions_test.py +137 -0
  68. pygitweb/tasks_routes_test.py +430 -0
  69. pygitweb/templates/addproject.html +174 -0
  70. pygitweb/templates/blobdiff.html +57 -0
  71. pygitweb/templates/board.html +31 -0
  72. pygitweb/templates/board_card.html +44 -0
  73. pygitweb/templates/commitdiff.html +57 -0
  74. pygitweb/templates/hooks_summary_cell.html +37 -0
  75. pygitweb/templates/login.html +37 -0
  76. pygitweb/templates/merge_request_summary_cell.html +18 -0
  77. pygitweb/templates/merge_request_tag.html +90 -0
  78. pygitweb/templates/pagination.html +44 -0
  79. pygitweb/templates/preamble.html +89 -0
  80. pygitweb/templates/project_settings.html +13 -0
  81. pygitweb/templates/pygit2_settings.html +12 -0
  82. pygitweb/templates/pygitweb_settings.html +12 -0
  83. pygitweb/templates/search.html +77 -0
  84. pygitweb/templates/settings_form_field.html +27 -0
  85. pygitweb/templates/table.html +15 -0
  86. pygitweb/templates/user_profile.html +10 -0
  87. pygitweb/templates_env.py +21 -0
  88. pygitweb/timeline_cache.py +243 -0
  89. pygitweb/validation.py +75 -0
  90. pygitweb/validation_test.py +167 -0
  91. pygitweb-0.1.0.dist-info/METADATA +165 -0
  92. pygitweb-0.1.0.dist-info/RECORD +95 -0
  93. pygitweb-0.1.0.dist-info/WHEEL +5 -0
  94. pygitweb-0.1.0.dist-info/licenses/LICENSE +21 -0
  95. pygitweb-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,186 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Generator
4
+ from pathlib import Path
5
+ from unittest.mock import patch
6
+
7
+ import pygit2
8
+ import pytest
9
+
10
+ import pygitweb.projects as projects
11
+ from pygitweb.config import settings
12
+
13
+
14
+ def _create_initial_commit(repo: pygit2.Repository, repo_dir: Path, message: str) -> None:
15
+ (repo_dir / "README.md").write_text(f"{message}\n", encoding="utf-8")
16
+ index = repo.index
17
+ index.add("README.md")
18
+ index.write()
19
+ tree = index.write_tree()
20
+ sig = pygit2.Signature("tester", "tester@example.com")
21
+ repo.create_commit("HEAD", sig, sig, message, tree, [])
22
+
23
+
24
+ class TestProjects:
25
+ @pytest.fixture(scope="class")
26
+ def project_env(self, tmp_path_factory: pytest.TempPathFactory) -> Generator[dict[str, str], None, None]:
27
+ root: Path = tmp_path_factory.mktemp("projects")
28
+
29
+ alpha_dir: Path = root / "alpha"
30
+ alpha_dir.mkdir()
31
+ alpha_repo = pygit2.init_repository(str(alpha_dir), bare=False)
32
+ _create_initial_commit(alpha_repo, alpha_dir, "alpha init")
33
+ (alpha_dir / "git-daemon-export-ok").write_text("", encoding="utf-8")
34
+
35
+ nested_dir: Path = root / "group"
36
+ nested_dir.mkdir()
37
+ beta_dir: Path = nested_dir / "beta"
38
+ beta_dir.mkdir()
39
+ beta_repo = pygit2.init_repository(str(beta_dir), bare=False)
40
+ _create_initial_commit(beta_repo, beta_dir, "beta init")
41
+ (beta_dir / "git-daemon-export-ok").write_text("", encoding="utf-8")
42
+
43
+ private_dir: Path = root / "private"
44
+ private_dir.mkdir()
45
+ private_repo = pygit2.init_repository(str(private_dir), bare=False)
46
+ _create_initial_commit(private_repo, private_dir, "private init")
47
+
48
+ (root / "not-a-repo").mkdir()
49
+
50
+ projects_list_file: Path = root / "projects.list"
51
+ projects_list_file.write_text(
52
+ "\n".join([
53
+ "alpha Alice",
54
+ "group/beta Bob%20Owner",
55
+ "private",
56
+ "name%20with%20space Owner%20Space",
57
+ ])
58
+ + "\n",
59
+ encoding="utf-8",
60
+ )
61
+
62
+ try:
63
+ yield {
64
+ "root": str(root),
65
+ "alpha": "alpha",
66
+ "beta": "group/beta",
67
+ "private": "private",
68
+ "projects_list_file": str(projects_list_file),
69
+ }
70
+ finally:
71
+ projects._gitweb_project_owner = None
72
+
73
+ class TestProjectInList:
74
+ def test_project_in_list_true(self) -> None:
75
+ def getter() -> list[dict[str, str]]:
76
+ return [{"path": "alpha"}, {"path": "beta"}]
77
+
78
+ assert projects.project_in_list("alpha", getter) is True
79
+
80
+ def test_project_in_list_false(self) -> None:
81
+ def getter() -> list[dict[str, str]]:
82
+ return [{"path": "alpha"}]
83
+
84
+ assert projects.project_in_list("missing", getter) is False
85
+
86
+ class TestProjectDiscovery:
87
+ def test_git_get_projects_list_directory_mode(self, project_env: dict[str, str]) -> None:
88
+ with (
89
+ patch.object(settings, "PROJECTROOT", project_env["root"]),
90
+ patch.object(settings, "PROJECTS_LIST", project_env["root"]),
91
+ patch.object(settings, "PROJECT_MAXDEPTH", 3),
92
+ patch.object(settings, "LIST_ALL", True),
93
+ ):
94
+ result = projects.git_get_projects_list(export_ok="git-daemon-export-ok")
95
+ paths = {entry["path"] for entry in result}
96
+ assert {"alpha", "group/beta", "private"} <= paths
97
+
98
+ def test_git_get_projects_list_respects_export_ok_when_list_all_false(
99
+ self,
100
+ project_env: dict[str, str],
101
+ ) -> None:
102
+ with (
103
+ patch.object(settings, "PROJECTROOT", project_env["root"]),
104
+ patch.object(settings, "PROJECTS_LIST", project_env["root"]),
105
+ patch.object(settings, "PROJECT_MAXDEPTH", 3),
106
+ patch.object(settings, "LIST_ALL", False),
107
+ ):
108
+ result = projects.git_get_projects_list(export_ok="git-daemon-export-ok")
109
+ paths = {entry["path"] for entry in result}
110
+ assert "alpha" in paths
111
+ assert "group/beta" in paths
112
+ assert "private" not in paths
113
+
114
+ def test_git_get_projects_list_filter_path(self, project_env: dict[str, str]) -> None:
115
+ with (
116
+ patch.object(settings, "PROJECTROOT", project_env["root"]),
117
+ patch.object(settings, "PROJECTS_LIST", project_env["root"]),
118
+ patch.object(settings, "PROJECT_MAXDEPTH", 3),
119
+ patch.object(settings, "LIST_ALL", True),
120
+ ):
121
+ result = projects.git_get_projects_list(filter_path="group")
122
+ assert result == [{"path": "group/beta"}]
123
+
124
+ def test_git_get_projects_list_file_mode(self, project_env: dict[str, str]) -> None:
125
+ with (
126
+ patch.object(settings, "PROJECTROOT", project_env["root"]),
127
+ patch.object(settings, "PROJECTS_LIST", project_env["projects_list_file"]),
128
+ patch.object(settings, "LIST_ALL", True),
129
+ ):
130
+ result = projects.git_get_projects_list()
131
+ assert result == [
132
+ {"path": "alpha", "owner": "Alice"},
133
+ {"path": "group/beta", "owner": "Bob Owner"},
134
+ {"path": "private"},
135
+ {"path": "name with space", "owner": "Owner Space"},
136
+ ]
137
+
138
+ class TestProjectOwnerAndActivity:
139
+ def test_git_get_project_list_from_file_and_cache(self, project_env: dict[str, str]) -> None:
140
+ projects._gitweb_project_owner = None
141
+ with patch.object(settings, "PROJECTS_LIST", project_env["projects_list_file"]):
142
+ owners_first = projects.git_get_project_list_from_file()
143
+ owners_second = projects.git_get_project_list_from_file()
144
+ assert owners_first is owners_second
145
+ assert owners_first["alpha"] == "Alice"
146
+ assert owners_first["group/beta"] == "Bob Owner"
147
+
148
+ def test_git_get_project_owner_from_file(self, project_env: dict[str, str]) -> None:
149
+ projects._gitweb_project_owner = None
150
+ with (
151
+ patch.object(settings, "PROJECTROOT", project_env["root"]),
152
+ patch.object(settings, "PROJECTS_LIST", project_env["projects_list_file"]),
153
+ ):
154
+ owner = projects.git_get_project_owner("alpha")
155
+ assert owner == "Alice"
156
+
157
+ def test_git_get_project_owner_from_config_fallback(self, project_env: dict[str, str]) -> None:
158
+ projects._gitweb_project_owner = None
159
+ with (
160
+ patch.object(settings, "PROJECTROOT", project_env["root"]),
161
+ patch.object(settings, "PROJECTS_LIST", project_env["projects_list_file"]),
162
+ ):
163
+ owner = projects.git_get_project_owner("private", get_project_config=lambda _p, _k: "Config Owner")
164
+ assert owner == "Config Owner"
165
+
166
+ def test_git_get_last_activity_for_repo_and_missing_project(self, project_env: dict[str, str]) -> None:
167
+ with patch.object(settings, "PROJECTROOT", project_env["root"]):
168
+ last_activity = projects.git_get_last_activity(project_env["alpha"])
169
+ missing_activity = projects.git_get_last_activity("does-not-exist")
170
+ assert isinstance(last_activity, int)
171
+ assert last_activity > 0
172
+ assert missing_activity is None
173
+
174
+ class TestSearchProjects:
175
+ def test_search_projects_list_by_tag_and_regex(self) -> None:
176
+ projlist: list[dict[str, object]] = [
177
+ {"path": "alpha", "descr_long": "backend api", "ctags": {"infra": 1}},
178
+ {"path": "beta", "descr_long": "frontend web", "ctags": {"ui": 1}},
179
+ ]
180
+ result = projects.search_projects_list(projlist, tagfilter="infra", search_regexp="backend")
181
+ assert result == [projlist[0]]
182
+
183
+ def test_search_projects_list_invalid_regex_returns_empty(self) -> None:
184
+ projlist: list[dict[str, object]] = [{"path": "alpha", "descr_long": "desc"}]
185
+ result = projects.search_projects_list(projlist, search_regexp="(")
186
+ assert result == []
pygitweb/sessions.py ADDED
@@ -0,0 +1,73 @@
1
+ """
2
+ In-process opaque session IDs (browser cookie / Bearer token value).
3
+
4
+ Single-process only; restarting the server clears every session (empty dict).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import secrets
10
+ import threading
11
+ import time
12
+ from dataclasses import dataclass
13
+ from typing import Literal
14
+
15
+ _lock = threading.Lock()
16
+
17
+ AuthMethod = Literal["local", "oauth"]
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Session:
22
+ username: str
23
+ created_at: float
24
+ subject: str | None = None
25
+ email: str | None = None
26
+ auth_method: AuthMethod = "local"
27
+
28
+
29
+ _sessions: dict[str, Session] = {}
30
+
31
+
32
+ def create_session(
33
+ username: str,
34
+ *,
35
+ subject: str | None = None,
36
+ email: str | None = None,
37
+ auth_method: AuthMethod = "local",
38
+ ) -> str:
39
+ sid = secrets.token_urlsafe(32)
40
+ with _lock:
41
+ _sessions[sid] = Session(
42
+ username=username,
43
+ created_at=time.time(),
44
+ subject=subject,
45
+ email=email,
46
+ auth_method=auth_method,
47
+ )
48
+ return sid
49
+
50
+
51
+ def get_session(session_id: str | None) -> Session | None:
52
+ if not session_id:
53
+ return None
54
+ raw = session_id.strip()
55
+ if not raw:
56
+ return None
57
+ with _lock:
58
+ return _sessions.get(raw)
59
+
60
+
61
+ def revoke_session(session_id: str | None) -> None:
62
+ if not session_id:
63
+ return
64
+ raw = session_id.strip()
65
+ if not raw:
66
+ return
67
+ with _lock:
68
+ _sessions.pop(raw, None)
69
+
70
+
71
+ def clear_all_sessions() -> None:
72
+ with _lock:
73
+ _sessions.clear()
pygitweb/settings.py ADDED
@@ -0,0 +1,412 @@
1
+ """
2
+ Settings routes: PyGitWeb global options, PyGit2 library settings, and per-project git config.
3
+ Forms are generated from type() and docstrings; project config shows only LOCAL/WORKTREE entries.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ from contextlib import suppress
10
+ from typing import Any
11
+ from urllib.parse import quote
12
+
13
+ import pygit2
14
+ from fastapi import APIRouter, Depends, Request
15
+ from fastapi.responses import HTMLResponse, RedirectResponse
16
+
17
+ from pygitweb.auth import require_permission
18
+ from pygitweb.config import settings
19
+ from pygitweb.dependencies import ValidatedSettingsProject
20
+ from pygitweb.permissions import Permission
21
+ from pygitweb.settings_config import settings_batch_update
22
+ from pygitweb.templates_env import POSTAMBLE, PREAMBLE, env, jinja_escape
23
+
24
+
25
+ def _quote_path(path: str) -> str:
26
+ """Quote path segment for URL (e.g. project name with slashes)."""
27
+ return quote(path, safe="/")
28
+
29
+
30
+ # libgit2 config levels: only local (5) and worktree (6) for per-repo editing
31
+ GIT_CONFIG_LEVEL_LOCAL = 5
32
+ GIT_CONFIG_LEVEL_WORKTREE = 6
33
+
34
+ router = APIRouter(
35
+ prefix="/settings",
36
+ tags=["settings"],
37
+ dependencies=[Depends(require_permission(Permission.SETTINGS))],
38
+ )
39
+
40
+
41
+ # ---------- PyGitWeb settings schema ----------
42
+ # Name, type, docstring for form generation. Must match Settings field names.
43
+ PYGITWEB_SETTINGS: list[tuple[str, type, str]] = [
44
+ ("PROJECTROOT", str, "Root filesystem path under which git repositories live."),
45
+ ("PROJECTS_LIST", str, "Path used for listing projects (often same as PROJECTROOT)."),
46
+ ("SITE_NAME", str, "Site name shown in the web interface."),
47
+ ("EXPORT_OK", str, "If set, only repos with this file (or matching path) are listed."),
48
+ ("LIST_ALL", bool, "When true, list all directories under project root without export_ok checks."),
49
+ ("STRICT_EXPORT", bool, "When true, require export_ok (or path match) to list projects."),
50
+ ("GIT", str, "Path to the git executable (e.g. for maintenance)."),
51
+ ("MAXLOAD", float, "Max load average; 503 when exceeded. Empty to disable."),
52
+ ]
53
+
54
+
55
+ def _get_pygitweb_values() -> list[tuple[str, Any, type, str]]:
56
+ """Return (name, current_value, type, docstring) for each PyGitWeb setting."""
57
+ return [(name, getattr(settings, name), expected_type, doc) for name, expected_type, doc in PYGITWEB_SETTINGS]
58
+
59
+
60
+ def _render_form_field(name: str, value: Any, value_type: type, docstring: str, name_prefix: str = "") -> str:
61
+ """Generate HTML for a single form field based on type."""
62
+ field_name = f"{name_prefix}{name}" if name_prefix else name
63
+ safe_name = field_name.replace(".", "_")
64
+ tpl = env.get_template("settings_form_field.html")
65
+ if value_type is bool:
66
+ return tpl.render(
67
+ kind="bool",
68
+ safe_name=safe_name,
69
+ field_name=field_name,
70
+ name=name,
71
+ checked=bool(value),
72
+ hint_text=docstring,
73
+ )
74
+ if value_type in (int, float):
75
+ raw = "" if value is None else str(value)
76
+ return tpl.render(
77
+ kind="number",
78
+ safe_name=safe_name,
79
+ field_name=field_name,
80
+ name=name,
81
+ str_val=raw,
82
+ hint_text=docstring,
83
+ number_step="any",
84
+ )
85
+ raw = "" if value is None else str(value)
86
+ return tpl.render(
87
+ kind="text",
88
+ safe_name=safe_name,
89
+ field_name=field_name,
90
+ name=name,
91
+ str_val=raw,
92
+ hint_text=docstring,
93
+ )
94
+
95
+
96
+ # ---------- PyGit2 Settings schema ----------
97
+ # List of (attr_name, docstring, value_kind: 'bool'|'int'|'str'|'readonly').
98
+ # Based on https://www.pygit2.org/settings.html
99
+ PYGIT2_SETTINGS = [
100
+ (
101
+ "cache_max_size",
102
+ "Maximum total data size (bytes) cached in memory across all repositories. Default 256MB.",
103
+ "int",
104
+ ),
105
+ (
106
+ "cache_object_limit",
107
+ "Max size per object type for caching (use cache_object_limit_commit etc. for fine-grained).",
108
+ "skip",
109
+ ), # multi-param
110
+ (
111
+ "cached_memory",
112
+ "Current bytes in cache and maximum allowed (read-only).",
113
+ "readonly",
114
+ ),
115
+ (
116
+ "disable_pack_keep_file_checks",
117
+ "Skip .keep file checks when accessing packfiles; can help on remote filesystems.",
118
+ "bool",
119
+ ),
120
+ ("enable_caching", "Enable or disable caching completely.", "bool"),
121
+ (
122
+ "enable_fsync_gitdir",
123
+ "Enable or disable fsync for git directory operations.",
124
+ "bool",
125
+ ),
126
+ (
127
+ "enable_http_expect_continue",
128
+ "Enable or disable HTTP Expect/Continue for large pushes.",
129
+ "bool",
130
+ ),
131
+ ("enable_ofs_delta", "Enable or disable offset delta encoding.", "bool"),
132
+ (
133
+ "enable_strict_hash_verification",
134
+ "Enable or disable strict hash verification.",
135
+ "bool",
136
+ ),
137
+ (
138
+ "enable_strict_object_creation",
139
+ "Enable or disable strict object creation validation.",
140
+ "bool",
141
+ ),
142
+ (
143
+ "enable_strict_symbolic_ref_creation",
144
+ "Enable or disable strict symbolic reference creation validation.",
145
+ "bool",
146
+ ),
147
+ (
148
+ "enable_unsaved_index_safety",
149
+ "Enable or disable unsaved index safety checks.",
150
+ "bool",
151
+ ),
152
+ ("extensions", "List of enabled extensions (read-only).", "readonly"),
153
+ ("homedir", "Home directory for config lookup.", "str"),
154
+ ("mwindow_file_limit", "Maximum number of files to be mapped at any time.", "int"),
155
+ (
156
+ "mwindow_mapped_limit",
157
+ "Maximum memory that will be mapped in total by the library.",
158
+ "int",
159
+ ),
160
+ ("mwindow_size", "Maximum mmap window size.", "int"),
161
+ (
162
+ "owner_validation",
163
+ "Validate that repository directories are owned by the current user.",
164
+ "bool",
165
+ ),
166
+ ("pack_max_objects", "Maximum number of objects in a pack.", "int"),
167
+ ("search_path", "Configuration file search path (read-only).", "readonly"),
168
+ ("server_connect_timeout", "Server connection timeout in milliseconds.", "int"),
169
+ ("server_timeout", "Server timeout in milliseconds.", "int"),
170
+ ("ssl_cert_dir", "TLS certificates lookup directory path.", "str"),
171
+ ("ssl_cert_file", "TLS certificate file path.", "str"),
172
+ ("template_path", "Default template path for new repositories.", "str"),
173
+ ("user_agent", "User agent string for network operations.", "str"),
174
+ ("user_agent_product", "User agent product name.", "str"),
175
+ ("windows_sharemode", "Windows share mode for opening files.", "int"),
176
+ ]
177
+
178
+
179
+ def _get_pygit2_values() -> list[tuple[str, Any, str, str]]:
180
+ """Return (name, value, kind, docstring) for each PyGit2 setting we can show."""
181
+ st = pygit2.Settings
182
+ instance = pygit2.Settings() # need instance to read property values
183
+ out = []
184
+ for attr, docstring, kind in PYGIT2_SETTINGS:
185
+ if kind == "skip":
186
+ continue
187
+ if not hasattr(st, attr):
188
+ continue
189
+ try:
190
+ prop = getattr(st, attr)
191
+ if callable(prop) and not isinstance(prop, property):
192
+ continue
193
+ val = getattr(instance, attr)
194
+ if isinstance(val, (list, tuple)):
195
+ val = ", ".join(str(x) for x in val) if val else ""
196
+ elif val is None:
197
+ val = ""
198
+ out.append((attr, val, kind, docstring))
199
+ except (TypeError, AttributeError):
200
+ continue
201
+ return out
202
+
203
+
204
+ def _render_pygit2_field(name: str, value: Any, kind: str, docstring: str, name_prefix: str = "pygit2_") -> str:
205
+ """Generate HTML for a PyGit2 form field."""
206
+ field_name = f"{name_prefix}{name}"
207
+ safe_name = field_name.replace(".", "_")
208
+ tpl = env.get_template("settings_form_field.html")
209
+ if kind == "readonly":
210
+ raw = str(value) if value != "" else "(not set)"
211
+ return tpl.render(
212
+ kind="readonly",
213
+ safe_name=safe_name,
214
+ field_name=field_name,
215
+ name=name,
216
+ str_val=raw,
217
+ hint_text=docstring,
218
+ )
219
+ if kind == "bool":
220
+ checked_attr = (
221
+ " checked"
222
+ if (value is True or (isinstance(value, str) and value.lower() in ("true", "1", "on", "yes")))
223
+ else ""
224
+ )
225
+ return tpl.render(
226
+ kind="bool",
227
+ safe_name=safe_name,
228
+ field_name=field_name,
229
+ name=name,
230
+ checked=(checked_attr != ""),
231
+ hint_text=docstring,
232
+ )
233
+ if kind == "int":
234
+ raw = str(value) if value != "" and value is not None else ""
235
+ return tpl.render(
236
+ kind="number",
237
+ safe_name=safe_name,
238
+ field_name=field_name,
239
+ name=name,
240
+ str_val=raw,
241
+ hint_text=docstring,
242
+ )
243
+ raw = str(value) if value is not None else ""
244
+ return tpl.render(
245
+ kind="text",
246
+ safe_name=safe_name,
247
+ field_name=field_name,
248
+ name=name,
249
+ str_val=raw,
250
+ hint_text=docstring,
251
+ )
252
+
253
+
254
+ # ---------- Project config (local/worktree only) ----------
255
+ def _get_project_config_entries(project: str) -> list[tuple[str, str]]:
256
+ """
257
+ Return list of (name, value) for repo config, only from LOCAL (5) or WORKTREE (6).
258
+ For each name we keep the last value (highest priority when iterating).
259
+ """
260
+ repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
261
+ cfg = repo.config
262
+ # Iterate; for level in (5, 6) keep last value per name
263
+ by_name: dict[str, str] = {}
264
+ for entry in cfg:
265
+ if entry.level not in (GIT_CONFIG_LEVEL_LOCAL, GIT_CONFIG_LEVEL_WORKTREE):
266
+ continue
267
+ by_name[entry.name] = entry.value or ""
268
+ return [(k, v) for k, v in sorted(by_name.items())]
269
+
270
+
271
+ def _project_config_table_row(key: str, value: str, index: int) -> list[str]:
272
+ """One table row as [key_cell_html, value_cell_html] for project config form."""
273
+ key_name = f"config_key_{index}"
274
+ val_name = f"config_value_{index}"
275
+ key_cell = (
276
+ '<input type="text" class="form-control form-control-sm" '
277
+ f'id="{key_name}" name="{key_name}" '
278
+ f'value="{jinja_escape(key)}" placeholder="e.g. user.name">'
279
+ )
280
+ val_cell = (
281
+ '<input type="text" class="form-control form-control-sm" '
282
+ f'id="{val_name}" name="{val_name}" '
283
+ f'value="{jinja_escape(value)}" placeholder="value">'
284
+ )
285
+ return [key_cell, val_cell]
286
+
287
+
288
+ # ---------- Routes: PyGitWeb ----------
289
+ @router.get("/pygitweb", response_class=HTMLResponse)
290
+ def settings_pygitweb_page(request: Request):
291
+ """PyGitWeb global settings form."""
292
+ fields_html = []
293
+ for name, val, value_type, doc in _get_pygitweb_values():
294
+ fields_html.append(_render_form_field(name, val, value_type, doc))
295
+ form_body = "\n".join(fields_html)
296
+ pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - PyGitWeb settings", site_name=settings.SITE_NAME)
297
+ body = env.get_template("pygitweb_settings.html").render(form_body=form_body)
298
+ return HTMLResponse(f"{pre}{body}{POSTAMBLE}")
299
+
300
+
301
+ @router.post("/pygitweb/submit", response_class=HTMLResponse)
302
+ async def settings_pygitweb_submit(request: Request):
303
+ """Apply PyGitWeb settings and persist to the settings JSON file."""
304
+ form = await request.form()
305
+
306
+ def _get(k: str) -> str:
307
+ return str(form.get(k) or "").strip()
308
+
309
+ _TRUTHY = {"on", "1", "true", "yes"}
310
+ with settings_batch_update(settings):
311
+ for name, expected_type, _doc in PYGITWEB_SETTINGS:
312
+ raw = _get(name)
313
+ if expected_type is bool:
314
+ setattr(settings, name, raw.lower() in _TRUTHY)
315
+ elif expected_type is float:
316
+ with suppress(ValueError):
317
+ setattr(settings, name, float(raw) if raw else None)
318
+ elif raw:
319
+ setattr(settings, name, raw)
320
+ return RedirectResponse(url="/settings/pygitweb", status_code=303)
321
+
322
+
323
+ # ---------- Routes: PyGit2 ----------
324
+ @router.get("/pygit2", response_class=HTMLResponse)
325
+ def settings_pygit2_page(request: Request):
326
+ """PyGit2 library settings form."""
327
+ fields_html = []
328
+ for name, val, kind, doc in _get_pygit2_values():
329
+ fields_html.append(_render_pygit2_field(name, val, kind, doc))
330
+ form_body = "\n".join(fields_html)
331
+ pre = PREAMBLE.render(title=f"{settings.SITE_NAME} - PyGit2 settings", site_name=settings.SITE_NAME)
332
+ body = env.get_template("pygit2_settings.html").render(form_body=form_body)
333
+ return HTMLResponse(f"{pre}{body}{POSTAMBLE}")
334
+
335
+
336
+ @router.post("/pygit2/submit", response_class=HTMLResponse)
337
+ async def settings_pygit2_submit(request: Request):
338
+ """Apply PyGit2 settings from form (all pygit2_* fields)."""
339
+ form = await request.form()
340
+ st = pygit2.Settings
341
+ for key, form_value in form.items():
342
+ if not key.startswith("pygit2_"):
343
+ continue
344
+ attr = key[7:] # strip pygit2_
345
+ if attr not in [x[0] for x in PYGIT2_SETTINGS]:
346
+ continue
347
+ kind = next((k[2] for k in PYGIT2_SETTINGS if k[0] == attr), "str")
348
+ if kind in ("readonly", "skip"):
349
+ continue
350
+ try:
351
+ if kind == "bool":
352
+ _ = str(form_value or "").strip().lower() in ("on", "1", "true", "yes")
353
+ setattr(st, attr, _)
354
+ elif kind == "int":
355
+ s = str(form_value or "").strip()
356
+ _ = int(s) if s else 0
357
+ setattr(st, attr, _)
358
+ else:
359
+ setattr(st, attr, str(form_value).strip() if form_value else None)
360
+ except (TypeError, AttributeError, ValueError):
361
+ continue
362
+ return RedirectResponse(url="/settings/pygit2", status_code=303)
363
+
364
+
365
+ # ---------- Routes: Project ----------
366
+ @router.get("/project/{name:path}", response_class=HTMLResponse)
367
+ def settings_project_page(request: Request, name: ValidatedSettingsProject):
368
+ """Project-specific git config form (local/worktree only)."""
369
+ entries = _get_project_config_entries(name)
370
+ rows = [_project_config_table_row(k, v, i) for i, (k, v) in enumerate(entries)]
371
+ # One empty row for adding new
372
+ rows.append(_project_config_table_row("", "", len(entries)))
373
+ table_html = env.get_template("table.html").render(cols=["Key", "Value"], rows=rows)
374
+ pre = PREAMBLE.render(
375
+ title=f"{settings.SITE_NAME} - Project settings: {name}",
376
+ site_name=settings.SITE_NAME,
377
+ )
378
+ submit_url = f"/settings/project/{_quote_path(name)}/submit"
379
+ cancel_url = f"/project/{_quote_path(name)}"
380
+ body = env.get_template("project_settings.html").render(
381
+ project_title=name,
382
+ submit_url=submit_url,
383
+ cancel_url=cancel_url,
384
+ table_html=table_html,
385
+ )
386
+ return HTMLResponse(f"{pre}{body}{POSTAMBLE}")
387
+
388
+
389
+ @router.post("/project/{name:path}/submit", response_class=HTMLResponse)
390
+ async def settings_project_submit(request: Request, name: ValidatedSettingsProject):
391
+ """Apply project config from form."""
392
+ form = await request.form()
393
+ # Collect key/value pairs; keys are config_key_0, config_value_0, ...
394
+ indices = set()
395
+ for form_key in form:
396
+ if form_key.startswith("config_key_"):
397
+ with suppress(ValueError):
398
+ indices.add(int(form_key.split("_")[-1]))
399
+ pairs = []
400
+ for i in sorted(indices):
401
+ k = str(form.get(f"config_key_{i}") or "").strip() or ""
402
+ v = str(form.get(f"config_value_{i}") or "").strip() or ""
403
+ if k:
404
+ pairs.append((k, v))
405
+ repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, name))
406
+ cfg = repo.config
407
+ for config_key, config_value in pairs:
408
+ try:
409
+ cfg[config_key] = config_value
410
+ except (pygit2.GitError, ValueError, KeyError):
411
+ continue
412
+ return RedirectResponse(url=f"/settings/project/{_quote_path(name)}", status_code=303)