Skip to main content

euv_cli/dx/output/
fn.rs

1use super::*;
2
3/// Formats an elapsed duration in milliseconds into a concise human-readable token (`42ms`, `1.25s`, `2m 05s`).
4///
5/// # Arguments
6///
7/// - `u128` - Duration in milliseconds.
8///
9/// # Returns
10///
11/// - `String` - Formatted duration text.
12#[must_use]
13pub fn format_duration_ms(elapsed_ms: u128) -> String {
14    if elapsed_ms < 1_000 {
15        return format!("{elapsed_ms}ms");
16    }
17    if elapsed_ms < 60_000 {
18        let secs: u128 = elapsed_ms / 1_000;
19        let hundredths: u128 = (elapsed_ms % 1_000) / 10;
20        return format!("{secs}.{hundredths:02}s");
21    }
22    let total_secs: u128 = elapsed_ms / 1_000;
23    let mins: u128 = total_secs / 60;
24    let rem_secs: u128 = total_secs % 60;
25    format!("{mins}m {rem_secs:02}s")
26}
27
28/// Formats a raw byte count into binary human units (`B`, `KiB`, `MiB`, `GiB`).
29///
30/// # Arguments
31///
32/// - `u64` - Byte length.
33///
34/// # Returns
35///
36/// - `String` - Formatted size string.
37#[must_use]
38pub fn format_bytes_human(bytes: u64) -> String {
39    const KIB: u64 = 1024;
40    const MIB: u64 = 1024 * 1024;
41    const GIB: u64 = 1024 * 1024 * 1024;
42    if bytes < KIB {
43        format!("{bytes} {BYTES_UNIT_B}")
44    } else if bytes < MIB {
45        format!("{:.1} {BYTES_UNIT_KIB}", (bytes as f64) / (KIB as f64))
46    } else if bytes < GIB {
47        format!("{:.2} {BYTES_UNIT_MIB}", (bytes as f64) / (MIB as f64))
48    } else {
49        format!("{:.2} {BYTES_UNIT_GIB}", (bytes as f64) / (GIB as f64))
50    }
51}
52
53/// Renders a list of `StepTiming` entries as an aligned summary table with totals.
54///
55/// # Arguments
56///
57/// - `&[StepTiming]` - Ordered step execution records.
58///
59/// # Returns
60///
61/// - `String` - Human-readable summary table and aggregate pass/skip/fail counters.
62#[must_use]
63pub fn format_step_summary(steps: &[StepTiming]) -> String {
64    let mut table: TerminalTable = TerminalTable::with_headers(vec![
65        HEADER_STATUS.to_string(),
66        HEADER_STEP.to_string(),
67        HEADER_ELAPSED.to_string(),
68        HEADER_DETAIL.to_string(),
69    ]);
70    let mut pass_count: usize = 0;
71    let mut skip_count: usize = 0;
72    let mut fail_count: usize = 0;
73    let mut total_ms: u128 = 0;
74    for step in steps.iter() {
75        match step.get_status() {
76            StatusBadge::Pass => pass_count += 1,
77            StatusBadge::Skip => skip_count += 1,
78            StatusBadge::Fail => fail_count += 1,
79            StatusBadge::Warn | StatusBadge::Info => {}
80        }
81        total_ms = total_ms.saturating_add(step.get_elapsed_ms());
82        table.push_row(vec![
83            step.get_status().as_str().to_string(),
84            step.get_label().clone(),
85            format_duration_ms(step.get_elapsed_ms()),
86            step.get_detail().clone(),
87        ]);
88    }
89    let mut out: String = table.render();
90    out.push_str(&format!(
91        "Summary: {} passed, {} skipped, {} failed ({})\n",
92        pass_count,
93        skip_count,
94        fail_count,
95        format_duration_ms(total_ms)
96    ));
97    out
98}
99
100/// Executes an external command with live streaming output (or inherited TTY) and records wall-clock elapsed timing.
101///
102/// # Arguments
103///
104/// - `&str` - Executable binary name.
105/// - `&[String]` - Command arguments.
106/// - `Option<&Path>` - Optional working directory override.
107/// - `&[(&str, &str)]` - Additional environment variable pairs.
108/// - `bool` - When `true`, inherits stdin/stdout/stderr directly for live output and interactive TTY apps.
109///
110/// # Returns
111///
112/// - `io::Result<CommandRunMetrics>` - Execution metrics or non-zero exit error.
113pub fn run_command_streaming(
114    program: &str,
115    args: &[String],
116    cwd: Option<&Path>,
117    envs: &[(&str, &str)],
118    inherit_tty: bool,
119) -> io::Result<CommandRunMetrics> {
120    let started: time::Instant = time::Instant::now();
121    let mut command: Command = Command::new(program);
122    let _: &mut Command = command.args(args);
123    if let Some(dir) = cwd {
124        let _: &mut Command = command.current_dir(dir);
125    }
126    for (key, val) in envs.iter() {
127        let _: &mut Command = command.env(key, val);
128    }
129    if inherit_tty {
130        let status: ExitStatus = command
131            .stdin(Stdio::inherit())
132            .stdout(Stdio::inherit())
133            .stderr(Stdio::inherit())
134            .status()?;
135        let elapsed_ms: u128 = started.elapsed().as_millis();
136        let exit_code: i32 = status.code().unwrap_or(-1);
137        if !status.success() {
138            return Err(Error::other(format!(
139                "{ERR_STREAM_COMMAND_FAILED} ({program} exit={exit_code})"
140            )));
141        }
142        return Ok(CommandRunMetrics::new(
143            program.to_string(),
144            args.to_vec(),
145            exit_code,
146            elapsed_ms,
147        ));
148    }
149    let output: Output = command.output()?;
150    let elapsed_ms: u128 = started.elapsed().as_millis();
151    let exit_code: i32 = output.status.code().unwrap_or(-1);
152    if !output.status.success() {
153        let stderr_text: String = String::from_utf8_lossy(&output.stderr).into_owned();
154        return Err(Error::other(format!(
155            "{ERR_STREAM_COMMAND_FAILED} ({program} exit={exit_code}): {stderr_text}"
156        )));
157    }
158    Ok(CommandRunMetrics::new(
159        program.to_string(),
160        args.to_vec(),
161        exit_code,
162        elapsed_ms,
163    ))
164}
165
166/// Appends one padded row to `out` using column `widths`.
167///
168/// # Arguments
169///
170/// - `&mut String` - Destination text buffer.
171/// - `&[String]` - Row cells.
172/// - `&[usize]` - Column width vector.
173pub(crate) fn write_table_row(out: &mut String, row: &[String], widths: &[usize]) {
174    let last_idx: usize = widths.len().saturating_sub(1);
175    for (idx, width) in widths.iter().enumerate() {
176        let cell: &str = row.get(idx).map(String::as_str).unwrap_or("");
177        if idx > 0 {
178            out.push_str(TABLE_COL_SEP);
179        }
180        out.push_str(cell);
181        if idx < last_idx {
182            let cell_len: usize = cell.chars().count();
183            let pad: usize = width.saturating_sub(cell_len);
184            for _ in 0..pad {
185                out.push(' ');
186            }
187        }
188    }
189    out.push('\n');
190}