1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
"""
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 time
from typing import Any
import pygit2
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from fastapi.responses import JSONResponse
from pygittools.tasks import (
BOARD_REF_PREFIX,
TASK_REF_PREFIX,
Board,
Comment,
Task,
get_board,
get_comment,
get_task,
get_task_by_oid,
)
from pygitweb.auth import require_active_user_if_auth_enabled
from pygitweb.config import settings
from pygitweb.dependencies import ValidatedQueryProject
# Well-known empty tree OID for boards/tasks when repo has no HEAD
EMPTY_TREE_OID = pygit2.Oid(hex="4b825dc642cb6eb9a060e54bf8d69288fbee4904")
def _board_ref(name: str) -> str:
return f"{BOARD_REF_PREFIX}{name}"
def _task_ref(task_id: str) -> str:
return f"{TASK_REF_PREFIX}{task_id}"
def _repo_head_or_empty(repo: pygit2.Repository) -> pygit2.Oid | str:
if repo.head:
return repo.head.target
return EMPTY_TREE_OID
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 = _board_ref(name)
if ref in repo.references:
raise HTTPException(status_code=409, detail="Board already exists")
target = _repo_head_or_empty(repo)
board = Board(target, ref, tagger="", description=description)
board.write(repo)
return ref
# ---------- Board Routes ----------
board_router = APIRouter(tags=["boards"], dependencies=[Depends(require_active_user_if_auth_enabled)])
@board_router.get("/list", response_class=JSONResponse)
def boards_list(project: ValidatedQueryProject) -> JSONResponse:
"""List all boards for the 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 JSONResponse(content=boards)
@board_router.post("/create", response_class=JSONResponse)
def boards_create(
project: ValidatedQueryProject,
name: str = Query(..., description="Board name"),
description: str = Query("", description="Board description"),
) -> JSONResponse:
"""Create a new board."""
if not name or "/" in name or ".." in name:
raise HTTPException(status_code=400, detail="Invalid board name")
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
ref = _board_ref(name)
if ref in repo.references:
raise HTTPException(status_code=409, detail="Board already exists")
target = _repo_head_or_empty(repo)
board = Board(target, ref, tagger="", description=description or "")
oid = board.write(repo)
return JSONResponse(content={"name": name, "ref": ref, "oid": str(oid)})
@board_router.post("/delete", response_class=JSONResponse)
def boards_delete(
project: ValidatedQueryProject,
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 = _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"], dependencies=[Depends(require_active_user_if_auth_enabled)])
def _task_to_json(t: Task) -> dict[str, Any]:
return {
"ref": 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,
"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 = _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:
oid = pygit2.Oid(hex=oid_hex) if isinstance(oid_hex, str) else oid_hex
t = get_task_by_oid(repo, oid)
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, []),
}
for s in BOARD_STATUS_ORDER
]
@task_router.get("/list", response_class=JSONResponse)
def task_list(
project: ValidatedQueryProject,
board: str = Query(..., description="Board name"),
) -> JSONResponse:
"""List all tasks on a board."""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
ref = _board_ref(board)
b = get_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:
oid = pygit2.Oid(hex=oid_hex) if isinstance(oid_hex, str) else oid_hex
t = get_task_by_oid(repo, oid)
if t:
tasks.append(_task_to_json(t))
except (ValueError, KeyError, TypeError):
continue
return JSONResponse(content=tasks)
@task_router.post("/create", response_class=JSONResponse)
def task_create(
project: ValidatedQueryProject,
board: str = Query(..., description="Board name"),
title: str = Query(..., description="Task title"),
description: str = Query("", description="Task description"),
status: str = Query("TODO", description="Task status"),
priority: str = Query("LOW", description="Task priority"),
assignee: str = Query("", description="Assignee"),
due_date: str = Query("", description="Due date ISO"),
) -> JSONResponse:
"""Create a new task on a board."""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
board_ref = _board_ref(board)
b = get_board(repo, board_ref)
if not b:
raise HTTPException(status_code=404, detail="Board not found")
task_id = f"task_{int(time.time() * 1000)}"
ref = _task_ref(task_id)
target = _repo_head_or_empty(repo)
status_enum = getattr(Task.Status, status, None) or Task.Status.TODO
priority_enum = getattr(Task.Priority, priority, None) or Task.Priority.LOW
due = None
if due_date:
try:
from datetime import datetime
due = datetime.fromisoformat(due_date.replace("Z", "+00:00"))
except ValueError:
pass
task = Task(
target,
ref,
tagger="",
title=title,
description=description or "",
status=status_enum,
priority=priority_enum,
assignee=assignee or None,
due_date=due,
)
oid = task.write(repo)
b.tasks = getattr(b, "tasks", []) or []
b.tasks.append(str(oid))
b.update_message()
b.write(repo)
return JSONResponse(content={"task_id": task_id, "ref": ref, "oid": str(oid)})
@task_router.post("/update", response_class=JSONResponse)
async def task_update(
request: Request,
project: ValidatedQueryProject,
board: str = Query(..., description="Board name"),
task_ref: str = Query(..., alias="task", description="Task ref (e.g. refs/tags/tasks/task_123)"),
) -> JSONResponse:
"""Update a task (body: optional title, description, status, priority, assignee, due_date)."""
try:
body = await request.json() if request.headers.get("content-type", "").startswith("application/json") else {}
except Exception:
body = {}
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
ref = task_ref if task_ref.startswith("refs/") else _task_ref(task_ref)
t = get_task(repo, ref)
if not t:
raise HTTPException(status_code=404, detail="Task not found")
status_changed = bool("status" in body and hasattr(Task.Status, body["status"]))
if "title" in body:
t.title = body["title"]
if "description" in body:
t.description = body.get("description", "")
if status_changed:
t.status = Task.Status(body["status"])
if "priority" in body and hasattr(Task.Priority, body["priority"]):
t.priority = Task.Priority(body["priority"])
if "assignee" in body:
t.assignee = body["assignee"] or None
if "due_date" in body:
try:
from datetime import datetime
t.due_date = (
datetime.fromisoformat(str(body["due_date"]).replace("Z", "+00:00")) if body["due_date"] else None
)
except ValueError:
pass
old_oid = str(repo.references[ref].resolve().target)
t.update_message()
new_oid = t.write(repo)
board_ref = _board_ref(board)
b = get_board(repo, board_ref)
if b and getattr(b, "tasks", None):
new_oid_str = str(new_oid)
tasks_list = [new_oid_str if o == old_oid else o for o in b.tasks]
if status_changed 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)
return JSONResponse(content=_task_to_json(t))
@task_router.post("/delete", response_class=JSONResponse)
def task_delete(
project: ValidatedQueryProject,
board: str = Query(..., description="Board name"),
task_ref: str = Query(..., alias="task", description="Task ref"),
) -> JSONResponse:
"""Delete a task (remove ref and remove from board.tasks)."""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
ref = task_ref if task_ref.startswith("refs/") else _task_ref(task_ref)
if ref not in repo.references:
raise HTTPException(status_code=404, detail="Task not found")
oid_hex = str(repo.references[ref].resolve().target)
repo.references.delete(ref)
board_ref = _board_ref(board)
b = get_board(repo, board_ref)
if b and getattr(b, "tasks", None):
try:
b.tasks = [x for x in b.tasks if x != oid_hex]
b.update_message()
b.write(repo)
except Exception:
pass
return JSONResponse(content={"message": "Task deleted"})
# ---------- Comment Routes ----------
comment_router = APIRouter(tags=["comments"], dependencies=[Depends(require_active_user_if_auth_enabled)])
def _comment_to_json(c: Comment) -> dict[str, Any]:
return {
"content": c.content,
"tagger": c.tagger,
"created_at": c.created_at.isoformat() if c.created_at else None,
"edited_at": c.edited_at.isoformat() if c.edited_at else None,
}
@comment_router.get("/list", response_class=JSONResponse)
def comment_list(
project: ValidatedQueryProject,
board: str = Query(..., description="Board name"),
task: str = Query(..., description="Task ref (e.g. refs/tags/tasks/task_123)"),
) -> JSONResponse:
"""List all comments for a task."""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
task_ref = task if task.startswith("refs/") else _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
return JSONResponse(content=comments)
@comment_router.post("/create", response_class=JSONResponse)
def comment_create(
project: ValidatedQueryProject,
board: str = Query(..., description="Board name"),
task: str = Query(..., description="Task ref"),
content: str = Query(..., description="Comment content"),
) -> JSONResponse:
"""Create a new comment on a task."""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
task_ref = task if task.startswith("refs/") else _task_ref(task)
t = get_task(repo, task_ref)
if not t:
raise HTTPException(status_code=404, detail="Task not found")
resolved = repo.revparse_single(task_ref)
target_oid = resolved.oid if hasattr(resolved, "oid") else pygit2.Oid(hex=str(resolved))
comment = Comment(target=target_oid, tagger="", content=content or "")
comment_oid = comment.write(repo)
t.comments = getattr(t, "comments", []) or []
t.comments.append(str(comment_oid))
t.update_message()
t.write(repo)
return JSONResponse(content={"oid": str(comment_oid), "message": "Comment created"})
@comment_router.post("/update", response_class=JSONResponse)
async def comment_update(
request: Request,
project: ValidatedQueryProject,
board: str = Query(..., description="Board name"),
task: str = Query(..., description="Task ref (to update task.comments)"),
comment_oid: str = Query(..., alias="comment", description="Comment OID hex"),
) -> JSONResponse:
"""Update a comment (body: content). Writes new comment object and updates task.comments."""
try:
body = await request.json() if request.headers.get("content-type", "").startswith("application/json") else {}
except Exception:
body = {}
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")
if "content" in body:
c.content = body["content"]
from datetime import datetime
c.edited_at = datetime.now()
c.update_message()
new_oid = c.write(repo)
task_ref = task if task.startswith("refs/") else _task_ref(task)
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]
t.update_message()
t.write(repo)
return JSONResponse(
content={
**_comment_to_json(c),
"oid": str(new_oid),
"message": "Comment updated",
}
)
@comment_router.post("/delete", response_class=JSONResponse)
def comment_delete(
project: ValidatedQueryProject,
board: str = Query(..., description="Board name"),
comment_oid: str = Query(..., alias="comment", description="Comment OID hex"),
) -> JSONResponse:
"""Delete a comment (object remains in ODB; caller may remove from task.comments)."""
repo = pygit2.Repository(os.path.join(settings.PROJECTROOT, project))
oid = pygit2.Oid(hex=comment_oid)
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"})