/** * 第 10 章 · 实战项目 — CLI 入口 * * 用法: * todo add "学 Kotlin" * todo add "做项目" --priority HIGH --due 2026-05-01 * todo list [active|done|all] * todo done * todo rm * todo stats * todo help */ import kotlinx.coroutines.runBlocking fun main(args: Array) = runBlocking { try { val cmd = CommandParser.parse(args) execute(cmd) } catch (e: IllegalArgumentException) { System.err.println("❌ ${e.message}") kotlin.system.exitProcess(1) } catch (e: IllegalStateException) { System.err.println("❌ ${e.message}") kotlin.system.exitProcess(1) } catch (e: Throwable) { System.err.println("❌ 内部错误: ${e.message}") e.printStackTrace() kotlin.system.exitProcess(2) } } private suspend fun execute(cmd: Command) { val todos = Repository.load() when (cmd) { is Command.Add -> { val newTodo = Todo( id = Repository.nextId(todos), title = cmd.title, priority = cmd.priority, due = cmd.due, ) todos.add(newTodo) Repository.save(todos) println("✅ 添加成功: ${newTodo.format()}") } is Command.Done -> { val idx = todos.indexOfFirst { it.id == cmd.id } require(idx >= 0) { "找不到 #${cmd.id}" } todos[idx] = todos[idx].copy(done = true) Repository.save(todos) println("✅ 完成: ${todos[idx].format()}") } is Command.Remove -> { val removed = todos.removeIf { it.id == cmd.id } require(removed) { "找不到 #${cmd.id}" } Repository.save(todos) println("🗑️ 删除 #${cmd.id}") } is Command.List -> { val filtered = todos.filter { when (cmd.filter) { Command.Filter.ACTIVE -> !it.done Command.Filter.DONE -> it.done Command.Filter.ALL -> true } } // 按优先级倒序 + 创建时间正序 val sorted = filtered.sortedWith( compareByDescending { it.priority.ordinal } .thenBy { it.createdAt } ) if (sorted.isEmpty()) { println("(空)") } else { sorted.forEach { println(it.format()) } println("\n${sorted.summary()}") } } Command.Stats -> { println(todos.summary()) // 按优先级分组统计 val byPriority = todos.groupingBy { it.priority }.eachCount() println("按优先级:") Priority.entries.forEach { p -> println(" ${p.name.padEnd(4)}: ${byPriority[p] ?: 0}") } } Command.Help -> println(HELP_TEXT) } } private val HELP_TEXT = """ Todo CLI - 一个用 Kotlin 写的 todo 工具 用法: todo add [--priority LOW|MID|HIGH] [--due YYYY-MM-DD] todo done <id> 标记完成 todo rm <id> 删除 todo list [active|done|all] todo stats 统计 todo help 显示帮助 例子: todo add "学 Kotlin" todo add "做项目" --priority HIGH --due 2026-05-01 todo list active """.trimIndent()