From fec75d898411eacb040ea7e28cefdd8d547e355d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robin=20B=C3=BCrgi?= Date: Tue, 1 Dec 2026 21:03:07 +0000 Subject: [PATCH 1/2] Replace live progress with partial results after Ctrl+C --- Cargo.lock | 28 ++++++++++ Cargo.toml | 1 + src/progress.rs | 62 +++++++++++++++++++--- tests/cli_terminal.rs | 120 +++++++++++++++++++++++++++++++++++++----- 4 files changed, 192 insertions(+), 19 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c56f82c..45934f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -61,6 +61,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "arrayvec" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47a64a0fd06e123e9e3cf3ad01432af17dcab8185e8023edcf184fe696f9675d" + [[package]] name = "atomic-waker" version = "1.1.2" @@ -167,6 +173,7 @@ dependencies = [ "reqwest", "serde", "serde_json", + "vt100", ] [[package]] @@ -1787,6 +1794,27 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vt100" +version = "0.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "054ff75fb8fa83e609e685106df4faeffdf3a735d3c74ebce97ec557d5d36fd9" +dependencies = [ + "itoa", + "unicode-width", + "vte", +] + +[[package]] +name = "vte" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5924018406ce0063cd67f8e008104968b74b563ee1b85dde3ed1f7cb87d3dbd" +dependencies = [ + "arrayvec", + "memchr", +] + [[package]] name = "walkdir" version = "2.5.1" diff --git a/Cargo.toml b/Cargo.toml index aa27e31..ad9a3a7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,3 +29,4 @@ indicatif = { version = "0.18", default-features = false, features = ["unicode-w [target.'cfg(any(target_os = "linux", target_os = "macos"))'.dev-dependencies] nix = { version = "0.32", features = ["term"] } +vt100 = "0.16" diff --git a/src/progress.rs b/src/progress.rs index b3504c5..a11e72c 100644 --- a/src/progress.rs +++ b/src/progress.rs @@ -1,7 +1,7 @@ use crate::{measurements::transfer_columns, stdout, OutputFormat}; -use console::{measure_text_width, Term}; -use indicatif::{ProgressBar, ProgressDrawTarget, ProgressState, ProgressStyle}; -use std::{borrow::Cow, fmt}; +use console::{is_dumb, measure_text_width, Term}; +use indicatif::{ProgressBar, ProgressDrawTarget, ProgressState, ProgressStyle, TermLike}; +use std::{borrow::Cow, fmt, io}; pub fn print_progress(name: &str, curr: u32, max: u32) { const BAR_LEN: u32 = 30; @@ -35,11 +35,13 @@ impl Progress { if !Self::allows_live_output(output_format) || len == 0 { return Self(None); } - let target = ProgressDrawTarget::stderr(); - if target.is_hidden() { + let terminal = Term::buffered_stderr(); + if !terminal.is_term() || is_dumb() { return Self(None); } - let columns = usize::from(Term::stderr().size().1); + let columns = usize::from(terminal.size().1); + let target = + ProgressDrawTarget::term_like_with_hz(Box::new(ProgressTerminal(terminal)), 20); let table_label = table_label.filter(|_| columns >= transfer_columns::ROW_WIDTH); let aligned = table_label.is_some(); let (label, template) = if let Some(label) = table_label { @@ -99,6 +101,54 @@ impl Progress { } } +#[derive(Debug)] +struct ProgressTerminal(Term); + +impl TermLike for ProgressTerminal { + fn width(&self) -> u16 { + self.0.size().1 + } + + fn height(&self) -> u16 { + self.0.size().0 + } + + fn move_cursor_up(&self, n: usize) -> io::Result<()> { + self.0.move_cursor_up(n) + } + + fn move_cursor_down(&self, n: usize) -> io::Result<()> { + self.0.move_cursor_down(n) + } + + fn move_cursor_right(&self, n: usize) -> io::Result<()> { + self.0.move_cursor_right(n) + } + + fn move_cursor_left(&self, n: usize) -> io::Result<()> { + self.0.move_cursor_left(n) + } + + fn write_line(&self, s: &str) -> io::Result<()> { + self.0.write_line(s) + } + + fn write_str(&self, s: &str) -> io::Result<()> { + self.0.write_str(s) + } + + fn clear_line(&self) -> io::Result<()> { + self.0.clear_line() + } + + fn flush(&self) -> io::Result<()> { + // Indicatif pads to the right margin. Cancel the pending wrap on the + // last line so an echoed ^C cannot move the cursor down before cleanup. + self.0.write_str("\r")?; + self.0.flush() + } +} + fn table_progress_template() -> String { use transfer_columns::{BAR_OFFSET, BAR_WIDTH, SAMPLES_WIDTH}; let row = transfer_columns::live_row( diff --git a/tests/cli_terminal.rs b/tests/cli_terminal.rs index ae0feb7..e7cfd65 100644 --- a/tests/cli_terminal.rs +++ b/tests/cli_terminal.rs @@ -3,20 +3,30 @@ mod support; use nix::pty::{openpty, Winsize}; +use nix::sys::termios::{tcgetattr, tcsetattr, LocalFlags, SetArg, SpecialCharacterIndices}; use std::cell::Cell; use std::fs::File; -use std::io::{self, Read}; -use std::process::Command; +use std::io::{self, Read, Write}; +use std::os::unix::process::CommandExt; +use std::process::{Command, ExitStatus}; use std::sync::mpsc; use std::thread; use std::time::{Duration, Instant}; use support::{finish, Response, Server}; -fn terminal_output(mut command: Command, log_filter: Option<&str>) -> Vec<(Instant, Vec)> { +const ROWS: u16 = 30; +const COLUMNS: u16 = 100; +type TerminalChunks = Vec<(Instant, Vec)>; + +fn terminal_run( + mut command: Command, + log_filter: Option<&str>, + interrupt_when: Option<&'static str>, +) -> (ExitStatus, TerminalChunks) { let pty = openpty( &Winsize { - ws_row: 30, - ws_col: 100, + ws_row: ROWS, + ws_col: COLUMNS, ws_xpixel: 0, ws_ypixel: 0, }, @@ -24,6 +34,26 @@ fn terminal_output(mut command: Command, log_filter: Option<&str>) -> Vec<(Insta ) .unwrap(); let slave = File::from(pty.slave); + if interrupt_when.is_some() { + let mut settings = tcgetattr(&slave).unwrap(); + settings + .local_flags + .insert(LocalFlags::ECHO | LocalFlags::ECHOCTL | LocalFlags::ISIG); + settings.control_chars[SpecialCharacterIndices::VINTR as usize] = 3; + tcsetattr(&slave, SetArg::TCSANOW, &settings).unwrap(); + command.stdin(slave.try_clone().unwrap()); + // Give the child a controlling terminal so the PTY generates SIGINT and + // echoes ^C, just as it would when typing Ctrl+C in a shell. + unsafe { + command.pre_exec(|| { + use nix::libc::{ioctl, setsid, STDIN_FILENO, TIOCSCTTY}; + if setsid() == -1 || ioctl(STDIN_FILENO, TIOCSCTTY, 0) == -1 { + return Err(io::Error::last_os_error()); + } + Ok(()) + }); + } + } command .stdout(slave.try_clone().unwrap()) .stderr(slave) @@ -39,11 +69,26 @@ fn terminal_output(mut command: Command, log_filter: Option<&str>) -> Vec<(Insta let reader = thread::spawn(move || { let mut master = File::from(pty.master); let mut chunks = Vec::new(); + let mut interrupt_when = interrupt_when; + let mut pending = Vec::new(); let mut buf = [0; 4096]; loop { match master.read(&mut buf) { Ok(0) => break, // macOS PTY EOF - Ok(size) => chunks.push((Instant::now(), buf[..size].to_vec())), + Ok(size) => { + let bytes = &buf[..size]; + chunks.push((Instant::now(), bytes.to_vec())); + if let Some(marker) = interrupt_when { + pending.extend_from_slice(bytes); + if pending + .windows(marker.len()) + .any(|bytes| bytes == marker.as_bytes()) + { + master.write_all(b"\x03").unwrap(); + interrupt_when = None; + } + } + } Err(err) if err.raw_os_error() == Some(nix::libc::EIO) => break, // Linux PTY EOF Err(err) if err.kind() == io::ErrorKind::Interrupted => continue, Err(err) => panic!("PTY read failed: {err}"), @@ -52,13 +97,12 @@ fn terminal_output(mut command: Command, log_filter: Option<&str>) -> Vec<(Insta chunks }); let output = finish(child, Duration::from_secs(8)); - let chunks = reader.join().unwrap(); - assert!( - output.status.success(), - "{}: {:?}", - output.status, - text(&chunks) - ); + (output.status, reader.join().unwrap()) +} + +fn terminal_output(command: Command, log_filter: Option<&str>) -> TerminalChunks { + let (status, chunks) = terminal_run(command, log_filter, None); + assert!(status.success(), "{status}: {:?}", text(&chunks)); chunks } @@ -130,6 +174,56 @@ fn shows_retry_during_backoff_without_counting_it_as_a_sample() { assert!(!after_row.contains('\x1b'), "{after_row:?}"); } +#[test] +fn ctrl_c_replaces_the_live_row_with_one_partial_result() { + let attempts = Cell::new(0); + let server = Server::new(move |path| { + if path == "/__down?bytes=100000" { + attempts.set(attempts.get() + 1); + if attempts.get() > 1 { + let mut response = Response::new(429, ""); + response.headers.push(("Retry-After".into(), "10".into())); + return response; + } + } + Response::normal(path) + }); + // Cancel with a live two-line display and one successful sample. The retry + // wait keeps the display still until the terminal receives the keypress. + let (status, chunks) = terminal_run( + server.command(&["-o", "stdout", "-n", "3"]), + None, + Some("HTTP 429; retrying in 10s"), + ); + let transcript = text(&chunks); + assert_eq!(status.code(), Some(130), "{transcript:?}"); + let (before, after) = transcript + .split_once("^C") + .unwrap_or_else(|| panic!("No Ctrl+C echo: {transcript:?}")); + let mut terminal = vt100::Parser::new(ROWS, COLUMNS, 0); + terminal.process(before.as_bytes()); + assert!(terminal + .screen() + .contents() + .contains("Download 100 KB [")); + terminal.process(b"^C"); + terminal.process(after.as_bytes()); + + let screen = terminal + .screen() + .rows(0, COLUMNS) + .collect::>() + .join("\n"); + let rows: Vec<_> = screen + .lines() + .filter(|line| line.starts_with("Download 100 KB")) + .collect(); + assert_eq!(rows.len(), 1, "Final screen:\n{screen}"); + assert!(rows[0].starts_with("Download 100 KB |"), "{screen}"); + assert!(rows[0].ends_with("1/3"), "{screen}"); + assert!(screen.contains("Run stopped: Cancelled"), "{screen}"); +} + #[test] fn keeps_dependency_logs_and_disables_terminal_redraws() { // The fixture closes each connection, so reqwest logs during each request. From 41b62e420a3893fa1380749711f95d97656c4192 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Robin=20B=C3=BCrgi?= Date: Tue, 1 Dec 2026 22:34:39 +0000 Subject: [PATCH 2/2] Pin the source-reviewed vt100 0.18.1 release Compare the published vt100, vte, and arrayvec package sources with their upstream tags and verify the archives against Cargo.lock. Keep vt100 test-only, pin its exact version, and adapt the terminal regression to the nonzero-dimensions API. --- Cargo.lock | 4 ++-- Cargo.toml | 2 +- tests/cli_terminal.rs | 7 ++++++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 45934f4..e87d373 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1796,9 +1796,9 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "vt100" -version = "0.16.2" +version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "054ff75fb8fa83e609e685106df4faeffdf3a735d3c74ebce97ec557d5d36fd9" +checksum = "eb05cdd19ae8707bf6a0a269972c07e6358103a7079faec749dec318a5b3dc23" dependencies = [ "itoa", "unicode-width", diff --git a/Cargo.toml b/Cargo.toml index ad9a3a7..1386d01 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,4 +29,4 @@ indicatif = { version = "0.18", default-features = false, features = ["unicode-w [target.'cfg(any(target_os = "linux", target_os = "macos"))'.dev-dependencies] nix = { version = "0.32", features = ["term"] } -vt100 = "0.16" +vt100 = "=0.18.1" diff --git a/tests/cli_terminal.rs b/tests/cli_terminal.rs index e7cfd65..c85d7d2 100644 --- a/tests/cli_terminal.rs +++ b/tests/cli_terminal.rs @@ -7,6 +7,7 @@ use nix::sys::termios::{tcgetattr, tcsetattr, LocalFlags, SetArg, SpecialCharact use std::cell::Cell; use std::fs::File; use std::io::{self, Read, Write}; +use std::num::NonZeroU16; use std::os::unix::process::CommandExt; use std::process::{Command, ExitStatus}; use std::sync::mpsc; @@ -200,7 +201,11 @@ fn ctrl_c_replaces_the_live_row_with_one_partial_result() { let (before, after) = transcript .split_once("^C") .unwrap_or_else(|| panic!("No Ctrl+C echo: {transcript:?}")); - let mut terminal = vt100::Parser::new(ROWS, COLUMNS, 0); + let mut terminal = vt100::Parser::new( + NonZeroU16::new(ROWS).unwrap(), + NonZeroU16::new(COLUMNS).unwrap(), + 0, + ); terminal.process(before.as_bytes()); assert!(terminal .screen()