use std::borrow::BorrowMut;
use std::io::Read;
use std::process::{Command, ExitStatus, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, Once, Weak};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use crate::block::Block;
use crate::display::{self, Mode, lock, lock_patiently};
use crate::history::{self, History};
use crate::output::{self, Val};
use crate::style::palette::{AMBER, MUTED, RED, ROSE, SOFT, TEXT};
use crate::style::{Line, Rgb, mix, paint};
use crate::watch::{Focus, Watch};
use crate::widgets::{self, BarStyle, Card, Spinner};
use crate::{format, notify, term};
mod command;
mod render;
#[cfg(test)]
mod tests;
mod timeline;
pub use self::command::*;
pub(crate) use self::render::one_row;
use self::{render::*, timeline::*};
const MAX_WIDTH: usize = 76;
const AWAY_FRAME: Duration = Duration::from_millis(250);
const DEFAULT_NOTIFY_AFTER: Duration = Duration::from_secs(10);
const MIN_ESTIMATE: f64 = 1.0;
const HIDE_CURSOR: &str = "\x1b[?25l";
const SHOW_CURSOR: &str = "\x1b[?25h";
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum State {
Pending,
Active,
Done,
Warn,
Fail,
Skipped,
Cancelled,
Waiting,
}
impl State {
fn name(self) -> &'static str {
match self {
State::Pending => "pending",
State::Active => "running",
State::Done => "done",
State::Warn => "warn",
State::Fail => "fail",
State::Skipped => "skipped",
State::Cancelled => "cancelled",
State::Waiting => "waiting",
}
}
}
struct StepData {
label: String,
key: String,
depth: usize,
children: Vec<usize>,
state: State,
started: Option<Instant>,
ended: Option<Instant>,
waiting_since: Option<Instant>,
detail: String,
note: String,
progress: Option<(f32, String)>,
estimate: Option<f64>,
}
struct Shared {
title: String,
target: String,
steps: Vec<StepData>,
roots: Vec<usize>,
footer: Vec<String>,
logs: Vec<String>,
t0: Instant,
clock: Option<Duration>,
drawn: usize,
committed: usize,
header_drawn: bool,
abandoned: bool,
mode: Mode,
spinner: Spinner,
bar: BarStyle,
fps: u32,
history: Option<History>,
focus: Option<Arc<Focus>>,
watch: Option<Watch>,
wants_focus: bool,
paused: u32,
refocus: bool,
}
impl Shared {
fn now(&self) -> Instant {
match self.clock {
Some(offset) => self.t0 + offset,
None => Instant::now(),
}
}
}
#[must_use = "a live display finishes as soon as it's dropped"]
pub struct Live {
shared: Arc<Mutex<Shared>>,
stop: Arc<AtomicBool>,
started: Once,
thread: Mutex<Option<JoinHandle<()>>>,
notify_after: Option<Duration>,
history: Option<String>,
mode: Mode,
closed: bool,
prev_interrupt: Mutex<Option<usize>>,
}
#[derive(Clone)]
pub struct Step {
shared: Arc<Mutex<Shared>>,
idx: usize,
}
fn content_width() -> usize {
term::width().min(MAX_WIDTH)
}
fn fmt_secs(s: f64) -> String {
format::duration(Duration::try_from_secs_f64(s).unwrap_or_default())
}
fn approx(secs: f64) -> String {
if secs < 60.0 {
format!("{}s", secs.ceil().max(1.0))
} else {
format::duration(Duration::try_from_secs_f64(secs).unwrap_or(Duration::MAX))
}
}
fn time_left(elapsed: f64, fraction: f32) -> Option<f64> {
let p = f64::from(fraction);
(elapsed >= 2.0 && (0.04..1.0).contains(&p)).then(|| elapsed * (1.0 - p) / p)
}
fn estimated_fraction(elapsed: f64, usual: f64) -> f32 {
let x = elapsed / usual;
let f = if x < 0.9 {
x
} else {
0.9 + 0.09 * (1.0 - (-(x - 0.9) * 3.0).exp())
};
f as f32
}
pub(crate) fn abandon_all() -> bool {
display::abandon_all()
}
impl display::Shown for Mutex<Shared> {
fn pause(&self) {
let watch = {
let mut s = lock(self);
if s.paused == 0 {
paint_frame(&mut s, false);
s.drawn = 0;
}
s.paused += 1;
s.focus = None;
s.watch.take()
};
if let Some(mut watch) = watch {
watch.stop();
}
}
fn resume(&self) {
let mut s = lock(self);
s.paused -= 1;
if s.paused == 0 {
s.refocus = true;
output::write(HIDE_CURSOR);
}
}
fn log(&self, lines: &[&str], patient: bool) -> bool {
let Some(mut s) = display::lock_if(self, patient) else {
return false;
};
s.logs.extend(lines.iter().map(|l| l.to_string()));
true
}
fn abandon(&self) {
let Some(mut s) = lock_patiently(self) else { return };
let now = s.now();
for step in s.steps.iter_mut().filter(|st| st.state == State::Active) {
step.state = State::Fail;
step.ended = Some(now);
step.note = "interrupted by a panic".into();
}
paint_frame(&mut s, true);
s.abandoned = true;
output::write(SHOW_CURSOR);
}
}
impl std::fmt::Debug for Live {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = lock(&self.shared);
f.debug_struct("Live")
.field("title", &s.title)
.field("subject", &s.target)
.field("steps", &s.steps.len())
.finish_non_exhaustive()
}
}
impl std::fmt::Debug for Step {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let s = lock(&self.shared);
let step = &s.steps[self.idx];
f.debug_struct("Step")
.field("label", &step.label)
.field("state", &step.state)
.finish_non_exhaustive()
}
}
impl Live {
pub fn new(title: impl Into<String>, subject: impl Into<String>) -> Self {
Live::with_mode(title.into(), subject.into(), Mode::now())
}
fn start(&self) {
self.started.call_once(|| match self.mode {
Mode::Plain => {
let s = lock(&self.shared);
output::line(&format!("{} {}", s.title, s.target));
}
Mode::Json => {
let s = lock(&self.shared);
output::emit(
"live",
&[("title", Val::Str(&s.title)), ("target", Val::Str(&s.target))],
);
}
Mode::Draw => self.start_drawing(),
Mode::Quiet | Mode::Headless => {}
});
}
pub fn headless(title: impl Into<String>, subject: impl Into<String>) -> Self {
let live = Live::with_mode(title.into(), subject.into(), Mode::Headless);
lock(&live.shared).clock = Some(Duration::ZERO);
live
}
fn with_mode(title: String, target: String, mode: Mode) -> Self {
Live {
shared: Arc::new(Mutex::new(Shared {
title,
target,
steps: Vec::new(),
roots: Vec::new(),
footer: Vec::new(),
logs: Vec::new(),
t0: Instant::now(),
clock: None,
drawn: 0,
committed: 0,
header_drawn: false,
abandoned: false,
mode,
spinner: Spinner::default(),
bar: BarStyle::default(),
fps: 0,
history: None,
focus: None,
watch: None,
wants_focus: mode == Mode::Draw,
paused: 0,
refocus: false,
})),
stop: Arc::new(AtomicBool::new(false)),
started: Once::new(),
thread: Mutex::new(None),
notify_after: Some(DEFAULT_NOTIFY_AFTER),
history: Some(History::default_app()),
mode,
closed: false,
prev_interrupt: Mutex::new(None),
}
}
fn start_drawing(&self) {
crate::style::theme();
*lock(&self.prev_interrupt) = term::guard_interrupt();
{
let mut s = lock(&self.shared);
s.history = self.history.as_deref().and_then(History::open);
}
display::add(Arc::downgrade(&self.shared) as Weak<dyn display::Shown>);
output::write(HIDE_CURSOR);
let (shared, stop) = (self.shared.clone(), self.stop.clone());
*lock(&self.thread) = Some(thread::spawn(move || {
let mut first = true;
while !stop.load(Ordering::Relaxed) {
if lock(&shared).paused > 0 {
thread::sleep(crate::fps::frame(lock(&shared).fps));
continue;
}
draw(&shared, false);
let frame = crate::fps::frame(lock(&shared).fps);
if std::mem::take(&mut first) || std::mem::take(&mut lock(&shared).refocus) {
thread::sleep(frame);
watch_focus(&shared);
continue;
}
let away = lock(&shared).focus.as_ref().is_some_and(|f| f.away());
thread::sleep(if away { AWAY_FRAME.max(frame) } else { frame });
}
}));
}
pub fn fps(self, fps: u32) -> Self {
lock(&self.shared).fps = fps.clamp(1, 240);
self
}
pub fn no_focus(self) -> Self {
let watch = {
let mut s = lock(&self.shared);
s.wants_focus = false;
s.focus = None;
s.watch.take()
};
if let Some(mut watch) = watch {
watch.stop();
}
self
}
pub fn step(&self, label: impl Into<String>) -> Step {
let step = add_step(&self.shared, None, label.into());
self.start();
step
}
pub fn log(&self, text: impl AsRef<str>) {
self.start();
log(&self.shared, None, text.as_ref());
}
pub fn spinner(self, spinner: Spinner) -> Self {
lock(&self.shared).spinner = spinner;
self
}
pub fn bar(self, bar: BarStyle) -> Self {
lock(&self.shared).bar = bar;
self
}
pub fn remember_as(mut self, name: impl Into<String>) -> Self {
self.history = Some(name.into());
self
}
pub fn no_history(mut self) -> Self {
self.history = None;
lock(&self.shared).history = None;
self
}
pub fn notify_after(mut self, after: Duration) -> Self {
self.notify_after = Some(after);
self
}
pub fn no_notify(mut self) -> Self {
self.notify_after = None;
self
}
pub fn elapsed(&self) -> Duration {
let s = lock(&self.shared);
s.now() - s.t0
}
pub fn advance(&self, by: Duration) {
let mut s = lock(&self.shared);
if let Some(clock) = s.clock.as_mut() {
*clock += by;
}
}
pub fn snapshot(&self) -> Block {
let s = lock(&self.shared);
let mut lines = header(&s);
lines.extend(s.logs.iter().cloned());
lines.extend(render(&s, s.now(), content_width(), true));
lines.into()
}
pub fn timeline(&self) -> Block {
timeline(&lock(&self.shared), content_width()).into()
}
pub fn finish_with_timeline(mut self) {
{
let mut s = lock(&self.shared);
let mut footer = vec![String::new()];
footer.extend(timeline(&s, content_width()));
s.footer = footer;
}
self.close();
}
pub fn finish(mut self) {
self.close();
}
pub fn finish_with_card(mut self, card: Card) {
lock(&self.shared).footer = card.lines().into_lines();
self.close();
}
fn close(&mut self) {
if std::mem::replace(&mut self.closed, true) {
return;
}
self.start();
match self.mode {
Mode::Plain => {
for line in &lock(&self.shared).footer {
output::line(line);
}
return;
}
Mode::Json => {
let s = lock(&self.shared);
let secs = (s.now() - s.t0).as_secs_f64();
let card: Vec<String> = s.footer.iter().map(|l| crate::text::strip_ansi(l)).collect();
let fields = [
("title", Val::Str(&s.title)),
("outcome", Val::Str(outcome(&s))),
("secs", Val::Num(secs)),
("card", Val::List(&card)),
];
output::emit("finish", &fields);
return;
}
Mode::Quiet | Mode::Headless => return,
Mode::Draw => {}
}
self.stop.store(true, Ordering::Relaxed);
let _ = lock(&self.thread).take().map(JoinHandle::join);
draw(&self.shared, true);
display::remove(Arc::as_ptr(&self.shared));
let watch = lock(&self.shared).watch.take();
let away = watch.as_ref().is_some_and(|w| w.focus.away());
if let Some(mut watch) = watch {
watch.stop();
}
output::write(SHOW_CURSOR);
term::restore_interrupt(lock(&self.prev_interrupt).take());
let mut s = lock(&self.shared);
if away && self.notify_after.is_some_and(|after| s.t0.elapsed() >= after) {
notify::notify(&format!("{} {}", s.title, s.target), &summary(&s));
}
record_history(&mut s);
}
}
impl Drop for Live {
fn drop(&mut self) {
self.close();
}
}
fn watch_focus(shared: &Mutex<Shared>) {
let mut s = lock(shared);
if !s.wants_focus {
return;
}
if s.paused > 0 {
s.refocus = true;
return;
}
let Some(watch) = Watch::start() else { return };
s.focus = Some(watch.focus.clone());
s.watch = Some(watch);
}
fn add_step(shared: &Arc<Mutex<Shared>>, parent: Option<usize>, label: String) -> Step {
let mut s = lock(shared);
let idx = s.steps.len();
let (key, depth) = match parent {
Some(p) => (history::key(&s.steps[p].key, &label), s.steps[p].depth + 1),
None => (history::key(&s.title, &label), 0),
};
s.steps.push(StepData {
label,
key,
depth,
children: Vec::new(),
state: State::Pending,
started: None,
ended: None,
waiting_since: None,
detail: String::new(),
note: String::new(),
progress: None,
estimate: None,
});
match parent {
Some(p) => s.steps[p].children.push(idx),
None => s.roots.push(idx),
}
drop(s);
Step {
shared: shared.clone(),
idx,
}
}
fn log(shared: &Mutex<Shared>, step: Option<usize>, text: &str) {
let mut s = lock(shared);
let label = step.map(|i| s.steps[i].label.clone());
match s.mode {
Mode::Draw | Mode::Headless => {
let indent = " ".repeat(2 + s.spinner.width() + 2);
let line = match &label {
Some(l) => format!("{indent}{} {}", paint(MUTED, l), paint(SOFT, text)),
None => format!("{indent}{}", paint(SOFT, text)),
};
s.logs.push(line);
}
Mode::Plain => match &label {
Some(l) => output::line(&format!(" {l}: {text}")),
None => output::line(&format!(" {text}")),
},
Mode::Json => {
let step = label.unwrap_or_default();
output::emit(
"log",
&[
("title", Val::Str(&s.title)),
("step", Val::Str(&step)),
("text", Val::Str(text)),
],
);
}
Mode::Quiet => {}
}
}
fn record_history(s: &mut Shared) {
let Some(mut history) = s.history.take() else { return };
let runs = s
.steps
.iter()
.filter(|st| matches!(st.state, State::Done | State::Warn))
.filter_map(|st| Some((&st.key, (st.ended? - st.started?).as_secs_f64())));
for (key, secs) in runs {
history.record(key, secs);
}
history.save();
s.history = Some(history);
}
fn outcome(s: &Shared) -> &'static str {
if s.steps.iter().any(|st| st.state == State::Fail) {
"fail"
} else if s.steps.iter().any(|st| st.state == State::Cancelled) {
"cancelled"
} else if s.steps.iter().any(|st| st.state == State::Warn) {
"warn"
} else {
"ok"
}
}
fn summary(s: &Shared) -> String {
let took = format::duration(s.t0.elapsed());
if let Some(failed) = s.steps.iter().find(|st| st.state == State::Fail) {
return format!("✕ {} failed after {took}", failed.label);
}
if let Some(cancelled) = s.steps.iter().find(|st| st.state == State::Cancelled) {
return format!("⊘ {} cancelled after {took}", cancelled.label);
}
match s.steps.iter().filter(|st| st.state == State::Warn).count() {
0 => format!("● finished in {took}"),
n => format!("▲ finished in {took}, with {}", format::plural(n as u64, "warning")),
}
}
impl Step {
fn with<R>(&self, f: impl FnOnce(&mut StepData) -> R) -> R {
f(&mut lock(&self.shared).steps[self.idx])
}
#[allow(clippy::return_self_not_must_use)]
pub fn step(&self, label: impl Into<String>) -> Step {
add_step(&self.shared, Some(self.idx), label.into())
}
pub fn start(&self) {
let mut s = lock(&self.shared);
let now = s.now();
let estimate = s.history.as_ref().and_then(|h| h.estimate(&s.steps[self.idx].key));
let step = &mut s.steps[self.idx];
step.state = State::Active;
step.started = Some(now);
step.ended = None;
step.waiting_since = None;
step.note.clear();
step.estimate = estimate;
if s.mode == Mode::Json {
emit_step(&s, self.idx, None);
}
}
pub fn detail(&self, text: impl Into<String>) {
let text = text.into();
self.with(|s| s.detail = text);
}
pub fn progress(&self, fraction: f32, text: impl Into<String>) {
let text = text.into();
self.with(|s| s.progress = Some((crate::widgets::fraction(fraction), text)));
}
pub fn log(&self, text: impl AsRef<str>) {
log(&self.shared, Some(self.idx), text.as_ref());
}
pub fn done(&self) {
self.end(State::Done, String::new());
}
pub fn warn(&self, note: impl Into<String>) {
self.end(State::Warn, note.into());
}
pub fn fail(&self, note: impl Into<String>) {
self.end(State::Fail, note.into());
}
pub fn skip(&self, reason: impl Into<String>) {
self.end(State::Skipped, reason.into());
}
pub fn cancel(&self, reason: impl Into<String>) {
self.end(State::Cancelled, reason.into());
}
pub fn wait(&self, on: impl Into<String>) {
let mut s = lock(&self.shared);
let now = s.now();
let mode = s.mode;
let step = &mut s.steps[self.idx];
step.state = State::Waiting;
step.waiting_since = Some(now);
step.ended = None;
step.detail.clear();
step.progress = None;
step.note = on.into();
match mode {
Mode::Plain => output::line(&plain_line(step, None)),
Mode::Quiet => output::err_line(&plain_line(step, None)),
Mode::Json => emit_step(&s, self.idx, None),
_ => {}
}
}
pub fn try_run<T, E: std::fmt::Display>(&self, f: impl FnOnce() -> Result<T, E>) -> Result<T, E> {
self.start_if_pending();
let result = f();
self.ran(result.as_ref().err().map(ToString::to_string));
result
}
fn ran(&self, error: Option<String>) {
match error {
None => self.done(),
Some(e) => self.fail(e),
}
}
pub fn retry<T, E: std::fmt::Display>(&self, retries: u32, mut f: impl FnMut() -> Result<T, E>) -> Result<T, E> {
self.start_if_pending();
let mut attempt = 0;
loop {
let result = f();
if !self.try_again(result.as_ref().err().map(ToString::to_string), &mut attempt, retries) {
return result;
}
}
}
fn try_again(&self, error: Option<String>, attempt: &mut u32, retries: u32) -> bool {
match error {
None => self.settle_after(*attempt),
Some(e) if *attempt < retries => {
*attempt += 1;
self.detail(format!("attempt {} of {} · {e}", *attempt + 1, retries + 1));
thread::sleep(backoff(*attempt));
return true;
}
Some(e) => self.fail(attempts_note(&e, *attempt)),
}
false
}
pub fn run<'c>(&self, command: impl BorrowMut<Command> + Send + Sync + 'c) -> Result<String, RunError> {
self.command(command).run()
}
pub fn command<'c>(&self, command: impl BorrowMut<Command> + Send + Sync + 'c) -> StepCommand<'_, 'c> {
StepCommand {
step: self,
command: Box::new(command),
stdin: None,
timeout: None,
retries: 0,
tail: 12,
}
}
fn start_if_pending(&self) {
if self.with(|s| s.state == State::Pending) {
self.start();
}
}
fn settle_after(&self, retries: u32) {
if retries == 0 {
self.done();
} else {
self.warn(format!("succeeded on attempt {}", retries + 1));
}
}
fn end(&self, state: State, note: String) {
let mut s = lock(&self.shared);
let now = s.now();
let mode = s.mode;
let step = &mut s.steps[self.idx];
let ran = match state {
State::Skipped => false,
State::Cancelled => step.state == State::Active,
_ => true,
};
let started = if ran {
Some(*step.started.get_or_insert(now))
} else {
step.started = None;
None
};
step.state = state;
step.ended = Some(now);
step.waiting_since = None;
step.detail.clear();
step.progress = None;
step.note = note;
let secs = started.map(|b| (now - b).as_secs_f64());
match mode {
Mode::Plain => output::line(&plain_line(&s.steps[self.idx], secs)),
Mode::Quiet if state == State::Fail => output::err_line(&plain_line(&s.steps[self.idx], secs)),
Mode::Json => emit_step(&s, self.idx, secs),
_ => {}
}
}
}
fn plain_line(step: &StepData, secs: Option<f64>) -> String {
let mark = match step.state {
State::Warn => "warn",
State::Fail => "FAIL",
State::Skipped => "skip",
State::Cancelled => "cancelled",
State::Waiting => "wait",
_ => "ok",
};
let indent = " ".repeat(step.depth + 1);
let mut note = step.note.lines();
let tail = note.next().map(|first| format!(" - {first}")).unwrap_or_default();
let took = secs.map(|s| format!(" ({})", fmt_secs(s))).unwrap_or_default();
let mut out = format!("{indent}[{mark}] {}{took}{tail}", step.label);
for line in note {
out += &format!("\n{indent} | {line}");
}
out
}
fn emit_step(s: &Shared, idx: usize, secs: Option<f64>) {
let step = &s.steps[idx];
let mut path = vec![step.label.clone()];
let mut at = idx;
while let Some(parent) = s.steps.iter().position(|p| p.children.contains(&at)) {
path.insert(0, s.steps[parent].label.clone());
at = parent;
}
let mut fields = vec![
("title", Val::Str(&s.title)),
("step", Val::Str(&step.label)),
("path", Val::List(&path)),
("state", Val::Str(step.state.name())),
];
if let Some(secs) = secs {
fields.push(("secs", Val::Num(secs)));
}
if !step.note.is_empty() {
fields.push(("note", Val::Str(&step.note)));
}
output::emit("step", &fields);
}