From 8e00e2cdf145a8742c3bec017b29b0a7223d5556 Mon Sep 17 00:00:00 2001 From: lanyuanxiaoyao Date: Wed, 10 Jun 2026 08:56:44 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=20validateTaskFormat?= =?UTF-8?q?=20=E6=A0=A1=E9=AA=8C=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/task-parser.ts | 19 +++++++++++++++++++ tests/core/task-parser.test.ts | 28 +++++++++++++++++++++++++++- 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/core/task-parser.ts b/src/core/task-parser.ts index 2480db3..b3cc9ae 100644 --- a/src/core/task-parser.ts +++ b/src/core/task-parser.ts @@ -14,3 +14,22 @@ export function parseTasks(content: string): TaskItem[] { } return tasks; } + +export class TaskFormatError extends Error { + constructor(message: string) { + super(message); + this.name = this.constructor.name; + } +} + +export function validateTaskFormat(content: string): void { + const tasks = parseTasks(content); + if (tasks.length === 0) { + throw new TaskFormatError("task.md 必须包含至少一个 checkbox 项"); + } + for (const task of tasks) { + if (task.text.trim() === "") { + throw new TaskFormatError("task.md 中每个 checkbox 项必须有非空描述"); + } + } +} diff --git a/tests/core/task-parser.test.ts b/tests/core/task-parser.test.ts index 15e5c38..6201ed7 100644 --- a/tests/core/task-parser.test.ts +++ b/tests/core/task-parser.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from "bun:test"; -import { parseTasks } from "../../src/core/task-parser.ts"; +import { parseTasks, validateTaskFormat, TaskFormatError } from "../../src/core/task-parser.ts"; describe("parseTasks", () => { it("解析标准 checkbox 格式", () => { @@ -52,3 +52,29 @@ describe("parseTasks", () => { expect(tasks.length).toBe(3); }); }); + +describe("validateTaskFormat", () => { + it("合法 task 内容通过校验", () => { + expect(() => validateTaskFormat("- [x] 已完成\n- [ ] 未完成")).not.toThrow(); + }); + + it("无 checkbox 项时抛错", () => { + expect(() => validateTaskFormat("# 标题\n一些描述")).toThrow(TaskFormatError); + }); + + it("空内容抛错", () => { + expect(() => validateTaskFormat("")).toThrow(TaskFormatError); + }); + + it("checkbox 文本为空时抛错", () => { + expect(() => validateTaskFormat("- [ ] \n- [x] 有内容")).toThrow(TaskFormatError); + }); + + it("checkbox 文本仅空格时抛错", () => { + expect(() => validateTaskFormat("- [ ] ")).toThrow(TaskFormatError); + }); + + it("有 checkbox 且文本非空时通过", () => { + expect(() => validateTaskFormat("- [ ] 实现功能A")).not.toThrow(); + }); +});