use std::fmt::Display;
use std::io::{IsTerminal, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use crate::output::{self, Val};
use crate::style::palette::{MUTED, RED, ROSE, SOFT, TEXT};
use crate::style::{mix, paint};
use crate::widgets::{BarStyle, Spinner, shimmer};
use crate::{format, term};
struct Ticker {
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
prev_interrupt: Option<usize>,
}
impl Ticker {
fn start(frame: impl Fn(f32) -> String + Send + 'static) -> Ticker {
let prev_interrupt = term::guard_interrupt();
print!("\x1b[?25l\x1b[?7l");
let stop = Arc::new(AtomicBool::new(false));
let flag = stop.clone();
let thread = thread::spawn(move || {
let t0 = Instant::now();
while !flag.load(Ordering::Relaxed) {
print!("\r{}\x1b[K", frame(t0.elapsed().as_secs_f32()));
let _ = std::io::stdout().flush();
thread::sleep(Duration::from_millis(33));
}
});
Ticker {
stop,
thread: Some(thread),
prev_interrupt,
}
}
fn finish(&mut self, last: &str) {
let Some(thread) = self.thread.take() else {
return;
};
self.stop.store(true, Ordering::Relaxed);
let _ = thread.join();
print!("\r{last}\x1b[K\n\x1b[?7h\x1b[?25h");
let _ = std::io::stdout().flush();
term::restore_interrupt(self.prev_interrupt.take());
}
}
impl Drop for Ticker {
fn drop(&mut self) {
self.finish("");
}
}
fn done_line(label: &str, took: Duration) -> String {
format!(
" {} {} {}",
paint(ROSE, "●"),
paint(TEXT, label),
paint(MUTED, &format::duration(took))
)
}
pub fn spin<T>(label: &str, f: impl FnOnce() -> T) -> T {
match try_spin(label, || Ok::<T, std::convert::Infallible>(f())) {
Ok(v) => v,
Err(never) => match never {},
}
}
pub fn try_spin<T, E: Display>(label: &str, f: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
let start = Instant::now();
if output::json() {
let result = f();
let mut fields = vec![
("label", Val::Str(label)),
("outcome", Val::Str(if result.is_ok() { "ok" } else { "fail" })),
("secs", Val::Num(start.elapsed().as_secs_f64())),
];
let error = result.as_ref().err().map(|e| e.to_string()).unwrap_or_default();
if result.is_err() {
fields.push(("error", Val::Str(&error)));
}
output::emit("task", &fields);
return result;
}
if output::quiet() || !std::io::stdout().is_terminal() {
let result = f();
let took = format::duration(start.elapsed());
match &result {
Err(e) => eprintln!(" [FAIL] {label} ({took}) - {e}"),
Ok(_) if !output::quiet() => println!(" [ok] {label} ({took})"),
Ok(_) => {}
}
return result;
}
let owned = label.to_string();
let mut ticker = Ticker::start(move |t| format!(" {} {}", Spinner::default().frame(t), shimmer(&owned, t)));
let result = f();
match &result {
Ok(_) => ticker.finish(&done_line(label, start.elapsed())),
Err(e) => {
let took = paint(RED, &format::duration(start.elapsed()));
ticker.finish(&format!(" {} {} {took}", paint(RED, "✕"), paint(RED, label)));
println!(" {}", paint(mix(RED, SOFT, 0.3), &e.to_string()));
}
}
result
}
struct Counts {
done: u64,
total: Option<u64>,
bytes: bool,
bar: BarStyle,
}
pub struct Progress {
counts: Arc<Mutex<Counts>>,
label: String,
start: Instant,
ticker: Option<Ticker>,
finished: bool,
}
impl Progress {
pub fn new(label: impl Into<String>, total: u64) -> Self {
Progress::start(label.into(), Some(total))
}
pub fn unknown(label: impl Into<String>) -> Self {
Progress::start(label.into(), None)
}
fn start(label: String, total: Option<u64>) -> Self {
let counts = Arc::new(Mutex::new(Counts {
done: 0,
total,
bytes: false,
bar: BarStyle::default(),
}));
let start = Instant::now();
let drawn = output::output() == output::Output::Pretty && std::io::stdout().is_terminal();
let ticker = drawn.then(|| {
let (counts, label) = (counts.clone(), label.clone());
Ticker::start(move |t| progress_line(&label, &lock(&counts), start.elapsed(), t))
});
Progress {
counts,
label,
start,
ticker,
finished: false,
}
}
pub fn bytes(self) -> Self {
lock(&self.counts).bytes = true;
self
}
pub fn with_bar(self, bar: BarStyle) -> Self {
lock(&self.counts).bar = bar;
self
}
pub fn inc(&self, n: u64) {
let mut c = lock(&self.counts);
c.done += n;
if let Some(total) = c.total {
c.done = c.done.min(total);
}
}
pub fn set(&self, n: u64) {
let mut c = lock(&self.counts);
c.done = c.total.map_or(n, |total| n.min(total));
}
pub fn set_total(&self, total: u64) {
let mut c = lock(&self.counts);
c.total = Some(total);
c.done = c.done.min(total);
}
pub fn add_total(&self, n: u64) {
let mut c = lock(&self.counts);
c.total = Some(c.total.unwrap_or(0) + n);
}
pub fn finish(mut self) {
self.end();
}
fn end(&mut self) {
if std::mem::replace(&mut self.finished, true) {
return;
}
let took = self.start.elapsed();
if let Some(t) = self.ticker.as_mut() {
return t.finish(&done_line(&self.label, took));
}
if output::json() {
let c = lock(&self.counts);
let mut fields = vec![
("label", Val::Str(&self.label)),
("done", Val::Num(c.done as f64)),
("secs", Val::Num(took.as_secs_f64())),
];
if let Some(total) = c.total {
fields.push(("total", Val::Num(total as f64)));
}
output::emit("progress", &fields);
} else if !output::quiet() {
println!(" [ok] {} ({})", self.label, format::duration(took));
}
}
}
impl Drop for Progress {
fn drop(&mut self) {
self.end();
}
}
pub trait ProgressIterator: Iterator + Sized {
fn progress(self, label: impl Into<String>) -> WithProgress<Self>;
}
impl<I: Iterator> ProgressIterator for I {
fn progress(self, label: impl Into<String>) -> WithProgress<Self> {
let total = match self.size_hint() {
(lo, Some(hi)) if lo == hi => Some(lo as u64),
_ => None,
};
WithProgress {
inner: self,
bar: Some(Progress::start(label.into(), total)),
}
}
}
pub struct WithProgress<I> {
inner: I,
bar: Option<Progress>,
}
impl<I> WithProgress<I> {
pub fn with_bar(self, bar: BarStyle) -> Self {
if let Some(p) = &self.bar {
lock(&p.counts).bar = bar;
}
self
}
pub fn bar(&self) -> Option<&Progress> {
self.bar.as_ref()
}
}
impl<I: Iterator> Iterator for WithProgress<I> {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> {
let item = self.inner.next();
match &item {
Some(_) => {
if let Some(bar) = &self.bar {
bar.inc(1);
}
}
None => drop(self.bar.take()),
}
item
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
fn lock(counts: &Mutex<Counts>) -> std::sync::MutexGuard<'_, Counts> {
counts.lock().unwrap_or_else(|e| e.into_inner())
}
fn progress_line(label: &str, c: &Counts, elapsed: Duration, t: f32) -> String {
let amount = |n: u64| {
if c.bytes { format::bytes(n) } else { format::count(n) }
};
let rate = c.done as f64 / elapsed.as_secs_f64().max(0.001);
let spinner = Spinner::default().frame(t);
let Some(total) = c.total else {
let mut stats = amount(c.done);
if c.done > 0 {
stats += &format!(" · {}/s", amount(rate as u64));
}
return format!(" {spinner} {} {}", shimmer(label, t), paint(SOFT, &stats));
};
let f = if total == 0 { 1.0 } else { c.done as f32 / total as f32 };
let mut stats = format!("{:>3.0}% {} / {}", f * 100.0, amount(c.done), amount(total));
if c.done > 0 && rate > 0.0 {
let left = Duration::from_secs_f64(total.saturating_sub(c.done) as f64 / rate);
stats += &format!(" · {}/s · {} left", amount(rate as u64), format::duration(left));
}
format!(
" {spinner} {} {} {}",
paint(TEXT, label),
c.bar.draw(f, 24, t),
paint(SOFT, &stats)
)
}