Compare commits

..
4 Commits
Author SHA1 Message Date
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
9 changed files with 613 additions and 84 deletions
+5 -1
View File
@@ -37,6 +37,7 @@
- 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,7 +49,10 @@
- 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
- 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
Generated
+2 -1
View File
@@ -1029,13 +1029,14 @@ dependencies = [
[[package]]
name = "worklane"
version = "0.2.1"
version = "0.3.1"
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.1"
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.
+5 -2
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_" {
+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));
}
+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"));
}