1use crate::measure::Observer;
15use std::io::{IsTerminal, Write};
16use std::sync::atomic::{AtomicBool, Ordering};
17use std::sync::{Arc, Mutex, PoisonError};
18use std::thread::JoinHandle;
19use std::time::{Duration, Instant};
20
21const LOG_EVERY: Duration = Duration::from_secs(30);
23
24const TICK: Duration = Duration::from_secs(1);
27
28pub struct Bar {
32 state: Arc<Mutex<State>>,
33 stop: Arc<AtomicBool>,
34 ticker: Option<JoinHandle<()>>,
35}
36
37impl Bar {
38 pub fn new(label: &str, names: Vec<String>) -> Self {
39 let state = Arc::new(Mutex::new(State::new(label, names)));
40 let stop = Arc::new(AtomicBool::new(false));
41 let ticker = {
42 let (state, stop) = (Arc::clone(&state), Arc::clone(&stop));
43 std::thread::spawn(move || {
44 while !stop.load(Ordering::Relaxed) {
45 std::thread::park_timeout(TICK);
46 if !stop.load(Ordering::Relaxed) {
47 lock(&state).tick();
48 }
49 }
50 })
51 };
52 Bar {
53 state,
54 stop,
55 ticker: Some(ticker),
56 }
57 }
58
59 pub fn finish(&mut self) {
62 self.stop.store(true, Ordering::Relaxed);
63 if let Some(t) = self.ticker.take() {
64 t.thread().unpark();
65 t.join().ok();
66 }
67 lock(&self.state).clear();
68 }
69}
70
71impl Drop for Bar {
72 fn drop(&mut self) {
73 self.finish();
74 }
75}
76
77fn lock(state: &Mutex<State>) -> std::sync::MutexGuard<'_, State> {
79 state.lock().unwrap_or_else(PoisonError::into_inner)
80}
81
82impl Observer for Bar {
83 fn planned(&mut self, remaining: &[u64]) {
84 lock(&self.state).planned(remaining);
85 }
86 fn started(&mut self, subject: usize) {
87 lock(&self.state).started(subject);
88 }
89 fn finished(&mut self, subject: usize, elapsed: Duration) {
90 lock(&self.state).finished(subject, elapsed);
91 }
92 fn dropped(&mut self, subject: usize) {
93 lock(&self.state).dropped(subject);
94 }
95}
96
97struct State {
98 label: String,
99 names: Vec<String>,
100 remaining: Vec<u64>,
101 spent: Vec<(Duration, u32)>,
103 done: u64,
104 current: Option<usize>,
105 started: Instant,
106 tty: bool,
107 last_log: Instant,
108 last_tenth: u64,
109 drawn: bool,
110}
111
112impl State {
113 fn new(label: &str, names: Vec<String>) -> Self {
114 let n = names.len();
115 let now = Instant::now();
116 State {
117 label: label.to_string(),
118 names,
119 remaining: vec![0; n],
120 spent: vec![(Duration::ZERO, 0); n],
121 done: 0,
122 current: None,
123 started: now,
124 tty: std::io::stderr().is_terminal(),
125 last_log: now,
126 last_tenth: 0,
127 drawn: false,
128 }
129 }
130
131 fn total(&self) -> u64 {
132 self.done + self.remaining.iter().sum::<u64>()
133 }
134
135 fn eta(&self) -> Option<Duration> {
137 let (all, n) = self
138 .spent
139 .iter()
140 .fold((Duration::ZERO, 0u32), |(t, c), &(d, k)| (t + d, c + k));
141 if n == 0 {
142 return None;
143 }
144 let fallback = all / n;
147 let secs: f64 = self
148 .remaining
149 .iter()
150 .zip(&self.spent)
151 .map(|(&left, &(d, k))| {
152 let each = if k == 0 { fallback } else { d / k };
153 each.as_secs_f64() * left as f64
154 })
155 .sum();
156 Some(Duration::from_secs_f64(secs))
157 }
158
159 fn line(&self, width: usize) -> String {
160 let total = self.total().max(1);
161 let pct = self.done * 100 / total;
162 let eta = if self.remaining.iter().all(|&r| r == 0) && self.done > 0 {
163 "done".to_string()
164 } else {
165 self.eta()
166 .map_or_else(|| "estimating".to_string(), |d| format!("~{} left", fmt(d)))
167 };
168 let who = self.current.map_or("", |i| self.names[i].as_str());
169 let tail = format!(
170 " {}/{} {pct:>3}% {} elapsed, {eta} {who}",
171 self.done,
172 total,
173 fmt(self.started.elapsed())
174 );
175 if !self.tty {
176 return format!(" {}:{tail}", self.label);
177 }
178 let room = width.saturating_sub(self.label.len() + tail.len() + 6);
180 let cells = room.clamp(10, 30);
181 let filled = (cells as u64 * self.done / total) as usize;
182 let line = format!(
183 " {} [{}{}]{tail}",
184 self.label,
185 "#".repeat(filled),
186 "-".repeat(cells - filled)
187 );
188 line.chars().take(width.saturating_sub(1)).collect()
189 }
190
191 fn draw(&mut self, force: bool) {
192 if self.tty {
193 let width = std::env::var("COLUMNS")
194 .ok()
195 .and_then(|c| c.parse().ok())
196 .unwrap_or(80);
197 eprint!("\r\x1b[2K{}", self.line(width));
198 std::io::stderr().flush().ok();
199 self.drawn = true;
200 return;
201 }
202 let tenth = self.done * 10 / self.total().max(1);
203 if force || tenth > self.last_tenth || self.last_log.elapsed() >= LOG_EVERY {
204 eprintln!("{}", self.line(usize::MAX));
205 self.last_tenth = tenth;
206 self.last_log = Instant::now();
207 }
208 }
209
210 fn tick(&mut self) {
214 if self.total() == 0 {
215 return;
216 }
217 if self.tty {
218 if self.drawn {
219 self.draw(false);
220 }
221 } else if self.last_log.elapsed() >= LOG_EVERY {
222 self.draw(true);
223 }
224 }
225
226 fn clear(&mut self) {
227 if self.tty && self.drawn {
228 eprint!("\r\x1b[2K");
229 std::io::stderr().flush().ok();
230 self.drawn = false;
231 }
232 }
233}
234
235impl Observer for State {
236 fn planned(&mut self, remaining: &[u64]) {
237 self.remaining = remaining.to_vec();
238 self.draw(false);
239 }
240
241 fn started(&mut self, subject: usize) {
242 self.current = Some(subject);
243 if self.tty {
244 self.draw(false);
245 }
246 }
247
248 fn finished(&mut self, subject: usize, elapsed: Duration) {
249 self.remaining[subject] = self.remaining[subject].saturating_sub(1);
250 let (d, k) = &mut self.spent[subject];
251 *d += elapsed;
252 *k += 1;
253 self.done += 1;
254 self.current = None;
255 let last = self.remaining.iter().all(|&r| r == 0);
256 self.draw(last);
257 }
258
259 fn dropped(&mut self, subject: usize) {
260 self.remaining[subject] = 0;
261 self.current = None;
262 self.draw(false);
263 }
264}
265
266pub fn fmt(d: Duration) -> String {
268 let s = d.as_secs();
269 match s {
270 0 => format!("{}ms", d.as_millis()),
271 1..60 => format!("{s}s"),
272 60..3600 => format!("{}m{:02}s", s / 60, s % 60),
273 _ => format!("{}h{:02}m", s / 3600, (s % 3600) / 60),
274 }
275}
276
277#[cfg(test)]
278mod tests {
279 use super::*;
280
281 fn bar(names: &[&str]) -> State {
282 let mut b = State::new("b", names.iter().map(|s| s.to_string()).collect());
283 b.tty = false;
284 b.last_log = Instant::now();
285 b
286 }
287
288 #[test]
289 fn durations_read_naturally() {
290 assert_eq!(fmt(Duration::from_millis(850)), "850ms");
291 assert_eq!(fmt(Duration::from_secs(42)), "42s");
292 assert_eq!(fmt(Duration::from_secs(185)), "3m05s");
293 assert_eq!(fmt(Duration::from_secs(3720)), "1h02m");
294 }
295
296 #[test]
299 fn the_estimate_is_per_subject() {
300 let mut b = bar(&["fast", "slow"]);
301 b.planned(&[11, 6]);
302 b.finished(0, Duration::from_millis(100));
303 b.finished(1, Duration::from_secs(20));
304 let eta = b.eta().unwrap().as_secs_f64();
306 assert!((eta - 101.0).abs() < 0.01, "{eta}");
307 }
308
309 #[test]
310 fn an_untimed_subject_is_guessed_at_the_average() {
311 let mut b = bar(&["a", "b"]);
312 b.planned(&[2, 3]);
313 assert_eq!(b.eta(), None, "nothing timed yet");
314 b.finished(0, Duration::from_secs(2));
315 assert_eq!(b.eta(), Some(Duration::from_secs(8)));
317 }
318
319 #[test]
320 fn a_dropped_subject_leaves_the_estimate() {
321 let mut b = bar(&["a", "b"]);
322 b.planned(&[2, 5]);
323 b.finished(0, Duration::from_secs(1));
324 b.finished(1, Duration::from_secs(10));
325 b.dropped(1);
326 assert_eq!(b.eta(), Some(Duration::from_secs(1)));
327 assert_eq!(b.total(), 3);
328 }
329
330 #[test]
331 fn the_bar_fits_the_terminal() {
332 let mut b = bar(&["aube"]);
333 b.tty = true;
334 b.planned(&[40]);
335 for _ in 0..10 {
336 b.finished(0, Duration::from_millis(250));
337 }
338 let line = b.line(80);
339 assert!(line.chars().count() < 80, "{line}");
340 assert!(line.contains("10/40") && line.contains("25%"), "{line}");
341 assert!(line.contains("~7s left"), "{line}");
342 }
343
344 #[test]
347 fn a_log_hears_from_a_long_sample_before_it_finishes() {
348 let mut b = bar(&["slow"]);
349 b.planned(&[5]);
350 b.started(0);
351 let before = b.last_log;
352 b.tick();
353 assert_eq!(b.last_log, before, "too soon to log again");
354 b.last_log = Instant::now() - LOG_EVERY;
355 b.tick();
356 assert!(b.last_log > before, "the ticker logged mid-sample");
357 }
358
359 #[test]
362 fn the_ticker_stops_when_finished() {
363 let mut b = Bar::new("b", vec!["a".into()]);
364 b.planned(&[1]);
365 b.finished(0, Duration::from_millis(1));
366 b.finish();
367 assert!(b.ticker.is_none());
368 }
369}