Project: pygitweb
"""
Task-related routes: Task, comment, board creation, listing, and management.
Data is stored in the repo ODB/RefDB via pygittools.tasks (Board, Task, Comment).
"""
from __future__ import annotations
import os
import re
from datetime import datetime
from typing import Annotated, Any
from urllib.parse import quote
import pygit2
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel, BeforeValidator, Field
from pygit2 import Oid
from pygittools.merge import (
MR_REF_PREFIX,
create_mr_comment,
delete_mr_comment,
get_merge_request,
modify_mr_comment,
)
from pygittools.tasks import (
ARCHIVE_BOARD_NAME,
BOARD_REF_PREFIX,
SPRINT_POINTS,
TASK_REF_PREFIX,
Board,
Comment,
Task,
archive_task_local,
create_comment,
create_task,
delete_comment,
delete_task_local,
format_task_tags,
get_board,
get_board_ref,
get_comment,
get_repo_head_or_empty,
get_task,
get_task_by_oid,
get_task_ref,
modify_comment,
parse_task_tags,
)
from pygitweb.auth import (
access_token_from_request,
ensure_active_user_if_auth_enabled,
is_superuser,
principal_from_session,
)
from pygitweb.config import settings
from pygitweb.dependencies import (
RequirePermission,
ValidatedReadableProject,
filter_projects_by_read_access,
)
from pygitweb.gravatar import gravatar_url
from pygitweb.permissions import Permission, PermissionPrincipal
from pygitweb.projects import git_get_projects_list
from pygitweb.templates_env import (
Cell,
html_link,
person_label,
priority_badge,
render_page,
status_badge,
)
EMPTY_TREE_OID = Oid(hex="4b825dc642cb6eb9a060e54bf8d69288fbee4904")
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
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 (content only; resource ids live in the query string) ----------
def _validate_sprint_points(value: object) -> int | None:
if value is None:
return None
if isinstance(value, bool) or not isinstance(value, int):
raise ValueError("points must be an integer")
if value not in SPRINT_POINTS:
raise ValueError(f"points must be one of {SPRINT_POINTS}")
return value
SprintPoints = Annotated[int | None, BeforeValidator(_validate_sprint_points)]
class BoardCreateBody(BaseModel):
description: str = ""
class TaskCreateBody(BaseModel):
title: str
description: str = ""
status: Task.Status = Task.Status.TODO
priority: Task.Priority = Task.Priority.LOW
assignee: str = ""
due_date: datetime | None = None
tags: dict[str, str] = Field(default_factory=dict)
points: SprintPoints = None
class TaskUpdateBody(BaseModel):
"""Only the fields present in the request are changed."""
title: str | None = None
description: str | None = None
status: Task.Status | None = None
priority: Task.Priority | None = None
assignee: str | None = None
due_date: datetime | None = None
tags: dict[str, str] | None = None
points: SprintPoints = None
class CommentCreateBody(BaseModel):
content: str
class CommentModifyBody(BaseModel):
content: str | None = None
def _sync_board_task_oid(
repo: pygit2.Repository,
board: str,
old_oid: str,
new_oid: pygit2.Oid | str,
*,
move_to_end: bool = False,
) -> None:
"""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)
def _task_from_board_entry(
repo: pygit2.Repository,
oid_hex: str | pygit2.Oid,
*,
board: str | None = None,
) -> Task | None:
"""
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
def create_board_for_project(
project: str,
name: str = "Tasks",
description: str = "",
) -> str:
"""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
# ---------- Board Routes ----------
board_router = APIRouter(tags=["boards"])
def list_project_boards(project: str) -> list[dict[str, Any]]:
"""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
@board_router.get("/list")
def boards_list(project: ValidatedReadableProject) -> JSONResponse:
"""List all boards for the project."""
return JSONResponse(content=list_project_boards(project))
@board_router.post(
"/create",
dependencies=[Depends(RequirePermission(Permission.BOARDS))],
)
def boards_create(
project: ValidatedReadableProject,
name: str = Query(..., description="Board name"),
fields: BoardCreateBody | None = None,
) -> JSONResponse:
"""Create a new board."""
if not name or not pygit2.reference_is_valid_name(get_board_ref(name)):
raise HTTPException(status_code=400, detail="Invalid board name")
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)
description = (fields.description if fields else "") or ""
board = Board(target, ref, tagger="", description=description)
oid = board.write(repo)
return JSONResponse(content={"name": name, "ref": ref, "oid": str(oid)})
@board_router.post(
"/delete",
dependencies=[Depends(RequirePermission(Permission.BOARDS))],
)
def boards_delete(
project: ValidatedReadableProject,
name: str = Query(..., description="Board name"),
) -> JSONResponse:
"""Delete a board (removes ref; tag object remains in ODB)."""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
ref = get_board_ref(name)
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"})
# ---------- Task Routes ----------
task_router = APIRouter(tags=["tasks"])
def _task_display_id(ref: str) -> str:
"""Numeric task id for UI (task_1730000000000 -> 1730000000000)."""
slug = ref.removeprefix(TASK_REF_PREFIX)
if slug.startswith("task_"):
return slug.removeprefix("task_")
return slug
def _task_to_json(t: Task) -> dict[str, Any]:
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": parse_task_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", [])),
}
# Status order for board columns
BOARD_STATUS_ORDER = ["TODO", "IN_PROGRESS", "IN_REVIEW", "DONE", "CANCELLED"]
def get_board_tasks_grouped(
project: str,
board_name: str,
) -> list[dict[str, Any]]:
"""
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
]
def get_all_project_tasks(project: str) -> list[dict[str, Any]]:
"""
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
@task_router.get("", response_class=HTMLResponse)
def all_tasks_page(
token: Annotated[str | None, Depends(access_token_from_request)],
status: Annotated[Task.Status | None, Query()] = None,
) -> HTMLResponse:
"""Flat list of every task across every project and board you can read."""
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 is not None and task_status != status.value:
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": s,
"label": s.replace("_", " ").title(),
"selected": status is not None and status.value == s,
}
for s in BOARD_STATUS_ORDER
]
return render_page(
"tasks.html",
title=f"{settings.SITE_NAME} - Tasks",
status_filter=status.value if status is not None else "",
statuses=statuses,
cols=["Task", "Project", "Board", "Status", "Priority", "Assignee", "Points"],
rows=rows,
nav="tasks",
)
@task_router.get("/list")
def task_list(
project: ValidatedReadableProject,
board: str = Query(..., description="Board name"),
) -> JSONResponse:
"""List all tasks on a board."""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
ref = get_board_ref(board)
b = _find_board(repo, ref)
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)
@task_router.post(
"/create",
dependencies=[Depends(RequirePermission(Permission.TASKS))],
)
def task_create(
project: ValidatedReadableProject,
task: TaskCreateBody,
board: str = Query(..., description="Board name"),
) -> JSONResponse:
"""Create a new task on a board."""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
b = _find_board(repo, get_board_ref(board))
if not b:
raise HTTPException(status_code=404, detail="Board not found")
result = create_task(
repo=repo,
board=b,
title=task.title,
description=task.description,
status=task.status,
priority=task.priority,
assignee=task.assignee,
due_date=task.due_date,
tags=format_task_tags(task.tags),
points=task.points,
)
return JSONResponse(content={"task_id": result["id"], "ref": result["ref"], "oid": str(result["oid"])})
@task_router.post(
"/update",
dependencies=[Depends(RequirePermission(Permission.TASKS))],
)
def task_update(
project: ValidatedReadableProject,
fields: TaskUpdateBody,
board: str = Query(..., description="Board name"),
task: str = Query(..., description="Task ref (refs/tags/tasks/task_123) or bare id (task_123)"),
) -> JSONResponse:
"""Update a task. Only the fields present in the request are changed."""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
ref = _full_task_ref(task)
t = _find_task(repo, ref)
if not t:
raise HTTPException(status_code=404, detail="Task not found")
# Check the board before writing, so a bad board name can't leave a half-applied update.
if get_board_ref(board) not in repo.references:
raise HTTPException(status_code=404, detail="Board not found")
present = fields.model_fields_set
if "title" in present and fields.title is not None:
t.title = fields.title
if "description" in present:
t.description = fields.description or ""
if fields.status is not None:
t.status = fields.status
if fields.priority is not None:
t.priority = fields.priority
if "assignee" in present:
t.assignee = fields.assignee or None
if "points" in present:
t.points = fields.points
if "due_date" in present:
t.due_date = fields.due_date
if "tags" in present:
t.tags = format_task_tags(fields.tags)
old_oid = str(repo.references[ref].resolve().target)
t.update_message()
new_oid = t.write(repo)
_sync_board_task_oid(repo, board, old_oid, new_oid, move_to_end=fields.status is not None)
return JSONResponse(content=_task_to_json(t))
@task_router.post(
"/delete",
dependencies=[Depends(RequirePermission(Permission.TASKS))],
)
def task_delete(
project: ValidatedReadableProject,
board: str = Query(..., description="Board name"),
task: str = Query(..., description="Task ref"),
) -> JSONResponse:
"""Delete a task (remove ref, comments, and board entries)."""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
ref = _full_task_ref(task)
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"})
@task_router.post(
"/archive",
dependencies=[Depends(RequirePermission(Permission.TASKS))],
)
def task_archive(
project: ValidatedReadableProject,
board: str = Query(..., description="Source board name"),
task: str = Query(..., description="Task ref"),
archive_board: str = Query(ARCHIVE_BOARD_NAME, description="Archive board name"),
) -> JSONResponse:
"""Move a task from a board to the archive board (creates archive board if needed)."""
if not archive_board or "/" in archive_board or ".." in archive_board:
raise HTTPException(status_code=400, detail="Invalid archive board name")
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
ref = _full_task_ref(task)
try:
archive_ref = archive_task_local(repo, ref, board, archive_board_name=archive_board)
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,
}
)
@task_router.post(
"/move",
dependencies=[Depends(RequirePermission(Permission.TASKS))],
)
def task_move(
project: ValidatedReadableProject,
board: str = Query(..., description="Source board name"),
task: str = Query(..., description="Task ref"),
target: str = Query(..., description="Target board name (e.g. a sprint board)"),
) -> JSONResponse:
"""Move a task onto another board (e.g. pulling it into a sprint board)."""
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")
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
ref = _full_task_ref(task)
if ref not in repo.references:
raise HTTPException(status_code=404, detail="Task not found")
source_ref = get_board_ref(board)
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})
# ---------- Comment Routes ----------
comment_router = APIRouter(tags=["comments"])
def _parse_tagger_display(tagger: str) -> tuple[str, str | None]:
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)
def _tagger_from_principal(principal: PermissionPrincipal | None) -> str:
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}>"
def _principal_matches_comment_tagger(tagger: str, principal: PermissionPrincipal) -> bool:
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)
def _is_comment_author(token: str | None, tagger: str) -> bool:
principal = principal_from_session(token)
return principal is not None and _principal_matches_comment_tagger(tagger, principal)
def _comment_can_edit(project: str, token: str | None, tagger: str) -> bool:
if not settings.AUTH:
return True
return _is_comment_author(token, tagger)
def _comment_can_delete(project: str, token: str | None, tagger: str) -> bool:
if not settings.AUTH:
return True
if _is_comment_author(token, tagger):
return True
return is_superuser(token=token)
def _ensure_comment_edit_allowed(project: str, token: str | None, tagger: str) -> None:
"""Authors may edit their own comments; others cannot rewrite them."""
ensure_active_user_if_auth_enabled(token)
if _comment_can_edit(project, token, tagger):
return
raise HTTPException(status_code=403, detail="Insufficient permissions")
def _ensure_comment_delete_allowed(project: str, token: str | None, tagger: str) -> None:
"""Authors may delete their own comments; ``*`` grant holders may delete any."""
ensure_active_user_if_auth_enabled(token)
if _comment_can_delete(project, token, tagger):
return
raise HTTPException(status_code=403, detail="Insufficient permissions")
def _parse_comment_oid(comment: str) -> pygit2.Oid:
try:
return pygit2.Oid(hex=comment)
except (TypeError, ValueError) as exc:
raise HTTPException(status_code=404, detail="Comment not found") from exc
def _load_comment(repo: pygit2.Repository, comment: str) -> tuple[pygit2.Oid, Comment]:
oid = _parse_comment_oid(comment)
try:
loaded = get_comment(repo, oid)
except (ValueError, KeyError) as exc:
raise HTTPException(status_code=404, detail="Comment not found") from exc
return oid, loaded
def _comment_to_json(
c: Comment,
*,
oid: str,
project: str,
token: str | None,
) -> dict[str, Any]:
author, email = _parse_tagger_display(c.tagger)
return {
"oid": oid,
"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,
"can_edit": _comment_can_edit(project, token, c.tagger),
"can_delete": _comment_can_delete(project, token, c.tagger),
}
def _comment_sort_key(entry: dict[str, Any]) -> str:
return entry.get("created_at") or ""
def _normalize_mr_ref(mr: str) -> str:
if mr.startswith("refs/"):
return mr
if mr.startswith("mr/"):
return f"refs/tags/{mr}"
return f"{MR_REF_PREFIX}{mr}"
def _comment_parent(
board: str | None,
task: str | None,
mr: str | None,
) -> tuple[str, str, str | None]:
"""Return ``(kind, parent_ref, board)`` where kind is ``task`` or ``mr``."""
has_task = bool(task and task.strip())
has_mr = bool(mr and mr.strip())
if has_task == has_mr:
raise HTTPException(
status_code=422,
detail="Provide either task and board, or mr",
)
if has_mr:
assert mr is not None
return ("mr", _normalize_mr_ref(mr), None)
if not board or not board.strip():
raise HTTPException(status_code=422, detail="board is required when task is set")
assert task is not None
return ("task", _full_task_ref(task), board)
def _comment_oids_for_parent(
repo: pygit2.Repository,
kind: str,
parent_ref: str,
) -> list[str | pygit2.Oid]:
if kind == "mr":
try:
mr_obj = get_merge_request(repo, parent_ref)
except (KeyError, ValueError) as exc:
raise HTTPException(status_code=404, detail="Merge request not found") from exc
return list(mr_obj.comments or [])
t = _find_task(repo, parent_ref)
if not t:
raise HTTPException(status_code=404, detail="Task not found")
return list(getattr(t, "comments", []) or [])
def _comments_json_for_oids(
repo: pygit2.Repository,
comment_oids: list[str | pygit2.Oid],
*,
project: str,
token: str | None,
) -> list[dict[str, Any]]:
comments: list[dict[str, Any]] = []
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)
comments.append(_comment_to_json(c, oid=str(oid), project=project, token=token))
except (ValueError, KeyError, TypeError):
continue
comments.sort(key=_comment_sort_key)
return comments
@comment_router.get("/list")
def comment_list(
project: ValidatedReadableProject,
board: str | None = Query(None, description="Board name (required with task)"),
task: str | None = Query(None, description="Task ref (e.g. refs/tags/tasks/task_123)"),
mr: str | None = Query(None, description="Merge request ref (e.g. refs/tags/mr/...)"),
token: Annotated[str | None, Depends(access_token_from_request)] = None,
) -> JSONResponse:
"""List comments for a task or merge request."""
kind, parent_ref, _board = _comment_parent(board, task, mr)
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
comment_oids = _comment_oids_for_parent(repo, kind, parent_ref)
return JSONResponse(content=_comments_json_for_oids(repo, comment_oids, project=project, token=token))
@comment_router.post(
"/create",
dependencies=[Depends(RequirePermission(Permission.COMMENTS))],
)
def comment_create(
project: ValidatedReadableProject,
comment: CommentCreateBody,
board: str | None = Query(None, description="Board name (required with task)"),
task: str | None = Query(None, description="Task ref"),
mr: str | None = Query(None, description="Merge request ref"),
token: Annotated[str | None, Depends(access_token_from_request)] = None,
) -> JSONResponse:
"""Create a new comment on a task or merge request."""
kind, parent_ref, board_name = _comment_parent(board, task, mr)
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
tagger = _tagger_from_principal(principal_from_session(token))
try:
if kind == "mr":
result_mr = create_mr_comment(
repo,
parent_ref,
comment.content or "",
tagger=tagger,
)
mr_after = get_merge_request(repo, parent_ref)
comments_count = len(mr_after.comments or [])
return JSONResponse(
content={
"oid": str(result_mr["oid"]),
"message": "Comment created",
"comments_count": comments_count,
"mr_oid": str(result_mr["mr_oid"]),
}
)
if _find_task(repo, parent_ref) is None:
raise HTTPException(status_code=404, detail="Task not found")
result = create_comment(
repo,
parent_ref,
comment.content or "",
tagger=tagger,
board=board_name,
)
except KeyError as exc:
detail = "Merge request not found" if kind == "mr" else "Task not found"
raise HTTPException(status_code=404, detail=detail) from exc
task_after = get_task(repo, parent_ref)
comments_count = len(getattr(task_after, "comments", []) or []) if task_after else 1
return JSONResponse(
content={
"oid": str(result["oid"]),
"message": "Comment created",
"comments_count": comments_count,
}
)
@comment_router.post("/modify")
def comment_modify(
project: ValidatedReadableProject,
fields: CommentModifyBody,
comment: str = Query(..., description="Comment OID hex"),
board: str | None = Query(None, description="Board name (required with task)"),
task: str | None = Query(None, description="Task ref"),
mr: str | None = Query(None, description="Merge request ref"),
token: Annotated[str | None, Depends(access_token_from_request)] = None,
) -> JSONResponse:
"""Modify a comment's content. Author only."""
kind, parent_ref, board_name = _comment_parent(board, task, mr)
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
oid, c = _load_comment(repo, comment)
_ensure_comment_edit_allowed(project, token, c.tagger)
content = c.content if fields.content is None else fields.content
try:
if kind == "mr":
result_mr = modify_mr_comment(repo, oid, content, mr_ref=parent_ref)
return JSONResponse(
content={
**_comment_to_json(
result_mr["comment"],
oid=str(result_mr["oid"]),
project=project,
token=token,
),
"message": "Comment updated",
"mr_oid": str(result_mr["mr_oid"]),
}
)
result = modify_comment(
repo,
oid,
content,
task_ref=parent_ref,
board=board_name,
)
except KeyError as exc:
raise HTTPException(status_code=404, detail="Comment not found") from exc
return JSONResponse(
content={
**_comment_to_json(
result["comment"],
oid=str(result["oid"]),
project=project,
token=token,
),
"message": "Comment updated",
}
)
@comment_router.post("/delete")
def comment_delete(
project: ValidatedReadableProject,
comment: str = Query(..., description="Comment OID hex"),
board: str | None = Query(None, description="Board name (required with task)"),
task: str | None = Query(None, description="Task ref"),
mr: str | None = Query(None, description="Merge request ref"),
token: Annotated[str | None, Depends(access_token_from_request)] = None,
) -> JSONResponse:
"""Delete a comment. Author or ``*`` (superuser) grant required."""
kind, parent_ref, board_name = _comment_parent(board, task, mr)
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
oid, c = _load_comment(repo, comment)
_ensure_comment_delete_allowed(project, token, c.tagger)
try:
if kind == "mr":
mr_oid = delete_mr_comment(repo, oid, mr_ref=parent_ref)
return JSONResponse(content={"message": "Comment deleted", "mr_oid": str(mr_oid)})
delete_comment(repo, oid, task_ref=parent_ref, board=board_name)
except KeyError as exc:
raise HTTPException(status_code=404, detail="Comment not found") from exc
return JSONResponse(content={"message": "Comment deleted"})