diff --git a/Cargo.lock b/Cargo.lock index f8636de..9b83f36 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1563,7 +1563,7 @@ dependencies = [ [[package]] name = "worklane" -version = "0.33.1" +version = "0.33.2" dependencies = [ "anyhow", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 1749612..bd3f451 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "worklane" -version = "0.33.1" +version = "0.33.2" edition = "2024" [dependencies] diff --git a/docs/relations.md b/docs/relations.md index febb3aa..a20a81d 100644 --- a/docs/relations.md +++ b/docs/relations.md @@ -26,7 +26,7 @@ Recording an edge between two tickets, and drawing the block that reports them. - **A dependent may stand level with its blocker but never ahead of it.** `blocks_move` is the rule: the move is refused exactly when the status moved into is further down `Status::ALL` than the blocker's own, so a blocker in reviewing lets the dependent be committed and reviewed and gates only done. The first shape of this refused every move while a blocker was not done, which read as one rule rather than a table of transitions but stopped the work it was meant to order: a pair is usually built and reviewed together, and waiting for the blocker to land cost a `-f` on every move and left the rule enforcing nothing - **A finished blocker is answered by `is_open`, and a discard target by name.** Done landed and discarded never will, so neither holds anything up, and that is the one place the board decides what finished means. Discarded is last in `Status::ALL` for the stamp rule's sake, so a comparison of positions alone would read a discard as the furthest move of all: `blocks_move` returns false for it outright, since abandoning a ticket is not carrying it along the flow and owes nothing to what it waits on. A status that is not one of the five holds up every move, the direction `is_open` already takes with such a value: a fault surfaces rather than quietly letting a dependent past - **The blocker check runs on every move**, after the already-in-that-status return and behind `force`, with the target status passed in as what decides the answer. A move to the status the ticket is already in is not a move, so it is not refused. A backward move never is either, being at or behind everything, and it needs `-f` for its own reason anyway. `-f` bypasses three rules, which is the right home for it: each one is a deliberate override of something the board would otherwise keep true -- **A blocker that is not on the board warns and allows the move.** Refusing would wedge the ticket with no way out but `-f`, and a uuid nothing carries is a bookkeeping fault rather than a dependency. The refusal names **every** blocker still behind the move and the status it was for, since advancing the one that happened to be printed would leave the ticket held up, and a ticket refused the next stage after moving once is otherwise told nothing about what changed. A blocker further along than the move is left out of the list entirely: a dependent told to wait for work already ahead of it has nothing to act on +- **A blocker that is not on the board warns and allows the move.** Refusing would wedge the ticket with no way out but `-f`, and a uuid nothing carries is a bookkeeping fault rather than a dependency. The warning goes through the sink `check_blockers` is handed, which is why a guard that says nothing on the happy path takes one at all: the same helper runs from the board's command prompt, where the process's stderr is the alternate screen. See [The Command Prompt](tui-prompts.md). The refusal names **every** blocker still behind the move and the status it was for, since advancing the one that happened to be printed would leave the ticket held up, and a ticket refused the next stage after moving once is otherwise told nothing about what changed. A blocker further along than the move is left out of the list entirely: a dependent told to wait for work already ahead of it has nothing to act on - Left out on purpose: removing a relation, which 4179958 assigns to 74904dc. The blocked marker on the card landed in b8ce18c, and it cost no scan of the board: the blockers ride along on the read that already builds the cards. It asks `blocks_move` about the status one stage ahead of the column the card is in, so the mark means the card cannot advance and not that a dependency was ever recorded. See [The Board View](tui-board.md) ## The Relations Block diff --git a/docs/tui-prompts.md b/docs/tui-prompts.md index ee548e4..2c793c6 100644 --- a/docs/tui-prompts.md +++ b/docs/tui-prompts.md @@ -26,6 +26,7 @@ The three input modes on the board and the key that copies an id off it. - **Enter runs it, through `main.rs`'s `dispatch` and never through a handler this file names.** That match is the one mapping from a parsed command to the function that performs it: `main` calls it with its own stdout and the working directory, `Board::run` calls it with a buffer and the selected tab's root. A second copy inside `tui.rs` would drift the first time a command was added, and it would drift *silently*, since both halves go on compiling. The match is exhaustive so a new verb cannot fall into an `_` arm and do nothing, and `main_and_the_prompt_run_one_dispatch_table` reads both files as text to pin it. Only `tui` is matched outside the table, in `main`, because the board is that table's caller rather than an entry in it; reached from the prompt it is refused in those words - **`from_arg_matches` on the same matches gives `run` the typed values.** One parse, two readings: `command_name` walks the subcommands to name what resolved and `from_arg_matches` reconstructs the `Cli`. A `match` over every `Command` variant to get one or the other would be a second list of every verb the CLI has - **The handler's own words are what the board reports, word for word.** Those messages are written for a person already, and a second set kept here would go stale the first time one of them changed. The sink is a buffer, so the words come back as text and the board styles them; it is plain for the same reason `Detail` holds spans, since a ratatui paragraph prints an escape rather than obeying it. An error never goes through a sink at all — `color_text` asks the *process* about its stdout, which under the board answers yes about a terminal the message is not going to — so `error_lines` runs `without_escapes` over it and puts each cause on a line of its own +- **A warning goes through the sink's second stream, and never through `eprintln!`.** `Sink` carries two writers because the CLI's two streams are two: `Sink::std` hands the answer to stdout and an aside to stderr, and a shell has to go on reading the same line on the same stream. Under the board neither is a stream at all — stderr is the alternate screen with the columns on it — so `Sink::buffer` *holds* its warnings and `Board::run` reads them back with `Sink::warnings` and puts them above the answer, on both outcomes: a `mv` that warns about a dangling blocker and is then refused by a real one wrote the aside first, and it is the half that says why the refusal names one blocker and the ticket records two. That is c680e24: one `eprintln!` in `check_blockers` outlived fa5662a because a helper had no sink to reach, and ratatui does not repaint a cell it believes is unchanged, so the fragment stayed on the columns until something else redrew them. `no_handler_or_helper_reaches_a_print_macro` walks `src` for the next one, each file cut at its test module, so a print site in a module added tomorrow is caught the day it is added - **A handler that errors leaves the prompt open with the line intact.** The usual cause is an ambiguous id, and the fix is two more characters rather than the whole line retyped from `:`. Ambiguity is an `Err` carrying the candidates, not a print and an `exit`, which is what makes it safe to reach from here at all - **The reload after a command is unconditional, and runs whether it failed or not.** `tick` reloads on the digest, which is right for a change made in another pane and needless latency for one the board just made: the reader would watch their own `mv` take up to a poll interval to appear. Either way, because a handler that failed part way through has still written - **The selection is restored by uuid across that reload, never by index.** `mv` puts the card in another column, `set --title` renames its file, and a filter can drop it out of view entirely, so the slot is not the ticket. `Board::reselect` has three answers: the card is in a drawn column and the selection goes to it; it is on the board but in a column the rotation is hiding, which is where `--status done` lands by default, so the notice says where it went and which key shows it; or the filter no longer holds it, which is said too, since a card vanishing from under the highlight reads as a bug in the board diff --git a/src/handlers.rs b/src/handlers.rs index 94758d3..5ce0ce7 100644 --- a/src/handlers.rs +++ b/src/handlers.rs @@ -501,7 +501,18 @@ fn move_ticket_file( /// A target the board does not have warns and allows the move. Refusing there would /// wedge the ticket behind a bookkeeping fault with no way out but `--force`, and a /// dangling uuid is not a dependency. -fn check_blockers(worklane_dir: &Path, content: &str, title: &str, target: Status) -> Result<()> { +/// +/// The warning goes through the `sink` rather than through `eprintln!`, which is why a +/// helper that says nothing on the happy path takes one at all: this runs from the +/// board's command prompt as well as from `main`, and there the process's stderr is the +/// alternate screen. The refusal takes its colour from the sink for the same reason. +fn check_blockers( + worklane_dir: &Path, + content: &str, + title: &str, + target: Status, + sink: &mut Sink, +) -> Result<()> { let edges: Vec = parse_relations(content, title)? .into_iter() .filter(|relation| relation.kind == RelationKind::BlockedBy) @@ -522,15 +533,15 @@ fn check_blockers(worklane_dir: &Path, content: &str, title: &str, target: Statu Some(blocker) if !blocks_move(target, &blocker.status) => {} Some(blocker) => behind.push(format!( " ({}) {} [{}]", - color_text(short_id(&blocker.uuid), Color::Red), + sink.color(short_id(&blocker.uuid), Color::Red), blocker.title, - color_text(&blocker.status, Color::Orange), + sink.color(&blocker.status, Color::Orange), )), - None => eprintln!( + None => sink.warnln(&format!( "Warning: ticket '{}' is blocked by {}, which is not on the board.", title, short_id(&edge.target), - ), + ))?, } } @@ -544,8 +555,8 @@ fn check_blockers(worklane_dir: &Path, content: &str, title: &str, target: Statu // next stage is otherwise told nothing about what changed. Err(anyhow!( "Cannot move '{}' to {} while it is blocked by:\n{}\nA ticket cannot move ahead of what it waits on. Use --force (-f) to move it anyway.", - color_text(title, Color::Green), - color_text(target.as_str(), Color::Orange), + sink.color(title, Color::Green), + sink.color(target.as_str(), Color::Orange), behind.join("\n"), )) } @@ -558,7 +569,11 @@ fn check_blockers(worklane_dir: &Path, content: &str, title: &str, target: Statu /// /// Tickets already done or discarded do not hold it up: a dependency that was satisfied /// or abandoned is nobody's plan anymore. -fn check_dependents(worklane_dir: &Path, uuid: &str, title: &str) -> Result<()> { +/// +/// The `sink` is here for the colour alone, the rule [`check_blockers`] follows: this +/// refusal is drawn by the board as well as printed by the CLI, and a helper that asks +/// the process about its stdout answers about a terminal the message is not going to. +fn check_dependents(worklane_dir: &Path, uuid: &str, title: &str, sink: &mut Sink) -> Result<()> { let index = RelationIndex::load(worklane_dir)?; // Every open dependent, not the first, for the reason `check_blockers` names them @@ -575,9 +590,9 @@ fn check_dependents(worklane_dir: &Path, uuid: &str, title: &str) -> Result<()> .map(|ticket| { format!( " ({}) {} [{}]", - color_text(short_id(&ticket.uuid), Color::Red), + sink.color(short_id(&ticket.uuid), Color::Red), ticket.title, - color_text(&ticket.status, Color::Orange), + sink.color(&ticket.status, Color::Orange), ) }) .collect(); @@ -588,7 +603,7 @@ fn check_dependents(worklane_dir: &Path, uuid: &str, title: &str) -> Result<()> Err(anyhow!( "Cannot discard '{}' while open tickets are blocked by it:\n{}\nUse --force (-f) to discard it anyway.", - color_text(title, Color::Green), + sink.color(title, Color::Green), waiting.join("\n"), )) } @@ -694,8 +709,10 @@ pub fn cmd_mv(args: &MvArgs, start: &Path, sink: &mut Sink) -> Result<()> { // it. if !force { match discarding { - true => check_dependents(&worklane_dir, &parse_ticket_field(&resolved, "ID"), &title)?, - false => check_blockers(&worklane_dir, &resolved, &title, *target)?, + true => { + check_dependents(&worklane_dir, &parse_ticket_field(&resolved, "ID"), &title, sink)? + } + false => check_blockers(&worklane_dir, &resolved, &title, *target, sink)?, } } @@ -2231,6 +2248,12 @@ mod sink_tests { } fn ticket(dir: &Path, status: &str, uuid: &str) { + ticket_with(dir, status, uuid, ""); + } + + /// The same ticket with `extra` appended, for a test about a section the plain + /// fixture does not carry. + fn ticket_with(dir: &Path, status: &str, uuid: &str, extra: &str) { fs::write( dir.join(status).join(format!("{}_ticket.md", uuid)), format!( @@ -2246,14 +2269,31 @@ mod sink_tests { - **Tags**: _None_\n\ - **Owner**: alice\n\ - **Created At**: 2026-08-21 02:10:17\n\ - - **Status**: {status}\n", + - **Status**: {status}\n\ + {extra}", u = uuid, status = status, + extra = extra, ), ) .unwrap(); } + /// A project directory with a real board under it, for a handler that takes the path + /// a shell would have been run from and walks up from it. [`temp_worklane`] is the + /// board itself, which is what a handler already handed one takes. + /// + /// A [`Fixture`], so the tree goes when the test does whether it passed or not, which + /// is the rule for a unit-test fixture in this crate. + fn temp_project() -> Fixture { + let root = Fixture::new("wl-sink-project").child("project"); + let dir = root.join(".worklane"); + for status in status_dirs() { + fs::create_dir_all(dir.join(status)).unwrap(); + } + root + } + /// A handler writes through the sink it is handed, and a caller can read the bytes /// back without a terminal or a real stdout. #[test] @@ -2314,4 +2354,133 @@ mod sink_tests { fs::remove_dir_all(&dir).ok(); } + /// The aside `check_blockers` writes for a blocker the board does not hold goes to + /// the sink's warnings, and not into what the caller collects as the answer. + /// + /// Two destinations because the CLI's two are two: this has always been stderr and + /// the answer stdout, and the board reads the answer back to draw it, so a warning + /// folded into it would be indistinguishable from what the command said. What it + /// must not be is an `eprintln!`, which reaches the process's own stderr — under the + /// board that is the alternate screen with the columns on it. + #[test] + fn a_dangling_blocker_warns_through_the_sink() { + let root = temp_project(); + let dir = root.join(".worklane"); + ticket_with( + &dir, + "backlog", + "aaaa1111-aaaa-4000-8000-000000000000", + "\n## Relations\n\n- blocked by cccc3333-cccc-4000-8000-000000000000\n", + ); + + let args = MvArgs { + ticket: "aaaa1111".to_string(), + status: Status::Committed, + force: false, + actor: None, + actor_from_git: false, + reason: None, + }; + + let mut buf = Vec::new(); + let warned = { + let mut sink = Sink::buffer(&mut buf); + // A dangling uuid is a bookkeeping fault rather than a dependency, so the + // move happens and the warning is the whole of what is said about it. + cmd_mv(&args, &root, &mut sink).unwrap(); + sink.warnings() + }; + + assert!( + warned.contains("not on the board"), + "the warning did not reach the sink:\n{warned}" + ); + + let out = String::from_utf8(buf).unwrap(); + assert!(out.contains("Moved ticket"), "the move said nothing:\n{out}"); + assert!( + !out.contains("not on the board"), + "the warning landed in the answer:\n{out}" + ); + } + + /// A sink whose warnings have a stream of their own holds nothing back: those bytes + /// are gone to stderr, which is what [`Sink::std`] is for. Read back as empty rather + /// than as a copy, since a caller acting on both would report the warning twice. + #[test] + fn a_sink_with_a_stream_for_its_warnings_holds_none() { + let mut answer = Vec::new(); + let mut aside = Vec::new(); + let mut sink = Sink::with_warnings(Box::new(&mut answer), Box::new(&mut aside), false); + + sink.warnln("Warning: a blocker nothing holds").unwrap(); + sink.writeln("Moved ticket").unwrap(); + assert_eq!(sink.warnings(), "", "a warning with a stream was held as well as sent"); + sink.flush().unwrap(); + drop(sink); + + assert_eq!(String::from_utf8(aside).unwrap(), "Warning: a blocker nothing holds\n"); + assert_eq!(String::from_utf8(answer).unwrap(), "Moved ticket\n"); + } + + /// No handler and no helper reaches a print macro. Nowhere in `src`, not only in + /// this file. + /// + /// The caller chooses where a command's words go — `main` its own stdout and stderr, + /// the board a buffer it reads back and draws — and a `print!` writes to the + /// process's streams instead, which under the board is the alternate screen with the + /// columns on it. That is c680e24: one `eprintln!` in `check_blockers` outlived + /// fa5662a because a helper had no sink to reach, and ratatui does not repaint a cell + /// it believes is unchanged, so the fragment stayed on the columns until something + /// else redrew them. + /// + /// Over the directory rather than over a list of `include_str!`s, so a module added + /// tomorrow is scanned the day it is added: a list is what the fifty-first print site + /// hides behind. Each file is cut at its own test module, and comments are dropped, + /// because the docs around here name these macros to say why they are not called. + #[test] + fn no_handler_or_helper_reaches_a_print_macro() { + // The one site outside a test module that may, and it is not output: the fixture + // guard naming a directory it was told to leave behind, for the person reading the + // run rather than for anything collecting an answer. + let allowed = "eprintln!(\"kept fixture {}\", self.root.display());"; + + let mut printing: Vec = Vec::new(); + for entry in fs::read_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src")).unwrap() { + let path = entry.unwrap().path(); + if path.extension().and_then(|ext| ext.to_str()) != Some("rs") { + continue; + } + + let source = fs::read_to_string(&path).unwrap(); + let name = path.file_name().unwrap().to_string_lossy().to_string(); + printing.extend( + body_of(&source) + .map(str::trim) + .filter(|line| !line.starts_with("//") && *line != allowed) + .filter(|line| { + ["print!(", "println!(", "eprint!(", "eprintln!("] + .iter() + .any(|macro_call| line.contains(macro_call)) + }) + .map(|line| format!("{name}: {line}")), + ); + } + + assert!( + printing.is_empty(), + "a print macro writes to the process's own streams, which under the board is \ + the alternate screen. Take a `Sink` and use `writeln` for an answer or \ + `warnln` for an aside:\n{printing:#?}" + ); + } + + /// A file's lines up to its test module, which in this crate is the only inline + /// `mod` at column 0. A file's own assertions are allowed to name a macro the file + /// may not call, this test's own body first among them. + fn body_of(source: &str) -> impl Iterator { + source + .lines() + .take_while(|line| !(line.starts_with("mod ") && line.ends_with(" {"))) + } } diff --git a/src/tui.rs b/src/tui.rs index 3a3dbd1..ac82208 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -2535,14 +2535,22 @@ impl Board { .filter(|(uuid, _)| !is_unknown_value(uuid)); let mut buffer: Vec = Vec::new(); - let outcome = { + let (outcome, warned) = { let mut sink = Sink::buffer(&mut buffer); - crate::dispatch(command, &root, &mut sink).and_then(|()| sink.flush()) + let outcome = crate::dispatch(command, &root, &mut sink).and_then(|()| sink.flush()); + // Read on both outcomes and reported on both: a `mv` that warns about a + // dangling blocker and is then refused by a real one wrote the warning + // first, and dropping it there would lose the half that says why the + // refusal names one blocker and the ticket records two. + (outcome, sink.warnings()) }; + // The warning ahead of the answer, the order the handler wrote them in and the + // order a shell shows the two streams in. + // // Plain by construction, since the sink is: stripped anyway, because an escape // drawn into a ratatui paragraph is printed rather than obeyed, and this is the // one seam where a handler's bytes become a frame. - let said = without_escapes(&String::from_utf8_lossy(&buffer)) + let said = without_escapes(&format!("{warned}{}", String::from_utf8_lossy(&buffer))) .trim_end() .to_string(); @@ -2556,7 +2564,14 @@ impl Board { let moved = held.and_then(|(uuid, id)| self.reselect(&uuid, &id, screen)); match outcome { - Err(err) => self.notice = Some(Notice::failed(error_lines(&err))), + // The warning above the refusal, the order they were written in. + Err(err) => { + let failure = match said.is_empty() { + true => error_lines(&err), + false => format!("{said}\n{}", error_lines(&err)), + }; + self.notice = Some(Notice::failed(failure)); + } Ok(()) => { self.prompt = None; let words = match said.is_empty() { @@ -8226,6 +8241,85 @@ approach"; ); } + /// A warning comes back with the answer instead of going to stderr, which under the + /// board is the alternate screen: `eprintln!` drew the line straight onto the + /// columns, and ratatui does not repaint a cell it believes is unchanged, so the + /// fragment stayed there until something else redrew them. That is c680e24. + /// + /// Asserted on the notice for the reason `the_footer_reports_the_handlers_own_words` + /// is: the words being *there* is what says they were collected rather than printed. + #[test] + fn a_warning_is_reported_with_the_answer_rather_than_printed() { + let (root, mut board) = runnable(); + write_ticket( + &root.join(".worklane"), + "backlog", + WAITER, + "The waiter", + &blocked_by(ELSEWHERE), + ); + + // A dangling blocker is a bookkeeping fault rather than a dependency, so the + // move happens and the warning is the whole of what is said about it. + run_line(&mut board, "mv bbbbbbb --status committed"); + let notice = board.notice.as_ref().expect("the command said nothing"); + assert!(!notice.failed, "a dangling blocker refused the move: {}", notice.text); + assert_eq!(column_of(&board, "The waiter"), Some("committed")); + + let warning = notice.text.find("not on the board"); + let answer = notice.text.find("Moved ticket"); + assert!(warning.is_some(), "the warning never reached the board: {}", notice.text); + assert!( + warning < answer, + "the aside was not put above the answer it came before: {}", + notice.text + ); + + let screen = screen_text(&board); + for line in notice.lines() { + assert!(screen.contains(line.trim()), "`{line}` never reached the frame:\n{screen}"); + } + } + + /// Warned and then refused, which is one blocker the board does not hold and one it + /// does. Both are reported: the refusal names the blocker in the way and the ticket + /// records two, so dropping the aside is dropping the answer to why. + #[test] + fn a_refused_move_keeps_the_warning_that_came_before_it() { + let (root, mut board) = runnable(); + write_ticket( + &root.join(".worklane"), + "backlog", + WAITER, + "The waiter", + // `Alpha first`, which `runnable` leaves in the backlog: a blocker a ticket + // may stand level with and not move ahead of. + &format!( + "\n## Relations\n\n- blocked by {ELSEWHERE}\n\ + - blocked by 11111111-0000-4000-8000-000000000000\n" + ), + ); + + run_line(&mut board, "mv bbbbbbb --status committed"); + let notice = board.notice.as_ref().expect("the refusal said nothing"); + assert!(notice.failed, "a refused move was reported as a success"); + assert_eq!( + column_of(&board, "The waiter"), + Some("backlog"), + "the move happened anyway" + ); + + let warning = notice.text.find("not on the board"); + let refusal = notice.text.find("Cannot move"); + assert!( + warning.is_some(), + "the warning was dropped on the error path: {}", + notice.text + ); + assert!(refusal.is_some(), "the refusal was dropped: {}", notice.text); + assert!(warning < refusal, "the aside came after the refusal: {}", notice.text); + } + /// A handler that errors leaves the prompt open with the line exactly as it was: the /// usual cause is an ambiguous id, and the fix is two more characters rather than the /// whole line retyped from `:`. diff --git a/src/util.rs b/src/util.rs index 42eb347..30e9358 100644 --- a/src/util.rs +++ b/src/util.rs @@ -349,12 +349,33 @@ pub fn without_escapes(text: &str) -> String { /// `use_color` is the sink's answer, not a read of [`should_use_colors`]: a process /// whose stdout is a pipe still wants colour when the sink is a buffer a renderer /// will colour itself, and the board wants plain text however the terminal answers. +/// +/// A warning is the second stream, [`Warnings`], for the same reason the first one +/// exists: `eprintln!` in a helper reaches the process's stderr, which under the board +/// is the alternate screen. pub struct Sink<'a> { writer: Box, + /// Where a warning goes, which is not where the answer goes. + warnings: Warnings<'a>, /// Whether the bytes this sink writes carry colour escapes. pub use_color: bool, } +/// What a sink does with a warning: the aside a command writes on its way to an +/// answer, which the reader wants and no caller parses. +/// +/// Two streams rather than one, because the CLI's two are two: a warning has always +/// gone to stderr and the answer to stdout, and [`Sink::std`] cannot fold them +/// together without changing what a shell reads. Under the board neither is a stream +/// at all — stdout is the alternate screen in raw mode, and so is stderr — so the +/// warning is held instead and the board reports it beside the answer. +enum Warnings<'a> { + /// A writer of its own: `main`'s stderr. + Stream(Box), + /// Kept in memory for a caller that reads it back through [`Sink::warnings`]. + Held(Vec), +} + impl<'a> Sink<'a> { /// The process's stdout, coloured by what the terminal wants. /// @@ -362,8 +383,14 @@ impl<'a> Sink<'a> { /// command wrote to stdout through `println!`, and this sink writes to the same /// stdout through the same [`paint`]. pub fn std() -> Sink<'static> { - // Through `new` so the process's stdout is just another writer the sink wraps. - Sink::new(Box::new(std::io::stdout()), should_use_colors()) + // The one sink whose warnings have a stream to go to, and the reason there is a + // choice at all: stderr here is a terminal or a pipe the caller is reading, and + // holding a warning back would take it off a shell's screen. + Sink::with_warnings( + Box::new(std::io::stdout()), + Box::new(std::io::stderr()), + should_use_colors(), + ) } /// An in-memory buffer, plain, for a test or a caller that colours the text @@ -373,15 +400,33 @@ impl<'a> Sink<'a> { /// and the board styles them with ratatui, which is also why it must not be handed /// a coloured one — a paragraph prints an escape rather than obeying it. pub fn buffer(target: &'a mut Vec) -> Sink<'a> { + Sink::new(Box::new(target), false) + } + + /// Any writer, with the colour decision given. Its warnings are held: a caller + /// that named one destination named nowhere for an aside to go, and `main`'s + /// stderr is [`Sink::std`]'s alone. + pub fn new(writer: Box, use_color: bool) -> Sink<'a> { Sink { - writer: Box::new(target), - use_color: false, + writer, + warnings: Warnings::Held(Vec::new()), + use_color, } } - /// Any writer, with the colour decision given. - pub fn new(writer: Box, use_color: bool) -> Sink<'a> { - Sink { writer, use_color } + /// An answer and the asides that go with it, as two writers, with the colour + /// decision given. What [`Sink::std`] is built from, and the only way to a sink + /// whose warnings leave it rather than being held. + pub fn with_warnings( + writer: Box, + warnings: Box, + use_color: bool, + ) -> Sink<'a> { + Sink { + writer, + warnings: Warnings::Stream(warnings), + use_color, + } } /// The writer, for a caller that already knows how to fill it (the completions @@ -404,9 +449,51 @@ impl<'a> Sink<'a> { Ok(()) } + /// Write `text` and a newline as a warning, the way `eprintln!` did. + /// + /// For the aside a command makes on its way to an answer: something the reader + /// should know that does not stop the command and that nothing reading its output + /// should have to skip past. A handler reaching `eprintln!` instead wrote straight + /// to the process's stderr, which under the board is the alternate screen, and + /// ratatui does not repaint a cell it believes is unchanged — so the fragment stayed + /// on the columns until something else redrew them. + pub fn warnln(&mut self, text: &str) -> Result<()> { + match &mut self.warnings { + Warnings::Stream(writer) => { + writer.write_all(text.as_bytes())?; + writer.write_all(b"\n")?; + } + Warnings::Held(bytes) => { + bytes.extend_from_slice(text.as_bytes()); + bytes.push(b'\n'); + } + } + Ok(()) + } + + /// What this sink held back, for the caller that reads its warnings rather than + /// letting them reach a stream. + /// + /// Empty for a sink whose warnings have somewhere of their own to go, since those + /// bytes are already gone. Read it after the handler returns and on both outcomes: + /// a command that warns and is then refused wrote both, and the warning is the half + /// that says why the refusal names one blocker and not two. + pub fn warnings(&self) -> String { + match &self.warnings { + Warnings::Stream(_) => String::new(), + Warnings::Held(bytes) => String::from_utf8_lossy(bytes).to_string(), + } + } + /// Flush the writer, so a prompt reaches the terminal before a read. + /// + /// Both writers: a warning left in stderr's buffer while the answer reached stdout + /// is a warning the reader sees after the sentence it was about, or not at all. pub fn flush(&mut self) -> Result<()> { self.writer.flush()?; + if let Warnings::Stream(writer) = &mut self.warnings { + writer.flush()?; + } Ok(()) } diff --git a/tests/cmd_mv.rs b/tests/cmd_mv.rs index 06d0779..fdede48 100644 --- a/tests/cmd_mv.rs +++ b/tests/cmd_mv.rs @@ -906,6 +906,11 @@ fn mv_does_not_check_the_blockers_on_a_no_op() { /// A dangling target is a bookkeeping fault, not a dependency. Refusing there would /// wedge the ticket with no way out but `--force`. +/// +/// The stderr is asserted whole rather than searched, and that is the point of the +/// assertion: c680e24 moved this warning off `eprintln!` and onto the sink's second +/// stream so the board could collect it, and a shell has to go on reading the line it +/// always read, on the stream it always read it from. #[test] fn mv_warns_and_allows_when_a_blocker_is_not_on_the_board() { let temp = TempDir::new().unwrap(); @@ -920,10 +925,16 @@ fn mv_warns_and_allows_when_a_blocker_is_not_on_the_board() { let out = move_ticket(&temp, "aaaa1111", "committed", false); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!( + String::from_utf8_lossy(&out.stderr), + "Warning: ticket 'Gated Task' is blocked by bbbb222, which is not on the board.\n", + "the warning is not the line it was, on the stream it was on" + ); + // And it stays off stdout, which is what a caller reads the answer from. assert!( - String::from_utf8_lossy(&out.stderr).contains("not on the board"), - "{}", - String::from_utf8_lossy(&out.stderr) + !String::from_utf8_lossy(&out.stdout).contains("not on the board"), + "the warning landed in the answer: {}", + String::from_utf8_lossy(&out.stdout) ); assert!(worklane.join("committed").join(&filename).exists()); }