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
| from __future__ import annotations
import sys from datetime import datetime from pathlib import Path from typing import Any
import click
from .models import Task, Priority, Status from .storage import JsonStorage, TaskRepository from .config import TaskmanConfig from .formatter import TableFormatter, JsonFormatter, MarkdownFormatter
def get_repo(ctx: click.Context) -> TaskRepository: config = ctx.obj["config"] storage = JsonStorage(config.data_file) return TaskRepository(storage)
@click.group() @click.option("--config", "config_path", type=click.Path(), envvar="TASKMAN_CONFIG", help="Config file path") @click.option("--no-color", is_flag=True, help="Disable colored output") @click.version_option(version="1.0.0", prog_name="taskman") @click.pass_context def cli(ctx: click.Context, config_path: str | None, no_color: bool) -> None: """Taskman - A powerful task management CLI tool.""" ctx.ensure_object(dict) config = TaskmanConfig.load(Path(config_path) if config_path else None) if no_color: config.color_enabled = False ctx.obj["config"] = config
@cli.command() @click.argument("title") @click.option("-d", "--description", default="", help="Task description") @click.option("-p", "--priority", type=click.Choice(["low", "medium", "high", "critical"]), help="Task priority") @click.option("-c", "--category", help="Task category") @click.option("-t", "--tags", help="Comma-separated tags") @click.option("--due", type=click.DateTime(formats=["%Y-%m-%d", "%Y-%m-%d %H:%M"]), help="Due date") @click.pass_context def add( ctx: click.Context, title: str, description: str, priority: str | None, category: str | None, tags: str | None, due: datetime | None, ) -> None: """Add a new task.""" config = ctx.obj["config"] repo = get_repo(ctx)
task = Task( title=title, description=description, priority=Priority.from_str(priority or config.default_priority), category=category or config.default_category, tags=[t.strip() for t in tags.split(",")] if tags else [], due_date=due, )
added = repo.add(task) click.echo(f"✓ Task #{added.id} added: {added.title}")
@cli.command("list") @click.option("-s", "--status", type=click.Choice(["todo", "in_progress", "blocked", "done", "cancelled"]), help="Filter by status") @click.option("-p", "--priority", type=click.Choice(["low", "medium", "high", "critical"]), help="Filter by priority") @click.option("-c", "--category", help="Filter by category") @click.option("-t", "--tag", help="Filter by tag") @click.option("-q", "--query", help="Search in title and description") @click.option("--sort-by", type=click.Choice(["created_at", "updated_at", "priority", "due_date"]), help="Sort field") @click.option("--reverse/--no-reverse", default=True, help="Sort direction") @click.option("-f", "--format", "output_format", type=click.Choice(["table", "json", "markdown"]), help="Output format") @click.pass_context def list_tasks( ctx: click.Context, status: str | None, priority: str | None, category: str | None, tag: str | None, query: str | None, sort_by: str | None, reverse: bool, output_format: str | None, ) -> None: """List tasks with optional filters.""" config = ctx.obj["config"] repo = get_repo(ctx)
tasks = repo.list_all( status=status, category=category, priority=priority, tag=tag, query=query, sort_by=sort_by or config.sort_by, reverse=reverse if sort_by else config.sort_reverse, )
fmt = output_format or config.export_format if fmt == "json": click.echo(JsonFormatter.format_tasks(tasks)) elif fmt == "markdown": click.echo(MarkdownFormatter.format_tasks(tasks)) else: click.echo(TableFormatter.format_tasks(tasks, config.date_format))
@cli.command() @click.argument("task_id", type=int) @click.pass_context def show(ctx: click.Context, task_id: int) -> None: """Show task details.""" config = ctx.obj["config"] repo = get_repo(ctx)
task = repo.get(task_id) if task is None: click.echo(f"Error: Task #{task_id} not found.", err=True) sys.exit(1)
click.echo(TableFormatter.format_task_detail(task, config.date_format))
@cli.command() @click.argument("task_id", type=int) @click.option("-t", "--title", help="New title") @click.option("-d", "--description", help="New description") @click.option("-p", "--priority", type=click.Choice(["low", "medium", "high", "critical"]), help="New priority") @click.option("-c", "--category", help="New category") @click.option("-s", "--status", type=click.Choice(["todo", "in_progress", "blocked", "done", "cancelled"]), help="New status") @click.option("--due", type=click.DateTime(formats=["%Y-%m-%d", "%Y-%m-%d %H:%M"]), help="New due date") @click.option("--add-tags", help="Tags to add (comma-separated)") @click.option("--remove-tags", help="Tags to remove (comma-separated)") @click.pass_context def update( ctx: click.Context, task_id: int, title: str | None, description: str | None, priority: str | None, category: str | None, status: str | None, due: datetime | None, add_tags: str | None, remove_tags: str | None, ) -> None: """Update a task.""" repo = get_repo(ctx)
kwargs: dict[str, Any] = {} if title: kwargs["title"] = title if description is not None: kwargs["description"] = description if priority: kwargs["priority"] = Priority.from_str(priority) if category: kwargs["category"] = category if status: kwargs["status"] = Status.from_str(status) if due: kwargs["due_date"] = due
task = repo.get(task_id) if task is None: click.echo(f"Error: Task #{task_id} not found.", err=True) sys.exit(1)
if add_tags: new_tags = set(task.tags) | {t.strip() for t in add_tags.split(",")} kwargs["tags"] = list(new_tags) if remove_tags: new_tags = set(task.tags) - {t.strip() for t in remove_tags.split(",")} kwargs["tags"] = list(new_tags)
updated = repo.update(task_id, **kwargs) if updated: click.echo(f"✓ Task #{task_id} updated")
@cli.command() @click.argument("task_id", type=int) @click.confirmation_option(prompt="Delete this task?") @click.pass_context def delete(ctx: click.Context, task_id: int) -> None: """Delete a task.""" repo = get_repo(ctx)
if repo.delete(task_id): click.echo(f"✓ Task #{task_id} deleted") else: click.echo(f"Error: Task #{task_id} not found.", err=True) sys.exit(1)
@cli.command() @click.argument("task_id", type=int) @click.pass_context def done(ctx: click.Context, task_id: int) -> None: """Mark a task as done.""" repo = get_repo(ctx)
task = repo.get(task_id) if task is None: click.echo(f"Error: Task #{task_id} not found.", err=True) sys.exit(1)
task.mark_done() repo.update(task_id, status=Status.DONE, completed_at=task.completed_at) click.echo(f"✓ Task #{task_id} marked as done")
@cli.command() @click.argument("query") @click.option("-f", "--format", "output_format", type=click.Choice(["table", "json", "markdown"]), help="Output format") @click.pass_context def search(ctx: click.Context, query: str, output_format: str | None) -> None: """Search tasks by title or description.""" config = ctx.obj["config"] repo = get_repo(ctx)
tasks = repo.list_all(query=query)
fmt = output_format or config.export_format if fmt == "json": click.echo(JsonFormatter.format_tasks(tasks)) elif fmt == "markdown": click.echo(MarkdownFormatter.format_tasks(tasks)) else: click.echo(TableFormatter.format_tasks(tasks, config.date_format))
@cli.command() @click.pass_context def stats(ctx: click.Context) -> None: """Show task statistics.""" repo = get_repo(ctx) counts = repo.count() click.echo(TableFormatter.format_stats(counts))
@cli.command() @click.argument("file_path", type=click.Path()) @click.option("-f", "--format", "export_format", type=click.Choice(["json", "markdown"]), default="json", help="Export format") @click.pass_context def export(ctx: click.Context, file_path: str, export_format: str) -> None: """Export tasks to a file.""" repo = get_repo(ctx) path = Path(file_path)
if export_format == "json": content = JsonFormatter.format_tasks(repo.list_all()) else: content = MarkdownFormatter.format_tasks(repo.list_all())
path.write_text(content, encoding="utf-8") click.echo(f"✓ Exported {len(repo.list_all())} tasks to {file_path}")
@cli.command() @click.argument("file_path", type=click.Path(exists=True)) @click.option("-f", "--format", "import_format", type=click.Choice(["json"]), default="json", help="Import format") @click.pass_context def import_tasks(ctx: click.Context, file_path: str, import_format: str) -> None: """Import tasks from a file.""" repo = get_repo(ctx) path = Path(file_path)
content = path.read_text(encoding="utf-8") data = json.loads(content)
count = repo.import_data(data) click.echo(f"✓ Imported {count} tasks from {file_path}")
@cli.command() @click.option("--show", "show_config", is_flag=True, help="Show current configuration") @click.option("--set", "set_values", nargs=2, multiple=True, help="Set config key=value") @click.pass_context def config_cmd(ctx: click.Context, show_config: bool, set_values: tuple[tuple[str, str], ...]) -> None: """Manage configuration.""" cfg = ctx.obj["config"]
if show_config: click.echo(f"Config file: {TaskmanConfig.get_default_config_path() / 'config.yaml'}") click.echo(f"Data file: {cfg.data_file}") click.echo(f"Priority: {cfg.default_priority}") click.echo(f"Category: {cfg.default_category}") click.echo(f"Date format: {cfg.date_format}") click.echo(f"Color: {cfg.color_enabled}") click.echo(f"Editor: {cfg.editor}") click.echo(f"Pager: {cfg.pager}") return
for key, value in set_values: if hasattr(cfg, key): setattr(cfg, key, value) click.echo(f"✓ Set {key} = {value}") else: click.echo(f"Error: Unknown config key: {key}", err=True)
cfg.save()
def main() -> None: cli(obj={})
if __name__ == "__main__": main()
|