Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3810e442c6 | ||
|
|
6c43e62a4b | ||
|
|
39ee86e308 | ||
|
|
5a7cfeb849 | ||
|
|
e20396ce6b | ||
|
|
f5204f6d8b | ||
|
|
b28ddb9210 |
@@ -35,12 +35,15 @@ Add a new ticket to the backlog.
|
||||
- `--acceptance` (or `-a`): Acceptance criteria (repeat flag for each criterium)
|
||||
- `--plan` (or `-p`): Implementation plan steps (repeat flag for each step)
|
||||
- `--tags` (or `-g`): Tags (comma-separated)
|
||||
- `--due` (or `--due`): Due date in YYYY-MM-DD format
|
||||
- `--due`: Due date in YYYY-MM-DD format. No short form
|
||||
- `--owner` (or `-o`): Owner name
|
||||
- `--priority`: Priority level, 1 (most urgent) to 5 (least). Unset if omitted
|
||||
- `--priority`: Priority level, 1 (most urgent) to 5 (least). Unset if omitted. No short form
|
||||
|
||||
Tags are `-g`, not `-t`: `-t` is the title, and passing it twice is an error. Each
|
||||
plan step needs its own `-p`, since a bare value after one is not a second step.
|
||||
|
||||
```bash
|
||||
worklane add -t "Implement login" -d "Add user login page" -t login,auth -p "Design UI" "Build backend" "Write tests" --due 2026-06-01 --owner "ilya"
|
||||
worklane add -t "Implement login" -d "Add user login page" -g login,auth -p "Design UI" -p "Build backend" -p "Write tests" --due 2026-06-01 --owner "ilya"
|
||||
```
|
||||
|
||||
When there's multiple acceptance criteria, add each using a separate `--acceptance` or `-a` flag.
|
||||
@@ -79,7 +82,7 @@ worklane show "ticket title or uuid"
|
||||
Move a ticket between statuses.
|
||||
|
||||
**Positional arguments:**
|
||||
- `<id>`: Ticket UUID (8+ characters) or title
|
||||
- `<id>`: Ticket UUID prefix (4+ characters) or title
|
||||
|
||||
**Required options:**
|
||||
- `--status <target>`: Target status (`backlog`, `committed`, `reviewing`, `done`)
|
||||
@@ -98,12 +101,49 @@ worklane mv a1b2c3d4 --status committed # Move by UUID prefix
|
||||
worklane mv "My Ticket" --status done -f # Move by title with force
|
||||
```
|
||||
|
||||
### `worklane set`
|
||||
|
||||
Replace fields on an existing ticket. Only the fields given are touched; ticked
|
||||
criteria and handwritten sections are left alone. At least one field is required.
|
||||
|
||||
**Positional arguments:**
|
||||
- `<ticket>`: Ticket UUID prefix (4+ characters) or title
|
||||
|
||||
**Options:** `--title`, `--description` (or `-d`), `--acceptance` (or `-a`), `--plan`
|
||||
(or `-p`), `--tags` (or `-g`), `--due`, `--priority`
|
||||
|
||||
Owner is not settable here, and neither is status: `mv` owns status. Changing the
|
||||
title renames the file, keeping the UUID.
|
||||
|
||||
```bash
|
||||
worklane set a1b2c3d4 --priority 1
|
||||
worklane set a1b2c3d4 --title "A clearer title" --due 2026-12-31
|
||||
worklane set a1b2c3d4 -a "First criterium" -a "Second criterium"
|
||||
```
|
||||
|
||||
### `worklane append`
|
||||
|
||||
Add to a section without replacing what is there. The description gains a new
|
||||
paragraph; criteria and steps go on the end of their lists, steps numbered on from
|
||||
the last. At least one section is required.
|
||||
|
||||
**Positional arguments:**
|
||||
- `<ticket>`: Ticket UUID prefix (4+ characters) or title
|
||||
|
||||
**Options:** `--description` (or `-d`), `--acceptance` (or `-a`), `--plan` (or `-p`)
|
||||
|
||||
```bash
|
||||
worklane append a1b2c3d4 -d "A paragraph amending the description."
|
||||
worklane append a1b2c3d4 -a "One more criterium"
|
||||
worklane append a1b2c3d4 -p "A later step"
|
||||
```
|
||||
|
||||
### `worklane comment`
|
||||
|
||||
Add a comment to a ticket.
|
||||
|
||||
**Positional arguments:**
|
||||
- `<ticket>`: Ticket UUID (8+ characters) or title
|
||||
- `<ticket>`: Ticket UUID prefix (4+ characters) or title
|
||||
- `<body>`: Comment text
|
||||
|
||||
Comments are stored as timestamped markdown files in `.worklane/comments/<ticket-uuid>/` and include the git author and timestamp.
|
||||
@@ -122,4 +162,5 @@ worklane comment a1b2c3d4 "LGTM, approved"
|
||||
2. Use `worklane ls [status]` to view tickets by status
|
||||
3. Use `worklane show <id>` to view full ticket details
|
||||
4. Use `worklane mv <id> --status <target>` to move tickets through the workflow
|
||||
5. Use `worklane comment <ticket> <body>` to add notes to tickets
|
||||
5. Use `worklane set <ticket>` to correct a field, or `worklane append <ticket>` to add to a section
|
||||
6. Use `worklane comment <ticket> <body>` to add notes to tickets
|
||||
|
||||
+184
-24
@@ -38,6 +38,39 @@ async function run(cmd: string[], context: ToolContext): Promise<string> {
|
||||
return stdout.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Description lines as worklane wants them, one --description value per line,
|
||||
* blank ones included.
|
||||
*
|
||||
* cmd_add joins the values with a single newline, so an empty value is how a
|
||||
* paragraph break is spelled. Dropping the blanks here, which is what the old
|
||||
* filter(Boolean) did, collapsed every multi paragraph description into a single
|
||||
* paragraph, against this tool's own instruction to separate paragraphs with
|
||||
* newlines.
|
||||
*
|
||||
* Only the ends are trimmed, and only trailing whitespace within a line. Leading
|
||||
* whitespace is content: it is what makes a nested markdown list or an indented
|
||||
* block survive the trip.
|
||||
*/
|
||||
function descriptionLines(text: string): string[] {
|
||||
const lines = text.split("\n").map((line: string) => line.trimEnd());
|
||||
|
||||
let start = 0;
|
||||
let end = lines.length;
|
||||
while (start < end && lines[start] === "") start++;
|
||||
while (end > start && lines[end - 1] === "") end--;
|
||||
|
||||
return lines.slice(start, end);
|
||||
}
|
||||
|
||||
/** One value per non-empty line, for the arguments that hold a list of items. */
|
||||
function itemLines(text: string): string[] {
|
||||
return text
|
||||
.split("\n")
|
||||
.map((line: string) => line.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
export const init = tool({
|
||||
description:
|
||||
"Initialize worklane in the current project. Creates the .worklane/ directory with backlog, committed, reviewing, and done subdirectories.",
|
||||
@@ -54,28 +87,37 @@ export const init = tool({
|
||||
export const add = tool({
|
||||
description:
|
||||
"Add a new ticket to the worklane backlog. Requires a title. Description, acceptance criteria, and plan each support multiple lines (one item per line). Tags are comma-separated.",
|
||||
// Title is the only required field. Every other flag is left off entirely when
|
||||
// the field is omitted, so an unmarked schema only forced the model to invent a
|
||||
// value for fields it had nothing to say about.
|
||||
args: {
|
||||
title: tool.schema
|
||||
.string()
|
||||
.describe("Ticket title (required)"),
|
||||
description: tool.schema
|
||||
.string()
|
||||
.describe("Description text. Use newlines between paragraphs."),
|
||||
.describe("Description text. Use newlines between paragraphs.")
|
||||
.optional(),
|
||||
acceptance: tool.schema
|
||||
.string()
|
||||
.describe("Acceptance criteria, one per line. Put each criterium on its own line."),
|
||||
.describe("Acceptance criteria, one per line. Put each criterium on its own line.")
|
||||
.optional(),
|
||||
plan: tool.schema
|
||||
.string()
|
||||
.describe("Implementation plan steps, one per line. Put each step on its own line."),
|
||||
.describe("Implementation plan steps, one per line. Put each step on its own line.")
|
||||
.optional(),
|
||||
tags: tool.schema
|
||||
.string()
|
||||
.describe("Comma-separated tags, e.g. 'bug,frontend,urgent'"),
|
||||
.describe("Comma-separated tags, e.g. 'bug,frontend,urgent'")
|
||||
.optional(),
|
||||
due: tool.schema
|
||||
.string()
|
||||
.describe("Due date in YYYY-MM-DD format"),
|
||||
.describe("Due date in YYYY-MM-DD format")
|
||||
.optional(),
|
||||
owner: tool.schema
|
||||
.string()
|
||||
.describe("Ticket owner name. If omitted, defaults to the git user."),
|
||||
.describe("Ticket owner name. If omitted, defaults to the git user.")
|
||||
.optional(),
|
||||
priority: tool.schema
|
||||
.string()
|
||||
.describe("Priority level, 1 (most urgent) to 5 (least). Left unset if omitted.")
|
||||
@@ -87,27 +129,21 @@ export const add = tool({
|
||||
}
|
||||
const cmd: string[] = ["add", "--title", args.title];
|
||||
if (args.description) {
|
||||
args.description
|
||||
.split("\n")
|
||||
.map((l: string) => l.trim())
|
||||
.filter(Boolean)
|
||||
.forEach((line: string) => cmd.push("--description", line));
|
||||
descriptionLines(args.description).forEach((line: string) =>
|
||||
cmd.push("--description", line),
|
||||
);
|
||||
}
|
||||
|
||||
// Blanks are dropped from these two on purpose: each value is one criterium or
|
||||
// one step, so an empty line between them is spacing rather than content.
|
||||
if (args.acceptance) {
|
||||
args.acceptance
|
||||
.split("\n")
|
||||
.map((l: string) => l.trim())
|
||||
.filter(Boolean)
|
||||
.forEach((line: string) => cmd.push("--acceptance", line));
|
||||
itemLines(args.acceptance).forEach((line: string) =>
|
||||
cmd.push("--acceptance", line),
|
||||
);
|
||||
}
|
||||
|
||||
if (args.plan) {
|
||||
args.plan
|
||||
.split("\n")
|
||||
.map((l: string) => l.trim())
|
||||
.filter(Boolean)
|
||||
.forEach((line: string) => cmd.push("--plan", line));
|
||||
itemLines(args.plan).forEach((line: string) => cmd.push("--plan", line));
|
||||
}
|
||||
|
||||
if (args.tags) cmd.push("--tags", args.tags);
|
||||
@@ -155,7 +191,7 @@ export const show = tool({
|
||||
args: {
|
||||
id: tool.schema
|
||||
.string()
|
||||
.describe("Ticket UUID (8+ chars) or title substring (required)"),
|
||||
.describe("Ticket UUID prefix (4+ chars) or title substring (required)"),
|
||||
},
|
||||
async execute(args: Record<string, any>, context: ToolContext) {
|
||||
if (!args.id) {
|
||||
@@ -175,7 +211,7 @@ export const mv = tool({
|
||||
args: {
|
||||
ticket: tool.schema
|
||||
.string()
|
||||
.describe("Ticket UUID (8+ chars) or title substring (required)"),
|
||||
.describe("Ticket UUID prefix (4+ chars) or title substring (required)"),
|
||||
status: tool.schema
|
||||
.enum(["backlog", "committed", "reviewing", "done"])
|
||||
.describe("Target status (required)"),
|
||||
@@ -207,7 +243,7 @@ export const comment = tool({
|
||||
args: {
|
||||
ticket: tool.schema
|
||||
.string()
|
||||
.describe("Ticket UUID (8+ chars) or title substring (required)"),
|
||||
.describe("Ticket UUID prefix (4+ chars) or title substring (required)"),
|
||||
body: tool.schema
|
||||
.string()
|
||||
.describe("Comment body text (required). Supports markdown formatting and multiple paragraphs separated by newlines."),
|
||||
@@ -234,3 +270,127 @@ export const comment = tool({
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
export const set = tool({
|
||||
description:
|
||||
"Replace fields on an existing worklane ticket. Only the fields given are touched; everything else in the file, including ticked criteria and handwritten sections, is left alone. Owner is not settable here, use chown. Status is not settable here, use mv. To add to a section instead of replacing it, use append.",
|
||||
args: {
|
||||
ticket: tool.schema
|
||||
.string()
|
||||
.describe("Ticket UUID prefix (4+ chars) or title substring (required)"),
|
||||
title: tool.schema
|
||||
.string()
|
||||
.describe("New title. The file is renamed to match, keeping the UUID.")
|
||||
.optional(),
|
||||
description: tool.schema
|
||||
.string()
|
||||
.describe("New description, replacing the whole section. Use newlines between paragraphs.")
|
||||
.optional(),
|
||||
acceptance: tool.schema
|
||||
.string()
|
||||
.describe("New acceptance criteria, one per line, replacing the whole list.")
|
||||
.optional(),
|
||||
plan: tool.schema
|
||||
.string()
|
||||
.describe("New implementation plan steps, one per line, replacing the whole list.")
|
||||
.optional(),
|
||||
tags: tool.schema
|
||||
.string()
|
||||
.describe("New comma-separated tags, replacing the existing ones.")
|
||||
.optional(),
|
||||
due: tool.schema
|
||||
.string()
|
||||
.describe("New due date in YYYY-MM-DD format")
|
||||
.optional(),
|
||||
priority: tool.schema
|
||||
.string()
|
||||
.describe("New priority level, 1 (most urgent) to 5 (least)")
|
||||
.optional(),
|
||||
},
|
||||
async execute(args: Record<string, any>, context: ToolContext) {
|
||||
if (!args.ticket) {
|
||||
return "Error setting fields: ticket is required";
|
||||
}
|
||||
|
||||
const cmd: string[] = ["set", args.ticket];
|
||||
if (args.title) cmd.push("--title", args.title);
|
||||
if (args.description) {
|
||||
descriptionLines(args.description).forEach((line: string) =>
|
||||
cmd.push("--description", line),
|
||||
);
|
||||
}
|
||||
if (args.acceptance) {
|
||||
itemLines(args.acceptance).forEach((line: string) =>
|
||||
cmd.push("--acceptance", line),
|
||||
);
|
||||
}
|
||||
if (args.plan) {
|
||||
itemLines(args.plan).forEach((line: string) => cmd.push("--plan", line));
|
||||
}
|
||||
if (args.tags) cmd.push("--tags", args.tags);
|
||||
if (args.due) cmd.push("--due", args.due);
|
||||
if (args.priority) cmd.push("--priority", String(args.priority));
|
||||
|
||||
if (cmd.length === 2) {
|
||||
return "Error setting fields: give at least one field to change";
|
||||
}
|
||||
|
||||
try {
|
||||
return await run(cmd, context);
|
||||
} catch (err: any) {
|
||||
return `Error setting fields: ${err.message}`;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
export const append = tool({
|
||||
description:
|
||||
"Add to a section of an existing worklane ticket without replacing what is there. The description gains a new paragraph; acceptance criteria and plan steps are added to the end of their lists, with steps numbered on from the last. Ticked criteria and handwritten content are left alone. To replace a section outright, use set.",
|
||||
args: {
|
||||
ticket: tool.schema
|
||||
.string()
|
||||
.describe("Ticket UUID prefix (4+ chars) or title substring (required)"),
|
||||
description: tool.schema
|
||||
.string()
|
||||
.describe("Text to add as a new paragraph at the end of the description.")
|
||||
.optional(),
|
||||
acceptance: tool.schema
|
||||
.string()
|
||||
.describe("Acceptance criteria to add, one per line.")
|
||||
.optional(),
|
||||
plan: tool.schema
|
||||
.string()
|
||||
.describe("Implementation plan steps to add, one per line.")
|
||||
.optional(),
|
||||
},
|
||||
async execute(args: Record<string, any>, context: ToolContext) {
|
||||
if (!args.ticket) {
|
||||
return "Error appending: ticket is required";
|
||||
}
|
||||
|
||||
const cmd: string[] = ["append", args.ticket];
|
||||
if (args.description) {
|
||||
descriptionLines(args.description).forEach((line: string) =>
|
||||
cmd.push("--description", line),
|
||||
);
|
||||
}
|
||||
if (args.acceptance) {
|
||||
itemLines(args.acceptance).forEach((line: string) =>
|
||||
cmd.push("--acceptance", line),
|
||||
);
|
||||
}
|
||||
if (args.plan) {
|
||||
itemLines(args.plan).forEach((line: string) => cmd.push("--plan", line));
|
||||
}
|
||||
|
||||
if (cmd.length === 2) {
|
||||
return "Error appending: give at least one section to add to";
|
||||
}
|
||||
|
||||
try {
|
||||
return await run(cmd, context);
|
||||
} catch (err: any) {
|
||||
return `Error appending: ${err.message}`;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -31,12 +31,34 @@
|
||||
- Use `unwrap_or_else(|| expr)` for lazy defaults, `unwrap_or(val)` for eager defaults
|
||||
- Use `anyhow!()` with context strings that include identifying info (e.g. UUID, title) not bare values
|
||||
|
||||
### CLI Arguments
|
||||
- The prose arguments carry `allow_hyphen_values`, via the `PROSE` constant in `command.rs`: `add --title`, `--description`, `--acceptance`, `--plan`, and the `comment` body. Ticket text quotes flag names constantly, and without it a criterion reading `--print is supported` is parsed as a flag and the whole ticket is refused with nothing written
|
||||
- **The trade:** on those five arguments a genuinely mistyped flag now lands as content rather than raising a usage error. That is the right way round for prose and the wrong way round for anything else, which is why `due`, `priority`, `tags`, `owner` and `status` are deliberately left without it. A mistyped flag there is still a usage error, exit 2, and no ticket is written. Do not add `PROSE` to a new argument unless it holds prose
|
||||
- The ticket positionals (`show <id>`, `mv <ticket>`, `comment <ticket>`) are also left alone, so a search term starting with a hyphen is a usage error. Reachable now that a hyphen-leading title can be stored: use the UUID, or put the flags first and separate with `--`, as in `mv --status committed -- -leading-title`
|
||||
- A bare `--` is a value when it follows an option (`--title -- ` stores `--`) and clap's end-of-options marker when it sits in a positional. So a `comment` body of exactly `--` needs its own separator, `comment <ticket> -- --`. Without it the body is reported missing and nothing is written, which is a clear failure rather than a silent drop
|
||||
- `add` has no positionals, so anything after a bare `--` is an unexpected argument and fails
|
||||
- **A paragraph break in a description is an empty `--description` value.** `cmd_add` joins the values with a single newline, so `-d "First." -d "" -d "Second."` writes the blank line. `trim_blank_ends()` drops blank values at either end, so a break never lands against a section heading, and an all-blank description reads as no description. Interior runs are kept verbatim rather than collapsed
|
||||
- `--acceptance` and `--plan` are lists, one criterium or step per value, so a blank there is spacing rather than content and the opencode wrapper drops it. Only `--description` preserves blanks
|
||||
|
||||
### Editing a Ticket
|
||||
- `set` replaces a field, `append` adds to a section. The verb carries the meaning, so no flag needs a replace-or-append prefix, and `append` only offers the sections that hold multiple lines
|
||||
- **One field, one writer.** `set` has no `--owner` (that is `chown`'s, once it exists) and no `--status` (that is `mv`'s). Do not add either
|
||||
- Sections are a table in `util.rs`: `DESCRIPTION`, `ACCEPTANCE`, `PLAN`, each with a heading, a label, the placeholder `add` writes when empty, and a `SectionKind`. Adding a section later is one entry, not edits in both commands
|
||||
- Everything is targeted line surgery, never a regenerated file. That is what keeps a ticked criterion ticked and a handwritten `## Notes` section intact when an unrelated field changes. `section_body()` finds the lines to touch, `set_metadata_line()` does the metadata, and every other byte is copied through
|
||||
- Appending to a numbered section continues from the count of steps already there and does not renumber what is above it, so a handwritten line in the section survives exactly as written
|
||||
- Appending to an empty section replaces the placeholder rather than following it, or the ticket would read `_No description provided._` above its description
|
||||
- An empty value is a paragraph break for the three sections and a usage error for the scalars, via `non_empty` in `command.rs`. Clearing a field is not supported yet, and the error says so rather than guessing
|
||||
- No-op detection compares the whole file before and after each edit, so a field set to the value it already holds is reported unchanged and nothing is written
|
||||
- `find_ticket_file()` matches on the uuid, never the title. Duplicate titles are allowed, so a title scan can land on a different ticket than the one resolved: `mv <uuid-of-second>` used to move the first ticket sharing its title
|
||||
- `write_then_replace()` is the only way a ticket file is written. Content first, rename second, so a failure leaves a correct ticket under a stale name rather than a half-written one
|
||||
|
||||
### Color and Output
|
||||
- Use `color_text()` helper for colored output — it respects `should_use_colors()` (terminal detection)
|
||||
- Color codes are defined in `get_color()`: red (31), cyan (36), orange (33), green (32), grey (38;5;8), magenta (1;35), brightred (38;5;9)
|
||||
- Reset color with `\x1b[0m` after colored text
|
||||
- Bold uses `\x1b[1;35m` (magenta bold)
|
||||
- Always test color output works correctly in both terminal and pipe modes
|
||||
- `quiet_broken_pipe()` runs first in `main`, restoring the default `SIGPIPE` disposition. A truncated pipe therefore kills the process with signal 13, which a shell reports as 141, instead of making `println!` panic. Do not wrap prints to handle write errors and do not reinstate `SIG_IGN`; the exit codes are documented in the README
|
||||
|
||||
### Color Guideline
|
||||
- UUID → red (31)
|
||||
@@ -54,11 +76,14 @@
|
||||
- Rules under headings are measured on the displayed name in characters, never on the raw line or in bytes
|
||||
- `resolve_ticket()` scans all status directories — it's the single source for ticket lookup by UUID prefix, title, or filename
|
||||
- `parse_ticket_field()` handles extracting metadata values from markdown format
|
||||
- `move_ticket_file()` stages the updated content in a temp file under `.worklane/`, renames it over the source, and only then renames the file into the target directory. Do not reorder these: renaming first and writing second leaves a ticket in its new directory claiming the old status, and writing to the target then deleting the source puts it in two directories at once. The temp lives outside the status directories so a leftover is never read as a ticket. A failure at the last step leaves the ticket in its old directory with a Status one move ahead, which the next `mv` corrects
|
||||
- Field lookup, read and write, is scoped to the lines under the `## Metadata` heading and anchored to the start of the line. Prose above it is free text: tickets in this repo quote field markers in their descriptions, and an unscoped search reads or rewrites those instead. `set_status_field()` carries the same scoping
|
||||
|
||||
### Ticket Resolution
|
||||
- `resolve_ticket()` returns `(status, title, content)` tuple
|
||||
- Priority: exact UUID prefix (8+ chars) > title substring > filename substring
|
||||
- Three tiers, evaluated in order: UUID prefix > title substring > filename substring. The first non-empty tier wins outright and later tiers are not consulted. This is not cosmetic: ticket titles reference other tickets by id, so a flat OR of the three reported an exact prefix match as ambiguous against whichever title mentioned it
|
||||
- The UUID tier applies from `MIN_ID_SEARCH` (4) characters up. Not 8: `ls` prints `SHORT_ID_WIDTH` (7) characters, so a longer minimum would drop the printed id out of the UUID tier and let any title quoting it win instead. Below the minimum the search is text, so `show 641` is a title search
|
||||
- The filename tier earns its place by reaching the middle of a UUID, which the prefix tier cannot. It is also why a short UUID search still resolves under a longer minimum, just at the wrong precedence, so a test for the minimum needs a decoy title to be meaningful
|
||||
- Ambiguous matches (multiple results) print options and exit(1)
|
||||
- Never return empty strings for required fields — use `_Not set_` or `_None_` as defaults
|
||||
|
||||
|
||||
Generated
+2
-1
@@ -1029,13 +1029,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "worklane"
|
||||
version = "0.3.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"assert_cmd",
|
||||
"assert_fs",
|
||||
"chrono",
|
||||
"clap",
|
||||
"libc",
|
||||
"tempfile",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "worklane"
|
||||
version = "0.3.0"
|
||||
version = "0.5.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
@@ -8,6 +8,7 @@ clap = { version = "4", features = ["derive"] }
|
||||
anyhow = "1"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
assert_cmd = "2"
|
||||
|
||||
@@ -8,6 +8,26 @@ Worklane is a local Kanban flow for agentic software development.
|
||||
| `worklane init` | Creates `.worklane/` with backlog, committed, reviewing, done directories |
|
||||
| `worklane add` | Creates a ticket in backlog with `--title`, `--description`, `--acceptance`, `--plan`, `--tags`, `--due`, `--owner`, `--priority` flags |
|
||||
| `worklane ls [status]` | Lists tickets, sorted by priority then title. Optional positional status, and `--priority <1-5>` |
|
||||
| `worklane show <id>` | Shows ticket by UUID prefix (8+ chars) or title substring |
|
||||
| `worklane show <id>` | Shows ticket by UUID prefix (4+ chars), title substring, or filename substring |
|
||||
| `worklane mv <id> --status <target> [-f]` | Moves ticket between statuses. Default: forward only, one stage at a time. `-f` bypasses both restrictions |
|
||||
| `worklane set <ticket>` | Replaces fields with `--title`, `--description`, `--acceptance`, `--plan`, `--tags`, `--due`, `--priority`. At least one required. Changing the title renames the file, keeping the UUID |
|
||||
| `worklane append <ticket>` | Adds to a section with `--description`, `--acceptance`, `--plan`. At least one required. The description gains a paragraph; list items go on the end, steps numbered on from the last |
|
||||
| `worklane comment <ticket> <body>` | Adds a comment to a ticket by UUID or title |
|
||||
|
||||
## Exit codes
|
||||
| Code | Meaning |
|
||||
|------|---------|
|
||||
| 0 | Success |
|
||||
| 1 | An error, such as no matching ticket or an ambiguous search |
|
||||
| 2 | A usage mistake, such as an unknown flag |
|
||||
| 141 | Output was piped to a reader that stopped early, for example `worklane ls \| head -3` |
|
||||
|
||||
141 is 128 + 13, the shell's way of reporting death by `SIGPIPE`. Worklane restores
|
||||
the default signal disposition so a truncated pipe is quiet, the way `head` and
|
||||
`sort` are, rather than printing a panic. A script using `set -o pipefail` will see
|
||||
141 for a case that is not a failure, so guard for it there.
|
||||
|
||||
Whether a truncated pipe reports 141 or 0 depends on the size of the output, not on
|
||||
the command. A pipe holds 64 KiB, so a listing that fits lands in the buffer whole
|
||||
and the writer never learns the reader left, giving 0. Only output past that gets far
|
||||
enough to be cut off. Either way nothing is printed to stderr.
|
||||
|
||||
+108
-4
@@ -37,6 +37,32 @@ pub struct Cli {
|
||||
pub command: Command,
|
||||
}
|
||||
|
||||
/// Reject an empty value at parse time, so it lands as a usage error rather than a
|
||||
/// runtime one.
|
||||
///
|
||||
/// An empty value looks like a way to clear a field, and clearing is not supported
|
||||
/// yet. Refusing it keeps the gap visible and stops an accidentally empty variable
|
||||
/// from silently blanking a field. Only the scalars use this: for the multi-line
|
||||
/// sections an empty value is a paragraph break.
|
||||
fn non_empty(raw: &str) -> Result<String, String> {
|
||||
if raw.trim().is_empty() {
|
||||
return Err("value cannot be empty, and clearing a field is not supported yet".to_string());
|
||||
}
|
||||
|
||||
Ok(raw.to_string())
|
||||
}
|
||||
|
||||
/// Arguments that carry prose, and therefore have to accept a value starting with
|
||||
/// a hyphen.
|
||||
///
|
||||
/// Ticket text quotes flag names constantly, and without this a criterion reading
|
||||
/// "--print is supported" is parsed as a flag and the whole ticket is refused. The
|
||||
/// trade, spelled out in AGENTS.md: on these arguments a genuinely mistyped flag
|
||||
/// now lands as content instead of raising a usage error. That is the right way
|
||||
/// round for prose, and it is why `due`, `priority`, `tags`, `owner` and `status`
|
||||
/// are deliberately left without it.
|
||||
const PROSE: bool = true;
|
||||
|
||||
#[derive(clap::Subcommand)]
|
||||
pub enum Command {
|
||||
/// Initialize worklane in the current project
|
||||
@@ -45,19 +71,19 @@ pub enum Command {
|
||||
/// Add a new ticket to the backlog
|
||||
Add {
|
||||
/// Ticket title
|
||||
#[arg(short, long)]
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
title: String,
|
||||
|
||||
/// Ticket description. Use multiple flags to create multiline descriptions.
|
||||
#[arg(short, long)]
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
description: Vec<String>,
|
||||
|
||||
/// Acceptance criteria. Accepts multiple flags, each will be interpreted as a single criterium
|
||||
#[arg(short, long)]
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
acceptance: Vec<String>,
|
||||
|
||||
/// Implementation plan. Accepts multiple flags, each will be interpreted as a single step
|
||||
#[arg(short, long)]
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
plan: Vec<String>,
|
||||
|
||||
/// Tags (comma-separated)
|
||||
@@ -108,12 +134,19 @@ pub enum Command {
|
||||
force: bool,
|
||||
},
|
||||
|
||||
/// Replace fields on an existing ticket
|
||||
Set(SetArgs),
|
||||
|
||||
/// Add to a section of an existing ticket
|
||||
Append(AppendArgs),
|
||||
|
||||
/// Add a comment to a ticket
|
||||
Comment {
|
||||
/// Ticket UUID or title
|
||||
ticket: String,
|
||||
|
||||
/// Comment body (required)
|
||||
#[arg(allow_hyphen_values = PROSE)]
|
||||
body: String,
|
||||
|
||||
/// Owner
|
||||
@@ -121,3 +154,74 @@ pub enum Command {
|
||||
owner: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
/// `set` replaces a field outright. Owner is deliberately absent: `chown` owns that
|
||||
/// field, and status is `mv`'s, so no field has two writers.
|
||||
///
|
||||
/// The group makes at least one field mandatory, so a bare `worklane set <ticket>` is
|
||||
/// a usage error rather than a silent no-op.
|
||||
#[derive(clap::Args)]
|
||||
#[command(group(
|
||||
clap::ArgGroup::new("set_fields")
|
||||
.required(true)
|
||||
.multiple(true)
|
||||
.args(["title", "description", "acceptance", "plan", "tags", "due", "priority"])
|
||||
))]
|
||||
pub struct SetArgs {
|
||||
/// Ticket UUID or title
|
||||
pub ticket: String,
|
||||
|
||||
/// Replace the ticket title, renaming the file to match
|
||||
#[arg(short, long, allow_hyphen_values = PROSE, value_parser = non_empty)]
|
||||
pub title: Option<String>,
|
||||
|
||||
/// Replace the description. Repeat the flag for more lines, empty for a paragraph break
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
pub description: Vec<String>,
|
||||
|
||||
/// Replace the acceptance criteria. Repeat the flag, one criterium per value
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
pub acceptance: Vec<String>,
|
||||
|
||||
/// Replace the implementation plan. Repeat the flag, one step per value
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
pub plan: Vec<String>,
|
||||
|
||||
/// Replace the tags
|
||||
#[arg(short = 'g', long, value_parser = non_empty)]
|
||||
pub tags: Vec<String>,
|
||||
|
||||
/// Replace the due date (YYYY-MM-DD)
|
||||
#[arg(long, value_parser = non_empty)]
|
||||
pub due: Option<String>,
|
||||
|
||||
/// Replace the priority, 1 (most urgent) to 5 (least)
|
||||
#[arg(long, value_parser = priority_level)]
|
||||
pub priority: Option<u8>,
|
||||
}
|
||||
|
||||
/// `append` only offers the sections that hold multiple lines, since appending to a
|
||||
/// scalar has no meaning.
|
||||
#[derive(clap::Args)]
|
||||
#[command(group(
|
||||
clap::ArgGroup::new("append_fields")
|
||||
.required(true)
|
||||
.multiple(true)
|
||||
.args(["description", "acceptance", "plan"])
|
||||
))]
|
||||
pub struct AppendArgs {
|
||||
/// Ticket UUID or title
|
||||
pub ticket: String,
|
||||
|
||||
/// Add a paragraph to the description. Repeat the flag for more lines within it
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
pub description: Vec<String>,
|
||||
|
||||
/// Add acceptance criteria. Repeat the flag, one criterium per value
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
pub acceptance: Vec<String>,
|
||||
|
||||
/// Add implementation plan steps, numbered on from the last. Repeat the flag
|
||||
#[arg(short, long, allow_hyphen_values = PROSE)]
|
||||
pub plan: Vec<String>,
|
||||
}
|
||||
|
||||
+299
-38
@@ -4,6 +4,7 @@ use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::command::{AppendArgs, SetArgs};
|
||||
use crate::util::*;
|
||||
|
||||
pub fn cmd_init(start: &Path) -> Result<()> {
|
||||
@@ -136,6 +137,9 @@ pub fn cmd_add(
|
||||
return Err(anyhow!("A ticket with this title already exists."));
|
||||
}
|
||||
|
||||
// Joined with a single newline, so an empty value is how a caller spells a
|
||||
// paragraph break and an all-blank description is no description at all.
|
||||
let description = trim_blank_ends(description);
|
||||
let description_text = if description.is_empty() {
|
||||
"_No description provided._".to_string()
|
||||
} else {
|
||||
@@ -311,6 +315,120 @@ pub fn cmd_show(search: &str, worklane_dir: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write `content` over `path`, without ever leaving half a file behind.
|
||||
///
|
||||
/// Staged in a temp file and renamed into place, because `fs::write` truncates before
|
||||
/// it writes and a partial write would corrupt the ticket. The temp sits under
|
||||
/// `.worklane/` rather than beside the ticket, so a leftover from a hard kill is
|
||||
/// invisible to ticket lookup and to the listing instead of showing up as a stray
|
||||
/// untitled ticket.
|
||||
fn write_then_replace(
|
||||
worklane_dir: &Path,
|
||||
path: &Path,
|
||||
filename: &str,
|
||||
content: &str,
|
||||
title: &str,
|
||||
) -> Result<()> {
|
||||
let temp = worklane_dir.join(format!(".wl-{}.tmp", filename));
|
||||
|
||||
if let Err(e) = fs::write(&temp, content) {
|
||||
let _ = fs::remove_file(&temp);
|
||||
return Err(anyhow!(
|
||||
"Could not stage the update for ticket '{}' at {}: {}",
|
||||
title,
|
||||
temp.display(),
|
||||
e
|
||||
));
|
||||
}
|
||||
|
||||
if let Err(e) = fs::rename(&temp, path) {
|
||||
let _ = fs::remove_file(&temp);
|
||||
return Err(anyhow!(
|
||||
"Could not write ticket '{}' at {}: {}",
|
||||
title,
|
||||
path.display(),
|
||||
e
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The ticket file in `dir` carrying `uuid`.
|
||||
///
|
||||
/// Matched on the uuid, not the title. Titles are not unique, `add` allows duplicates
|
||||
/// on purpose, so a title scan could land on a different ticket than the one that was
|
||||
/// resolved: `mv <uuid-of-second>` moved the first ticket sharing its title.
|
||||
fn find_ticket_file(dir: &Path, uuid: &str, title: &str) -> Result<String> {
|
||||
if uuid.trim().is_empty() || is_unknown_value(uuid) {
|
||||
return Err(anyhow!(
|
||||
"Ticket '{}' has no ID field, so its file cannot be located",
|
||||
title
|
||||
));
|
||||
}
|
||||
|
||||
for entry in fs::read_dir(dir)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
if !path.extension().map_or(false, |e| e == "md") {
|
||||
continue;
|
||||
}
|
||||
|
||||
let name = match path.file_name() {
|
||||
Some(name) => name.to_string_lossy().to_string(),
|
||||
None => continue,
|
||||
};
|
||||
|
||||
if name.starts_with(uuid) {
|
||||
return Ok(name);
|
||||
}
|
||||
}
|
||||
|
||||
Err(anyhow!(
|
||||
"Could not find the file for ticket '{}' in {}",
|
||||
title,
|
||||
dir.display()
|
||||
))
|
||||
}
|
||||
|
||||
/// Put `content` in `filename` and move it from `from` to `to`, without ever
|
||||
/// leaving the ticket in two status directories or with half a file in it.
|
||||
///
|
||||
/// Two atomic steps, in this order. The content is staged in a temp file and
|
||||
/// renamed over the source, so a partial write is thrown away and the original is
|
||||
/// untouched. Only then is the file renamed into the target directory.
|
||||
///
|
||||
/// The old order renamed first and wrote second, so a failure in between left the
|
||||
/// ticket sitting in its new directory still claiming the old status. Writing
|
||||
/// straight to the target and deleting the source afterwards would instead have it
|
||||
/// in both directories at once. Neither happens here. The worst case is a ticket
|
||||
/// still in its old directory carrying a Status field one move ahead, which the
|
||||
/// next `mv` corrects, since the directory is what decides the current status.
|
||||
fn move_ticket_file(
|
||||
worklane_dir: &Path,
|
||||
from: &Path,
|
||||
to: &Path,
|
||||
filename: &str,
|
||||
content: &str,
|
||||
title: &str,
|
||||
) -> Result<()> {
|
||||
let source = from.join(filename);
|
||||
let dest = to.join(filename);
|
||||
|
||||
write_then_replace(worklane_dir, &source, filename, content, title)?;
|
||||
|
||||
// The content is correct and in one place by now, so a failure here leaves the
|
||||
// ticket where it started rather than half moved.
|
||||
fs::rename(&source, &dest).map_err(|e| {
|
||||
anyhow!(
|
||||
"Could not move ticket '{}' to {}: {}",
|
||||
title,
|
||||
dest.display(),
|
||||
e
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn cmd_mv(ticket_id: &str, target_status: &str, force: bool, start: &Path) -> Result<()> {
|
||||
let valid_statuses = ["backlog", "committed", "reviewing", "done"];
|
||||
let forward_order = ["backlog", "committed", "reviewing", "done"];
|
||||
@@ -324,7 +442,7 @@ pub fn cmd_mv(ticket_id: &str, target_status: &str, force: bool, start: &Path) -
|
||||
}
|
||||
|
||||
let worklane_dir = find_worklane_dir(start)?;
|
||||
let (current_status, title, _) = resolve_ticket(ticket_id, &worklane_dir)?;
|
||||
let (current_status, title, resolved) = resolve_ticket(ticket_id, &worklane_dir)?;
|
||||
|
||||
let current_idx = forward_order
|
||||
.iter()
|
||||
@@ -360,45 +478,21 @@ pub fn cmd_mv(ticket_id: &str, target_status: &str, force: bool, start: &Path) -
|
||||
let current_path = worklane_dir.join(¤t_status);
|
||||
let target_path = worklane_dir.join(target_status);
|
||||
|
||||
// Find the ticket file
|
||||
let mut found_filename = String::new();
|
||||
for entry in fs::read_dir(¤t_path)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
if path.extension().map_or(false, |e| e == "md") {
|
||||
let file_content = fs::read_to_string(&path)?;
|
||||
let file_title = file_content
|
||||
.lines()
|
||||
.find(|l| l.starts_with("# "))
|
||||
.map(|l| l[2..].trim())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
if file_title == title {
|
||||
found_filename = path.file_name().unwrap().to_string_lossy().to_string();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Updated before the file is even located, so a ticket without a Status field is
|
||||
// refused for that reason rather than for whatever the lookup notices first.
|
||||
let content = set_status_field(&resolved, target_status, &title)?;
|
||||
|
||||
if found_filename.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"Could not find ticket file in {}",
|
||||
color_text(¤t_status, "orange")
|
||||
));
|
||||
}
|
||||
let found_filename =
|
||||
find_ticket_file(¤t_path, &parse_ticket_field(&resolved, "ID"), &title)?;
|
||||
|
||||
// Read and update the ticket content before touching the filesystem, so a ticket
|
||||
// without a Status field is never half-moved.
|
||||
let source_path = current_path.join(&found_filename);
|
||||
let content = fs::read_to_string(&source_path)?;
|
||||
let content = set_status_field(&content, target_status, &title)?;
|
||||
|
||||
// Move the file
|
||||
let dest_path = target_path.join(&found_filename);
|
||||
fs::rename(&source_path, &dest_path)?;
|
||||
|
||||
// Write back updated content
|
||||
fs::write(&dest_path, content)?;
|
||||
move_ticket_file(
|
||||
&worklane_dir,
|
||||
¤t_path,
|
||||
&target_path,
|
||||
&found_filename,
|
||||
&content,
|
||||
&title,
|
||||
)?;
|
||||
|
||||
println!(
|
||||
"Moved ticket '{}' from {} to {}",
|
||||
@@ -488,3 +582,170 @@ pub fn cmd_comment(
|
||||
println!("Comment added to '{}' ({})", title, filename);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The sections `set` and `append` can rewrite, paired with the flag that carries them.
|
||||
///
|
||||
/// One list, so both commands walk the same table and a section added later needs no
|
||||
/// change here.
|
||||
fn section_args<'a>(
|
||||
description: &'a [String],
|
||||
acceptance: &'a [String],
|
||||
plan: &'a [String],
|
||||
) -> [(&'static Section, &'a [String]); 3] {
|
||||
[
|
||||
(&DESCRIPTION, description),
|
||||
(&ACCEPTANCE, acceptance),
|
||||
(&PLAN, plan),
|
||||
]
|
||||
}
|
||||
|
||||
/// Write the ticket back, renaming the file when a new title changes its slug.
|
||||
///
|
||||
/// The content goes down first and the rename second, the same order and for the same
|
||||
/// reason as `mv`: a failure at the rename leaves a correct ticket under a stale name,
|
||||
/// which lookup still finds by uuid or title, rather than a half-written one.
|
||||
fn save_ticket(
|
||||
worklane_dir: &Path,
|
||||
status: &str,
|
||||
uuid: &str,
|
||||
title: &str,
|
||||
new_title: Option<&String>,
|
||||
content: &str,
|
||||
) -> Result<()> {
|
||||
let status_path = worklane_dir.join(status);
|
||||
let filename = find_ticket_file(&status_path, uuid, title)?;
|
||||
let path = status_path.join(&filename);
|
||||
|
||||
write_then_replace(worklane_dir, &path, &filename, content, title)?;
|
||||
|
||||
// The uuid is kept, so the new name cannot collide with another ticket, and an
|
||||
// unchanged slug means there is nothing to rename.
|
||||
if let Some(new_title) = new_title {
|
||||
let renamed = format!("{}_{}.md", uuid, slug(new_title));
|
||||
if renamed != filename {
|
||||
let destination = status_path.join(&renamed);
|
||||
fs::rename(&path, &destination).map_err(|e| {
|
||||
anyhow!(
|
||||
"Ticket '{}' was updated but could not be renamed to {}: {}",
|
||||
title,
|
||||
destination.display(),
|
||||
e
|
||||
)
|
||||
})?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn report(fields: &[&str], title: &str, verb: &str) {
|
||||
if fields.is_empty() {
|
||||
println!("No changes to '{}'", color_text(title, "green"));
|
||||
return;
|
||||
}
|
||||
|
||||
println!(
|
||||
"{} {} on '{}'",
|
||||
verb,
|
||||
fields.join(", "),
|
||||
color_text(title, "green")
|
||||
);
|
||||
}
|
||||
|
||||
pub fn cmd_set(args: &SetArgs, start: &Path) -> Result<()> {
|
||||
let worklane_dir = find_worklane_dir(start)?;
|
||||
let (status, title, original) = resolve_ticket(&args.ticket, &worklane_dir)?;
|
||||
let uuid = parse_ticket_field(&original, "ID");
|
||||
|
||||
let mut content = original.clone();
|
||||
let mut changed: Vec<&str> = Vec::new();
|
||||
|
||||
// Each edit is compared against the content going in, so a field set to the value
|
||||
// it already holds is reported as unchanged rather than claimed as an update.
|
||||
let mut apply = |content: &mut String, field: &'static str, next: String| {
|
||||
if *content != next {
|
||||
content.clone_from(&next);
|
||||
changed.push(field);
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(new_title) = &args.title {
|
||||
let next = set_title(&content, new_title)?;
|
||||
apply(&mut content, "title", next);
|
||||
}
|
||||
|
||||
for (section, values) in section_args(&args.description, &args.acceptance, &args.plan) {
|
||||
if values.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let items = section.normalise(values);
|
||||
if items.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"An empty {} is not a way to clear the section, and clearing is not supported yet",
|
||||
section.label
|
||||
));
|
||||
}
|
||||
|
||||
let next = set_section_body(&content, section, &items)?;
|
||||
apply(&mut content, section.label, next);
|
||||
}
|
||||
|
||||
if !args.tags.is_empty() {
|
||||
let next = set_metadata_field(&content, "Tags", &args.tags.join(", "), &title)?;
|
||||
apply(&mut content, "tags", next);
|
||||
}
|
||||
|
||||
if let Some(due) = &args.due {
|
||||
let next = set_metadata_field(&content, "Due", due, &title)?;
|
||||
apply(&mut content, "due", next);
|
||||
}
|
||||
|
||||
if let Some(priority) = args.priority {
|
||||
let next = set_metadata_field(&content, "Priority", &priority.to_string(), &title)?;
|
||||
apply(&mut content, "priority", next);
|
||||
}
|
||||
|
||||
if changed.is_empty() {
|
||||
report(&changed, &title, "Updated");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let renamed = changed.contains(&"title").then_some(()).and(args.title.as_ref());
|
||||
save_ticket(&worklane_dir, &status, &uuid, &title, renamed, &content)?;
|
||||
|
||||
let shown = args.title.clone().unwrap_or(title);
|
||||
report(&changed, &shown, "Updated");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn cmd_append(args: &AppendArgs, start: &Path) -> Result<()> {
|
||||
let worklane_dir = find_worklane_dir(start)?;
|
||||
let (status, title, original) = resolve_ticket(&args.ticket, &worklane_dir)?;
|
||||
let uuid = parse_ticket_field(&original, "ID");
|
||||
|
||||
let mut content = original.clone();
|
||||
let mut changed: Vec<&str> = Vec::new();
|
||||
|
||||
for (section, values) in section_args(&args.description, &args.acceptance, &args.plan) {
|
||||
if values.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let items = section.normalise(values);
|
||||
if items.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"Nothing to append to the {}: every value given was blank",
|
||||
section.label
|
||||
));
|
||||
}
|
||||
|
||||
content = append_section_body(&content, section, &items)?;
|
||||
changed.push(section.label);
|
||||
}
|
||||
|
||||
save_ticket(&worklane_dir, &status, &uuid, &title, None, &content)?;
|
||||
|
||||
report(&changed, &title, "Appended to");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+23
@@ -9,7 +9,28 @@ use command::*;
|
||||
use handlers::*;
|
||||
use util::*;
|
||||
|
||||
/// Die quietly when stdout is closed early, the way every other Unix tool does.
|
||||
///
|
||||
/// Rust sets `SIGPIPE` to `SIG_IGN` at startup, which turns a closed pipe into an
|
||||
/// io error that `println!` panics on. So `worklane ls | head -3` printed a panic
|
||||
/// and a backtrace instead of three lines, which is both alarming and easy to
|
||||
/// mistake for a real fault. Restoring the default handler makes `| head` behave.
|
||||
///
|
||||
/// The cost is that a truncated pipe now kills the process with signal 13 rather
|
||||
/// than returning a code, so `pipefail` sees 141 instead of 101. That is what
|
||||
/// `head` and `sort` do, and it is recorded in the README.
|
||||
fn quiet_broken_pipe() {
|
||||
// SAFETY: setting a signal disposition to the default is always valid, and
|
||||
// this runs before any thread is spawned.
|
||||
unsafe {
|
||||
libc::signal(libc::SIGPIPE, libc::SIG_DFL);
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
// Before any output, so no write can beat it to a closed pipe.
|
||||
quiet_broken_pipe();
|
||||
|
||||
let cli = Cli::parse();
|
||||
|
||||
let start = std::env::current_dir()?;
|
||||
@@ -49,6 +70,8 @@ fn main() -> Result<()> {
|
||||
status,
|
||||
force,
|
||||
} => cmd_mv(&ticket, &status, force, &start),
|
||||
Command::Set(args) => cmd_set(&args, &start),
|
||||
Command::Append(args) => cmd_append(&args, &start),
|
||||
Command::Comment { ticket, body, owner } => cmd_comment(&ticket, &body, &owner, &start),
|
||||
}
|
||||
}
|
||||
|
||||
+328
-27
@@ -177,11 +177,28 @@ fn ambiguous(search: &str, matches: &[(String, String, String, String)]) -> anyh
|
||||
anyhow!(message)
|
||||
}
|
||||
|
||||
pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, String, String)> {
|
||||
let statuses = status_dirs();
|
||||
let mut matches: Vec<(String, String, String, String)> = Vec::new();
|
||||
/// Shortest search tried as a UUID prefix. Below it the search is text, so a one or
|
||||
/// two character term is a title search rather than a prefix matching half the board.
|
||||
///
|
||||
/// Four, not eight. The guard this replaces read `short_id.len() >= 8`, and `short_id`
|
||||
/// there was always the full 36 character uuid, so it was always true and any length
|
||||
/// already worked. Requiring eight would have broken the id the tool prints itself:
|
||||
/// `ls` shows [`SHORT_ID_WIDTH`] characters, and pasting that back has to resolve.
|
||||
pub const MIN_ID_SEARCH: usize = 4;
|
||||
|
||||
for status in &statuses {
|
||||
pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, String, String)> {
|
||||
let search_lower = search.to_lowercase();
|
||||
let long_enough_for_an_id = search.chars().count() >= MIN_ID_SEARCH;
|
||||
|
||||
// Three tiers, filled in one pass and consulted in order. A uuid prefix has to win
|
||||
// outright rather than join a flat list: ticket titles reference other tickets by
|
||||
// id, so an exact prefix match was reported as ambiguous against whichever title
|
||||
// happened to mention it.
|
||||
let mut by_id: Vec<(String, String, String, String)> = Vec::new();
|
||||
let mut by_title: Vec<(String, String, String, String)> = Vec::new();
|
||||
let mut by_filename: Vec<(String, String, String, String)> = Vec::new();
|
||||
|
||||
for status in status_dirs() {
|
||||
let status_path = worklane_dir.join(status);
|
||||
if !status_path.exists() {
|
||||
continue;
|
||||
@@ -206,23 +223,34 @@ pub fn resolve_ticket(search: &str, worklane_dir: &Path) -> Result<(String, Stri
|
||||
.file_stem()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
let short_id = filename.split('_').next().unwrap_or("");
|
||||
let uuid = filename.split('_').next().unwrap_or("");
|
||||
|
||||
let search_lower = search.to_lowercase();
|
||||
let title_lower = title.to_lowercase();
|
||||
let filename_lower = filename.to_lowercase();
|
||||
let by_prefix = long_enough_for_an_id && uuid.to_lowercase().starts_with(&search_lower);
|
||||
let in_title = title.to_lowercase().contains(&search_lower);
|
||||
// Still reaches the middle of a uuid, which the prefix tier cannot.
|
||||
let in_filename = filename.to_lowercase().contains(&search_lower);
|
||||
|
||||
let id_match =
|
||||
short_id.to_lowercase().starts_with(&search_lower) && short_id.len() >= 8;
|
||||
let title_match = title_lower.contains(&search_lower);
|
||||
let filename_match = filename_lower.contains(&search_lower);
|
||||
if !(by_prefix || in_title || in_filename) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if id_match || title_match || filename_match {
|
||||
matches.push((status.to_string(), title, content, short_id.to_string()));
|
||||
let found = (status.to_string(), title, content, uuid.to_string());
|
||||
if by_prefix {
|
||||
by_id.push(found);
|
||||
} else if in_title {
|
||||
by_title.push(found);
|
||||
} else {
|
||||
by_filename.push(found);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut matches = match (by_id.is_empty(), by_title.is_empty()) {
|
||||
(false, _) => by_id,
|
||||
(true, false) => by_title,
|
||||
(true, true) => by_filename,
|
||||
};
|
||||
|
||||
if matches.is_empty() {
|
||||
return Err(anyhow!("No ticket found matching '{}'", search));
|
||||
}
|
||||
@@ -550,12 +578,20 @@ fn is_status_line(line: &str) -> bool {
|
||||
body.starts_with("**Status**:") || body.starts_with("**-Status**:")
|
||||
}
|
||||
|
||||
// Rewrite the Status field in the Metadata section, leaving every other line untouched.
|
||||
//
|
||||
// Scoped to the section for the same reason as parse_ticket_field: a description line
|
||||
// shaped like the Status field would otherwise be rewritten in its place, corrupting
|
||||
// the prose and leaving the real metadata stale.
|
||||
pub fn set_status_field(content: &str, target_status: &str, title: &str) -> Result<String> {
|
||||
/// Rewrite one field in the Metadata section, leaving every other line untouched.
|
||||
///
|
||||
/// Scoped to the section for the same reason as `parse_ticket_field`: a description
|
||||
/// line shaped like a metadata field would otherwise be rewritten in its place,
|
||||
/// corrupting the prose and leaving the real metadata stale.
|
||||
///
|
||||
/// The matcher is a parameter because Status has a legacy spelling to repair, which no
|
||||
/// other field has.
|
||||
fn set_metadata_line(
|
||||
content: &str,
|
||||
field: &str,
|
||||
value: &str,
|
||||
matches: impl Fn(&str) -> bool,
|
||||
) -> Option<String> {
|
||||
let mut updated = String::with_capacity(content.len());
|
||||
let mut in_metadata = false;
|
||||
let mut found = false;
|
||||
@@ -565,9 +601,62 @@ pub fn set_status_field(content: &str, target_status: &str, title: &str) -> Resu
|
||||
in_metadata = is_metadata_heading(line);
|
||||
}
|
||||
|
||||
if in_metadata && !found && is_status_line(line) {
|
||||
updated.push_str("- **Status**: ");
|
||||
updated.push_str(target_status);
|
||||
if in_metadata && !found && matches(line) {
|
||||
updated.push_str("- **");
|
||||
updated.push_str(field);
|
||||
updated.push_str("**: ");
|
||||
updated.push_str(value);
|
||||
found = true;
|
||||
} else {
|
||||
updated.push_str(line);
|
||||
}
|
||||
updated.push('\n');
|
||||
}
|
||||
|
||||
if found { Some(updated) } else { None }
|
||||
}
|
||||
|
||||
pub fn set_status_field(content: &str, target_status: &str, title: &str) -> Result<String> {
|
||||
set_metadata_line(content, "Status", target_status, is_status_line).ok_or_else(|| {
|
||||
anyhow!(
|
||||
"Ticket '{}' has no Status field in its Metadata section",
|
||||
title
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Rewrite a metadata field other than Status.
|
||||
///
|
||||
/// A field that is not already in the file is an error rather than an insertion. Every
|
||||
/// ticket `add` writes carries the full set in a fixed order, and nothing else writes
|
||||
/// these files, so a missing field means a hand-made ticket and guessing where the line
|
||||
/// belongs would be inventing a format.
|
||||
pub fn set_metadata_field(content: &str, field: &str, value: &str, title: &str) -> Result<String> {
|
||||
let prefix = format!("**{}**:", field);
|
||||
|
||||
set_metadata_line(content, field, value, |line| {
|
||||
metadata_field_body(line).starts_with(&prefix)
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
anyhow!(
|
||||
"Ticket '{}' has no {} field in its Metadata section",
|
||||
title,
|
||||
field
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Rewrite the title heading, the first `# ` line in the file.
|
||||
///
|
||||
/// `## ` headings do not match: the second character has to be a space.
|
||||
pub fn set_title(content: &str, title: &str) -> Result<String> {
|
||||
let mut updated = String::with_capacity(content.len());
|
||||
let mut found = false;
|
||||
|
||||
for line in content.lines() {
|
||||
if !found && line.starts_with("# ") {
|
||||
updated.push_str("# ");
|
||||
updated.push_str(title);
|
||||
found = true;
|
||||
} else {
|
||||
updated.push_str(line);
|
||||
@@ -576,10 +665,7 @@ pub fn set_status_field(content: &str, target_status: &str, title: &str) -> Resu
|
||||
}
|
||||
|
||||
if !found {
|
||||
return Err(anyhow!(
|
||||
"Ticket '{}' has no Status field in its Metadata section",
|
||||
title
|
||||
));
|
||||
return Err(anyhow!("Ticket '{}' has no title heading", title));
|
||||
}
|
||||
|
||||
Ok(updated)
|
||||
@@ -597,6 +683,193 @@ pub fn format_created_at(created_at: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// How a section stores the lines the tool owns.
|
||||
pub enum SectionKind {
|
||||
/// Lines as written, a blank one acting as a paragraph break.
|
||||
Prose,
|
||||
/// One `- [ ] ` item per line.
|
||||
Checklist,
|
||||
/// One `N. ` step per line.
|
||||
Numbered,
|
||||
}
|
||||
|
||||
/// A section of a ticket whose body `set` and `append` can rewrite.
|
||||
///
|
||||
/// A table rather than a match arm per section, so adding a section later is one entry
|
||||
/// here instead of edits spread across both commands.
|
||||
pub struct Section {
|
||||
pub heading: &'static str,
|
||||
/// How the section is named in output, lowercase so it reads the same way the
|
||||
/// metadata field labels do.
|
||||
pub label: &'static str,
|
||||
/// What `add` writes when the section is left empty. Treated as no content, so
|
||||
/// appending to an empty section replaces the placeholder rather than following it.
|
||||
pub placeholder: &'static str,
|
||||
pub kind: SectionKind,
|
||||
}
|
||||
|
||||
pub const DESCRIPTION: Section = Section {
|
||||
heading: "## Description",
|
||||
label: "description",
|
||||
placeholder: "_No description provided._",
|
||||
kind: SectionKind::Prose,
|
||||
};
|
||||
|
||||
pub const ACCEPTANCE: Section = Section {
|
||||
heading: "## Acceptance Criteria",
|
||||
label: "acceptance criteria",
|
||||
placeholder: "_No acceptance criteria provided._",
|
||||
kind: SectionKind::Checklist,
|
||||
};
|
||||
|
||||
pub const PLAN: Section = Section {
|
||||
heading: "## Implementation Plan",
|
||||
label: "implementation plan",
|
||||
placeholder: "_No implementation plan provided._",
|
||||
kind: SectionKind::Numbered,
|
||||
};
|
||||
|
||||
impl Section {
|
||||
/// The values a caller supplied, reduced to the lines that belong in the body.
|
||||
///
|
||||
/// Prose keeps interior blanks, since those are paragraph breaks. A list has one
|
||||
/// item per value, so a blank there is nothing at all.
|
||||
pub fn normalise(&self, values: &[String]) -> Vec<String> {
|
||||
match self.kind {
|
||||
SectionKind::Prose => trim_blank_ends(values).to_vec(),
|
||||
SectionKind::Checklist | SectionKind::Numbered => values
|
||||
.iter()
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.cloned()
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `items` as body lines, numbering from `first` where the section is numbered.
|
||||
fn render(&self, items: &[String], first: usize) -> Vec<String> {
|
||||
match self.kind {
|
||||
SectionKind::Prose => items.to_vec(),
|
||||
SectionKind::Checklist => items.iter().map(|i| format!("- [ ] {}", i)).collect(),
|
||||
SectionKind::Numbered => items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(offset, step)| format!("{}. {}", first + offset, step))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the line opens with `N. `, the shape a numbered step is stored in.
|
||||
fn is_numbered_item(line: &str) -> bool {
|
||||
let digits = line.chars().take_while(|c| c.is_ascii_digit()).count();
|
||||
// ASCII digits are one byte each, so the count is also the byte offset.
|
||||
digits > 0 && line[digits..].starts_with(". ")
|
||||
}
|
||||
|
||||
/// The lines of a section's body, excluding the heading, running to the next `## `
|
||||
/// heading or the end of the file.
|
||||
fn section_body(lines: &[&str], heading: &str) -> Option<std::ops::Range<usize>> {
|
||||
let at = lines.iter().position(|line| line.trim_end() == heading)?;
|
||||
let after = at + 1;
|
||||
let end = lines[after..]
|
||||
.iter()
|
||||
.position(|line| line.starts_with("## "))
|
||||
.map_or(lines.len(), |offset| after + offset);
|
||||
|
||||
Some(after..end)
|
||||
}
|
||||
|
||||
/// Where the body's content ends, ignoring the blank lines that separate it from
|
||||
/// whatever follows.
|
||||
fn body_content_end(lines: &[&str], body: &std::ops::Range<usize>) -> usize {
|
||||
let mut end = body.end;
|
||||
while end > body.start && lines[end - 1].trim().is_empty() {
|
||||
end -= 1;
|
||||
}
|
||||
end
|
||||
}
|
||||
|
||||
fn join_lines(lines: &[String]) -> String {
|
||||
let mut out = lines.join("\n");
|
||||
out.push('\n');
|
||||
out
|
||||
}
|
||||
|
||||
/// Replace a section's body with `items`, leaving every line outside it untouched.
|
||||
pub fn set_section_body(content: &str, section: &Section, items: &[String]) -> Result<String> {
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
let body = section_body(&lines, section.heading)
|
||||
.ok_or_else(|| anyhow!("Ticket has no {} section", section.label))?;
|
||||
|
||||
let mut out: Vec<String> = lines[..body.start].iter().map(|l| l.to_string()).collect();
|
||||
out.extend(section.render(items, 1));
|
||||
// One blank line before whatever section follows, matching how `add` writes it.
|
||||
if body.end < lines.len() {
|
||||
out.push(String::new());
|
||||
}
|
||||
out.extend(lines[body.end..].iter().map(|l| l.to_string()));
|
||||
|
||||
Ok(join_lines(&out))
|
||||
}
|
||||
|
||||
/// Add `items` to the end of a section's body.
|
||||
///
|
||||
/// Prose gains a blank line first, so the addition reads as a new paragraph. A numbered
|
||||
/// section continues from the count of steps already there rather than renumbering what
|
||||
/// is above it, which keeps any handwritten line in the section exactly as it was.
|
||||
pub fn append_section_body(content: &str, section: &Section, items: &[String]) -> Result<String> {
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
let body = section_body(&lines, section.heading)
|
||||
.ok_or_else(|| anyhow!("Ticket has no {} section", section.label))?;
|
||||
|
||||
let at = body_content_end(&lines, &body);
|
||||
let existing: Vec<&&str> = lines[body.start..at]
|
||||
.iter()
|
||||
.filter(|line| !line.trim().is_empty())
|
||||
.collect();
|
||||
|
||||
// An empty section is a placeholder, and following it with a paragraph would leave
|
||||
// "_No description provided._" above the description.
|
||||
if existing.len() == 1 && existing[0].trim() == section.placeholder {
|
||||
return set_section_body(content, section, items);
|
||||
}
|
||||
|
||||
let first = match section.kind {
|
||||
SectionKind::Numbered => 1 + existing.iter().filter(|l| is_numbered_item(l)).count(),
|
||||
_ => 1,
|
||||
};
|
||||
|
||||
let mut out: Vec<String> = lines[..at].iter().map(|l| l.to_string()).collect();
|
||||
if matches!(section.kind, SectionKind::Prose) && at > body.start {
|
||||
out.push(String::new());
|
||||
}
|
||||
out.extend(section.render(items, first));
|
||||
out.extend(lines[at..].iter().map(|l| l.to_string()));
|
||||
|
||||
Ok(join_lines(&out))
|
||||
}
|
||||
|
||||
/// The slice with blank values trimmed from both ends, interior ones kept.
|
||||
///
|
||||
/// Description values are joined with a single newline, so an empty value is how a
|
||||
/// caller spells a paragraph break. That makes the interior blanks content, while a
|
||||
/// blank at either end would only open or close the section with a gap.
|
||||
pub fn trim_blank_ends(values: &[String]) -> &[String] {
|
||||
let first = values.iter().position(|v| !v.trim().is_empty());
|
||||
|
||||
match first {
|
||||
None => &[],
|
||||
Some(first) => {
|
||||
// Guaranteed to find one, since `first` is itself non-blank.
|
||||
let last = match values.iter().rposition(|v| !v.trim().is_empty()) {
|
||||
Some(last) => last,
|
||||
None => first,
|
||||
};
|
||||
&values[first..=last]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn status_dirs() -> Vec<&'static str> {
|
||||
vec!["backlog", "committed", "reviewing", "done"]
|
||||
}
|
||||
@@ -1087,6 +1360,34 @@ mod tests {
|
||||
assert!(rendered.ends_with("after\n"), "{rendered:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_values_are_trimmed_from_the_ends_but_kept_inside() {
|
||||
let owned = |values: &[&str]| -> Vec<String> {
|
||||
values.iter().map(|v| v.to_string()).collect()
|
||||
};
|
||||
|
||||
// A break between paragraphs is content
|
||||
let two_paragraphs = owned(&["First.", "", "Second."]);
|
||||
assert_eq!(trim_blank_ends(&two_paragraphs), two_paragraphs.as_slice());
|
||||
|
||||
// A run of them is kept verbatim rather than collapsed
|
||||
let wide = owned(&["A", "", "", "B"]);
|
||||
assert_eq!(trim_blank_ends(&wide), wide.as_slice());
|
||||
|
||||
// The ends are not
|
||||
assert_eq!(
|
||||
trim_blank_ends(&owned(&["", " ", "Only.", "", ""])),
|
||||
owned(&["Only."]).as_slice()
|
||||
);
|
||||
|
||||
// Nothing but blanks is nothing at all
|
||||
assert!(trim_blank_ends(&owned(&["", " ", ""])).is_empty());
|
||||
assert!(trim_blank_ends(&[]).is_empty());
|
||||
|
||||
// A single value survives either way
|
||||
assert_eq!(trim_blank_ends(&owned(&["One."])), owned(&["One."]).as_slice());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_level_in_range_parses() {
|
||||
for level in 1..=5u8 {
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
use assert_fs::TempDir;
|
||||
use assert_fs::fixture::{PathChild, PathCreateDir};
|
||||
use std::fs;
|
||||
use std::os::unix::process::ExitStatusExt;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
const BIN_NAME: &str = env!("CARGO_BIN_EXE_worklane");
|
||||
|
||||
/// What a truncated pipe costs: the process dies by signal rather than returning a
|
||||
/// code, so a shell reports 128 + 13. Asserted here so the README and the code stay
|
||||
/// honest about what `pipefail` sees.
|
||||
const SIGPIPE: i32 = 13;
|
||||
|
||||
/// A pipe holds 64 KiB on Linux before a write blocks. Below that the whole listing
|
||||
/// lands in the buffer, the writer never notices the reader is gone, and a test
|
||||
/// proves nothing. Every ticket here is one `ls` row of roughly a hundred bytes.
|
||||
const TICKETS: usize = 1200;
|
||||
|
||||
fn setup_crowded_board(temp: &TempDir) -> std::path::PathBuf {
|
||||
let worklane = temp.child(".worklane");
|
||||
worklane.create_dir_all().unwrap();
|
||||
|
||||
for dir in ["backlog", "committed", "reviewing", "done"] {
|
||||
worklane.child(dir).create_dir_all().unwrap();
|
||||
}
|
||||
|
||||
let backlog = worklane.path().join("backlog");
|
||||
for i in 0..TICKETS {
|
||||
let id = format!("{:08x}-0000-4000-8000-000000000000", i);
|
||||
let title = format!("A ticket with a title long enough to fill a row {}", i);
|
||||
fs::write(
|
||||
backlog.join(format!("{}_ticket-{}.md", id, i)),
|
||||
format!(
|
||||
"# {}\n\n## Metadata\n\n\
|
||||
- **ID**: {}\n\
|
||||
- **Owner**: someone with a name\n\
|
||||
- **Status**: backlog\n",
|
||||
title, id
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
temp.path().to_path_buf()
|
||||
}
|
||||
|
||||
fn panic_text(stderr: &str) -> bool {
|
||||
stderr.contains("panicked")
|
||||
|| stderr.contains("failed printing to stdout")
|
||||
|| stderr.contains("Broken pipe")
|
||||
}
|
||||
|
||||
/// The reader closed before the writer finished: dropping the read end here is the
|
||||
/// same thing `head` does when it has seen enough, without the timing luck.
|
||||
fn run_with_stdout_dropped(dir: &std::path::Path, args: &[&str]) -> std::process::Output {
|
||||
let mut child = Command::new(BIN_NAME)
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
|
||||
drop(child.stdout.take().unwrap());
|
||||
child.wait_with_output().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ls_says_nothing_when_the_reader_goes_away() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let dir = setup_crowded_board(&temp);
|
||||
|
||||
let output = run_with_stdout_dropped(&dir, &["ls", "backlog"]);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
assert!(!panic_text(&stderr), "stderr was {stderr:?}");
|
||||
assert_ne!(output.status.code(), Some(101), "panicked instead of dying");
|
||||
assert_eq!(
|
||||
output.status.signal(),
|
||||
Some(SIGPIPE),
|
||||
"expected death by SIGPIPE, got {:?}",
|
||||
output.status
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_says_nothing_when_the_reader_goes_away() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let dir = setup_crowded_board(&temp);
|
||||
|
||||
// A ticket carrying more comments than a pipe will hold, since the comment list
|
||||
// is the longest thing show prints and the last thing it reaches.
|
||||
let comments = temp
|
||||
.path()
|
||||
.join(".worklane")
|
||||
.join("comments")
|
||||
.join("00000000-0000-4000-8000-000000000000");
|
||||
fs::create_dir_all(&comments).unwrap();
|
||||
for i in 0..800 {
|
||||
fs::write(
|
||||
comments.join(format!("2026082{}_120000_{:06}.md", i % 10, i)),
|
||||
format!(
|
||||
"**Comment**\nA comment body long enough to be worth buffering, number {}.\n\n\
|
||||
**Author**: someone\n**Time**: 2026-08-20 12:00:00\n",
|
||||
i
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let output = run_with_stdout_dropped(&dir, &["show", "00000000-0000-4000"]);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
assert!(!panic_text(&stderr), "stderr was {stderr:?}");
|
||||
assert_ne!(output.status.code(), Some(101), "panicked instead of dying");
|
||||
assert_eq!(
|
||||
output.status.signal(),
|
||||
Some(SIGPIPE),
|
||||
"expected death by SIGPIPE, got {:?}",
|
||||
output.status
|
||||
);
|
||||
}
|
||||
|
||||
/// The real invocation, through a shell into `head`, which is how this was found.
|
||||
/// Whether the writer gets far enough to notice is up to the scheduler, so this
|
||||
/// asserts only what must hold either way: `head` gets its lines and nothing
|
||||
/// alarming reaches stderr.
|
||||
#[test]
|
||||
fn a_shell_pipeline_into_head_prints_lines_and_not_a_panic() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let dir = setup_crowded_board(&temp);
|
||||
|
||||
let output = Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(format!("{} ls backlog | head -3", BIN_NAME))
|
||||
.current_dir(&dir)
|
||||
.output()
|
||||
.unwrap();
|
||||
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
|
||||
assert_eq!(stdout.lines().count(), 3, "stdout was {stdout:?}");
|
||||
assert!(!panic_text(&stderr), "stderr was {stderr:?}");
|
||||
}
|
||||
|
||||
/// The reset must not touch anything else: a real failure still returns its code.
|
||||
#[test]
|
||||
fn real_exit_codes_are_unchanged() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let dir = setup_crowded_board(&temp);
|
||||
|
||||
let ok = Command::new(BIN_NAME)
|
||||
.args(["ls", "backlog"])
|
||||
.current_dir(&dir)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(ok.status.code(), Some(0));
|
||||
|
||||
let missing = Command::new(BIN_NAME)
|
||||
.args(["show", "no-such-ticket-anywhere"])
|
||||
.current_dir(&dir)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(missing.status.code(), Some(1));
|
||||
|
||||
let misuse = Command::new(BIN_NAME)
|
||||
.arg("--bogus")
|
||||
.current_dir(&dir)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(misuse.status.code(), Some(2));
|
||||
}
|
||||
@@ -262,3 +262,198 @@ fn add_rejects_a_level_outside_the_range() {
|
||||
let count = fs::read_dir(worklane.join("backlog")).unwrap().count();
|
||||
assert_eq!(count, 0, "a ticket was written despite a bad level");
|
||||
}
|
||||
|
||||
/// Ticket text quotes flag names constantly, and the space form is what both a
|
||||
/// person and the opencode wrapper produce. Every one of these used to be refused
|
||||
/// with "unexpected argument found", writing no ticket at all.
|
||||
#[test]
|
||||
fn add_accepts_prose_values_that_begin_with_a_hyphen() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["add", "--title", "-t is a flag name"])
|
||||
.args(["--description", "-x does nothing"])
|
||||
.args(["--acceptance", "--print should be supported"])
|
||||
.args(["--plan", "-f skips the check"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let content = only_ticket(&worklane);
|
||||
|
||||
// Stored verbatim, hyphens and all
|
||||
assert!(content.contains("# -t is a flag name"), "was {content:?}");
|
||||
assert!(content.contains("-x does nothing"), "was {content:?}");
|
||||
assert!(
|
||||
content.contains("- [ ] --print should be supported"),
|
||||
"was {content:?}"
|
||||
);
|
||||
assert!(content.contains("1. -f skips the check"), "was {content:?}");
|
||||
}
|
||||
|
||||
/// The docs and the habit both use it, and it reaches the parser as one token, so
|
||||
/// it has to keep working alongside the space form.
|
||||
#[test]
|
||||
fn add_still_accepts_the_equals_form() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["add", "--title=-x equals form"])
|
||||
.args(["--acceptance=--print via equals"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let content = only_ticket(&worklane);
|
||||
assert!(content.contains("# -x equals form"), "was {content:?}");
|
||||
assert!(
|
||||
content.contains("- [ ] --print via equals"),
|
||||
"was {content:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Never silently dropped: a value that is nothing but hyphens is content.
|
||||
#[test]
|
||||
fn add_stores_a_title_that_is_only_hyphens() {
|
||||
for bare in ["-", "--", "---"] {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["add", "--title", bare])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let content = only_ticket(&worklane);
|
||||
assert!(
|
||||
content.starts_with(&format!("# {}\n", bare)),
|
||||
"for {bare:?}: {content:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The other half of the trade. These arguments were deliberately left alone, so a
|
||||
/// mistyped flag there is still a usage error rather than stored text.
|
||||
#[test]
|
||||
fn add_still_rejects_a_mistyped_flag_on_a_non_prose_argument() {
|
||||
for flag in ["--due", "--priority", "--tags", "--owner"] {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["add", "--title", "Mistyped", flag, "--bogus"])
|
||||
.assert()
|
||||
.failure();
|
||||
|
||||
let count = fs::read_dir(worklane.join("backlog")).unwrap().count();
|
||||
assert_eq!(count, 0, "{flag} wrote a ticket anyway");
|
||||
}
|
||||
}
|
||||
|
||||
/// `add` has no positionals, so a bare `--` ends the options and whatever follows
|
||||
/// has nowhere to go. Recorded because clap's separator and a hyphen-leading value
|
||||
/// are easy to confuse.
|
||||
#[test]
|
||||
fn add_rejects_arguments_after_a_bare_separator() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["add", "--title", "Sep", "--", "--title", "second"])
|
||||
.assert()
|
||||
.failure();
|
||||
|
||||
let count = fs::read_dir(worklane.join("backlog")).unwrap().count();
|
||||
assert_eq!(count, 0);
|
||||
}
|
||||
|
||||
fn only_ticket(worklane: &PathBuf) -> String {
|
||||
let files: Vec<_> = fs::read_dir(worklane.join("backlog"))
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.collect();
|
||||
assert_eq!(files.len(), 1, "expected exactly one ticket");
|
||||
fs::read_to_string(files[0].path()).unwrap()
|
||||
}
|
||||
|
||||
/// The contract the opencode wrapper relies on: values are joined with a single
|
||||
/// newline, so an empty value is how a paragraph break is spelled. The wrapper used
|
||||
/// to drop those blanks, collapsing every multi paragraph description into one.
|
||||
#[test]
|
||||
fn add_keeps_a_paragraph_break_in_the_description() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["add", "--title", "Two Paras"])
|
||||
.args(["--description", "First paragraph."])
|
||||
.args(["--description", ""])
|
||||
.args(["--description", "Second paragraph."])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let content = only_ticket(&worklane);
|
||||
assert!(
|
||||
content.contains("## Description\nFirst paragraph.\n\nSecond paragraph.\n"),
|
||||
"was {content:?}"
|
||||
);
|
||||
|
||||
// And it survives the round trip back out
|
||||
let mut show = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
show.current_dir(&temp.path()).args(["show", "Two Paras"]);
|
||||
let stdout = String::from_utf8(show.assert().success().get_output().stdout.clone()).unwrap();
|
||||
assert!(
|
||||
stdout.contains("First paragraph.\n\nSecond paragraph."),
|
||||
"was {stdout:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A break belongs between paragraphs, not against the section headings.
|
||||
#[test]
|
||||
fn add_discards_blank_descriptions_at_either_end() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["add", "--title", "Padded"])
|
||||
.args(["--description", ""])
|
||||
.args(["--description", " "])
|
||||
.args(["--description", "The only line."])
|
||||
.args(["--description", ""])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let content = only_ticket(&worklane);
|
||||
assert!(
|
||||
content.contains("## Description\nThe only line.\n\n## Acceptance Criteria"),
|
||||
"was {content:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Nothing but blanks is no description, not an empty section.
|
||||
#[test]
|
||||
fn add_treats_an_all_blank_description_as_none() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["add", "--title", "Blank"])
|
||||
.args(["--description", ""])
|
||||
.args(["--description", " "])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let content = only_ticket(&worklane);
|
||||
assert!(
|
||||
content.contains("## Description\n_No description provided._"),
|
||||
"was {content:?}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -250,3 +250,92 @@ fn comments_added_back_to_back_are_both_kept() {
|
||||
let third = stdout.find("third comment").expect("third comment missing");
|
||||
assert!(first < second && second < third, "comments out of order");
|
||||
}
|
||||
|
||||
/// The body is a positional, and the case that motivated this: a review comment
|
||||
/// quoting a flag name used to be refused outright.
|
||||
#[test]
|
||||
fn comment_accepts_a_body_that_begins_with_a_hyphen() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
let uuid = create_ticket(&worklane, "backlog", "Hyphen body");
|
||||
|
||||
for body in ["--print is the flag I mean", "-f skips the check", "-"] {
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["comment", &uuid, body])
|
||||
.assert()
|
||||
.success();
|
||||
}
|
||||
|
||||
let bodies: String = fs::read_dir(worklane.join("comments").join(&uuid))
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| fs::read_to_string(e.path()).unwrap())
|
||||
.collect();
|
||||
|
||||
for body in ["--print is the flag I mean", "-f skips the check"] {
|
||||
assert!(bodies.contains(body), "{body:?} missing from {bodies:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The ticket positional was deliberately left alone, so a hyphen-leading search
|
||||
/// term is still a usage error. A bare separator is the way through, and it is the
|
||||
/// only way through for `comment` since the body follows in the same position.
|
||||
#[test]
|
||||
fn comment_needs_a_separator_for_a_hyphen_leading_ticket() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane, "backlog", "-leading");
|
||||
|
||||
let mut without = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
without
|
||||
.current_dir(&temp.path())
|
||||
.args(["comment", "-leading", "a body"])
|
||||
.assert()
|
||||
.failure();
|
||||
|
||||
let mut with = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
with.current_dir(&temp.path())
|
||||
.args(["comment", "--", "-leading", "a body"])
|
||||
.assert()
|
||||
.success();
|
||||
}
|
||||
|
||||
/// The one shape `allow_hyphen_values` does not reach: a lone `--` in a positional
|
||||
/// is clap's end-of-options marker, consumed before any value is assigned. So a
|
||||
/// comment body of exactly `--` needs its own separator in front of it.
|
||||
///
|
||||
/// Not a silent drop either way, which is what matters: without the separator the
|
||||
/// body is reported missing and nothing is written.
|
||||
#[test]
|
||||
fn a_bare_double_hyphen_body_needs_a_separator() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
let uuid = create_ticket(&worklane, "backlog", "Bare separator");
|
||||
|
||||
let mut without = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
let assert = without
|
||||
.current_dir(&temp.path())
|
||||
.args(["comment", &uuid, "--"])
|
||||
.assert()
|
||||
.failure();
|
||||
let stderr = String::from_utf8(assert.get_output().stderr.clone()).unwrap();
|
||||
assert!(stderr.contains("<BODY>"), "unclear error: {stderr}");
|
||||
assert!(
|
||||
!worklane.join("comments").join(&uuid).exists(),
|
||||
"a comment was written despite the error"
|
||||
);
|
||||
|
||||
let mut with = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
with.current_dir(&temp.path())
|
||||
.args(["comment", &uuid, "--", "--"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let stored: String = fs::read_dir(worklane.join("comments").join(&uuid))
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| fs::read_to_string(e.path()).unwrap())
|
||||
.collect();
|
||||
assert!(stored.contains("**Comment**\n--\n"), "was {stored:?}");
|
||||
}
|
||||
|
||||
+209
@@ -431,3 +431,212 @@ fn mv_fails_when_status_field_is_missing() {
|
||||
assert!(worklane.join("backlog").join(filename).exists());
|
||||
assert!(!worklane.join("committed").join(filename).exists());
|
||||
}
|
||||
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
fn chmod(path: &std::path::Path, mode: u32) {
|
||||
let mut perms = fs::metadata(path).unwrap().permissions();
|
||||
perms.set_mode(mode);
|
||||
fs::set_permissions(path, perms).unwrap();
|
||||
}
|
||||
|
||||
fn md_files(dir: &std::path::Path) -> Vec<String> {
|
||||
match fs::read_dir(dir) {
|
||||
Ok(entries) => entries
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().into_string().unwrap())
|
||||
.filter(|name| name.ends_with(".md"))
|
||||
.collect(),
|
||||
Err(_) => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Nothing is staged in a status directory, so nothing can be left behind that the
|
||||
/// listing would read as a ticket.
|
||||
fn stray_files(worklane: &std::path::Path) -> Vec<String> {
|
||||
let mut stray: Vec<String> = fs::read_dir(worklane)
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().into_string().unwrap())
|
||||
.filter(|name| !["backlog", "committed", "reviewing", "done", "comments"].contains(&name.as_str()))
|
||||
.collect();
|
||||
|
||||
for dir in ["backlog", "committed", "reviewing", "done"] {
|
||||
stray.extend(
|
||||
fs::read_dir(worklane.join(dir))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().into_string().unwrap())
|
||||
.filter(|name| !name.ends_with(".md")),
|
||||
);
|
||||
}
|
||||
|
||||
stray
|
||||
}
|
||||
|
||||
/// The bug this fixes. The old order renamed first and wrote second, so a write
|
||||
/// that failed left the ticket in its new directory still claiming the old status.
|
||||
/// A read-only ticket file is the cheapest way to make the write fail.
|
||||
#[test]
|
||||
fn mv_never_leaves_stale_content_in_the_target_directory() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let filename = create_ticket(
|
||||
&worklane,
|
||||
"backlog",
|
||||
"Read Only",
|
||||
"A description.",
|
||||
"abc123def456789012345678901234567890",
|
||||
"alice",
|
||||
"2026-12-31",
|
||||
"test",
|
||||
);
|
||||
|
||||
let source = worklane.join("backlog").join(&filename);
|
||||
chmod(&source, 0o444);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["mv", "abc123def4567", "--status", "committed"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
// Wherever it ended up, its Status must agree with the directory it is in
|
||||
let moved = worklane.join("committed").join(&filename);
|
||||
assert!(moved.exists(), "ticket did not move");
|
||||
let content = fs::read_to_string(&moved).unwrap();
|
||||
assert!(
|
||||
content.contains("- **Status**: committed"),
|
||||
"stale status: {content:?}"
|
||||
);
|
||||
assert!(!content.contains("- **Status**: backlog"), "{content:?}");
|
||||
|
||||
assert_eq!(md_files(&worklane.join("backlog")).len(), 0);
|
||||
assert_eq!(stray_files(&worklane), Vec::<String>::new());
|
||||
}
|
||||
|
||||
/// The other criterion: one directory or the other, never both. An unwritable
|
||||
/// target directory fails the move at the last step, which is the step that would
|
||||
/// have to be reordered to break this.
|
||||
#[test]
|
||||
fn mv_leaves_the_ticket_in_one_place_when_the_move_fails() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let filename = create_ticket(
|
||||
&worklane,
|
||||
"backlog",
|
||||
"Blocked Move",
|
||||
"A description.",
|
||||
"abc123def456789012345678901234567890",
|
||||
"alice",
|
||||
"2026-12-31",
|
||||
"test",
|
||||
);
|
||||
|
||||
let target = worklane.join("committed");
|
||||
chmod(&target, 0o555);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
let assert = cmd
|
||||
.current_dir(&temp.path())
|
||||
.args(["mv", "abc123def4567", "--status", "committed"])
|
||||
.assert()
|
||||
.failure();
|
||||
|
||||
let stderr = String::from_utf8(assert.get_output().stderr.clone()).unwrap();
|
||||
// Named, not a bare io error
|
||||
assert!(stderr.contains("Blocked Move"), "{stderr}");
|
||||
|
||||
assert_eq!(
|
||||
md_files(&worklane.join("backlog")),
|
||||
vec![filename.clone()],
|
||||
"the ticket left its own directory"
|
||||
);
|
||||
assert_eq!(md_files(&target).len(), 0, "the ticket is in both places");
|
||||
assert_eq!(stray_files(&worklane), Vec::<String>::new());
|
||||
|
||||
// The documented worst case: still in its old directory, carrying a Status one
|
||||
// move ahead because the content was written before the move was attempted.
|
||||
let left = fs::read_to_string(worklane.join("backlog").join(&filename)).unwrap();
|
||||
assert!(left.contains("- **Status**: committed"), "{left:?}");
|
||||
|
||||
// And the state is recoverable, because the directory is what decides the
|
||||
// current status, so a retry moves it rather than refusing.
|
||||
chmod(&target, 0o755);
|
||||
|
||||
let mut retry = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
retry
|
||||
.current_dir(&temp.path())
|
||||
.args(["mv", "abc123def4567", "--status", "committed"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
assert_eq!(md_files(&target), vec![filename]);
|
||||
assert_eq!(md_files(&worklane.join("backlog")).len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mv_leaves_nothing_behind_on_success() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
create_ticket(
|
||||
&worklane,
|
||||
"backlog",
|
||||
"Clean Move",
|
||||
"A description.",
|
||||
"abc123def456789012345678901234567890",
|
||||
"alice",
|
||||
"2026-12-31",
|
||||
"test",
|
||||
);
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["mv", "abc123def4567", "--status", "committed"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
assert_eq!(stray_files(&worklane), Vec::<String>::new());
|
||||
}
|
||||
|
||||
/// Duplicate titles are allowed, so the file cannot be located by title. It used to be,
|
||||
/// and `mv <uuid-of-second>` moved the first ticket that shared its title.
|
||||
#[test]
|
||||
fn mv_moves_the_resolved_ticket_when_two_share_a_title() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
for uuid in [
|
||||
"11111111-aaaa-bbbb-cccc-dddddddddddd",
|
||||
"22222222-aaaa-bbbb-cccc-dddddddddddd",
|
||||
] {
|
||||
fs::write(
|
||||
worklane.join("backlog").join(format!("{}_foo.md", uuid)),
|
||||
format!(
|
||||
"# Foo\n\n## Metadata\n\n- **ID**: {}\n- **Status**: backlog\n",
|
||||
uuid
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path())
|
||||
.args(["mv", "22222222", "--status", "committed"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
assert_eq!(
|
||||
md_files(&worklane.join("committed")),
|
||||
vec!["22222222-aaaa-bbbb-cccc-dddddddddddd_foo.md".to_string()],
|
||||
"the wrong ticket moved"
|
||||
);
|
||||
assert_eq!(
|
||||
md_files(&worklane.join("backlog")),
|
||||
vec!["11111111-aaaa-bbbb-cccc-dddddddddddd_foo.md".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
use assert_cmd::Command;
|
||||
use assert_fs::TempDir;
|
||||
use assert_fs::fixture::{PathChild, PathCreateDir};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
const BIN_NAME: &str = env!("CARGO_BIN_EXE_worklane");
|
||||
const UUID: &str = "475534a3-8a0d-45cb-9a97-39c251dd8e39";
|
||||
|
||||
fn setup_worklane(temp: &TempDir) -> PathBuf {
|
||||
let worklane = temp.child(".worklane");
|
||||
worklane.create_dir_all().unwrap();
|
||||
|
||||
for dir in ["backlog", "committed", "reviewing", "done"] {
|
||||
worklane.child(dir).create_dir_all().unwrap();
|
||||
}
|
||||
|
||||
worklane.path().to_path_buf()
|
||||
}
|
||||
|
||||
/// A fully populated ticket, with one criterion already ticked and a section the tool
|
||||
/// knows nothing about, so every test can check both survive.
|
||||
fn create_ticket(worklane: &PathBuf) -> String {
|
||||
let filename = format!("{}_original-title.md", UUID);
|
||||
fs::write(
|
||||
worklane.join("backlog").join(&filename),
|
||||
format!(
|
||||
"# Original title\n\
|
||||
\n\
|
||||
## Description\n\
|
||||
First paragraph.\n\
|
||||
\n\
|
||||
Second paragraph.\n\
|
||||
\n\
|
||||
## Acceptance Criteria\n\
|
||||
- [x] Crit one\n\
|
||||
- [ ] Crit two\n\
|
||||
\n\
|
||||
## Implementation Plan\n\
|
||||
1. Step one\n\
|
||||
2. Step two\n\
|
||||
\n\
|
||||
## Notes\n\
|
||||
A handwritten note the tool knows nothing about.\n\
|
||||
\n\
|
||||
## Metadata\n\
|
||||
\n\
|
||||
- **ID**: {}\n\
|
||||
- **Priority**: 3\n\
|
||||
- **Tags**: alpha\n\
|
||||
- **Due**: 2026-09-01\n\
|
||||
- **Owner**: alice\n\
|
||||
- **Created At**: 2026-08-21 02:10:17\n\
|
||||
- **Status**: backlog\n",
|
||||
UUID
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
filename
|
||||
}
|
||||
|
||||
fn run(temp: &TempDir, args: &[&str]) -> std::process::Output {
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path()).args(args);
|
||||
cmd.assert().get_output().clone()
|
||||
}
|
||||
|
||||
fn ticket(worklane: &PathBuf) -> String {
|
||||
let entry = fs::read_dir(worklane.join("backlog"))
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.find(|e| e.file_name().to_string_lossy().ends_with(".md"))
|
||||
.expect("no ticket file");
|
||||
fs::read_to_string(entry.path()).unwrap()
|
||||
}
|
||||
|
||||
fn stray_files(worklane: &PathBuf) -> Vec<String> {
|
||||
fs::read_dir(worklane)
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().into_string().unwrap())
|
||||
.filter(|name| {
|
||||
!["backlog", "committed", "reviewing", "done", "comments"].contains(&name.as_str())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_replaces_each_field_it_is_given() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane);
|
||||
|
||||
let out = run(
|
||||
&temp,
|
||||
&[
|
||||
"set", UUID,
|
||||
"--description", "Only paragraph.",
|
||||
"--acceptance", "New crit",
|
||||
"--plan", "New step",
|
||||
"--tags", "beta,gamma",
|
||||
"--due", "2026-12-31",
|
||||
"--priority", "1",
|
||||
],
|
||||
);
|
||||
assert!(out.status.success(), "{:?}", String::from_utf8_lossy(&out.stderr));
|
||||
|
||||
let content = ticket(&worklane);
|
||||
assert!(content.contains("## Description\nOnly paragraph.\n"), "{content}");
|
||||
assert!(content.contains("## Acceptance Criteria\n- [ ] New crit\n"), "{content}");
|
||||
assert!(content.contains("## Implementation Plan\n1. New step\n"), "{content}");
|
||||
assert!(content.contains("- **Tags**: beta,gamma"), "{content}");
|
||||
assert!(content.contains("- **Due**: 2026-12-31"), "{content}");
|
||||
assert!(content.contains("- **Priority**: 1"), "{content}");
|
||||
|
||||
// The fields it was not given are untouched
|
||||
assert!(content.contains("- **Owner**: alice"), "{content}");
|
||||
assert!(content.contains("- **Status**: backlog"), "{content}");
|
||||
}
|
||||
|
||||
/// The criterion is ticked in the fixture, so an unrelated edit must leave it ticked.
|
||||
#[test]
|
||||
fn set_leaves_a_ticked_criterion_and_an_unknown_section_alone() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane);
|
||||
|
||||
run(&temp, &["set", UUID, "--due", "2026-12-31"]);
|
||||
|
||||
let content = ticket(&worklane);
|
||||
assert!(content.contains("- [x] Crit one"), "the tick was lost: {content}");
|
||||
assert!(
|
||||
content.contains("## Notes\nA handwritten note the tool knows nothing about.\n"),
|
||||
"the unknown section was lost: {content}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_renames_the_file_for_a_new_title_and_keeps_the_uuid() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane);
|
||||
|
||||
run(&temp, &["set", UUID, "--title", "A brand new title"]);
|
||||
|
||||
let names: Vec<String> = fs::read_dir(worklane.join("backlog"))
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().into_string().unwrap())
|
||||
.collect();
|
||||
assert_eq!(names, vec![format!("{}_a-brand-new-title.md", UUID)]);
|
||||
assert!(ticket(&worklane).starts_with("# A brand new title\n"));
|
||||
|
||||
// And the renamed ticket is still reachable, by the new title and by the uuid
|
||||
for search in ["brand new", "475534a3"] {
|
||||
let out = run(&temp, &["show", search]);
|
||||
assert!(out.status.success(), "{search} did not resolve");
|
||||
assert!(String::from_utf8_lossy(&out.stdout).contains("A brand new title"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_reports_no_change_and_leaves_the_file_alone() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane);
|
||||
let before = ticket(&worklane);
|
||||
|
||||
let out = run(&temp, &["set", UUID, "--due", "2026-09-01", "--priority", "3"]);
|
||||
assert!(out.status.success());
|
||||
assert!(
|
||||
String::from_utf8_lossy(&out.stdout).contains("No changes"),
|
||||
"{:?}",
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
);
|
||||
assert_eq!(ticket(&worklane), before, "the file was rewritten anyway");
|
||||
}
|
||||
|
||||
/// Only the field that actually differs is claimed, so the report cannot overstate.
|
||||
#[test]
|
||||
fn set_reports_only_the_fields_that_changed() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane);
|
||||
|
||||
let out = run(&temp, &["set", UUID, "--due", "2026-09-01", "--priority", "5"]);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
|
||||
assert!(stdout.contains("priority"), "{stdout:?}");
|
||||
assert!(!stdout.contains("due"), "{stdout:?}");
|
||||
}
|
||||
|
||||
/// An empty scalar looks like a way to clear a field, and clearing is not supported.
|
||||
#[test]
|
||||
fn set_refuses_an_empty_scalar_as_a_usage_error() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane);
|
||||
let before = ticket(&worklane);
|
||||
|
||||
for flag in ["--title", "--due", "--tags"] {
|
||||
let out = run(&temp, &["set", UUID, flag, ""]);
|
||||
assert_eq!(out.status.code(), Some(2), "{flag} was accepted");
|
||||
assert!(
|
||||
String::from_utf8_lossy(&out.stderr).contains("clearing a field is not supported"),
|
||||
"{flag}: {:?}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
assert_eq!(ticket(&worklane), before);
|
||||
}
|
||||
|
||||
/// An empty value is a paragraph break for a section, so an all-blank one is a
|
||||
/// clearing attempt rather than a break.
|
||||
#[test]
|
||||
fn set_refuses_to_clear_a_section() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane);
|
||||
let before = ticket(&worklane);
|
||||
|
||||
let out = run(&temp, &["set", UUID, "--description", ""]);
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
assert!(
|
||||
String::from_utf8_lossy(&out.stderr).contains("clearing is not supported"),
|
||||
"{:?}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
assert_eq!(ticket(&worklane), before);
|
||||
}
|
||||
|
||||
/// A bare `set <ticket>` would otherwise be a silent no-op.
|
||||
#[test]
|
||||
fn set_requires_at_least_one_field() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane);
|
||||
|
||||
let out = run(&temp, &["set", UUID]);
|
||||
assert_eq!(out.status.code(), Some(2));
|
||||
}
|
||||
|
||||
/// Interior blanks are paragraph breaks, per 4c516e6, so they have to reach the file.
|
||||
#[test]
|
||||
fn set_keeps_a_paragraph_break_in_a_replaced_description() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane);
|
||||
|
||||
run(
|
||||
&temp,
|
||||
&["set", UUID, "-d", "One.", "-d", "", "-d", "Two."],
|
||||
);
|
||||
|
||||
assert!(
|
||||
ticket(&worklane).contains("## Description\nOne.\n\nTwo.\n\n## Acceptance"),
|
||||
"{}",
|
||||
ticket(&worklane)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_accepts_prose_that_begins_with_a_hyphen() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane);
|
||||
|
||||
let out = run(
|
||||
&temp,
|
||||
&["set", UUID, "-a", "--print should be supported", "-t", "-t is the title flag"],
|
||||
);
|
||||
assert!(out.status.success(), "{:?}", String::from_utf8_lossy(&out.stderr));
|
||||
|
||||
let content = ticket(&worklane);
|
||||
assert!(content.contains("- [ ] --print should be supported"), "{content}");
|
||||
assert!(content.starts_with("# -t is the title flag\n"), "{content}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_leaves_nothing_behind() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane);
|
||||
|
||||
run(&temp, &["set", UUID, "--due", "2026-12-31"]);
|
||||
assert_eq!(stray_files(&worklane), Vec::<String>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn append_adds_a_paragraph_items_and_numbered_steps() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane);
|
||||
|
||||
let out = run(
|
||||
&temp,
|
||||
&[
|
||||
"append", UUID,
|
||||
"-d", "A third paragraph.",
|
||||
"-a", "Crit three",
|
||||
"-a", "Crit four",
|
||||
"-p", "Step three",
|
||||
],
|
||||
);
|
||||
assert!(out.status.success(), "{:?}", String::from_utf8_lossy(&out.stderr));
|
||||
|
||||
let content = ticket(&worklane);
|
||||
assert!(
|
||||
content.contains("Second paragraph.\n\nA third paragraph.\n"),
|
||||
"no paragraph break: {content}"
|
||||
);
|
||||
assert!(
|
||||
content.contains("- [x] Crit one\n- [ ] Crit two\n- [ ] Crit three\n- [ ] Crit four\n"),
|
||||
"{content}"
|
||||
);
|
||||
// Numbered on from the last step, and the steps above are untouched
|
||||
assert!(
|
||||
content.contains("1. Step one\n2. Step two\n3. Step three\n"),
|
||||
"{content}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn append_replaces_an_empty_section_rather_than_following_its_placeholder() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let mut add = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
add.current_dir(&temp.path())
|
||||
.args(["add", "--title", "Bare ticket"])
|
||||
.assert()
|
||||
.success();
|
||||
|
||||
let uuid = fs::read_dir(worklane.join("backlog"))
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().into_string().unwrap())
|
||||
.next()
|
||||
.map(|name| name.split('_').next().unwrap().to_string())
|
||||
.unwrap();
|
||||
|
||||
run(
|
||||
&temp,
|
||||
&["append", &uuid, "-d", "A description arrives late.", "-a", "First crit", "-p", "First step"],
|
||||
);
|
||||
|
||||
let content = ticket(&worklane);
|
||||
assert!(!content.contains("_No description provided._"), "{content}");
|
||||
assert!(!content.contains("_No acceptance criteria provided._"), "{content}");
|
||||
assert!(!content.contains("_No implementation plan provided._"), "{content}");
|
||||
assert!(content.contains("## Description\nA description arrives late.\n"), "{content}");
|
||||
assert!(content.contains("## Implementation Plan\n1. First step\n"), "{content}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn append_leaves_a_ticked_criterion_and_an_unknown_section_alone() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane);
|
||||
|
||||
run(&temp, &["append", UUID, "-a", "Crit three"]);
|
||||
|
||||
let content = ticket(&worklane);
|
||||
assert!(content.contains("- [x] Crit one"), "{content}");
|
||||
assert!(
|
||||
content.contains("## Notes\nA handwritten note the tool knows nothing about.\n"),
|
||||
"{content}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn append_refuses_when_every_value_is_blank() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane);
|
||||
let before = ticket(&worklane);
|
||||
|
||||
let out = run(&temp, &["append", UUID, "-a", " "]);
|
||||
assert_eq!(out.status.code(), Some(1));
|
||||
assert!(
|
||||
String::from_utf8_lossy(&out.stderr).contains("Nothing to append"),
|
||||
"{:?}",
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
assert_eq!(ticket(&worklane), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn append_requires_at_least_one_section() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane);
|
||||
|
||||
assert_eq!(run(&temp, &["append", UUID]).status.code(), Some(2));
|
||||
}
|
||||
|
||||
/// Owner belongs to chown and status to mv, so neither command offers them.
|
||||
#[test]
|
||||
fn neither_command_can_write_owner_or_status() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
create_ticket(&worklane);
|
||||
|
||||
for args in [
|
||||
vec!["set", UUID, "--owner", "bob"],
|
||||
vec!["set", UUID, "--status", "committed"],
|
||||
vec!["append", UUID, "--owner", "bob"],
|
||||
] {
|
||||
let out = run(&temp, &args);
|
||||
assert_eq!(out.status.code(), Some(2), "{args:?} was accepted");
|
||||
}
|
||||
|
||||
let content = ticket(&worklane);
|
||||
assert!(content.contains("- **Owner**: alice"));
|
||||
assert!(content.contains("- **Status**: backlog"));
|
||||
}
|
||||
@@ -485,3 +485,193 @@ fn show_renders_the_metadata_as_an_aligned_table() {
|
||||
let content = fs::read_to_string(worklane.join("backlog").join(filename)).unwrap();
|
||||
assert!(content.contains("- **Owner**: alice"));
|
||||
}
|
||||
|
||||
/// Write a ticket with an exact uuid and title, since both matter to resolution.
|
||||
fn ticket_with(worklane: &std::path::Path, status: &str, uuid: &str, title: &str, slug: &str) {
|
||||
fs::write(
|
||||
worklane.join(status).join(format!("{}_{}.md", uuid, slug)),
|
||||
format!(
|
||||
"# {}\n\n## Metadata\n\n- **ID**: {}\n- **Status**: {}\n",
|
||||
title, uuid, status
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn show(temp: &TempDir, search: &str) -> std::process::Output {
|
||||
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
cmd.current_dir(&temp.path()).arg("show").arg(search);
|
||||
cmd.assert().get_output().clone()
|
||||
}
|
||||
|
||||
/// The bug. A flat OR of the three predicates put an exact uuid prefix and a title
|
||||
/// that merely mentions it in the same list, so the search reported as ambiguous
|
||||
/// the very id the listing had just printed.
|
||||
#[test]
|
||||
fn show_prefers_a_uuid_prefix_over_a_title_that_mentions_it() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
ticket_with(
|
||||
&worklane,
|
||||
"backlog",
|
||||
"641e3d5d-ef23-4213-8346-e8b0114b84e9",
|
||||
"Alpha",
|
||||
"alpha",
|
||||
);
|
||||
ticket_with(
|
||||
&worklane,
|
||||
"backlog",
|
||||
"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
|
||||
"Notes on 641e3d5 regression",
|
||||
"notes",
|
||||
);
|
||||
|
||||
let out = show(&temp, "641e3d5");
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
|
||||
assert!(out.status.success(), "{:?}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(stdout.contains("Alpha"), "{stdout:?}");
|
||||
assert!(!stdout.contains("Notes on"), "{stdout:?}");
|
||||
}
|
||||
|
||||
/// `ls` prints SHORT_ID_WIDTH characters, so pasting that back has to resolve. This
|
||||
/// is the guard against reinstating an eight character minimum.
|
||||
#[test]
|
||||
fn show_resolves_the_short_id_the_listing_prints() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
let uuid = "641e3d5d-ef23-4213-8346-e8b0114b84e9";
|
||||
ticket_with(&worklane, "backlog", uuid, "Alpha", "alpha");
|
||||
|
||||
let mut ls = Command::cargo_bin(BIN_NAME).unwrap();
|
||||
ls.current_dir(&temp.path()).args(["ls", "backlog"]);
|
||||
let listing = String::from_utf8(ls.assert().success().get_output().stdout.clone()).unwrap();
|
||||
|
||||
// Take the id exactly as printed, so this couples to the display width rather
|
||||
// than to a hardcoded number
|
||||
let printed = listing
|
||||
.split('(')
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split(')').next())
|
||||
.expect("no id in the listing")
|
||||
.to_string();
|
||||
assert!(printed.len() < 8, "the listing prints {} chars", printed.len());
|
||||
|
||||
// A decoy whose title quotes that id. Without it the search would still land on
|
||||
// Alpha through the filename tier, since the filename contains the uuid, and the
|
||||
// test would pass under a minimum longer than the printed id.
|
||||
ticket_with(
|
||||
&worklane,
|
||||
"backlog",
|
||||
"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
|
||||
&format!("Notes on {} regression", printed),
|
||||
"notes",
|
||||
);
|
||||
|
||||
let out = show(&temp, &printed);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(out.status.success(), "{printed} did not resolve");
|
||||
assert!(stdout.contains("Alpha"), "{stdout:?}");
|
||||
assert!(!stdout.contains("Notes on"), "{stdout:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn show_resolves_a_four_character_uuid_prefix() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
ticket_with(
|
||||
&worklane,
|
||||
"backlog",
|
||||
"641e3d5d-ef23-4213-8346-e8b0114b84e9",
|
||||
"Alpha",
|
||||
"alpha",
|
||||
);
|
||||
|
||||
let out = show(&temp, "641e");
|
||||
assert!(out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stdout).contains("Alpha"));
|
||||
}
|
||||
|
||||
/// Below four characters the search is text, so it must not be read as a prefix
|
||||
/// matching a large slice of the board.
|
||||
#[test]
|
||||
fn show_treats_a_search_below_four_characters_as_text() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
ticket_with(
|
||||
&worklane,
|
||||
"backlog",
|
||||
"641e3d5d-ef23-4213-8346-e8b0114b84e9",
|
||||
"Alpha",
|
||||
"alpha",
|
||||
);
|
||||
ticket_with(
|
||||
&worklane,
|
||||
"backlog",
|
||||
"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
|
||||
"Notes on 641 regression",
|
||||
"notes",
|
||||
);
|
||||
|
||||
// "641" prefixes Alpha's uuid, but it is too short to be read as one, so the
|
||||
// title match is the only match
|
||||
let out = show(&temp, "641");
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
|
||||
assert!(out.status.success(), "{:?}", String::from_utf8_lossy(&out.stderr));
|
||||
assert!(stdout.contains("Notes on"), "{stdout:?}");
|
||||
assert!(!stdout.contains("Alpha"), "{stdout:?}");
|
||||
}
|
||||
|
||||
/// The last tier earns its place: it reaches the middle of a uuid, which the prefix
|
||||
/// tier cannot.
|
||||
#[test]
|
||||
fn show_falls_back_to_the_filename_for_a_mid_uuid_substring() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
ticket_with(
|
||||
&worklane,
|
||||
"backlog",
|
||||
"641e3d5d-ef23-4213-8346-e8b0114b84e9",
|
||||
"Alpha",
|
||||
"alpha",
|
||||
);
|
||||
|
||||
let out = show(&temp, "ef23");
|
||||
assert!(out.status.success());
|
||||
assert!(String::from_utf8_lossy(&out.stdout).contains("Alpha"));
|
||||
}
|
||||
|
||||
/// Tiering removes false ambiguity across tiers, not real ambiguity inside one.
|
||||
#[test]
|
||||
fn show_still_reports_ambiguity_within_the_uuid_tier() {
|
||||
let temp = TempDir::new().unwrap();
|
||||
let worklane = setup_worklane(&temp);
|
||||
|
||||
ticket_with(
|
||||
&worklane,
|
||||
"backlog",
|
||||
"5eeddeed-1111-2222-3333-444444444444",
|
||||
"Beta",
|
||||
"beta",
|
||||
);
|
||||
ticket_with(
|
||||
&worklane,
|
||||
"backlog",
|
||||
"5eedbeef-9999-8888-7777-666666666666",
|
||||
"Gamma",
|
||||
"gamma",
|
||||
);
|
||||
|
||||
let out = show(&temp, "5eed");
|
||||
let stderr = String::from_utf8_lossy(&out.stderr);
|
||||
|
||||
assert!(!out.status.success());
|
||||
assert!(stderr.contains("Multiple tickets found"), "{stderr:?}");
|
||||
assert!(stderr.contains("Beta") && stderr.contains("Gamma"), "{stderr:?}");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user