diff --git a/AGENTS.md b/AGENTS.md index 5bf3511..037b813 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -117,6 +117,9 @@ and this file is for what someone changing worklane's own code needs. ### Color and Output - Use `color_text()` for coloured output — it respects `should_use_colors()` (terminal detection), and `paint()` is the same with the decision passed in +- **`color_text()` is for the CLI's own printing only. Anything reachable from `content_trim` takes the decision as an argument and calls `paint()`**, because the board renders with colour off and an escape sequence in a ratatui paragraph is drawn as literal bytes. `nothing_the_body_renders_asks_the_terminal_for_the_colour_decision` scans this file and fails on a new caller; the allowlist is `ambiguous`, which builds a failed-search message for stderr +- A function that takes an `enabled` flag must use it all the way down. `colorize_bold` honoured its flag on the early return and then asked `should_use_colors()` for the bold run, which made the flag a lie in half the function +- **A test that asserts an absence has to be paired with one that asserts the presence.** The guard for this, an assert that the detail view holds no escape byte, could not fail: a test binary has no tty, so `should_use_colors()` was false and the leaking branch was never taken. The pair is now `content_trim(.., false)` has no escape and `content_trim(.., true)` still colours, which pins the flag as the only thing that decides - **The palette is the `Color` enum, not a string.** `Color::ansi()` gives the CLI its SGR sequence and `From for ratatui::style::Color` gives the TUI its equivalent, so a colour that exists for one renderer and not the other is a compile error. The stringly-typed version needed a test for exactly that, and a missing entry silently produced an empty prefix, which is how `magenta` came to be undefined - Reset color with `\x1b[0m` after colored text - Bold uses `\x1b[1;35m` (magenta bold) @@ -133,7 +136,7 @@ and this file is for what someone changing worklane's own code needs. - 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_ordered`, `content_trim_colored`) handle markdown formatting +- Colorization functions (`colorize_ordered`, `colorize_bold`, `content_trim_colored`) handle markdown formatting. `colorize_line` is gone: it was a `pub` alias for `colorize_bold` with one caller, and the only thing it added was asking the terminal - `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 diff --git a/Cargo.lock b/Cargo.lock index 59a260e..416883c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1494,7 +1494,7 @@ dependencies = [ [[package]] name = "worklane" -version = "0.8.3" +version = "0.8.4" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 7c9638e..bad4c09 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "worklane" -version = "0.8.3" +version = "0.8.4" edition = "2024" [dependencies] diff --git a/src/util.rs b/src/util.rs index e75afa1..67be99c 100644 --- a/src/util.rs +++ b/src/util.rs @@ -403,7 +403,7 @@ pub fn content_trim(content: &str, colored: bool) -> String { // Implementation Plan - color numbers in cyan if current_section == "## Implementation Plan" { - result.push_str(&colorize_ordered(line)); + result.push_str(&colorize_ordered(line, colored)); result.push('\n'); continue; } @@ -454,7 +454,13 @@ pub fn content_trim(content: &str, colored: bool) -> String { result } -pub fn colorize_ordered(line: &str) -> String { +/// Colour the `1.` at the head of a numbered line, leaving the rest alone. +/// +/// Takes the decision rather than asking for it. Asking is what put `\x1b[36m` and +/// `\x1b[0m` around every Implementation Plan number in the board's detail view, +/// which renders with colour off precisely because a paragraph is not a place an +/// escape sequence can go. +fn colorize_ordered(line: &str, colored: bool) -> String { if line.chars().next().is_none_or(|c| !c.is_ascii_digit()) { return line.to_string(); } @@ -468,7 +474,7 @@ pub fn colorize_ordered(line: &str) -> String { // still scanning digits } else if *c == '.' && i + 1 < chars.len() && chars[i + 1] == ' ' { let number = &line[..i + 1]; - result.push_str(&color_text(number, Color::Cyan)); + result.push_str(&paint(number, Color::Cyan, colored)); result.push_str(&line[i + 1..]); return result; } else { @@ -558,7 +564,10 @@ fn render_metadata_table(lines: &[&str], colored: bool) -> String { result.push_str(METADATA_GUTTER); result.push_str(&metadata_value_cell(name, value, colored)); } - MetadataRow::Other(text) => result.push_str(&colorize_line(text)), + // The decision this row is rendered under, not the one the terminal + // would give: `colorize_line` asked `should_use_colors()` here, which is + // how escapes reached the board's detail view. + MetadataRow::Other(text) => result.push_str(&colorize_bold(text, colored)), } result.push('\n'); } @@ -571,10 +580,6 @@ pub fn is_unknown_value(value: &str) -> bool { trimmed == "_None_" || trimmed == "_Not set_" || trimmed == "-None-" || trimmed == "-Not set-" } -pub fn colorize_line(line: &str) -> String { - colorize_bold(line, should_use_colors()) -} - /// Replace `**bold**` with colour, or leave the line exactly as it is. /// /// Taking `enabled` rather than asking makes both paths testable, and the @@ -600,7 +605,9 @@ fn colorize_bold(line: &str, enabled: bool) -> String { match (i + 2..chars.len()).find(|&at| is_delimiter(&chars, at)) { Some(close) => { let bold: String = chars[i + 2..close].iter().collect(); - result.push_str(&color_text(&bold, Color::Magenta)); + // `enabled`, not `should_use_colors()`. Asking again here made the + // flag a lie: the early return above respected it and this did not. + result.push_str(&paint(&bold, Color::Magenta, enabled)); i = close + 2; } // Unterminated: the rest is literal. The old scan walked off the end @@ -1552,6 +1559,87 @@ mod tests { assert_eq!(rendered, format!("Priority {glyph} _Not set_\n")); } + /// A ticket with the two things that used to leak: a numbered plan, and a + /// hand-written line inside the Metadata section. + const BOTH_LEAKS: &str = "# T\n\n## Implementation Plan\n1. First step\n2. Second step\n\ + \n## Metadata\n\n- **ID**: abc\nA **handwritten** note\n"; + + /// The bug: the board asks for `content_trim(content, false)` because a paragraph + /// is no place for an escape sequence, and two paths asked the terminal instead. + #[test] + fn the_body_carries_no_escape_when_the_colour_is_off() { + let rendered = content_trim(BOTH_LEAKS, false); + + assert!( + !rendered.contains('\x1b'), + "an escape survived colour being off: {rendered:?}" + ); + // And the content is all still there, in plain form. + assert!(rendered.contains("1. First step"), "{rendered:?}"); + assert!(rendered.contains("**handwritten**"), "{rendered:?}"); + } + + /// The other half of the pair, and the one that makes the first mean something: + /// with the flag on, both paths still colour. Without this, the passing test above + /// could be a colouring path that was simply deleted. + #[test] + fn the_body_colours_the_plan_number_and_a_metadata_note_when_the_colour_is_on() { + let rendered = content_trim(BOTH_LEAKS, true); + + assert!( + rendered.contains(&format!("{}1.", Color::Cyan.ansi())), + "the plan number lost its colour: {rendered:?}" + ); + assert!( + rendered.contains(&format!("{}handwritten", Color::Magenta.ansi())), + "the bold run lost its colour: {rendered:?}" + ); + } + + /// The flag has to be the only thing that decides, or the disabled path is just + /// the terminal's answer in disguise — which is why the leak survived a test + /// asserting the detail view holds no escapes. In a test binary there is no tty, + /// so `should_use_colors()` is false and the leaking branch was never taken. + #[test] + fn nothing_the_body_renders_asks_the_terminal_for_the_colour_decision() { + let callers = callers_of_color_text(include_str!("util.rs")); + + // `ambiguous` is the one that may: it builds the candidate list for a failed + // search, reaches the user on stderr, and is not reachable from `content_trim`. + assert_eq!( + callers, + vec!["ambiguous".to_string()], + "`color_text` asks `should_use_colors()`. Everything reachable from \ + `content_trim` has to take the decision as an argument and pass it to \ + `paint` instead, because the board renders with colour off and an escape \ + in a ratatui paragraph is drawn as literal bytes. If the new caller really \ + is CLI-only, add it here and say why." + ); + } + + /// Which functions in this file call `color_text`, by name, definitions and the + /// test module excluded. + fn callers_of_color_text(source: &str) -> Vec { + let body = match source.find("\n#[cfg(test)]") { + Some(end) => &source[..end], + None => source, + }; + + let mut current = String::new(); + let mut callers = Vec::new(); + for line in body.lines() { + if let Some(rest) = line.strip_prefix("fn ").or_else(|| line.strip_prefix("pub fn ")) { + current = rest.split('(').next().unwrap_or_default().to_string(); + continue; + } + if line.contains("color_text(") && !callers.contains(¤t) { + callers.push(current.clone()); + } + } + + callers + } + #[test] fn a_section_rule_matches_the_width_of_its_name() { let rendered = content_trim_colored("# T\n\n## Description\nbody\n");