From 55ff6ed6aa02ff35ef6133ce484bb1e7e48ee901 Mon Sep 17 00:00:00 2001 From: Friedel Ziegelmayer Date: Thu, 26 Jan 2023 15:44:36 +0100 Subject: [PATCH] fix(cli): only write progress if TTY and write it stderr only --- Cargo.lock | 1 + Cargo.toml | 1 + src/main.rs | 70 ++++++++++++++++++++++++++++++++++++++++++----------- 3 files changed, 58 insertions(+), 14 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 52edb2ca6d..a86d3c66dc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1696,6 +1696,7 @@ dependencies = [ "futures", "hex", "indicatif", + "is-terminal", "postcard", "rand 0.7.3", "rcgen", diff --git a/Cargo.toml b/Cargo.toml index ffb090c66b..79fbc85674 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ ed25519-dalek = "1.0.1" futures = "0.3.25" hex = "0.4.3" indicatif = { version = "0.17.2", features = ["tokio"] } +is-terminal = "0.4.2" postcard = { version = "1.0.2", default-features = false, features = ["alloc", "use-std", "experimental-derive"] } rand = "0.7" rcgen = "0.10.0" diff --git a/src/main.rs b/src/main.rs index d2007b0abc..9849fb56b7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,11 @@ -use std::{net::SocketAddr, path::PathBuf, str::FromStr}; +use std::{io::Write, net::SocketAddr, path::PathBuf, str::FromStr}; use anyhow::{anyhow, ensure, Context, Result}; use clap::{Parser, Subcommand}; use console::style; use futures::StreamExt; use indicatif::{HumanDuration, ProgressBar, ProgressDrawTarget, ProgressState, ProgressStyle}; +use is_terminal::IsTerminal; use sendme::protocol::AuthToken; use tracing::trace; use tracing_subscriber::{fmt, prelude::*, EnvFilter}; @@ -40,10 +41,11 @@ enum Commands { #[clap(about = "Fetch the data from the hash")] Get { /// The authentication token to present to the server. + #[clap(long, short)] token: String, /// The root hash to retrieve. hash: bao::Hash, - #[clap(long)] + #[clap(long, short)] /// PeerId of the provider. peer_id: PeerId, #[clap(long, short)] @@ -54,6 +56,36 @@ enum Commands { }, } +// Note about writing to STDOUT vs STDERR +// Looking at https://unix.stackexchange.com/questions/331611/do-progress-reports-logging-information-belong-on-stderr-or-stdout +// it is a little complicated. +// The current setup is to write all progress information to STDERR and all data to STDOUT. + +struct OutWriter { + is_atty: bool, + stderr: std::io::Stderr, +} + +impl OutWriter { + pub fn new() -> Self { + let stderr = std::io::stderr(); + let is_atty = stderr.is_terminal(); + Self { is_atty, stderr } + } +} + +impl OutWriter { + pub fn println(&mut self, content: impl AsRef<[u8]>) { + if self.is_atty { + self.stderr.write_all(content.as_ref()).unwrap(); + self.stderr.write_all(b"\n").unwrap(); + } + } +} + +const PROGRESS_STYLE: &str = + "{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})"; + #[tokio::main(flavor = "multi_thread")] async fn main() -> Result<()> { tracing_subscriber::registry() @@ -63,6 +95,8 @@ async fn main() -> Result<()> { let cli = Cli::parse(); + let mut out_writer = OutWriter::new(); + match cli.command { Commands::Get { hash, @@ -71,7 +105,8 @@ async fn main() -> Result<()> { addr, out, } => { - println!("Fetching: {}", hash.to_hex()); + out_writer.println(format!("Fetching: {}", hash.to_hex())); + let mut opts = get::Options { peer_id: Some(peer_id), ..Default::default() @@ -82,7 +117,8 @@ async fn main() -> Result<()> { let token = AuthToken::from_str(&token).context("Wrong format for authentication token")?; - println!("{} Connecting ...", style("[1/3]").bold().dim()); + out_writer.println(format!("{} Connecting ...", style("[1/3]").bold().dim())); + let pb = ProgressBar::hidden(); let stream = get::run(hash, token, opts); tokio::pin!(stream); @@ -90,15 +126,22 @@ async fn main() -> Result<()> { trace!("client event: {:?}", event); match event? { get::Event::Connected => { - println!("{} Requesting ...", style("[2/3]").bold().dim()); + out_writer + .println(format!("{} Requesting ...", style("[2/3]").bold().dim())); } get::Event::Requested { size } => { - println!("{} Downloading ...", style("[3/3]").bold().dim()); + out_writer + .println(format!("{} Downloading ...", style("[3/3]").bold().dim())); pb.set_style( - ProgressStyle::with_template("{spinner:.green} [{elapsed_precise}] [{wide_bar:.cyan/blue}] {bytes}/{total_bytes} ({eta})") + ProgressStyle::with_template(PROGRESS_STYLE) .unwrap() - .with_key("eta", |state: &ProgressState, w: &mut dyn std::fmt::Write| write!(w, "{:.1}s", state.eta().as_secs_f64()).unwrap()) - .progress_chars("#>-") + .with_key( + "eta", + |state: &ProgressState, w: &mut dyn std::fmt::Write| { + write!(w, "{:.1}s", state.eta().as_secs_f64()).unwrap() + }, + ) + .progress_chars("#>-"), ); pb.set_length(size as u64); pb.set_draw_target(ProgressDrawTarget::stderr()); @@ -132,15 +175,14 @@ async fn main() -> Result<()> { .await? .context("Failed to write output file")?; } else { - // Write to STDOUT + // Write to OUT_WRITER let mut stdout = tokio::io::stdout(); tokio::io::copy(&mut reader, &mut stdout).await?; } } get::Event::Done(stats) => { pb.finish_and_clear(); - - println!("Done in {}", HumanDuration(stats.elapsed)); + out_writer.println(format!("Done in {}", HumanDuration(stats.elapsed))); } } } @@ -179,8 +221,8 @@ async fn main() -> Result<()> { } let mut provider = provider_builder.build()?; - println!("PeerID: {}", provider.peer_id()); - println!("Auth token: {}", provider.auth_token()); + out_writer.println(format!("PeerID: {}", provider.peer_id())); + out_writer.println(format!("Auth token: {}", provider.auth_token())); provider.run(opts).await?; // Drop tempath to signal it can be destroyed