use std::{path::Path, time::Duration};
use crate::process::CommandSpec;
pub(super) const PHASE_WIDTH: usize = 8;
const PROGRESS_WIDTH: usize = 22;
#[derive(Clone, Copy, Default)]
pub(super) struct TerminalCapabilities {
pub(super) stderr: StreamCapabilities,
pub(super) stdout: StreamCapabilities,
}
#[derive(Clone, Copy, Default)]
pub(super) struct StreamCapabilities {
pub(super) color: bool,
pub(super) live: bool,
}
#[derive(Clone)]
pub(super) struct LiveProgress {
pub(super) phase: String,
pub(super) completed: usize,
pub(super) total: Option<usize>,
pub(super) package: Option<String>,
}
#[derive(Clone)]
pub(super) struct LiveActivity {
pub(super) phase: String,
pub(super) message: String,
}
#[derive(Clone)]
pub(super) enum LiveDisplay {
Activity(LiveActivity),
Progress(LiveProgress),
}
#[derive(Clone, Copy)]
pub(super) enum Tone {
Accent,
Success,
Error,
Warning,
Muted,
Strong,
}
pub(super) fn command_action(command: &CommandSpec) -> &'static str {
match command.phase.as_str() {
"types" => "Generating TypeScript bindings",
"web" if command_has_argument(command, "build") => "Building frontend",
"web" => "Starting Vite",
"native" if command_has_argument(command, "build") => "Compiling native app",
"native" => "Starting native app",
"lockfile" => "Generating Cargo.lock",
"dependencies" => "Installing dependencies",
_ => "Running command",
}
}
fn command_has_argument(command: &CommandSpec, needle: &str) -> bool {
command.args.iter().any(|argument| {
argument
.to_string_lossy()
.split([':', '='])
.any(|part| part == needle)
})
}
pub(super) fn render_progress(progress: &LiveProgress, color: bool) -> String {
let phase = styled(
color,
Tone::Strong,
&format!("{:<PHASE_WIDTH$}", progress.phase),
);
let package = progress.package.as_deref().unwrap_or("Compiling");
if let Some(total) = progress.total {
let percent = progress_percent(progress.completed, total);
let filled = percent * PROGRESS_WIDTH / 100;
let bar = format!(
"{}{}",
"█".repeat(filled),
"░".repeat(PROGRESS_WIDTH - filled)
);
let bar = styled(color, Tone::Accent, &bar);
format!("\r ◐ {phase} {bar} {percent:>3}% {package}")
} else {
let bar = styled(color, Tone::Accent, "━━━━━━━━━━━━━━━━━━━━━━");
format!("\r ◐ {phase} {bar} {package}")
}
}
pub(super) fn render_live(display: &LiveDisplay, color: bool) -> String {
match display {
LiveDisplay::Progress(progress) => render_progress(progress, color),
LiveDisplay::Activity(activity) => {
let symbol = styled(color, Tone::Accent, "◇");
let phase = styled(
color,
Tone::Strong,
&format!("{:<PHASE_WIDTH$}", activity.phase),
);
format!("\r {symbol} {phase} {}", activity.message)
}
}
}
pub(super) fn progress_percent(completed: usize, total: usize) -> usize {
completed
.min(total)
.saturating_mul(100)
.checked_div(total)
.unwrap_or(0)
}
pub(super) fn osc_progress(state: usize, progress: usize) -> String {
format!("\u{1b}]9;4;{state};{}\u{7}", progress.min(100))
}
pub(super) fn clear_line() -> &'static str {
"\r\u{1b}[2K"
}
pub(super) fn friendly_path(path: &Path) -> String {
if let Ok(current_dir) = std::env::current_dir()
&& let Ok(relative) = path.strip_prefix(¤t_dir)
{
if relative.as_os_str().is_empty() {
return ".".to_owned();
}
return std::path::PathBuf::from(".")
.join(relative)
.display()
.to_string();
}
path.display().to_string()
}
pub(super) fn styled(enabled: bool, tone: Tone, text: &str) -> String {
if !enabled {
return text.to_owned();
}
let code = match tone {
Tone::Accent => "1;36",
Tone::Success => "1;32",
Tone::Error => "1;31",
Tone::Warning => "33",
Tone::Muted => "2",
Tone::Strong => "1",
};
format!("\u{1b}[{code}m{text}\u{1b}[0m")
}
pub(super) fn format_duration(duration: Duration) -> String {
if duration < Duration::from_secs(1) {
format!("{}ms", super::millis(duration))
} else {
format!("{:.2}s", duration.as_secs_f64())
}
}