use std::io::{IsTerminal, Read, Seek, Write};
use std::time::Duration;
use anyhow::{bail, Context, Result};
use super::{resolve_container, resolve_instance};
use crate::runtime::backend;
use crate::state::{PhaseView, State};
const FOLLOW_POLL: Duration = Duration::from_millis(500);
pub fn logs(name: &str, lines: usize) -> Result<()> {
let state = State::load()?;
let container = resolve_container(&state, name)?;
let out = backend().logs_tail(&container, lines)?;
if out.trim().is_empty() {
println!("(no log output)");
} else {
println!("{out}");
}
Ok(())
}
pub fn build_log(name: &str, follow: bool) -> Result<()> {
let state = State::load()?;
let key = resolve_instance(&state, name)?;
let instance_id = state.instances.get(&key).expect("key came from state").instance_id.clone();
let path = crate::build_log::path(&instance_id)?;
let mut file = match std::fs::File::open(&path) {
Ok(file) => file,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
bail!("`{key}` has no build log (no {})", path.display())
}
Err(e) => return Err(e).with_context(|| format!("cannot open {}", path.display())),
};
let mut out = std::io::stdout().lock();
let tty = if out.is_terminal() {
None
} else {
let head = crate::build_log::read_head(&mut file).with_context(|| format!("cannot read {}", path.display()))?;
crate::build_log::tty_header(&head)
};
if let (Some((size, header)), false) = (tty, follow) {
crate::build_log::replay_file(&mut file, size, header, &mut out).context("cannot print the build log")?;
return Ok(out.flush()?);
}
file.rewind().with_context(|| format!("cannot read {}", path.display()))?;
let mut strip = tty.map(|_| crate::build_log::Strip::default());
let mut drain = |file: &mut std::fs::File| -> Result<()> {
match &mut strip {
None => {
std::io::copy(file, &mut out).context("cannot print the build log")?;
}
Some(strip) => {
let mut bytes = Vec::new();
file.read_to_end(&mut bytes).context("cannot read the build log")?;
out.write_all(&strip.feed(&bytes)).context("cannot print the build log")?;
}
}
out.flush()?;
Ok(())
};
drain(&mut file)?;
if !follow {
return Ok(());
}
loop {
let view = State::load()?
.instances
.values()
.find(|i| i.instance_id == instance_id)
.map(|i| i.phase_view());
if !in_flight(view.as_ref()) {
return drain(&mut file);
}
std::thread::sleep(FOLLOW_POLL);
drain(&mut file)?;
}
}
fn in_flight(view: Option<&Option<PhaseView>>) -> bool {
matches!(view, Some(Some(PhaseView::InFlight(_))))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn follow_stops_unless_the_record_is_in_flight() {
assert!(in_flight(Some(&Some(PhaseView::InFlight("building".into())))));
assert!(!in_flight(Some(&None)));
let failed = PhaseView::Failed { at: "building".into(), error: "boom".into() };
assert!(!in_flight(Some(&Some(failed))));
assert!(!in_flight(None));
}
}