use super::*;
#[must_use]
pub fn format_duration_ms(elapsed_ms: u128) -> String {
if elapsed_ms < 1_000 {
return format!("{elapsed_ms}ms");
}
if elapsed_ms < 60_000 {
let secs: u128 = elapsed_ms / 1_000;
let hundredths: u128 = (elapsed_ms % 1_000) / 10;
return format!("{secs}.{hundredths:02}s");
}
let total_secs: u128 = elapsed_ms / 1_000;
let mins: u128 = total_secs / 60;
let rem_secs: u128 = total_secs % 60;
format!("{mins}m {rem_secs:02}s")
}
#[must_use]
pub fn format_bytes_human(bytes: u64) -> String {
const KIB: u64 = 1024;
const MIB: u64 = 1024 * 1024;
const GIB: u64 = 1024 * 1024 * 1024;
if bytes < KIB {
format!("{bytes} {BYTES_UNIT_B}")
} else if bytes < MIB {
format!("{:.1} {BYTES_UNIT_KIB}", (bytes as f64) / (KIB as f64))
} else if bytes < GIB {
format!("{:.2} {BYTES_UNIT_MIB}", (bytes as f64) / (MIB as f64))
} else {
format!("{:.2} {BYTES_UNIT_GIB}", (bytes as f64) / (GIB as f64))
}
}
#[must_use]
pub fn format_step_summary(steps: &[StepTiming]) -> String {
let mut table: TerminalTable = TerminalTable::with_headers(vec![
HEADER_STATUS.to_string(),
HEADER_STEP.to_string(),
HEADER_ELAPSED.to_string(),
HEADER_DETAIL.to_string(),
]);
let mut pass_count: usize = 0;
let mut skip_count: usize = 0;
let mut fail_count: usize = 0;
let mut total_ms: u128 = 0;
for step in steps.iter() {
match step.get_status() {
StatusBadge::Pass => pass_count += 1,
StatusBadge::Skip => skip_count += 1,
StatusBadge::Fail => fail_count += 1,
StatusBadge::Warn | StatusBadge::Info => {}
}
total_ms = total_ms.saturating_add(step.get_elapsed_ms());
table.push_row(vec![
step.get_status().as_str().to_string(),
step.get_label().clone(),
format_duration_ms(step.get_elapsed_ms()),
step.get_detail().clone(),
]);
}
let mut out: String = table.render();
out.push_str(&format!(
"Summary: {} passed, {} skipped, {} failed ({})\n",
pass_count,
skip_count,
fail_count,
format_duration_ms(total_ms)
));
out
}
pub fn run_command_streaming(
program: &str,
args: &[String],
cwd: Option<&Path>,
envs: &[(&str, &str)],
inherit_tty: bool,
) -> io::Result<CommandRunMetrics> {
let started: time::Instant = time::Instant::now();
let mut command: Command = Command::new(program);
let _: &mut Command = command.args(args);
if let Some(dir) = cwd {
let _: &mut Command = command.current_dir(dir);
}
for (key, val) in envs.iter() {
let _: &mut Command = command.env(key, val);
}
if inherit_tty {
let status: ExitStatus = command
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.status()?;
let elapsed_ms: u128 = started.elapsed().as_millis();
let exit_code: i32 = status.code().unwrap_or(-1);
if !status.success() {
return Err(Error::other(format!(
"{ERR_STREAM_COMMAND_FAILED} ({program} exit={exit_code})"
)));
}
return Ok(CommandRunMetrics::new(
program.to_string(),
args.to_vec(),
exit_code,
elapsed_ms,
));
}
let output: Output = command.output()?;
let elapsed_ms: u128 = started.elapsed().as_millis();
let exit_code: i32 = output.status.code().unwrap_or(-1);
if !output.status.success() {
let stderr_text: String = String::from_utf8_lossy(&output.stderr).into_owned();
return Err(Error::other(format!(
"{ERR_STREAM_COMMAND_FAILED} ({program} exit={exit_code}): {stderr_text}"
)));
}
Ok(CommandRunMetrics::new(
program.to_string(),
args.to_vec(),
exit_code,
elapsed_ms,
))
}
pub(crate) fn write_table_row(out: &mut String, row: &[String], widths: &[usize]) {
let last_idx: usize = widths.len().saturating_sub(1);
for (idx, width) in widths.iter().enumerate() {
let cell: &str = row.get(idx).map(String::as_str).unwrap_or("");
if idx > 0 {
out.push_str(TABLE_COL_SEP);
}
out.push_str(cell);
if idx < last_idx {
let cell_len: usize = cell.chars().count();
let pad: usize = width.saturating_sub(cell_len);
for _ in 0..pad {
out.push(' ');
}
}
}
out.push('\n');
}