mirror of
https://github.com/n0-computer/iroh.git
synced 2026-12-03 08:01:40 +00:00
fix(cli): only write progress if TTY and write it stderr only
This commit is contained in:
Generated
+1
@@ -1696,6 +1696,7 @@ dependencies = [
|
||||
"futures",
|
||||
"hex",
|
||||
"indicatif",
|
||||
"is-terminal",
|
||||
"postcard",
|
||||
"rand 0.7.3",
|
||||
"rcgen",
|
||||
|
||||
@@ -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"
|
||||
|
||||
+56
-14
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user