use std::path::PathBuf;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Capture {
Captured { shell: PathBuf, elapsed_ms: u64 },
Timeout { shell: PathBuf, limit_ms: u64 },
NoPath { shell: PathBuf, elapsed_ms: u64 },
StartFailed { shell: PathBuf, error: String },
Terminal,
Disabled,
Registry,
Other { reason: String },
}
const MILLISECONDS_PER_SECOND: u64 = 1000;
pub(super) fn seconds(milliseconds: u64) -> String {
format!(
"{:.1}",
milliseconds as f64 / MILLISECONDS_PER_SECOND as f64
)
}
pub(super) fn limit_seconds(milliseconds: u64) -> String {
if milliseconds.is_multiple_of(MILLISECONDS_PER_SECOND) {
(milliseconds / MILLISECONDS_PER_SECOND).to_string()
} else {
seconds(milliseconds)
}
}
impl Capture {
pub fn label(&self) -> &'static str {
match self {
Capture::Captured { .. } => "captured",
Capture::Timeout { .. } => "timeout",
Capture::NoPath { .. } => "no_path",
Capture::StartFailed { .. } => "start_failed",
Capture::Terminal => "terminal",
Capture::Disabled => "disabled",
Capture::Registry => "registry",
Capture::Other { .. } => "other",
}
}
pub fn failed(&self) -> bool {
matches!(
self,
Capture::Timeout { .. }
| Capture::NoPath { .. }
| Capture::StartFailed { .. }
| Capture::Other { .. }
)
}
pub fn seconds(&self) -> Option<String> {
match self {
Capture::Captured { elapsed_ms, .. } | Capture::NoPath { elapsed_ms, .. } => {
Some(seconds(*elapsed_ms))
}
Capture::Timeout { limit_ms, .. } => Some(seconds(*limit_ms)),
_ => None,
}
}
pub fn reason(&self) -> Option<String> {
let detail = match self {
Capture::Timeout { shell, limit_ms } => format!(
"{} did not finish starting within {} s",
shell.display(),
limit_seconds(*limit_ms)
),
Capture::NoPath { shell, .. } => {
format!("{} started but printed no PATH", shell.display())
}
Capture::StartFailed { shell, error } => {
format!("{} could not start: {error}", shell.display())
}
Capture::Other { reason } => reason.clone(),
_ => return None,
};
Some(format!("could not read your PATH: {detail}"))
}
}
pub(super) fn joined(directories: &[PathBuf]) -> String {
directories
.iter()
.map(|directory| directory.display().to_string())
.collect::<Vec<_>>()
.join(", ")
}