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
pygitweb/tasks.py ADDED
@@ -0,0 +1,595 @@
1
+ """
2
+ Task-related routes: Task, comment, board creation, listing, and management.
3
+ Data is stored in the repo ODB/RefDB via pygittools.tasks (Board, Task, Comment).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import re
10
+ import time
11
+ from typing import Annotated, Any
12
+
13
+ import pygit2
14
+ from fastapi import APIRouter, Depends, HTTPException, Query, Request
15
+ from fastapi.responses import JSONResponse
16
+
17
+ from pygittools.tasks import (
18
+ BOARD_REF_PREFIX,
19
+ TASK_REF_PREFIX,
20
+ Board,
21
+ Comment,
22
+ Task,
23
+ get_board,
24
+ get_comment,
25
+ get_task,
26
+ get_task_by_oid,
27
+ )
28
+ from pygitweb.auth import (
29
+ access_token_from_request,
30
+ principal_from_session,
31
+ require_active_user_if_auth_enabled,
32
+ require_permission,
33
+ )
34
+ from pygitweb.config import settings
35
+ from pygitweb.dependencies import ValidatedQueryProject
36
+ from pygitweb.gravatar import gravatar_url
37
+ from pygitweb.permissions import Permission, PermissionPrincipal
38
+
39
+ # Well-known empty tree OID for boards/tasks when repo has no HEAD
40
+ EMPTY_TREE_OID = pygit2.Oid(hex="4b825dc642cb6eb9a060e54bf8d69288fbee4904")
41
+
42
+
43
+ def _board_ref(name: str) -> str:
44
+ return f"{BOARD_REF_PREFIX}{name}"
45
+
46
+
47
+ def _task_ref(task_id: str) -> str:
48
+ return f"{TASK_REF_PREFIX}{task_id}"
49
+
50
+
51
+ def _repo_head_or_empty(repo: pygit2.Repository) -> pygit2.Oid | str:
52
+ try:
53
+ return repo.head.target
54
+ except KeyError:
55
+ return EMPTY_TREE_OID
56
+
57
+
58
+ def _sync_board_task_oid(
59
+ repo: pygit2.Repository,
60
+ board: str,
61
+ old_oid: str,
62
+ new_oid: pygit2.Oid | str,
63
+ *,
64
+ move_to_end: bool = False,
65
+ ) -> None:
66
+ """Replace a task OID on the board after the task tag object was rewritten."""
67
+ b = get_board(repo, _board_ref(board))
68
+ if not b or not getattr(b, "tasks", None):
69
+ return
70
+ new_oid_str = str(new_oid)
71
+ tasks_list = [new_oid_str if o == old_oid else o for o in b.tasks]
72
+ if move_to_end and new_oid_str in tasks_list:
73
+ tasks_list = [o for o in tasks_list if o != new_oid_str] + [new_oid_str]
74
+ b.tasks = tasks_list
75
+ b.update_message()
76
+ b.write(repo)
77
+
78
+
79
+ def _task_from_board_entry(
80
+ repo: pygit2.Repository,
81
+ oid_hex: str | pygit2.Oid,
82
+ *,
83
+ board: str | None = None,
84
+ ) -> Task | None:
85
+ """
86
+ Load a task listed on a board by OID.
87
+
88
+ Board entries can lag behind ``refs/tags/tasks/…`` after a task rewrite (e.g. a new
89
+ comment). When the ref points at a newer tag object, return that version and repair
90
+ the board list when ``board`` is provided.
91
+ """
92
+ oid = pygit2.Oid(hex=oid_hex) if isinstance(oid_hex, str) else oid_hex
93
+ t = get_task_by_oid(repo, oid)
94
+ if not t or not t.name:
95
+ return t
96
+ try:
97
+ if t.name not in repo.references:
98
+ return t
99
+ current_oid = repo.references[t.name].resolve().target
100
+ except KeyError:
101
+ return t
102
+ if str(current_oid) == str(oid):
103
+ return t
104
+ t_current = get_task(repo, t.name)
105
+ if t_current and board:
106
+ _sync_board_task_oid(repo, board, str(oid), current_oid)
107
+ return t_current or t
108
+
109
+
110
+ def create_board_for_project(
111
+ project: str,
112
+ name: str = "Tasks",
113
+ description: str = "",
114
+ ) -> str:
115
+ """Create a board in the project repo. Returns the board ref. Raises HTTPException on error."""
116
+ repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
117
+ ref = _board_ref(name)
118
+ if ref in repo.references:
119
+ raise HTTPException(status_code=409, detail="Board already exists")
120
+ target = _repo_head_or_empty(repo)
121
+ board = Board(target, ref, tagger="", description=description)
122
+ board.write(repo)
123
+ return ref
124
+
125
+
126
+ # ---------- Board Routes ----------
127
+
128
+ board_router = APIRouter(tags=["boards"])
129
+
130
+
131
+ @board_router.get(
132
+ "/list",
133
+ response_class=JSONResponse,
134
+ dependencies=[Depends(require_active_user_if_auth_enabled)],
135
+ )
136
+ def boards_list(project: ValidatedQueryProject) -> JSONResponse:
137
+ """List all boards for the project."""
138
+ repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
139
+ refs = [
140
+ (ref_name, str(repo.references[ref_name].resolve().target))
141
+ for ref_name in repo.references
142
+ if ref_name.startswith(BOARD_REF_PREFIX)
143
+ ]
144
+ boards = []
145
+ for ref_name, _ in refs:
146
+ try:
147
+ b = get_board(repo, ref_name)
148
+ if b:
149
+ boards.append({
150
+ "name": ref_name.replace(BOARD_REF_PREFIX, ""),
151
+ "description": getattr(b, "description", "") or "",
152
+ "task_count": len(getattr(b, "tasks", [])),
153
+ })
154
+ except (ValueError, KeyError):
155
+ continue
156
+ return JSONResponse(content=boards)
157
+
158
+
159
+ @board_router.post(
160
+ "/create",
161
+ response_class=JSONResponse,
162
+ dependencies=[Depends(require_permission(Permission.BOARDS, project_from_query=True))],
163
+ )
164
+ def boards_create(
165
+ project: ValidatedQueryProject,
166
+ name: str = Query(..., description="Board name"),
167
+ description: str = Query("", description="Board description"),
168
+ ) -> JSONResponse:
169
+ """Create a new board."""
170
+ if not name or "/" in name or ".." in name:
171
+ raise HTTPException(status_code=400, detail="Invalid board name")
172
+ repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
173
+ ref = _board_ref(name)
174
+ if ref in repo.references:
175
+ raise HTTPException(status_code=409, detail="Board already exists")
176
+ target = _repo_head_or_empty(repo)
177
+ board = Board(target, ref, tagger="", description=description or "")
178
+ oid = board.write(repo)
179
+ return JSONResponse(content={"name": name, "ref": ref, "oid": str(oid)})
180
+
181
+
182
+ @board_router.post(
183
+ "/delete",
184
+ response_class=JSONResponse,
185
+ dependencies=[Depends(require_permission(Permission.BOARDS, project_from_query=True))],
186
+ )
187
+ def boards_delete(
188
+ project: ValidatedQueryProject,
189
+ name: str = Query(..., description="Board name"),
190
+ ) -> JSONResponse:
191
+ """Delete a board (removes ref; tag object remains in ODB)."""
192
+ repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
193
+ ref = _board_ref(name)
194
+ if ref not in repo.references:
195
+ raise HTTPException(status_code=404, detail="Board not found")
196
+ repo.references.delete(ref)
197
+ return JSONResponse(content={"message": "Board deleted"})
198
+
199
+
200
+ # ---------- Task Routes ----------
201
+
202
+ task_router = APIRouter(tags=["tasks"])
203
+
204
+
205
+ def _task_to_json(t: Task) -> dict[str, Any]:
206
+ return {
207
+ "ref": t.name,
208
+ "title": t.title,
209
+ "description": getattr(t, "description", "") or "",
210
+ "status": t.status.value if t.status else None,
211
+ "priority": t.priority.value if t.priority else None,
212
+ "assignee": t.assignee,
213
+ "due_date": t.due_date.isoformat() if t.due_date else None,
214
+ "created_at": t.created_at.isoformat() if t.created_at else None,
215
+ "updated_at": t.updated_at.isoformat() if t.updated_at else None,
216
+ "comments_count": len(getattr(t, "comments", [])),
217
+ }
218
+
219
+
220
+ # Status order for board columns
221
+ BOARD_STATUS_ORDER = ["TODO", "IN_PROGRESS", "IN_REVIEW", "DONE", "CANCELLED"]
222
+
223
+
224
+ def get_board_tasks_grouped(
225
+ project: str,
226
+ board_name: str,
227
+ ) -> list[dict[str, Any]]:
228
+ """
229
+ Return tasks for a board grouped by status for board view.
230
+ Returns a list of { "status": str, "label": str, "tasks": [ _task_to_json, ... ] }
231
+ in BOARD_STATUS_ORDER. Skips validation/auth (caller must validate project).
232
+ """
233
+ repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
234
+ ref = _board_ref(board_name)
235
+ b = get_board(repo, ref)
236
+ task_oids = getattr(b, "tasks", []) or []
237
+ by_status: dict[str, list[dict[str, Any]]] = {s: [] for s in BOARD_STATUS_ORDER}
238
+ for oid_hex in task_oids:
239
+ try:
240
+ t = _task_from_board_entry(repo, oid_hex, board=board_name)
241
+ if t:
242
+ d = _task_to_json(t)
243
+ status_key = (d.get("status") or "TODO") if d else "TODO"
244
+ if status_key not in by_status:
245
+ by_status[status_key] = []
246
+ by_status[status_key].append(d)
247
+ except (ValueError, KeyError, TypeError):
248
+ continue
249
+ return [
250
+ {
251
+ "status": s,
252
+ "label": s.replace("_", " ").title(),
253
+ "tasks": by_status.get(s, []),
254
+ }
255
+ for s in BOARD_STATUS_ORDER
256
+ ]
257
+
258
+
259
+ @task_router.get(
260
+ "/list",
261
+ response_class=JSONResponse,
262
+ dependencies=[Depends(require_active_user_if_auth_enabled)],
263
+ )
264
+ def task_list(
265
+ project: ValidatedQueryProject,
266
+ board: str = Query(..., description="Board name"),
267
+ ) -> JSONResponse:
268
+ """List all tasks on a board."""
269
+ repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
270
+ ref = _board_ref(board)
271
+ b = get_board(repo, ref)
272
+ if not b:
273
+ raise HTTPException(status_code=404, detail="Board not found")
274
+ task_oids = getattr(b, "tasks", [])
275
+ tasks = []
276
+ for oid_hex in task_oids:
277
+ try:
278
+ t = _task_from_board_entry(repo, oid_hex, board=board)
279
+ if t:
280
+ tasks.append(_task_to_json(t))
281
+ except (ValueError, KeyError, TypeError):
282
+ continue
283
+ return JSONResponse(content=tasks)
284
+
285
+
286
+ @task_router.post(
287
+ "/create",
288
+ response_class=JSONResponse,
289
+ dependencies=[Depends(require_permission(Permission.TASKS, project_from_query=True))],
290
+ )
291
+ def task_create(
292
+ project: ValidatedQueryProject,
293
+ board: str = Query(..., description="Board name"),
294
+ title: str = Query(..., description="Task title"),
295
+ description: str = Query("", description="Task description"),
296
+ status: str = Query("TODO", description="Task status"),
297
+ priority: str = Query("LOW", description="Task priority"),
298
+ assignee: str = Query("", description="Assignee"),
299
+ due_date: str = Query("", description="Due date ISO"),
300
+ ) -> JSONResponse:
301
+ """Create a new task on a board."""
302
+ repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
303
+ board_ref = _board_ref(board)
304
+ b = get_board(repo, board_ref)
305
+ if not b:
306
+ raise HTTPException(status_code=404, detail="Board not found")
307
+ task_id = f"task_{int(time.time() * 1000)}"
308
+ ref = _task_ref(task_id)
309
+ target = _repo_head_or_empty(repo)
310
+ status_enum = getattr(Task.Status, status, None) or Task.Status.TODO
311
+ priority_enum = getattr(Task.Priority, priority, None) or Task.Priority.LOW
312
+ due = None
313
+ if due_date:
314
+ try:
315
+ from datetime import datetime
316
+
317
+ due = datetime.fromisoformat(due_date.replace("Z", "+00:00"))
318
+ except ValueError:
319
+ pass
320
+ task = Task(
321
+ target,
322
+ ref,
323
+ tagger="",
324
+ title=title,
325
+ description=description or "",
326
+ status=status_enum,
327
+ priority=priority_enum,
328
+ assignee=assignee or None,
329
+ due_date=due,
330
+ )
331
+ oid = task.write(repo)
332
+ b.tasks = getattr(b, "tasks", []) or []
333
+ b.tasks.append(str(oid))
334
+ b.update_message()
335
+ b.write(repo)
336
+ return JSONResponse(content={"task_id": task_id, "ref": ref, "oid": str(oid)})
337
+
338
+
339
+ @task_router.post(
340
+ "/update",
341
+ response_class=JSONResponse,
342
+ dependencies=[Depends(require_permission(Permission.TASKS, project_from_query=True))],
343
+ )
344
+ async def task_update(
345
+ request: Request,
346
+ project: ValidatedQueryProject,
347
+ board: str = Query(..., description="Board name"),
348
+ task_ref: str = Query(..., alias="task", description="Task ref (e.g. refs/tags/tasks/task_123)"),
349
+ ) -> JSONResponse:
350
+ """Update a task (body: optional title, description, status, priority, assignee, due_date)."""
351
+ try:
352
+ body = await request.json() if request.headers.get("content-type", "").startswith("application/json") else {}
353
+ except Exception:
354
+ body = {}
355
+ repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
356
+ ref = task_ref if task_ref.startswith("refs/") else _task_ref(task_ref)
357
+ t = get_task(repo, ref)
358
+ if not t:
359
+ raise HTTPException(status_code=404, detail="Task not found")
360
+ status_changed = bool("status" in body and hasattr(Task.Status, body["status"]))
361
+ if "title" in body:
362
+ t.title = body["title"]
363
+ if "description" in body:
364
+ t.description = body.get("description", "")
365
+ if status_changed:
366
+ t.status = Task.Status(body["status"])
367
+ if "priority" in body and hasattr(Task.Priority, body["priority"]):
368
+ t.priority = Task.Priority(body["priority"])
369
+ if "assignee" in body:
370
+ t.assignee = body["assignee"] or None
371
+ if "due_date" in body:
372
+ try:
373
+ from datetime import datetime
374
+
375
+ t.due_date = (
376
+ datetime.fromisoformat(str(body["due_date"]).replace("Z", "+00:00")) if body["due_date"] else None
377
+ )
378
+ except ValueError:
379
+ pass
380
+ old_oid = str(repo.references[ref].resolve().target)
381
+ t.update_message()
382
+ new_oid = t.write(repo)
383
+ _sync_board_task_oid(repo, board, old_oid, new_oid, move_to_end=status_changed)
384
+ return JSONResponse(content=_task_to_json(t))
385
+
386
+
387
+ @task_router.post(
388
+ "/delete",
389
+ response_class=JSONResponse,
390
+ dependencies=[Depends(require_permission(Permission.TASKS, project_from_query=True))],
391
+ )
392
+ def task_delete(
393
+ project: ValidatedQueryProject,
394
+ board: str = Query(..., description="Board name"),
395
+ task_ref: str = Query(..., alias="task", description="Task ref"),
396
+ ) -> JSONResponse:
397
+ """Delete a task (remove ref and remove from board.tasks)."""
398
+ repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
399
+ ref = task_ref if task_ref.startswith("refs/") else _task_ref(task_ref)
400
+ if ref not in repo.references:
401
+ raise HTTPException(status_code=404, detail="Task not found")
402
+ oid_hex = str(repo.references[ref].resolve().target)
403
+ repo.references.delete(ref)
404
+ board_ref = _board_ref(board)
405
+ b = get_board(repo, board_ref)
406
+ if b and getattr(b, "tasks", None):
407
+ try:
408
+ b.tasks = [x for x in b.tasks if x != oid_hex]
409
+ b.update_message()
410
+ b.write(repo)
411
+ except Exception:
412
+ pass
413
+ return JSONResponse(content={"message": "Task deleted"})
414
+
415
+
416
+ # ---------- Comment Routes ----------
417
+
418
+ comment_router = APIRouter(tags=["comments"])
419
+
420
+
421
+ def _parse_tagger_display(tagger: str) -> tuple[str, str | None]:
422
+ s = (tagger or "").strip()
423
+ if not s:
424
+ return ("Unknown", None)
425
+ m = re.match(r"^(.+?)\s*<([^>]+)>", s)
426
+ if m:
427
+ name = m.group(1).strip() or "Unknown"
428
+ return (name, m.group(2).strip())
429
+ return (s, None)
430
+
431
+
432
+ def _tagger_from_principal(principal: PermissionPrincipal | None) -> str:
433
+ if principal is None:
434
+ return ""
435
+ email = (principal.email or "").strip() or f"{principal.username}@local"
436
+ name = principal.username.strip() or email
437
+ return f"{name} <{email}>"
438
+
439
+
440
+ def _comment_to_json(c: Comment) -> dict[str, Any]:
441
+ author, email = _parse_tagger_display(c.tagger)
442
+ return {
443
+ "content": c.content,
444
+ "tagger": c.tagger,
445
+ "author": author,
446
+ "gravatar_url": gravatar_url(email) if email else None,
447
+ "created_at": c.created_at.isoformat() if c.created_at else None,
448
+ "edited_at": c.edited_at.isoformat() if c.edited_at else None,
449
+ }
450
+
451
+
452
+ def _comment_sort_key(entry: dict[str, Any]) -> str:
453
+ return entry.get("edited_at") or entry.get("created_at") or ""
454
+
455
+
456
+ @comment_router.get(
457
+ "/list",
458
+ response_class=JSONResponse,
459
+ dependencies=[Depends(require_active_user_if_auth_enabled)],
460
+ )
461
+ def comment_list(
462
+ project: ValidatedQueryProject,
463
+ board: str = Query(..., description="Board name"),
464
+ task: str = Query(..., description="Task ref (e.g. refs/tags/tasks/task_123)"),
465
+ ) -> JSONResponse:
466
+ """List all comments for a task."""
467
+ repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
468
+ task_ref = task if task.startswith("refs/") else _task_ref(task)
469
+ t = get_task(repo, task_ref)
470
+ if not t:
471
+ raise HTTPException(status_code=404, detail="Task not found")
472
+ comment_oids = getattr(t, "comments", []) or []
473
+ comments = []
474
+ for oid_hex in comment_oids:
475
+ try:
476
+ oid = pygit2.Oid(hex=oid_hex) if isinstance(oid_hex, str) else oid_hex
477
+ c = get_comment(repo, oid)
478
+ if c:
479
+ comments.append(_comment_to_json(c))
480
+ except (ValueError, KeyError, TypeError):
481
+ continue
482
+ comments.sort(key=_comment_sort_key)
483
+ return JSONResponse(content=comments)
484
+
485
+
486
+ @comment_router.post(
487
+ "/create",
488
+ response_class=JSONResponse,
489
+ dependencies=[Depends(require_permission(Permission.COMMENTS, project_from_query=True))],
490
+ )
491
+ def comment_create(
492
+ project: ValidatedQueryProject,
493
+ board: str = Query(..., description="Board name"),
494
+ task: str = Query(..., description="Task ref"),
495
+ content: str = Query(..., description="Comment content"),
496
+ token: Annotated[str | None, Depends(access_token_from_request)] = None,
497
+ ) -> JSONResponse:
498
+ """Create a new comment on a task."""
499
+ repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
500
+ task_ref = task if task.startswith("refs/") else _task_ref(task)
501
+ t = get_task(repo, task_ref)
502
+ if not t:
503
+ raise HTTPException(status_code=404, detail="Task not found")
504
+ try:
505
+ target_oid = repo.references[task_ref].resolve().target
506
+ except KeyError as exc:
507
+ raise HTTPException(status_code=404, detail="Task not found") from exc
508
+ tagger = _tagger_from_principal(principal_from_session(token))
509
+ comment = Comment(target=target_oid, tagger=tagger, content=content or "")
510
+ comment_oid = comment.write(repo)
511
+ t.comments = getattr(t, "comments", []) or []
512
+ t.comments.append(str(comment_oid))
513
+ old_task_oid = str(target_oid)
514
+ t.update_message()
515
+ new_task_oid = t.write(repo)
516
+ _sync_board_task_oid(repo, board, old_task_oid, new_task_oid)
517
+ return JSONResponse(
518
+ content={
519
+ "oid": str(comment_oid),
520
+ "message": "Comment created",
521
+ "comments_count": len(t.comments),
522
+ }
523
+ )
524
+
525
+
526
+ @comment_router.post(
527
+ "/update",
528
+ response_class=JSONResponse,
529
+ dependencies=[Depends(require_active_user_if_auth_enabled)],
530
+ )
531
+ async def comment_update(
532
+ request: Request,
533
+ project: ValidatedQueryProject,
534
+ board: str = Query(..., description="Board name"),
535
+ task: str = Query(..., description="Task ref (to update task.comments)"),
536
+ comment_oid: str = Query(..., alias="comment", description="Comment OID hex"),
537
+ ) -> JSONResponse:
538
+ """Update a comment (body: content). Writes new comment object and updates task.comments."""
539
+ try:
540
+ body = await request.json() if request.headers.get("content-type", "").startswith("application/json") else {}
541
+ except Exception:
542
+ body = {}
543
+ repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
544
+ oid = pygit2.Oid(hex=comment_oid)
545
+ c = get_comment(repo, oid)
546
+ if not c:
547
+ raise HTTPException(status_code=404, detail="Comment not found")
548
+ if "content" in body:
549
+ c.content = body["content"]
550
+ from datetime import datetime
551
+
552
+ c.edited_at = datetime.now()
553
+ c.update_message()
554
+ new_oid = c.write(repo)
555
+ task_ref = task if task.startswith("refs/") else _task_ref(task)
556
+ t = get_task(repo, task_ref)
557
+ if t and getattr(t, "comments", None):
558
+ t.comments = [str(new_oid) if str(co) == comment_oid else co for co in t.comments]
559
+ try:
560
+ old_task_oid = str(repo.references[task_ref].resolve().target)
561
+ except KeyError:
562
+ old_task_oid = ""
563
+ t.update_message()
564
+ new_task_oid = t.write(repo)
565
+ if old_task_oid:
566
+ _sync_board_task_oid(repo, board, old_task_oid, new_task_oid)
567
+ return JSONResponse(
568
+ content={
569
+ **_comment_to_json(c),
570
+ "oid": str(new_oid),
571
+ "message": "Comment updated",
572
+ }
573
+ )
574
+
575
+
576
+ @comment_router.post(
577
+ "/delete",
578
+ response_class=JSONResponse,
579
+ dependencies=[Depends(require_active_user_if_auth_enabled)],
580
+ )
581
+ def comment_delete(
582
+ project: ValidatedQueryProject,
583
+ board: str = Query(..., description="Board name"),
584
+ comment_oid: str = Query(..., alias="comment", description="Comment OID hex"),
585
+ ) -> JSONResponse:
586
+ """Delete a comment (object remains in ODB; caller may remove from task.comments)."""
587
+ repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
588
+ oid = pygit2.Oid(hex=comment_oid)
589
+ try:
590
+ c = get_comment(repo, oid)
591
+ except (ValueError, KeyError) as e:
592
+ raise HTTPException(status_code=404, detail="Comment not found") from e
593
+ if not c:
594
+ raise HTTPException(status_code=404, detail="Comment not found")
595
+ return JSONResponse(content={"message": "Comment deleted"})