Compare commits

..
6 Commits
Author SHA1 Message Date
Ansho ReiandClaude Opus 5 e20396ce6b (322150c) Make mv crash-safe by writing before renaming, and bump to 0.3.3
cmd_mv renamed the ticket into its new directory and only then wrote the updated
content, so a write that failed left the ticket in the target directory still
claiming the old status. Reproduced with a read-only ticket file: the move
reported a bare "Permission denied" and left the file in committed/ carrying
"Status: backlog".

move_ticket_file now stages the content in a temp file, renames it over the
source, and only then renames the file into the target directory. Two atomic
steps, so a partial write is discarded and the original is untouched. The other
obvious order, writing to the target and deleting the source afterwards, was
rejected because it has the ticket in two directories at once.

The worst case left is a ticket still in its old directory with a Status one
move ahead, which the next mv corrects since the directory is what decides the
current status. Tested, including the retry.

The temp file is staged 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 appearing as a stray untitled ticket. IO errors now name the ticket
and the path rather than propagating bare.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 23:12:17 +02:00
Ansho ReiandClaude Opus 5 f5204f6d8b (866a4eb) Accept prose values that begin with a hyphen, and bump to 0.3.2
clap read any value starting with a hyphen as a flag, so a criterion quoting
--print was refused with "unexpected argument found" and no ticket was written
at all. Ticket text quotes flag names constantly, and the space form is what
both a person and the opencode wrapper produce, so the failure was routine.

allow_hyphen_values on the five arguments that carry prose: add --title,
--description, --acceptance, --plan, and the comment body. The trade is that a
genuinely mistyped flag there now lands as content instead of raising a usage
error, which is the right way round for prose and the wrong way round for
anything else, so due, priority, tags, owner and status are left alone and still
fail with exit 2. Written down in AGENTS.md.

The bare double hyphen is the one shape this does not reach: as an option value
it is stored as text, but in a positional it is clap's end-of-options marker and
is consumed before assignment. A comment body of exactly -- therefore needs its
own separator. Without it the body is reported missing and nothing is written,
so it is a clear failure rather than a silent drop. Tested, along with the
ordering that lets mv reach a hyphen-leading title.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 18:00:52 +02:00
Ansho ReiandClaude Opus 5 b28ddb9210 (eed7309) Die quietly on a truncated pipe, and bump to 0.3.1
Rust sets SIGPIPE to SIG_IGN at startup, so a write to a closed pipe returned
EPIPE and println panicked on it. `worklane ls | head -3` printed a panic and a
backtrace on stderr instead of three lines, which reads as a real fault and is
not what any other tool in a pipeline does.

main now restores the default disposition before any output, the same six lines
frig carries for the same reason. The cost is that a truncated pipe kills the
process with signal 13, so a shell reports 141 rather than 101. That is what
head and sort do, and it is now in the README next to the other exit codes.

The tests drop the read end rather than racing head for it, over a listing large
enough to exceed the 64 KiB a pipe holds, since a smaller one lands entirely in
the buffer and proves nothing. A shell pipeline into head is covered too, and
the exit codes for a real error and a usage mistake are pinned so the reset
cannot quietly change them.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 17:34:45 +02:00
Ansho ReiandClaude Opus 5 f557437f62 (277a527) Render the metadata section as an aligned table, and bump to 0.3.0
show printed the Metadata block as the markdown list the file stores, so with
seven fields the values did not line up and the block read as file contents
rather than as a summary. It now renders as two aligned columns: field names
left, values right. The file is untouched, this is display only.

content_trim_colored streamed one line at a time, so nothing ever saw the whole
section. The Metadata lines are now taken as a block, since the field column
cannot be sized until every name has been seen.

Column width is measured on the raw names, in characters, and padding is applied
before anything is styled. Measuring a coloured name counts its escape sequences
towards its width, which tilts the table with colour on and not with it off.
paint() is color_text() with the decision passed in, which is what lets a test
render both ways in one process and compare.

colorize_metadata is folded into the renderer, its only caller. A line in the
section that is not a field is carried through rather than dropped, so a hand
written note survives, and an unrecognised field still gets a row.

Plain columns, no border characters: nothing to degrade on a font that lacks
them, and the section rules already carry the only box drawing here.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 17:12:57 +02:00
Ansho ReiandClaude Opus 5 75fb2b3a6d (4b1e7e8) Print the ticket title once in show
cmd_show printed the resolved title with its rule, then content_trim_colored
printed the "# " heading again out of the file content, so every show output
carried the title twice.

The body now skips the heading, along with the blank line the template puts
under it so nothing is left where it was. cmd_show keeps the surviving copy and
colours it green, which is where the colour guideline puts a title.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 17:12:22 +02:00
Ansho ReiandClaude Opus 5 8b440593e2 (594c741) Measure heading rules on the displayed name
Section rules repeated the character for the byte length of the whole heading
line, so every rule ran three past its heading for the "## " prefix. The title
rule in cmd_show used byte length, which over-draws for a non-ASCII title.

Both now count characters of the text as displayed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 17:11:43 +02:00
13 changed files with 1092 additions and 95 deletions
+13 -1
View File
@@ -31,12 +31,20 @@
- 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
### 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)
@@ -48,9 +56,13 @@
- Grey is indexed colour 8 in the 256-colour form, not SGR 90 or 37. Both of those failed on a real palette: 90 leans on the bright-black slot and 37 can sit on top of the default foreground. `\x1b[38;5;8m` is byte for byte what crossterm emits for ratatui's `Color::DarkGray`, the grey frig and pantop use for dimmed rows
### Code Organization
- Colorization functions (`colorize_line`, `colorize_metadata`, `colorize_ordered`, `content_trim_colored`) handle markdown formatting
- Colorization functions (`colorize_line`, `colorize_ordered`, `content_trim_colored`) handle markdown formatting
- `show` renders the Metadata section as a two column table via `render_metadata_table`, not line by line. Column width is measured on the raw field names in characters and padding is applied before anything is styled: measuring a coloured string counts its escapes towards its width. `paint()` is `color_text()` with the colour decision passed in, which is what lets a test render both ways in one process
- The title is printed once, by `cmd_show`. `content_trim_colored` skips the `# ` heading in the file content
- 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
Generated
+2 -1
View File
@@ -1029,13 +1029,14 @@ dependencies = [
[[package]]
name = "worklane"
version = "0.2.1"
version = "0.3.3"
dependencies = [
"anyhow",
"assert_cmd",
"assert_fs",
"chrono",
"clap",
"libc",
"tempfile",
"uuid",
]
+2 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "worklane"
version = "0.2.1"
version = "0.3.3"
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"
+13
View File
@@ -11,3 +11,16 @@ Worklane is a local Kanban flow for agentic software development.
| `worklane show <id>` | Shows ticket by UUID prefix (8+ chars) or title substring |
| `worklane mv <id> --status <target> [-f]` | Moves ticket between statuses. Default: forward only, one stage at a time. `-f` bypasses both restrictions |
| `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.
+16 -4
View File
@@ -37,6 +37,17 @@ pub struct Cli {
pub command: Command,
}
/// 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 +56,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)
@@ -114,6 +125,7 @@ pub enum Command {
ticket: String,
/// Comment body (required)
#[arg(allow_hyphen_values = PROSE)]
body: String,
/// Owner
+82 -9
View File
@@ -294,8 +294,11 @@ pub fn cmd_show(search: &str, worklane_dir: &Path) -> Result<()> {
let (_status, title, content) = resolve_ticket(search, worklane_dir)?;
let ticket_uuid = parse_ticket_field(&content, "ID");
println!("{}", title);
println!("{}", "─".repeat(title.len()));
// The only title in the output: content_trim_colored used to print it a second
// time from the file content. Green per the colour guideline, and the rule is
// measured in characters so a non-ASCII title is not over-drawn.
println!("{}", color_text(&title, "green"));
println!("{}", "─".repeat(title.chars().count()));
println!("\n{}", content_trim_colored(&content));
if ticket_uuid != "_Not set_" {
@@ -308,6 +311,67 @@ pub fn cmd_show(search: &str, worklane_dir: &Path) -> Result<()> {
Ok(())
}
/// 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);
// Staged outside the status directories on purpose: a temp file left behind by a
// hard kill is then invisible to ticket lookup and to the listing, rather than
// showing up as a stray untitled ticket.
let temp = worklane_dir.join(format!(".mv-{}.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, &source) {
let _ = fs::remove_file(&temp);
return Err(anyhow!(
"Could not update the status of ticket '{}' at {}: {}",
title,
source.display(),
e
));
}
// 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"];
@@ -387,15 +451,24 @@ pub fn cmd_mv(ticket_id: &str, target_status: &str, force: bool, start: &Path) -
// 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 = fs::read_to_string(&source_path).map_err(|e| {
anyhow!(
"Could not read ticket '{}' at {}: {}",
title,
source_path.display(),
e
)
})?;
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,
&current_path,
&target_path,
&found_filename,
&content,
&title,
)?;
println!(
"Moved ticket '{}' from {} to {}",
+21
View File
@@ -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()?;
+327 -79
View File
@@ -73,14 +73,22 @@ pub fn get_color(color: &str) -> &'static str {
}
}
pub fn color_text(text: &str, color: &str) -> String {
if should_use_colors() {
/// `color_text` with the decision passed in rather than asked for.
///
/// The seam matters for anything that aligns columns: a caller has to be able to
/// render both ways in one process to prove the padding does not depend on it.
pub fn paint(text: &str, color: &str, enabled: bool) -> String {
if enabled {
format!("{}{}{}", get_color(color), text, "\x1b[0m")
} else {
text.to_string()
}
}
pub fn color_text(text: &str, color: &str) -> String {
paint(text, color, should_use_colors())
}
pub fn find_worklane_dir(start: &Path) -> Result<std::path::PathBuf> {
let mut current = start.canonicalize()?;
@@ -251,30 +259,54 @@ pub fn format_comments(comments: &[(String, String, String, String)]) -> String
}
pub fn content_trim_colored(content: &str) -> String {
let lines: Vec<&str> = content.trim().lines().collect();
let colored = should_use_colors();
let mut result = String::new();
let mut current_section = "";
let mut i = 0;
while i < lines.len() {
let line = lines[i];
for line in &lines {
// Track current section
if line.starts_with("## ") {
if let Some(section_name) = line.strip_prefix("## ") {
current_section = line;
let section_name = &line[3..];
result.push_str(&color_text(section_name, "orange"));
result.push_str(&paint(section_name, "orange", colored));
result.push('\n');
result.push_str(&"─".repeat(line.len()));
// Measured on the name as displayed, in characters. The rule used to span
// the raw line, so it ran three past the heading for the "## ", and byte
// length over-drew for anything non-ASCII.
result.push_str(&"─".repeat(section_name.chars().count()));
result.push('\n');
result.push('\n');
i += 1;
// Metadata is rendered as a block, so it is consumed here rather than
// falling through to the line-at-a-time cases below.
if is_metadata_heading(line) {
let end = lines[i..]
.iter()
.position(|l| l.starts_with("## "))
.map_or(lines.len(), |offset| i + offset);
result.push_str(&render_metadata_table(&lines[i..end], colored));
i = end;
}
continue;
}
// First line is the title header - color it in green
// The title belongs to cmd_show, which prints it with its rule. Printing it
// again from the file content is what repeated it in every show output.
if line.starts_with("# ") && current_section.is_empty() {
let header = &line[2..]; // Remove "# "
result.push_str(&color_text(header, "green"));
result.push('\n');
i += 1;
// Along with the blank line the template puts under it, so dropping the
// title does not leave a gap where it used to be.
while i < lines.len() && lines[i].trim().is_empty() {
i += 1;
}
continue;
}
i += 1;
// Implementation Plan - color numbers in cyan
if current_section == "## Implementation Plan" {
result.push_str(&colorize_ordered(line));
@@ -282,16 +314,9 @@ pub fn content_trim_colored(content: &str) -> String {
continue;
}
// Metadata - color field names in RED
if current_section == "## Metadata" {
result.push_str(&colorize_metadata(line));
result.push('\n');
continue;
}
// Acceptance Criteria checkboxes
if line.starts_with("- [ ]") {
result.push_str(&color_text("- [ ]", "grey"));
result.push_str(&paint("- [ ]", "grey", colored));
result.push_str(&line[5..]);
result.push('\n');
continue;
@@ -346,56 +371,91 @@ pub fn colorize_ordered(line: &str) -> String {
line.to_string()
}
pub fn colorize_metadata(line: &str) -> String {
if !line.contains("**") {
return line.to_string();
/// Space between the field column and the value column.
const METADATA_GUTTER: &str = " ";
/// One line of the Metadata section, as the table sees it.
enum MetadataRow<'a> {
/// A `- **Name**: value` line, the shape the file stores fields in.
Field { name: &'a str, value: &'a str },
/// Anything else, carried through verbatim so a hand-written note in the
/// section is not dropped on the way to the screen.
Other(&'a str),
}
/// Split a metadata line into a field and its value, sharing the anchoring rules
/// `parse_ticket_field` uses: list marker optional, name matched at the start.
fn metadata_row(line: &str) -> MetadataRow<'_> {
let body = metadata_field_body(line);
let Some(rest) = body.strip_prefix("**") else {
return MetadataRow::Other(line);
};
let Some(close) = rest.find("**:") else {
return MetadataRow::Other(line);
};
MetadataRow::Field {
name: &rest[..close],
value: rest[close + "**:".len()..].trim(),
}
}
/// The value cell for a field, styled per the colour guideline.
fn metadata_value_cell(name: &str, value: &str, colored: bool) -> String {
if name == "Priority" {
// Reads as a glyph, while the file keeps storing the number.
let (glyph, colour) = priority_mark(priority_from_value(value));
return format!("{} {}", paint(glyph, colour, colored), value);
}
// Priority reads as a glyph here too, while the file keeps storing the number.
if let Some(value) = line.split("**Priority**:").nth(1) {
let priority = match value.trim().parse::<u8>() {
Ok(level) if PRIORITY_RANGE.contains(&level) => Priority::Level(level),
_ if is_unknown_value(value.trim()) => Priority::Unset,
_ => Priority::Invalid,
};
return format!(
"- {}: {} {}",
color_text("Priority", "red"),
show_priority(priority),
value.trim()
);
if is_unknown_value(value) {
return paint(value, "grey", colored);
}
let content = line;
let open_pos = match content.find("**") {
Some(p) => p,
None => return content.to_string(),
};
value.to_string()
}
let after_open = open_pos + 2;
let remaining = &content[after_open..];
let close_pos = match remaining.find("**") {
Some(p) => p,
None => return content.to_string(),
};
/// Render the Metadata section as two aligned columns.
///
/// Taken as a block rather than a line at a time because the field column cannot be
/// sized until every name has been seen. The file is untouched by this: it goes on
/// storing the markdown list, and this is only how the list is shown.
fn render_metadata_table(lines: &[&str], colored: bool) -> String {
// The heading already emits its own blank separator, so the one the template
// puts under it would otherwise open the section with a gap.
let start = lines
.iter()
.position(|line| !line.trim().is_empty())
.unwrap_or(lines.len());
let rows: Vec<MetadataRow> = lines[start..].iter().map(|line| metadata_row(line)).collect();
let field_name = &content[after_open..after_open + close_pos];
let after_field = &content[after_open + close_pos + 2..];
// Measured on the raw names, in characters, and padded before anything is
// styled. Measuring a coloured name counts its escape sequences towards its
// width, which is what tilts a table when colour is on and not when it is off.
let field_width = rows
.iter()
.filter_map(|row| match row {
MetadataRow::Field { name, .. } => Some(name.chars().count()),
MetadataRow::Other(_) => None,
})
.max()
.unwrap_or(0);
let colored_field = color_text(field_name, "red");
let value_text = after_field.strip_prefix(": ").map(|s| s.trim()).unwrap_or(after_field);
let after_field_colored = if is_unknown_value(value_text) {
color_text(after_field, "grey")
} else {
after_field.to_string()
};
let mut result = String::new();
for row in &rows {
match row {
MetadataRow::Field { name, value } => {
result.push_str(&paint(name, "red", colored));
result.push_str(&" ".repeat(field_width - name.chars().count()));
result.push_str(METADATA_GUTTER);
result.push_str(&metadata_value_cell(name, value, colored));
}
MetadataRow::Other(text) => result.push_str(&colorize_line(text)),
}
result.push('\n');
}
format!(
"{}{}{}",
&content[..open_pos],
colored_field,
after_field_colored
)
result
}
pub fn is_unknown_value(value: &str) -> bool {
@@ -568,19 +628,24 @@ impl Priority {
}
}
pub fn parse_priority(content: &str) -> Priority {
let raw = parse_ticket_field(content, "Priority");
/// A priority from the value alone, for callers that already have it in hand.
pub fn priority_from_value(raw: &str) -> Priority {
let raw = raw.trim();
if is_unknown_value(&raw) {
if is_unknown_value(raw) {
return Priority::Unset;
}
match raw.trim().parse::<u8>() {
match raw.parse::<u8>() {
Ok(level) if PRIORITY_RANGE.contains(&level) => Priority::Level(level),
_ => Priority::Invalid,
}
}
pub fn parse_priority(content: &str) -> Priority {
priority_from_value(&parse_ticket_field(content, "Priority"))
}
pub struct TicketItem {
pub title: String,
pub owner: String,
@@ -592,11 +657,11 @@ pub struct TicketItem {
/// Grey for a value that is not set, per the colour guideline.
///
/// `show` already did this through `colorize_metadata`, so the listing was the
/// one place that ignored the rule.
fn dim_if_unset(value: &str) -> String {
/// `show` already did this in its metadata rendering, so the listing was the one
/// place that ignored the rule.
fn dim_if_unset(value: &str, colored: bool) -> String {
if is_unknown_value(value) {
color_text(value, "grey")
paint(value, "grey", colored)
} else {
value.to_string()
}
@@ -645,17 +710,19 @@ pub fn priority_legend() -> String {
format!("Priority: {levels} {unset} unset 1 is most urgent")
}
fn show_priority(priority: Priority) -> String {
fn show_priority(priority: Priority, colored: bool) -> String {
let (glyph, colour) = priority_mark(priority);
color_text(glyph, colour)
paint(glyph, colour, colored)
}
pub fn display_ticket_items(items: &[TicketItem]) {
let colored = should_use_colors();
for item in items {
let id = color_text(&item.id, "red");
let owner = dim_if_unset(&item.owner);
let due = dim_if_unset(&item.due);
let priority = show_priority(item.priority);
let id = paint(&item.id, "red", colored);
let owner = dim_if_unset(&item.owner, colored);
let due = dim_if_unset(&item.due, colored);
let priority = show_priority(item.priority, colored);
if item.created.is_empty() {
println!(
@@ -663,7 +730,7 @@ pub fn display_ticket_items(items: &[TicketItem]) {
priority, id, item.title, owner, due
);
} else {
let created = color_text(&item.created, "cyan");
let created = paint(&item.created, "cyan", colored);
println!(
" {} {} ({}) {} | Owner: {} | Due: {}",
priority, created, id, item.title, owner, due
@@ -745,15 +812,18 @@ mod tests {
#[test]
fn unset_values_are_dimmed_and_set_ones_are_not() {
// Colour is off in a test process, so this asserts the decision, not the escape
// Both paths, now that the colour decision is a parameter: with colour off the
// text has to come back untouched, with it on only the unset values get wrapped
for unset in ["_Not set_", "_None_"] {
assert!(is_unknown_value(unset), "{unset} should count as unset");
assert_eq!(dim_if_unset(unset), unset);
assert_eq!(dim_if_unset(unset, false), unset);
assert_eq!(dim_if_unset(unset, true), paint(unset, "grey", true));
}
for set in ["alice", "2026-12-31", "bug,frontend"] {
assert!(!is_unknown_value(set));
assert_eq!(dim_if_unset(set), set);
assert_eq!(dim_if_unset(set, false), set);
assert_eq!(dim_if_unset(set, true), set);
}
}
@@ -839,6 +909,184 @@ mod tests {
assert!(set_status_field(content, "committed", "T").is_err());
}
/// SGR escapes removed, so a rendered cell can be measured as it lands on screen.
/// Test-only: production never measures a styled string, which is the point.
fn unstyled(text: &str) -> String {
let mut out = String::new();
let mut chars = text.chars();
while let Some(c) = chars.next() {
if c != '\x1b' {
out.push(c);
continue;
}
// Drop everything up to and including the 'm' that closes the sequence.
for c in chars.by_ref() {
if c == 'm' {
break;
}
}
}
out
}
#[test]
fn the_metadata_table_aligns_values_in_one_column() {
// The leading blank line is what the ticket template writes under the heading.
let rendered = render_metadata_table(
&[
"",
"- **ID**: abc",
"- **Created At**: 2026-08-20",
"- **Owner**: alice",
],
false,
);
assert_eq!(
rendered,
"ID abc\n\
Created At 2026-08-20\n\
Owner alice\n"
);
}
#[test]
fn a_long_field_name_widens_the_column_for_every_row() {
let rendered =
render_metadata_table(&["- **ID**: abc", "- **Handled By Team**: ops"], false);
assert_eq!(
rendered,
"ID abc\n\
Handled By Team ops\n"
);
}
/// The trap the ticket names: field names are coloured, unset values are greyed
/// and Priority carries a mark, so measuring the styled text would tilt the table
/// with colour on and not with it off.
#[test]
fn colour_does_not_change_the_alignment() {
let lines = [
"- **ID**: abc",
"- **Priority**: 2",
"- **Due**: _Not set_",
"- **Owner**: Ansho Rei",
];
let plain = render_metadata_table(&lines, false);
let coloured = render_metadata_table(&lines, true);
assert_ne!(coloured, plain, "colour produced no escapes at all");
assert_eq!(unstyled(&coloured), plain);
}
#[test]
fn a_non_ascii_field_name_is_measured_in_characters() {
// "Créé à" is 6 characters and 8 bytes, so a byte-width column pads it short
let rendered = render_metadata_table(&["- **Créé à**: oui", "- **ID**: abc"], false);
assert_eq!(
rendered,
"Créé à oui\n\
ID abc\n"
);
}
#[test]
fn a_non_ascii_value_leaves_the_column_alone() {
let lines = ["- **Owner**: 日本語", "- **ID**: abc"];
let rendered = render_metadata_table(&lines, false);
assert_eq!(
rendered,
"Owner 日本語\n\
ID abc\n"
);
}
#[test]
fn a_field_the_tool_does_not_know_still_gets_a_row() {
let rendered = render_metadata_table(&["- **ID**: abc", "- **Sprint**: 14"], false);
assert!(rendered.contains("Sprint 14"), "{rendered:?}");
}
#[test]
fn a_line_that_is_not_a_field_is_carried_through() {
let rendered =
render_metadata_table(&["- **ID**: abc", "a hand written note"], false);
assert_eq!(
rendered,
"ID abc\n\
a hand written note\n"
);
}
#[test]
fn the_priority_cell_carries_the_mark_and_the_stored_number() {
let rendered = render_metadata_table(&["- **Priority**: 2"], false);
let (glyph, _) = priority_mark(Priority::Level(2));
assert_eq!(rendered, format!("Priority {glyph} 2\n"));
}
#[test]
fn an_unset_priority_reads_as_unset_in_the_table() {
let rendered = render_metadata_table(&["- **Priority**: _Not set_"], false);
let (glyph, _) = priority_mark(Priority::Unset);
assert_eq!(rendered, format!("Priority {glyph} _Not set_\n"));
}
#[test]
fn a_section_rule_matches_the_width_of_its_name() {
let rendered = content_trim_colored("# T\n\n## Description\nbody\n");
// Eleven characters, not fourteen: the rule used to span "## Description"
assert!(
rendered.starts_with("Description\n───────────\n"),
"{rendered:?}"
);
}
#[test]
fn a_non_ascii_section_name_is_not_over_drawn() {
let rendered = content_trim_colored("# T\n\n## Résumé\nbody\n");
assert!(rendered.starts_with("Résumé\n──────\n"), "{rendered:?}");
}
#[test]
fn the_body_leaves_the_title_to_cmd_show() {
let rendered = content_trim_colored("# Only Once\n\n## Description\nbody\n");
assert!(!rendered.contains("Only Once"), "{rendered:?}");
// And no gap where it was
assert!(rendered.starts_with("Description"), "{rendered:?}");
}
#[test]
fn the_metadata_section_renders_as_a_table_inside_the_body() {
let content = "# T\n\n## Metadata\n\n- **ID**: abc\n- **Owner**: alice\n";
let rendered = content_trim_colored(content);
assert_eq!(rendered, "Metadata\n────────\n\nID abc\nOwner alice\n");
}
#[test]
fn a_section_after_metadata_still_renders() {
let content = "# T\n\n## Metadata\n\n- **ID**: abc\n\n## Notes\n\nafter\n";
let rendered = content_trim_colored(content);
assert!(rendered.contains("ID abc"), "{rendered:?}");
assert!(rendered.contains("Notes\n─────\n"), "{rendered:?}");
assert!(rendered.ends_with("after\n"), "{rendered:?}");
}
#[test]
fn a_level_in_range_parses() {
for level in 1..=5u8 {
+173
View File
@@ -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));
}
+118
View File
@@ -262,3 +262,121 @@ 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()
}
+89
View File
@@ -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:?}");
}
+171
View File
@@ -431,3 +431,174 @@ 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());
}
+65
View File
@@ -420,3 +420,68 @@ fn show_renders_the_priority_mark_beside_the_number() {
let content = fs::read_to_string(worklane.join("backlog").join(filename)).unwrap();
assert!(content.contains("- **Priority**: 2"));
}
#[test]
fn show_prints_the_title_once() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
create_ticket(
&worklane,
"backlog",
"Once Only",
"A description that does not name the title.",
"abc123def456789012345678901234567890",
"alice",
"2026-12-31",
"test",
);
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path()).arg("show").arg("Once Only");
let stdout = get_stdout(&mut cmd);
assert_eq!(
stdout.matches("Once Only").count(),
1,
"title repeated in {stdout:?}"
);
// The rule under it is still the width of the title
assert!(stdout.contains("Once Only\n─────────\n"), "{stdout:?}");
}
#[test]
fn show_renders_the_metadata_as_an_aligned_table() {
let temp = TempDir::new().unwrap();
let worklane = setup_worklane(&temp);
let filename = "abc123def456789012345678901234567890_table.md";
fs::write(
worklane.join("backlog").join(filename),
"# Table Ticket\n\n## Metadata\n\n\
- **ID**: abc123def456789012345678901234567890\n\
- **Created At**: 2026-08-20 15:51:01\n\
- **Owner**: alice\n\
- **Status**: backlog\n",
)
.unwrap();
let mut cmd = Command::cargo_bin(BIN_NAME).unwrap();
cmd.current_dir(&temp.path()).arg("show").arg("Table");
let stdout = get_stdout(&mut cmd);
// Every value starts in the same column, sized by the longest field name
assert!(
stdout.contains(
"ID abc123def456789012345678901234567890\n\
Created At 2026-08-20 15:51:01\n\
Owner alice\n\
Status backlog\n"
),
"{stdout:?}"
);
// Display only: the file is still the markdown list it was
let content = fs::read_to_string(worklane.join("backlog").join(filename)).unwrap();
assert!(content.contains("- **Owner**: alice"));
}