from typing import List, Sequence from .todo_item import Todo _HEADER = ( "id", "title", "notes", "done", "priority", "due", "tags", "recurrenceFrequency", "recurrenceInterval", "recurrenceAnchor", "createdAt", "completedAt", "order", ) def _field(text: str) -> str: """Quote a field only when RFC 4180 needs it: a comma, a double quote, CR or LF.""" if not any(ch in text for ch in ',"\r\n'): return text return '"' + text.replace('"', '""') + '"' def export_csv(todos: Sequence[Todo]) -> str: """Todos as CSV under a fixed 13-column header, one CRLF-ended row each, in the order given.""" lines: List[str] = [",".join(_HEADER)] for todo in todos: rule = todo.recurrence cells = [ todo.id, todo.title, todo.notes if todo.notes is not None else "", "true" if todo.done else "false", todo.priority, todo.due if todo.due is not None else "", " ".join(todo.tags), "" if rule is None else rule.frequency, "" if rule is None else str(rule.interval), "" if rule is None else rule.anchor, todo.created_at, todo.completed_at if todo.completed_at is not None else "", str(todo.order), ] lines.append(",".join(_field(cell) for cell in cells)) return "".join(line + "\r\n" for line in lines)