Project: pygitweb

9af949c """
Task-related routes: Task, comment, board creation, listing, and management.
5e51915 Data is stored in the repo ODB/RefDB via pygittools.tasks (Board, Task, Comment).
9af949c """
9af949c from __future__ import annotations
ddcd285 import contextlib
c0ed382 import os
3258e39 import re
from typing import Annotated, Any
52026a0 from urllib.parse import quote
9af949c
import pygit2
ddcd285 from fastapi import APIRouter, Depends, HTTPException, Query
52026a0 from fastapi.responses import HTMLResponse, JSONResponse
ddcd285 from pydantic import Field
c3ea5b9 from pygit2 import Oid
5e51915 from pygittools.tasks import (
73c9c30 ARCHIVE_BOARD_NAME,
BOARD_REF_PREFIX,
TASK_REF_PREFIX,
Board,
Comment,
Task,
_parse_dt,
archive_task_local,
create_task,
delete_task_local,
get_board,
get_board_ref,
get_comment,
get_repo_head_or_empty,
get_task,
get_task_by_oid,
get_task_ref,
parse_points,
997da40 )
1168630
3258e39 from pygitweb.auth import (
73c9c30 access_token_from_request,
ensure_active_user_if_auth_enabled,
has_permission,
principal_from_session,
3258e39 )
26f0919 from pygitweb.config import settings
c3ea5b9 from pygitweb.dependencies import (
ddcd285 ProjectBody,
73c9c30 ValidatedReadableQueryProject,
filter_projects_by_read_access,
ddcd285 project_body,
c3ea5b9 )
3258e39 from pygitweb.gravatar import gravatar_url
from pygitweb.permissions import Permission, PermissionPrincipal
52026a0 from pygitweb.projects import git_get_projects_list
c3ea5b9 from pygitweb.templates_env import (
73c9c30 Cell,
html_link,
person_label,
priority_badge,
render_page,
status_badge,
c3ea5b9 )
9af949c
c3ea5b9 EMPTY_TREE_OID = Oid(hex="4b825dc642cb6eb9a060e54bf8d69288fbee4904")
9af949c
d3658bc def _find_board(repo: pygit2.Repository, ref: str) -> Board | None:
"""Like get_board, but returns None for a missing ref instead of raising KeyError."""
try:
return get_board(repo, ref)
except KeyError:
return None
def _find_task(repo: pygit2.Repository, ref: str) -> Task | None:
"""Like get_task, but returns None for a missing ref instead of raising KeyError."""
try:
return get_task(repo, ref)
except KeyError:
return None
ddcd285 def _full_task_ref(task: str) -> str:
"""Accept either a full task ref or a bare task id."""
return task if task.startswith("refs/") else get_task_ref(task)
# ---------- Request bodies ----------
class BoardBody(ProjectBody):
name: str = Field(description="Board name")
class BoardCreateBody(BoardBody):
description: str = ""
class TaskCreateBody(ProjectBody):
board: str = Field(description="Board name")
title: str
description: str = ""
status: str = Field("TODO", description="Unknown values fall back to TODO")
priority: str = Field("LOW", description="Unknown values fall back to LOW")
assignee: str = ""
due_date: str = Field("", description="ISO 8601 date; malformed values are ignored")
tags: str = Field("", description="KEY=VALUE list")
points: int | str | None = Field(None, description="Story points (0,1,2,3,5,8,13,21); anything else is unestimated")
class TaskRefBody(ProjectBody):
board: str = Field(description="Board name")
task: str = Field(description="Task ref (refs/tags/tasks/task_123) or bare id (task_123)")
class TaskUpdateBody(TaskRefBody):
"""Only the fields present in the body are changed."""
title: str | None = None
description: str | None = None
status: str | None = Field(None, description="Unknown values are ignored")
priority: str | None = Field(None, description="Unknown values are ignored")
assignee: str | None = None
due_date: str | None = Field(None, description="ISO 8601 date; empty or null clears it")
tags: str | None = None
points: int | str | None = None
class TaskArchiveBody(TaskRefBody):
archive_board: str = ARCHIVE_BOARD_NAME
class TaskMoveBody(TaskRefBody):
target: str = Field(description="Target board name (e.g. a sprint board)")
class CommentCreateBody(TaskRefBody):
content: str
class CommentModifyBody(TaskRefBody):
comment: str = Field(description="Comment OID hex")
content: str | None = None
class CommentDeleteBody(ProjectBody):
board: str = Field(description="Board name")
comment: str = Field(description="Comment OID hex")
3258e39 def _sync_board_task_oid(
73c9c30 repo: pygit2.Repository,
board: str,
old_oid: str,
new_oid: pygit2.Oid | str,
*,
move_to_end: bool = False,
3258e39 ) -> None:
73c9c30 """Replace a task OID on the board after the task tag object was rewritten."""
b = get_board(repo, get_board_ref(board))
if not b or not getattr(b, "tasks", None):
return
new_oid_str = str(new_oid)
tasks_list = [new_oid_str if o == old_oid else o for o in b.tasks]
if move_to_end and new_oid_str in tasks_list:
tasks_list = [o for o in tasks_list if o != new_oid_str] + [new_oid_str]
b.tasks = tasks_list
b.update_message()
b.write(repo)
3258e39
def _task_from_board_entry(
73c9c30 repo: pygit2.Repository,
oid_hex: str | pygit2.Oid,
*,
board: str | None = None,
3258e39 ) -> Task | None:
73c9c30 """
Load a task listed on a board by OID.
Board entries can lag behind ``refs/tags/tasks/…`` after a task rewrite (e.g. a new
comment). When the ref points at a newer tag object, return that version and repair
the board list when ``board`` is provided.
"""
oid = pygit2.Oid(hex=oid_hex) if isinstance(oid_hex, str) else oid_hex
t = get_task_by_oid(repo, oid)
if not t or not t.name:
return t
try:
if t.name not in repo.references:
return t
current_oid = repo.references[t.name].resolve().target
except KeyError:
return t
if str(current_oid) == str(oid):
return t
t_current = get_task(repo, t.name)
if t_current and board:
_sync_board_task_oid(repo, board, str(oid), current_oid)
return t_current or t
3258e39
9af949c def create_board_for_project(
73c9c30 project: str,
name: str = "Tasks",
description: str = "",
9af949c ) -> str:
73c9c30 """Create a board in the project repo. Returns the board ref. Raises HTTPException on error."""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
ref = get_board_ref(name)
if ref in repo.references:
raise HTTPException(status_code=409, detail="Board already exists")
target = get_repo_head_or_empty(repo)
board = Board(target, ref, tagger="", description=description)
board.write(repo)
return ref
9af949c
# ---------- Board Routes ----------
e6c6972 board_router = APIRouter(tags=["boards"])
9af949c
52026a0 def list_project_boards(project: str) -> list[dict[str, Any]]:
73c9c30 """Return [{name, description, task_count}, ...] for every board in a project."""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
refs = [
(ref_name, str(repo.references[ref_name].resolve().target))
for ref_name in repo.references
if ref_name.startswith(BOARD_REF_PREFIX)
]
boards = []
for ref_name, _ in refs:
try:
b = get_board(repo, ref_name)
if b:
boards.append({
"name": ref_name.replace(BOARD_REF_PREFIX, ""),
"description": getattr(b, "description", "") or "",
"task_count": len(getattr(b, "tasks", [])),
})
except (ValueError, KeyError):
continue
return boards
52026a0
@board_router.get(
73c9c30 "/list",
response_class=JSONResponse,
52026a0 )
def boards_list(project: ValidatedReadableQueryProject) -> JSONResponse:
73c9c30 """List all boards for the project."""
return JSONResponse(content=list_project_boards(project))
9af949c
ddcd285 @board_router.post("/create", response_class=JSONResponse)
9af949c def boards_create(
ddcd285 body: Annotated[BoardCreateBody, Depends(project_body(BoardCreateBody, Permission.BOARDS))],
9af949c ) -> JSONResponse:
73c9c30 """Create a new board."""
ddcd285 name = body.name
73c9c30 if not name or not pygit2.reference_is_valid_name(get_board_ref(name)):
raise HTTPException(status_code=400, detail="Invalid board name")
ddcd285 repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, body.project))
73c9c30 ref = get_board_ref(name)
if ref in repo.references:
raise HTTPException(status_code=409, detail="Board already exists")
target = get_repo_head_or_empty(repo)
ddcd285 board = Board(target, ref, tagger="", description=body.description or "")
73c9c30 oid = board.write(repo)
return JSONResponse(content={"name": name, "ref": ref, "oid": str(oid)})
9af949c
ddcd285 @board_router.post("/delete", response_class=JSONResponse)
9af949c def boards_delete(
ddcd285 body: Annotated[BoardBody, Depends(project_body(BoardBody, Permission.BOARDS))],
9af949c ) -> JSONResponse:
73c9c30 """Delete a board (removes ref; tag object remains in ODB)."""
ddcd285 repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, body.project))
ref = get_board_ref(body.name)
73c9c30 if ref not in repo.references:
raise HTTPException(status_code=404, detail="Board not found")
repo.references.delete(ref)
return JSONResponse(content={"message": "Board deleted"})
9af949c
# ---------- Task Routes ----------
e6c6972 task_router = APIRouter(tags=["tasks"])
9af949c
bc06b34 def _task_display_id(ref: str) -> str:
73c9c30 """Numeric task id for UI (task_1730000000000 -> 1730000000000)."""
slug = ref.removeprefix(TASK_REF_PREFIX)
if slug.startswith("task_"):
return slug.removeprefix("task_")
return slug
bc06b34
9af949c def _task_to_json(t: Task) -> dict[str, Any]:
73c9c30 return {
"ref": t.name,
"id": _task_display_id(t.name),
"title": t.title,
"description": getattr(t, "description", "") or "",
"status": t.status.value if t.status else None,
"priority": t.priority.value if t.priority else None,
"assignee": t.assignee,
"due_date": t.due_date.isoformat() if t.due_date else None,
"tags": getattr(t, "tags", "") or "",
"points": getattr(t, "points", None),
"created_at": t.created_at.isoformat() if t.created_at else None,
"updated_at": t.updated_at.isoformat() if t.updated_at else None,
"comments_count": len(getattr(t, "comments", [])),
}
9af949c
# Status order for board columns
BOARD_STATUS_ORDER = ["TODO", "IN_PROGRESS", "IN_REVIEW", "DONE", "CANCELLED"]
def get_board_tasks_grouped(
73c9c30 project: str,
board_name: str,
9af949c ) -> list[dict[str, Any]]:
73c9c30 """
Return tasks for a board grouped by status for board view.
Returns a list of { "status": str, "label": str, "tasks": [ _task_to_json, ... ] }
in BOARD_STATUS_ORDER. Skips validation/auth (caller must validate project).
"""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
ref = get_board_ref(board_name)
b = get_board(repo, ref)
task_oids = getattr(b, "tasks", []) or []
by_status: dict[str, list[dict[str, Any]]] = {s: [] for s in BOARD_STATUS_ORDER}
for oid_hex in task_oids:
try:
t = _task_from_board_entry(repo, oid_hex, board=board_name)
if t:
d = _task_to_json(t)
status_key = (d.get("status") or "TODO") if d else "TODO"
if status_key not in by_status:
by_status[status_key] = []
by_status[status_key].append(d)
except (ValueError, KeyError, TypeError):
continue
return [
{
"status": s,
"label": s.replace("_", " ").title(),
"tasks": by_status.get(s, []),
"points_total": sum(t.get("points") or 0 for t in by_status.get(s, [])),
}
for s in BOARD_STATUS_ORDER
]
9af949c
52026a0 def get_all_project_tasks(project: str) -> list[dict[str, Any]]:
73c9c30 """
Return every task across all boards in a project, each tagged with its board name.
Used by the team overview page, which needs to see who has what regardless of
which board a task currently sits on. Skips validation/auth (caller must validate project).
"""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
out: list[dict[str, Any]] = []
for ref_name in repo.references:
if not ref_name.startswith(BOARD_REF_PREFIX):
continue
board_name = ref_name.removeprefix(BOARD_REF_PREFIX)
b = get_board(repo, ref_name)
for oid_hex in getattr(b, "tasks", []) or []:
try:
t = _task_from_board_entry(repo, oid_hex, board=board_name)
if t:
d = _task_to_json(t)
d["board"] = board_name
out.append(d)
except (ValueError, KeyError, TypeError):
continue
return out
52026a0
@task_router.get("", response_class=HTMLResponse)
def all_tasks_page(
73c9c30 token: Annotated[str | None, Depends(access_token_from_request)],
status: Annotated[str | None, Query()] = None,
52026a0 ) -> HTMLResponse:
73c9c30 """Flat list of every task across every project and board you can read."""
status_filter = (status or "").strip().upper() or None
projects = filter_projects_by_read_access(
git_get_projects_list(paranoid=settings.STRICT_EXPORT, export_ok=settings.EXPORT_OK),
token,
)
rows: list[list[Cell]] = []
for pr in projects:
project = pr.get("path", "")
if not project:
continue
try:
tasks = get_all_project_tasks(project)
except Exception:
continue
for t in tasks:
task_status = t.get("status") or "TODO"
if status_filter and task_status != status_filter:
continue
project_url = f"/project/{quote(project, safe='/')}"
board_url = f"{project_url}/board/?b={quote(t['board'], safe='')}"
task_url = f"{board_url}&task={quote(t['ref'], safe='')}"
rows.append([
html_link(task_url, t.get("title") or "(untitled)"),
html_link(project_url, project),
t.get("board") or "",
status_badge(task_status),
priority_badge(t.get("priority") or "LOW"),
person_label(t.get("assignee") or ""),
str(t.get("points") if t.get("points") is not None else ""),
])
statuses = [
{"value": status, "label": status.replace("_", " ").title(), "selected": status_filter == status}
for status in BOARD_STATUS_ORDER
]
return render_page(
"tasks.html",
title=f"{settings.SITE_NAME} - Tasks",
status_filter=status_filter or "",
statuses=statuses,
cols=["Task", "Project", "Board", "Status", "Priority", "Assignee", "Points"],
rows=rows,
nav="tasks",
)
52026a0
e6c6972 @task_router.get(
73c9c30 "/list",
response_class=JSONResponse,
e6c6972 )
9af949c def task_list(
73c9c30 project: ValidatedReadableQueryProject,
board: str = Query(..., description="Board name"),
9af949c ) -> JSONResponse:
73c9c30 """List all tasks on a board."""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
ref = get_board_ref(board)
d3658bc b = _find_board(repo, ref)
73c9c30 if not b:
raise HTTPException(status_code=404, detail="Board not found")
task_oids = getattr(b, "tasks", [])
tasks = []
for oid_hex in task_oids:
try:
t = _task_from_board_entry(repo, oid_hex, board=board)
if t:
tasks.append(_task_to_json(t))
except (ValueError, KeyError, TypeError):
continue
return JSONResponse(content=tasks)
9af949c
ddcd285 @task_router.post("/create", response_class=JSONResponse)
9af949c def task_create(
ddcd285 body: Annotated[TaskCreateBody, Depends(project_body(TaskCreateBody, Permission.TASKS))],
9af949c ) -> JSONResponse:
73c9c30 """Create a new task on a board."""
ddcd285 repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, body.project))
b = _find_board(repo, get_board_ref(body.board))
73c9c30 if not b:
raise HTTPException(status_code=404, detail="Board not found")
d3658bc # Unknown or malformed values fall back to the defaults rather than failing the request.
try:
ddcd285 due = _parse_dt(body.due_date)
d3658bc except ValueError:
due = None
73c9c30 result = create_task(
repo=repo,
board=b,
ddcd285 title=body.title,
description=body.description,
status=getattr(Task.Status, body.status, None) or Task.Status.TODO,
priority=getattr(Task.Priority, body.priority, None) or Task.Priority.LOW,
assignee=body.assignee,
d3658bc due_date=due,
ddcd285 tags=body.tags,
points=parse_points(body.points),
73c9c30 )
return JSONResponse(content={"task_id": result["id"], "ref": result["ref"], "oid": str(result["oid"])})
9af949c
ddcd285 @task_router.post("/update", response_class=JSONResponse)
def task_update(
body: Annotated[TaskUpdateBody, Depends(project_body(TaskUpdateBody, Permission.TASKS))],
9af949c ) -> JSONResponse:
ddcd285 """Update a task. Only the fields present in the body are changed."""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, body.project))
ref = _full_task_ref(body.task)
d3658bc t = _find_task(repo, ref)
73c9c30 if not t:
raise HTTPException(status_code=404, detail="Task not found")
d3658bc # Check the board before writing, so a bad board name can't leave a half-applied update.
ddcd285 if get_board_ref(body.board) not in repo.references:
d3658bc raise HTTPException(status_code=404, detail="Board not found")
ddcd285 present = body.model_fields_set
# Unknown status/priority values are ignored, as before.
new_status = getattr(Task.Status, body.status, None) if body.status else None
new_priority = getattr(Task.Priority, body.priority, None) if body.priority else None
if "title" in present and body.title is not None:
t.title = body.title
if "description" in present:
t.description = body.description or ""
if new_status is not None:
t.status = new_status
if new_priority is not None:
t.priority = new_priority
if "assignee" in present:
t.assignee = body.assignee or None
if "points" in present:
t.points = parse_points(body.points)
if "due_date" in present:
with contextlib.suppress(ValueError):
t.due_date = _parse_dt(body.due_date)
if "tags" in present:
t.tags = body.tags or ""
73c9c30 old_oid = str(repo.references[ref].resolve().target)
t.update_message()
new_oid = t.write(repo)
ddcd285 _sync_board_task_oid(repo, body.board, old_oid, new_oid, move_to_end=new_status is not None)
73c9c30 return JSONResponse(content=_task_to_json(t))
9af949c
ddcd285 @task_router.post("/delete", response_class=JSONResponse)
9af949c def task_delete(
ddcd285 body: Annotated[TaskRefBody, Depends(project_body(TaskRefBody, Permission.TASKS))],
9af949c ) -> JSONResponse:
73c9c30 """Delete a task (remove ref, comments, and board entries)."""
ddcd285 repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, body.project))
ref = _full_task_ref(body.task)
73c9c30 if ref not in repo.references:
raise HTTPException(status_code=404, detail="Task not found")
delete_task_local(repo, ref)
return JSONResponse(content={"message": "Task deleted"})
9af949c
ddcd285 @task_router.post("/archive", response_class=JSONResponse)
929fbde def task_archive(
ddcd285 body: Annotated[TaskArchiveBody, Depends(project_body(TaskArchiveBody, Permission.TASKS))],
929fbde ) -> JSONResponse:
73c9c30 """Move a task from a board to the archive board (creates archive board if needed)."""
ddcd285 archive_board = body.archive_board
73c9c30 if not archive_board or "/" in archive_board or ".." in archive_board:
raise HTTPException(status_code=400, detail="Invalid archive board name")
ddcd285 repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, body.project))
ref = _full_task_ref(body.task)
73c9c30 try:
ddcd285 archive_ref = archive_task_local(repo, ref, body.board, archive_board_name=archive_board)
73c9c30 except KeyError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
return JSONResponse(
content={
"message": "Task archived",
"archive_board": archive_board,
"archive_ref": archive_ref,
}
)
929fbde
ddcd285 @task_router.post("/move", response_class=JSONResponse)
52026a0 def task_move(
ddcd285 body: Annotated[TaskMoveBody, Depends(project_body(TaskMoveBody, Permission.TASKS))],
52026a0 ) -> JSONResponse:
73c9c30 """Move a task onto another board (e.g. pulling it into a sprint board)."""
ddcd285 target = body.target
73c9c30 target_ref = get_board_ref(target)
if not target or not pygit2.reference_is_valid_name(target_ref):
raise HTTPException(status_code=400, detail="Invalid board name")
ddcd285 repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, body.project))
ref = _full_task_ref(body.task)
73c9c30 if ref not in repo.references:
raise HTTPException(status_code=404, detail="Task not found")
ddcd285 source_ref = get_board_ref(body.board)
73c9c30 if target_ref not in repo.references:
raise HTTPException(status_code=404, detail="Target board not found")
tb = get_board(repo, target_ref)
if not tb:
raise HTTPException(status_code=404, detail="Target board not found")
if source_ref == target_ref:
return JSONResponse(content={"message": "Task already on board", "board": target})
oid_hex = str(repo.references[ref].resolve().target)
tb.tasks = getattr(tb, "tasks", []) or []
if oid_hex not in tb.tasks:
tb.tasks.append(oid_hex)
tb.update_message()
tb.write(repo)
sb = get_board(repo, source_ref) if source_ref in repo.references else None
if sb and getattr(sb, "tasks", None) and oid_hex in sb.tasks:
sb.tasks = [x for x in sb.tasks if x != oid_hex]
sb.update_message()
sb.write(repo)
return JSONResponse(content={"message": "Task moved", "board": target})
52026a0
9af949c # ---------- Comment Routes ----------
e6c6972 comment_router = APIRouter(tags=["comments"])
9af949c
3258e39 def _parse_tagger_display(tagger: str) -> tuple[str, str | None]:
73c9c30 s = (tagger or "").strip()
if not s:
return ("Unknown", None)
m = re.match(r"^(.+?)\s*<([^>]+)>", s)
if m:
name = m.group(1).strip() or "Unknown"
return (name, m.group(2).strip())
return (s, None)
3258e39
def _tagger_from_principal(principal: PermissionPrincipal | None) -> str:
73c9c30 if principal is None:
return ""
email = (principal.email or "").strip() or f"{principal.username}@local"
name = principal.username.strip() or email
return f"{name} <{email}>"
3258e39
dc408b2 def _principal_matches_comment_tagger(tagger: str, principal: PermissionPrincipal) -> bool:
73c9c30 identity = principal.identity
if not identity:
return False
raw = (tagger or "").strip()
if not raw:
return False
if raw == identity or raw.lower() == identity.lower():
return True
name, email = _parse_tagger_display(raw)
valid_email = email and email.lower() == identity.lower()
valid_name = name and (name == identity or name.lower() == identity.lower())
return bool(valid_email or valid_name)
dc408b2
def _ensure_comment_modify_allowed(project: str, token: str | None, tagger: str) -> None:
73c9c30 ensure_active_user_if_auth_enabled(token)
if has_permission(Permission.COMMENTS, project, token=token):
return
principal = principal_from_session(token)
if principal is not None and _principal_matches_comment_tagger(tagger, principal):
return
raise HTTPException(status_code=403, detail="Insufficient permissions")
dc408b2
9af949c def _comment_to_json(c: Comment) -> dict[str, Any]:
73c9c30 author, email = _parse_tagger_display(c.tagger)
return {
"content": c.content,
"tagger": c.tagger,
"author": author,
"gravatar_url": gravatar_url(email) if email else None,
"created_at": c.created_at.isoformat() if c.created_at else None,
"edited_at": c.edited_at.isoformat() if c.edited_at else None,
}
9af949c
3258e39 def _comment_sort_key(entry: dict[str, Any]) -> str:
73c9c30 return entry.get("edited_at") or entry.get("created_at") or ""
3258e39
e6c6972 @comment_router.get(
73c9c30 "/list",
response_class=JSONResponse,
e6c6972 )
9af949c def comment_list(
73c9c30 project: ValidatedReadableQueryProject,
board: str = Query(..., description="Board name"),
task: str = Query(..., description="Task ref (e.g. refs/tags/tasks/task_123)"),
9af949c ) -> JSONResponse:
73c9c30 """List all comments for a task."""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
task_ref = task if task.startswith("refs/") else get_task_ref(task)
t = get_task(repo, task_ref)
if not t:
raise HTTPException(status_code=404, detail="Task not found")
comment_oids = getattr(t, "comments", []) or []
comments = []
for oid_hex in comment_oids:
try:
oid = pygit2.Oid(hex=oid_hex) if isinstance(oid_hex, str) else oid_hex
c = get_comment(repo, oid)
if c:
comments.append(_comment_to_json(c))
except (ValueError, KeyError, TypeError):
continue
comments.sort(key=_comment_sort_key)
return JSONResponse(content=comments)
9af949c
ddcd285 @comment_router.post("/create", response_class=JSONResponse)
9af949c def comment_create(
ddcd285 body: Annotated[CommentCreateBody, Depends(project_body(CommentCreateBody, Permission.COMMENTS))],
73c9c30 token: Annotated[str | None, Depends(access_token_from_request)] = None,
9af949c ) -> JSONResponse:
73c9c30 """Create a new comment on a task."""
ddcd285 repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, body.project))
board = body.board
task_ref = _full_task_ref(body.task)
73c9c30 t = get_task(repo, task_ref)
if not t:
raise HTTPException(status_code=404, detail="Task not found")
try:
target_oid = repo.references[task_ref].resolve().target
except KeyError as exc:
raise HTTPException(status_code=404, detail="Task not found") from exc
tagger = _tagger_from_principal(principal_from_session(token))
ddcd285 comment = Comment(target=target_oid, tagger=tagger, content=body.content or "")
73c9c30 comment_oid = comment.write(repo)
t.comments = getattr(t, "comments", []) or []
t.comments.append(str(comment_oid))
old_task_oid = str(target_oid)
t.update_message()
new_task_oid = t.write(repo)
_sync_board_task_oid(repo, board, old_task_oid, new_task_oid)
return JSONResponse(
content={
"oid": str(comment_oid),
"message": "Comment created",
"comments_count": len(t.comments),
}
)
9af949c
ddcd285 @comment_router.post("/modify", response_class=JSONResponse)
def comment_modify(
# No permission here: authors may edit their own comments (checked below).
body: Annotated[CommentModifyBody, Depends(project_body(CommentModifyBody))],
73c9c30 token: Annotated[str | None, Depends(access_token_from_request)] = None,
9af949c ) -> JSONResponse:
ddcd285 """Modify a comment's content. Author or pgw.comments grant required."""
project, board, comment_oid = body.project, body.board, body.comment
73c9c30 repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
oid = pygit2.Oid(hex=comment_oid)
c = get_comment(repo, oid)
if not c:
raise HTTPException(status_code=404, detail="Comment not found")
_ensure_comment_modify_allowed(project, token, c.tagger)
ddcd285 if body.content is not None:
c.content = body.content
73c9c30 from datetime import datetime
c.edited_at = datetime.now()
c.update_message()
new_oid = c.write(repo)
ddcd285 task_ref = _full_task_ref(body.task)
73c9c30 t = get_task(repo, task_ref)
if t and getattr(t, "comments", None):
t.comments = [str(new_oid) if str(co) == comment_oid else co for co in t.comments]
try:
old_task_oid = str(repo.references[task_ref].resolve().target)
except KeyError:
old_task_oid = ""
t.update_message()
new_task_oid = t.write(repo)
if old_task_oid:
_sync_board_task_oid(repo, board, old_task_oid, new_task_oid)
return JSONResponse(
content={
**_comment_to_json(c),
"oid": str(new_oid),
"message": "Comment updated",
}
)
9af949c
ddcd285 @comment_router.post("/delete", response_class=JSONResponse)
9af949c def comment_delete(
ddcd285 body: Annotated[CommentDeleteBody, Depends(project_body(CommentDeleteBody, Permission.COMMENTS))],
9af949c ) -> JSONResponse:
73c9c30 """Delete a comment (object remains in ODB; caller may remove from task.comments)."""
ddcd285 repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, body.project))
oid = pygit2.Oid(hex=body.comment)
73c9c30 try:
c = get_comment(repo, oid)
except (ValueError, KeyError) as e:
raise HTTPException(status_code=404, detail="Comment not found") from e
if not c:
raise HTTPException(status_code=404, detail="Comment not found")
return JSONResponse(content={"message": "Comment deleted"})