Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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.18.1"
62 changes: 56 additions & 6 deletions src/progress.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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(
Expand Down
125 changes: 112 additions & 13 deletions tests/cli_terminal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,58 @@
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::num::NonZeroU16;
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<u8>)> {
const ROWS: u16 = 30;
const COLUMNS: u16 = 100;
type TerminalChunks = Vec<(Instant, Vec<u8>)>;

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,
},
None,
)
.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)
Expand All @@ -39,11 +70,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}"),
Expand All @@ -52,13 +98,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
}

Expand Down Expand Up @@ -130,6 +175,60 @@ 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(
NonZeroU16::new(ROWS).unwrap(),
NonZeroU16::new(COLUMNS).unwrap(),
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::<Vec<_>>()
.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.
Expand Down
Loading