use std::io::Read;
use std::process::{Command, ExitStatus, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, TryLockError, Weak};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use crate::block::Block;
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};
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",
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Mode {
Draw,
Plain,
Json,
Quiet,
Headless,
}
impl Mode {
fn pick(out: output::Output, terminal: bool) -> Mode {
match out {
output::Output::Json => Mode::Json,
output::Output::Quiet => Mode::Quiet,
output::Output::Pretty if terminal => Mode::Draw,
output::Output::Pretty => Mode::Plain,
}
}
}
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,
}
impl Shared {
fn now(&self) -> Instant {
match self.clock {
Some(offset) => self.t0 + offset,
None => Instant::now(),
}
}
}
pub struct Live {
shared: Arc<Mutex<Shared>>,
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
notify_after: Option<Duration>,
mode: Mode,
closed: bool,
prev_interrupt: Option<usize>,
}
#[derive(Clone)]
pub struct Step {
shared: Arc<Mutex<Shared>>,
idx: usize,
}
fn lock(shared: &Mutex<Shared>) -> MutexGuard<'_, Shared> {
shared.lock().unwrap_or_else(|e| e.into_inner())
}
fn content_width() -> usize {
term::width().min(MAX_WIDTH)
}
fn fmt_secs(s: f64) -> String {
if s < 60.0 {
format!("{s:.1}s")
} else {
format!("{}m{:02}s", (s / 60.0) as u64, (s % 60.0) as u64)
}
}
fn approx(secs: f64) -> String {
if secs < 60.0 {
format!("{}s", secs.ceil().max(1.0))
} else {
format::duration(Duration::from_secs_f64(secs))
}
}
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
}
static DRAWING: Mutex<Vec<Weak<Mutex<Shared>>>> = Mutex::new(Vec::new());
pub(crate) fn abandon_all() -> bool {
let drawing = std::mem::take(&mut *DRAWING.lock().unwrap_or_else(|e| e.into_inner()));
let mut any = false;
for shared in drawing.iter().filter_map(Weak::upgrade) {
let mut s = None;
for _ in 0..50 {
match shared.try_lock() {
Ok(guard) => s = Some(guard),
Err(TryLockError::Poisoned(e)) => s = Some(e.into_inner()),
Err(TryLockError::WouldBlock) => {
thread::sleep(Duration::from_millis(2));
continue;
}
}
break;
}
let Some(mut s) = s else { continue };
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);
any = true;
}
any
}
impl Live {
pub fn new(title: impl Into<String>, target: impl Into<String>) -> Self {
let mode = Mode::pick(output::output(), output::is_terminal());
let mut live = Live::with_mode(title.into(), target.into(), mode);
match mode {
Mode::Plain => {
let s = lock(&live.shared);
output::line(&format!("{} {}", s.title, s.target));
}
Mode::Json => {
let s = lock(&live.shared);
output::emit(
"live",
&[("title", Val::Str(&s.title)), ("target", Val::Str(&s.target))],
);
}
Mode::Draw => live.start_drawing(),
Mode::Quiet | Mode::Headless => {}
}
live
}
pub fn headless(title: impl Into<String>, target: impl Into<String>) -> Self {
let live = Live::with_mode(title.into(), target.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: false,
})),
stop: Arc::new(AtomicBool::new(false)),
thread: None,
notify_after: Some(DEFAULT_NOTIFY_AFTER),
mode,
closed: false,
prev_interrupt: None,
}
}
fn start_drawing(&mut self) {
crate::style::theme();
self.prev_interrupt = term::guard_interrupt();
{
let mut s = lock(&self.shared);
s.history = History::open(&History::default_app());
s.wants_focus = true;
}
DRAWING
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(Arc::downgrade(&self.shared));
output::write(HIDE_CURSOR);
let (shared, stop) = (self.shared.clone(), self.stop.clone());
self.thread = Some(thread::spawn(move || {
let mut first = true;
while !stop.load(Ordering::Relaxed) {
draw(&shared, false);
let frame = crate::fps::frame(lock(&shared).fps);
if std::mem::take(&mut first) {
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 {
add_step(&self.shared, None, label.into())
}
pub fn log(&self, text: impl AsRef<str>) {
log(&self.shared, None, text.as_ref());
}
pub fn with_spinner(self, spinner: Spinner) -> Self {
lock(&self.shared).spinner = spinner;
self
}
pub fn with_bar(self, bar: BarStyle) -> Self {
lock(&self.shared).bar = bar;
self
}
pub fn remember_as(self, name: &str) -> Self {
if self.mode == Mode::Draw {
lock(&self.shared).history = History::open(name);
}
self
}
pub fn no_history(self) -> Self {
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;
}
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);
if let Some(handle) = self.thread.take() {
let _ = handle.join();
}
draw(&self.shared, true);
DRAWING
.lock()
.unwrap_or_else(|e| e.into_inner())
.retain(|w| w.upgrade().is_some_and(|s| !Arc::ptr_eq(&s, &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(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>) {
if !lock(shared).wants_focus {
return;
}
let Some(mut watch) = Watch::start() else { return };
let mut s = lock(shared);
if s.wants_focus {
s.focus = Some(watch.focus.clone());
s.watch = Some(watch);
} else {
drop(s);
watch.stop();
}
}
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 };
for step in s
.steps
.iter()
.filter(|st| matches!(st.state, State::Done | State::Warn))
{
if let (Some(began), Some(ended)) = (step.started, step.ended) {
history.record(&step.key, (ended - began).as_secs_f64());
}
}
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])
}
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((fraction.clamp(0.0, 1.0), 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 => eprintln!("{}", 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();
match &result {
Ok(_) => self.done(),
Err(e) => self.fail(e.to_string()),
}
result
}
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 {
match f() {
Ok(v) => {
self.settle_after(attempt);
return Ok(v);
}
Err(e) if attempt < retries => {
attempt += 1;
self.detail(format!("attempt {} of {} · {e}", attempt + 1, retries + 1));
thread::sleep(backoff(attempt));
}
Err(e) => {
self.fail(attempts_note(&e.to_string(), attempt));
return Err(e);
}
}
}
}
pub fn run(&self, command: &mut Command) -> Result<String, RunError> {
self.command(command).run()
}
pub fn command<'c>(&self, command: &'c mut Command) -> StepCommand<'_, 'c> {
StepCommand {
step: self,
command,
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 => eprintln!("{}", 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);
}
fn backoff(attempt: u32) -> Duration {
Duration::from_millis(500 * 2u64.pow(attempt.saturating_sub(1).min(4)))
}
fn attempts_note(error: &str, retries: u32) -> String {
match retries {
0 => error.to_string(),
n => {
let (first, rest) = error.split_once('\n').unwrap_or((error, ""));
let rest = if rest.is_empty() {
String::new()
} else {
format!("\n{rest}")
};
format!("{first} (after {} attempts){rest}", n + 1)
}
}
}
pub struct StepCommand<'a, 'c> {
step: &'a Step,
command: &'c mut Command,
timeout: Option<Duration>,
retries: u32,
tail: usize,
}
impl StepCommand<'_, '_> {
pub fn timeout(mut self, limit: Duration) -> Self {
self.timeout = Some(limit);
self
}
pub fn retries(mut self, n: u32) -> Self {
self.retries = n;
self
}
pub fn tail(mut self, lines: usize) -> Self {
self.tail = lines;
self
}
pub fn run(mut self) -> Result<String, RunError> {
self.step.start_if_pending();
let mut attempt = 0;
loop {
match self.once() {
Ok(output) => {
self.step.settle_after(attempt);
return Ok(output);
}
Err(e) if attempt < self.retries && e.kind.retryable() => {
attempt += 1;
self.step
.detail(format!("attempt {} of {} · {e}", attempt + 1, self.retries + 1));
thread::sleep(backoff(attempt));
}
Err(e) => {
let mut note = e.to_string();
let lines: Vec<&str> = e.output.lines().filter(|l| !l.trim().is_empty()).collect();
for line in &lines[lines.len().saturating_sub(self.tail)..] {
note += "\n";
note += line;
}
self.step.fail(attempts_note(¬e, attempt));
return Err(e);
}
}
}
}
fn once(&mut self) -> Result<String, RunError> {
let program = self.command.get_program().to_string_lossy().into_owned();
let mut child = self
.command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| RunError {
program: program.clone(),
output: String::new(),
kind: RunErrorKind::Spawn(e),
})?;
let lines = Arc::new(Mutex::new(Vec::<String>::new()));
let readers: Vec<JoinHandle<()>> = [
child.stdout.take().map(|p| Box::new(p) as Box<dyn Read + Send>),
child.stderr.take().map(|p| Box::new(p) as Box<dyn Read + Send>),
]
.into_iter()
.flatten()
.map(|pipe| {
let (lines, step) = (lines.clone(), self.step.clone());
thread::spawn(move || read_lines(pipe, &lines, &step))
})
.collect();
let started = Instant::now();
let outcome = loop {
match child.try_wait() {
Ok(Some(status)) => break Ok(status),
Ok(None) if self.timeout.is_some_and(|t| started.elapsed() >= t) => {
let _ = child.kill();
let _ = child.wait();
break Err(RunErrorKind::TimedOut(self.timeout.unwrap_or_default()));
}
Ok(None) => thread::sleep(Duration::from_millis(30)),
Err(e) => break Err(RunErrorKind::Spawn(e)),
}
};
let grace = Instant::now() + Duration::from_millis(250);
while readers.iter().any(|r| !r.is_finished()) && Instant::now() < grace {
thread::sleep(Duration::from_millis(10));
}
for reader in readers.into_iter().filter(JoinHandle::is_finished) {
let _ = reader.join();
}
let output = lock_lines(&lines).join("\n");
let kind = match outcome {
Ok(status) if status.success() => return Ok(output),
Ok(status) => RunErrorKind::Exit(status),
Err(kind) => kind,
};
Err(RunError { program, output, kind })
}
}
fn lock_lines(lines: &Mutex<Vec<String>>) -> MutexGuard<'_, Vec<String>> {
lines.lock().unwrap_or_else(|e| e.into_inner())
}
fn read_lines(mut pipe: Box<dyn Read + Send>, lines: &Mutex<Vec<String>>, step: &Step) {
let mut pending = Vec::new();
let mut buf = [0u8; 4096];
let finish = |bytes: &mut Vec<u8>| {
let line = crate::text::strip_ansi(&String::from_utf8_lossy(bytes));
bytes.clear();
let line = line.trim_end().to_string();
if line.trim().is_empty() {
return;
}
step.detail(crate::text::truncate(line.trim(), 60));
lock_lines(lines).push(line);
};
loop {
let n = match pipe.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => n,
};
for &b in &buf[..n] {
if b == b'\n' || b == b'\r' {
finish(&mut pending);
} else {
pending.push(b);
}
}
}
finish(&mut pending);
}
#[derive(Debug)]
pub struct RunError {
program: String,
output: String,
kind: RunErrorKind,
}
#[derive(Debug)]
enum RunErrorKind {
Spawn(std::io::Error),
Exit(ExitStatus),
TimedOut(Duration),
}
impl RunErrorKind {
fn retryable(&self) -> bool {
!matches!(self, RunErrorKind::Spawn(_))
}
}
impl RunError {
pub fn output(&self) -> &str {
&self.output
}
pub fn status(&self) -> Option<ExitStatus> {
match self.kind {
RunErrorKind::Exit(status) => Some(status),
_ => None,
}
}
pub fn timed_out(&self) -> bool {
matches!(self.kind, RunErrorKind::TimedOut(_))
}
}
impl std::fmt::Display for RunError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let program = &self.program;
match &self.kind {
RunErrorKind::Spawn(e) => write!(f, "couldn't run {program}: {e}"),
RunErrorKind::Exit(status) => match status.code() {
Some(code) => write!(f, "{program} exited with status {code}"),
None => write!(f, "{program} was stopped by a signal"),
},
RunErrorKind::TimedOut(limit) => write!(f, "{program} timed out after {}", format::duration(*limit)),
}
}
}
impl std::error::Error for RunError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
RunErrorKind::Spawn(e) => Some(e),
_ => None,
}
}
}
fn timeline(s: &Shared, width: usize) -> Vec<String> {
let now = s.now();
let mut order = Vec::new();
fn visit(s: &Shared, idx: usize, order: &mut Vec<usize>) {
order.push(idx);
for &c in &s.steps[idx].children {
visit(s, c, order);
}
}
for &r in &s.roots {
visit(s, r, &mut order);
}
let end = s
.steps
.iter()
.filter_map(|st| st.started.map(|b| st.ended.unwrap_or(now).max(b)))
.max()
.unwrap_or(now);
let total = (end - s.t0).as_secs_f64().max(0.001);
let label = |st: &StepData| format!("{}{}", " ".repeat(st.depth), st.label);
let label_w = order
.iter()
.map(|&i| crate::text::width(&label(&s.steps[i])))
.max()
.unwrap_or(0);
let time_w = 7;
let track = width.saturating_sub(2 + label_w + 2 + 2 + time_w).max(10);
let col = |at: Instant| ((at - s.t0).as_secs_f64() / total * track as f64).round() as usize;
let mut out = Vec::new();
for &i in &order {
let st = &s.steps[i];
let name = crate::text::pad(&label(st), label_w);
let Some(began) = st.started else {
out.push(format!(" {}", paint(MUTED, &name)));
continue;
};
let finished = st.ended.unwrap_or(now);
let (a, b) = (col(began).min(track - 1), col(finished).min(track));
let color = match st.state {
State::Done => ROSE,
State::Warn => AMBER,
State::Fail => RED,
State::Cancelled => MUTED,
State::Waiting => mix(AMBER, MUTED, 0.35),
_ => crate::style::palette::BLUSH,
};
let bar = "━".repeat(b.saturating_sub(a).max(1));
let took = fmt_secs((finished - began).as_secs_f64());
let gap = track.saturating_sub(a + crate::text::width(&bar));
out.push(format!(
" {} {}{}{} {}",
paint(if st.depth > 0 { SOFT } else { TEXT }, &name),
" ".repeat(a),
paint(color, &bar),
" ".repeat(gap),
paint(MUTED, &format!("{took:>time_w$}"))
));
}
let axis_pad = " ".repeat(2 + label_w + 2);
out.push(format!(
"{axis_pad}{}",
paint(crate::style::palette::LINE, &"─".repeat(track))
));
let total_label = fmt_secs(total);
out.push(format!(
"{axis_pad}{}{}",
paint(MUTED, "0s"),
paint(MUTED, &format!("{total_label:>w$}", w = track.saturating_sub(2)))
));
out
}
fn draw(shared: &Mutex<Shared>, settled: bool) {
paint_frame(&mut lock(shared), settled);
}
fn paint_frame(s: &mut Shared, settled: bool) {
if s.abandoned {
return;
}
let mut buf = if s.drawn > 0 {
format!("\x1b[{}F", s.drawn)
} else {
String::new()
};
let mut kept = Vec::new();
if !std::mem::replace(&mut s.header_drawn, true) {
kept = header(s);
}
kept.append(&mut s.logs);
for line in &kept {
buf += line;
buf += "\x1b[K\n";
}
buf += "\x1b[?7l";
let lines = render(s, s.now(), content_width(), settled);
let rest = &lines[s.committed.min(lines.len())..];
let room = term::height().saturating_sub(1).max(1);
let (commit, tail) = if !settled && rest.len() > room {
rest.split_at(rest.len() - room)
} else {
(&rest[..0], rest)
};
for line in commit.iter().chain(tail) {
buf += line;
buf += "\x1b[K\n";
}
buf += "\x1b[J\x1b[?7h";
s.drawn = tail.len();
s.committed += commit.len();
output::write(&buf);
}
fn header(s: &Shared) -> Vec<String> {
let header = format!(" {} {}", paint(ROSE, &s.title), paint(SOFT, &s.target));
vec![String::new(), header, String::new()]
}
struct Frame {
spinner: Spinner,
bar: BarStyle,
now: Instant,
t: f32,
width: usize,
settled: bool,
returned: Option<(Instant, Instant)>,
}
fn render(s: &Shared, now: Instant, width: usize, settled: bool) -> Vec<String> {
let frame = Frame {
spinner: s.spinner,
bar: s.bar,
now,
t: (now - s.t0).as_secs_f32(),
width,
settled,
returned: s.focus.as_ref().and_then(|f| f.just_returned(now)),
};
let mut lines = Vec::new();
for &idx in &s.roots {
walk(s, idx, &frame, &mut lines);
}
lines.extend(s.footer.iter().cloned());
lines
}
fn walk(s: &Shared, idx: usize, frame: &Frame, out: &mut Vec<String>) {
let step = &s.steps[idx];
step_lines(step, frame, out);
let folded = matches!(step.state, State::Done | State::Skipped) && step.children.iter().all(|&c| !troubled(s, c));
if !folded {
for &child in &step.children {
walk(s, child, frame, out);
}
}
}
fn troubled(s: &Shared, idx: usize) -> bool {
let step = &s.steps[idx];
matches!(
step.state,
State::Warn | State::Fail | State::Cancelled | State::Waiting
) || step.children.iter().any(|&c| troubled(s, c))
}
fn step_lines(st: &StepData, f: &Frame, out: &mut Vec<String>) {
let gutter = f.spinner.width();
let nest = st.depth * (gutter + 2);
let indent = " ".repeat(2 + nest + gutter + 2);
let took = st
.started
.map(|b| fmt_secs((st.ended.unwrap_or(f.now) - b).as_secs_f64()))
.unwrap_or_default();
let row_with = |glyph: Line, label: Line, right: &str, right_color: Rgb| {
let left = Line::new().space(2 + nest).append(glyph).space(2).append(label);
let pad = f.width.saturating_sub(left.width() + right.chars().count() + 2).max(1);
format!("{left}{}{}", " ".repeat(pad), paint(right_color, right))
};
let row = |glyph: Line, label: Line, right_color: Rgb| row_with(glyph, label, &took, right_color);
let centred = |mark: Line| {
Line::new()
.space((gutter - 1) / 2)
.append(mark)
.space(gutter - 1 - (gutter - 1) / 2)
};
let plain = |glyph: &str, glyph_color: Rgb, label_color: Rgb| {
(
centred(Line::new().push(glyph, glyph_color)),
Line::new().push(&st.label, label_color),
)
};
let note = |color: Rgb, out: &mut Vec<String>| {
for (i, line) in st.note.lines().enumerate() {
out.push(format!("{indent}{}", paint(if i == 0 { color } else { MUTED }, line)));
}
};
match st.state {
State::Pending => {
let (g, l) = plain("○", MUTED, MUTED);
out.push(row(g, l, MUTED));
}
State::Active => {
out.push(row(f.spinner.frame(f.t), widgets::shimmer(&st.label, f.t), MUTED));
let usual = st.estimate.filter(|e| *e >= MIN_ESTIMATE);
if let Some((p, text)) = &st.progress {
let mut stats = paint(SOFT, &format!("{:>3.0}% {text}", p * 100.0));
if let Some(left) = st.started.and_then(|b| time_left((f.now - b).as_secs_f64(), *p)) {
stats += &paint(MUTED, &format!(" · {} left", approx(left)));
}
out.push(format!("{indent}{} {stats}", f.bar.draw(*p, 30, f.t)));
} else if let (Some(usual), Some(started)) = (usual, st.started) {
let elapsed = (f.now - started).as_secs_f64();
let (text, color) = if elapsed <= usual {
(
format!("usually {} · {} left", approx(usual), approx(usual - elapsed)),
SOFT,
)
} else if elapsed <= usual * 1.25 {
(format!("usually {} · nearly there", approx(usual)), SOFT)
} else {
(
format!("slower than usual · usually {}", approx(usual)),
mix(AMBER, SOFT, 0.35),
)
};
let bar = f.bar.draw(estimated_fraction(elapsed, usual), 30, f.t);
out.push(format!("{indent}{bar} {}", paint(color, &text)));
}
if st.progress.is_none() && !st.detail.is_empty() {
out.push(format!("{indent}{}", paint(MUTED, &st.detail)));
}
}
State::Done => {
let mut age = st.ended.map_or(f32::MAX, |e| (f.now - e).as_secs_f32());
if let (Some((left, back)), Some(ended)) = (f.returned, st.ended) {
if ended >= left && ended <= back {
age = (f.now - back).as_secs_f32();
}
}
let mark = widgets::pop(age)
.filter(|_| !f.settled)
.unwrap_or_else(|| Line::new().push("●", ROSE));
out.push(row(centred(mark), Line::new().push(&st.label, TEXT), MUTED));
}
State::Warn => {
let (g, l) = plain("▲", AMBER, TEXT);
out.push(row(g, l, MUTED));
note(mix(AMBER, MUTED, 0.35), out);
}
State::Fail => {
let (g, l) = plain("✕", RED, RED);
out.push(row(g, l, RED));
note(mix(RED, SOFT, 0.3), out);
}
State::Skipped => {
let (g, l) = plain("–", MUTED, MUTED);
out.push(row_with(g, l, "skipped", MUTED));
note(MUTED, out);
}
State::Cancelled => {
let (g, l) = plain("⊘", SOFT, SOFT);
let right = if st.started.is_some() {
took.as_str()
} else {
"cancelled"
};
out.push(row_with(g, l, right, MUTED));
note(MUTED, out);
}
State::Waiting => {
let glow = if f.settled {
AMBER
} else {
mix(AMBER, MUTED, 0.5 - 0.5 * (f.t * 2.4).cos())
};
let (g, l) = plain("◌", glow, TEXT);
let waited = st
.waiting_since
.map(|w| fmt_secs((f.now - w).as_secs_f64()))
.unwrap_or_default();
out.push(row_with(g, l, &waited, MUTED));
note(mix(AMBER, MUTED, 0.35), out);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn estimates_never_look_finished_early() {
assert!((estimated_fraction(21.0, 42.0) - 0.5).abs() < 1e-6);
assert!(estimated_fraction(42.0, 42.0) < 0.95);
assert!(estimated_fraction(1000.0, 42.0) < 0.991);
assert!(estimated_fraction(60.0, 42.0) > estimated_fraction(50.0, 42.0));
}
#[test]
fn history_keeps_one_time_per_step_and_only_for_steps_that_ran() {
let live = Live::headless("deploy", "my-app");
lock(&live.shared).history = Some(History::scratch());
let (upload, lint, ship) = (live.step("Upload"), live.step("Lint"), live.step("Ship"));
upload.start();
live.advance(Duration::from_secs(2));
upload.done();
upload.start();
live.advance(Duration::from_secs(3));
upload.done();
lint.skip("");
ship.start();
live.advance(Duration::from_secs(1));
ship.cancel("");
let mut s = lock(&live.shared);
record_history(&mut s);
let history = s.history.as_ref().unwrap();
assert_eq!(history.runs("deploy › Upload"), [3.0]);
assert!(history.runs("deploy › Lint").is_empty());
assert!(history.runs("deploy › Ship").is_empty());
}
#[test]
fn only_a_terminal_gets_a_drawn_display() {
use output::Output;
assert_eq!(Mode::pick(Output::Pretty, true), Mode::Draw);
assert_eq!(Mode::pick(Output::Pretty, false), Mode::Plain);
assert_eq!(Mode::pick(Output::Json, true), Mode::Json);
assert_eq!(Mode::pick(Output::Quiet, true), Mode::Quiet);
}
#[test]
fn approximations_round_up_to_whole_seconds() {
assert_eq!(approx(41.2), "42s");
assert_eq!(approx(0.3), "1s");
assert_eq!(approx(187.0), "3m07s");
}
}