diff --git a/AGENTS.md b/AGENTS.md index f291666..28ad6e4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,7 +48,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 diff --git a/Cargo.lock b/Cargo.lock index 36784e6..9e25868 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1029,7 +1029,7 @@ dependencies = [ [[package]] name = "worklane" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 892f4bc..928ff06 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "worklane" -version = "0.2.1" +version = "0.3.0" edition = "2024" [dependencies] diff --git a/src/util.rs b/src/util.rs index 6030190..dfb7503 100644 --- a/src/util.rs +++ b/src/util.rs @@ -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 { let mut current = start.canonicalize()?; @@ -251,20 +259,18 @@ 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; - // Indexed rather than a plain iteration: dropping the title means also dropping - // the blank line under it, which needs a look at what comes next. while i < lines.len() { let line = lines[i]; - i += 1; // Track current section if let Some(section_name) = line.strip_prefix("## ") { current_section = line; - result.push_str(&color_text(section_name, "orange")); + result.push_str(&paint(section_name, "orange", colored)); result.push('\n'); // 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 @@ -272,12 +278,25 @@ pub fn content_trim_colored(content: &str) -> String { 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; } // 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() { + 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() { @@ -286,6 +305,8 @@ pub fn content_trim_colored(content: &str) -> String { continue; } + i += 1; + // Implementation Plan - color numbers in cyan if current_section == "## Implementation Plan" { result.push_str(&colorize_ordered(line)); @@ -293,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; @@ -357,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::() { - 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 = 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 { @@ -579,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::() { + match raw.parse::() { 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, @@ -603,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() } @@ -656,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!( @@ -674,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 @@ -756,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); } } @@ -850,13 +909,137 @@ mod tests { assert!(set_status_field(content, "committed", "T").is_err()); } - #[test] - fn the_body_leaves_the_title_to_cmd_show() { - let rendered = content_trim_colored("# Only Once\n\n## Description\nbody\n"); + /// 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(); - assert!(!rendered.contains("Only Once"), "{rendered:?}"); - // And no gap left where it was - assert!(rendered.starts_with("Description"), "{rendered:?}"); + 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] @@ -865,7 +1048,7 @@ mod tests { // Eleven characters, not fourteen: the rule used to span "## Description" assert!( - rendered.contains("Description\n───────────\n"), + rendered.starts_with("Description\n───────────\n"), "{rendered:?}" ); } @@ -874,7 +1057,34 @@ mod tests { fn a_non_ascii_section_name_is_not_over_drawn() { let rendered = content_trim_colored("# T\n\n## Résumé\nbody\n"); - assert!(rendered.contains("Résumé\n──────\n"), "{rendered:?}"); + 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] diff --git a/tests/cmd_show.rs b/tests/cmd_show.rs index 8b9d993..1f88f11 100644 --- a/tests/cmd_show.rs +++ b/tests/cmd_show.rs @@ -394,6 +394,33 @@ fn show_searches_across_all_statuses() { assert!(stdout.contains("This is in committed.")); } +#[test] +fn show_renders_the_priority_mark_beside_the_number() { + let temp = TempDir::new().unwrap(); + let worklane = setup_worklane(&temp); + + let filename = "abc123def456789012345678901234567890_prio.md"; + fs::write( + worklane.join("backlog").join(filename), + "# Prio Ticket\n\n## Metadata\n\n- **ID**: abc123def456789012345678901234567890\n\ + - **Priority**: 2\n- **Status**: backlog\n", + ) + .unwrap(); + + let mut cmd = Command::cargo_bin(BIN_NAME).unwrap(); + cmd.current_dir(&temp.path()).arg("show").arg("Prio"); + let stdout = get_stdout(&mut cmd); + + // Mark for the eye, number still there for the file's sake + assert!(stdout.contains("\u{25cf}\u{25d0}"), "no mark in {stdout:?}"); + assert!(stdout.contains("Priority")); + assert!(stdout.contains('2')); + + // And the file itself is untouched + 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(); @@ -424,28 +451,37 @@ fn show_prints_the_title_once() { } #[test] -fn show_renders_the_priority_mark_beside_the_number() { +fn show_renders_the_metadata_as_an_aligned_table() { let temp = TempDir::new().unwrap(); let worklane = setup_worklane(&temp); - let filename = "abc123def456789012345678901234567890_prio.md"; + let filename = "abc123def456789012345678901234567890_table.md"; fs::write( worklane.join("backlog").join(filename), - "# Prio Ticket\n\n## Metadata\n\n- **ID**: abc123def456789012345678901234567890\n\ - - **Priority**: 2\n- **Status**: backlog\n", + "# 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("Prio"); + cmd.current_dir(&temp.path()).arg("show").arg("Table"); let stdout = get_stdout(&mut cmd); - // Mark for the eye, number still there for the file's sake - assert!(stdout.contains("\u{25cf}\u{25d0}"), "no mark in {stdout:?}"); - assert!(stdout.contains("Priority")); - assert!(stdout.contains('2')); + // 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:?}" + ); - // And the file itself is untouched + // 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("- **Priority**: 2")); + assert!(content.contains("- **Owner**: alice")); }