subspace_core/path/
capture.rs1use std::path::PathBuf;
5
6use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
11#[serde(tag = "kind", rename_all = "snake_case")]
12pub enum Capture {
13 Captured { shell: PathBuf, elapsed_ms: u64 },
15 Timeout { shell: PathBuf, limit_ms: u64 },
17 NoPath { shell: PathBuf, elapsed_ms: u64 },
19 StartFailed { shell: PathBuf, error: String },
22 Terminal,
24 Disabled,
26 Registry,
28 Other { reason: String },
31}
32
33const MILLISECONDS_PER_SECOND: u64 = 1000;
34
35pub(super) fn seconds(milliseconds: u64) -> String {
37 format!(
38 "{:.1}",
39 milliseconds as f64 / MILLISECONDS_PER_SECOND as f64
40 )
41}
42
43pub(super) fn limit_seconds(milliseconds: u64) -> String {
45 if milliseconds.is_multiple_of(MILLISECONDS_PER_SECOND) {
46 (milliseconds / MILLISECONDS_PER_SECOND).to_string()
47 } else {
48 seconds(milliseconds)
49 }
50}
51
52impl Capture {
53 pub fn label(&self) -> &'static str {
55 match self {
56 Capture::Captured { .. } => "captured",
57 Capture::Timeout { .. } => "timeout",
58 Capture::NoPath { .. } => "no_path",
59 Capture::StartFailed { .. } => "start_failed",
60 Capture::Terminal => "terminal",
61 Capture::Disabled => "disabled",
62 Capture::Registry => "registry",
63 Capture::Other { .. } => "other",
64 }
65 }
66
67 pub fn failed(&self) -> bool {
69 matches!(
70 self,
71 Capture::Timeout { .. }
72 | Capture::NoPath { .. }
73 | Capture::StartFailed { .. }
74 | Capture::Other { .. }
75 )
76 }
77
78 pub fn seconds(&self) -> Option<String> {
81 match self {
82 Capture::Captured { elapsed_ms, .. } | Capture::NoPath { elapsed_ms, .. } => {
83 Some(seconds(*elapsed_ms))
84 }
85 Capture::Timeout { limit_ms, .. } => Some(seconds(*limit_ms)),
86 _ => None,
87 }
88 }
89
90 pub fn reason(&self) -> Option<String> {
94 let detail = match self {
95 Capture::Timeout { shell, limit_ms } => format!(
96 "{} did not finish starting within {} s",
97 shell.display(),
98 limit_seconds(*limit_ms)
99 ),
100 Capture::NoPath { shell, .. } => {
101 format!("{} started but printed no PATH", shell.display())
102 }
103 Capture::StartFailed { shell, error } => {
104 format!("{} could not start: {error}", shell.display())
105 }
106 Capture::Other { reason } => reason.clone(),
107 _ => return None,
108 };
109 Some(format!("could not read your PATH: {detail}"))
110 }
111}
112
113pub(super) fn joined(directories: &[PathBuf]) -> String {
115 directories
116 .iter()
117 .map(|directory| directory.display().to_string())
118 .collect::<Vec<_>>()
119 .join(", ")
120}