Skip to main content

subspace_core/path/
capture.rs

1//! What the login-shell capture did, and its product-neutral reason text.
2//! Nothing here holds a `PATH` value or an environment variable value.
3
4use std::path::PathBuf;
5
6use serde::{Deserialize, Serialize};
7
8/// The result of asking the login shell (or, on Windows, the registry) for
9/// the `PATH` a terminal has.
10#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
11#[serde(tag = "kind", rename_all = "snake_case")]
12pub enum Capture {
13    /// The login shell printed its PATH.
14    Captured { shell: PathBuf, elapsed_ms: u64 },
15    /// The login shell did not print its PATH within the limit.
16    Timeout { shell: PathBuf, limit_ms: u64 },
17    /// The login shell started but printed no PATH between the markers.
18    NoPath { shell: PathBuf, elapsed_ms: u64 },
19    /// The login shell could not start; `error` is the io::ErrorKind text
20    /// only (e.g. "entity not found"), never paths or env.
21    StartFailed { shell: PathBuf, error: String },
22    /// Not attempted: started from a terminal.
23    Terminal,
24    /// Not attempted: SUBSPACE_GUI_LOGIN_PATH=0.
25    Disabled,
26    /// Windows: the registry supplied Path.
27    Registry,
28    /// Any other failure (Windows registry errors), reason text without env
29    /// values.
30    Other { reason: String },
31}
32
33const MILLISECONDS_PER_SECOND: u64 = 1000;
34
35/// `3.4` for 3 449 ms: the log and Details precision.
36pub(super) fn seconds(milliseconds: u64) -> String {
37    format!(
38        "{:.1}",
39        milliseconds as f64 / MILLISECONDS_PER_SECOND as f64
40    )
41}
42
43/// `10` for 10 000 ms, `2.5` for 2 500 ms: a limit as people write it.
44pub(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    /// The snake_case kind, as serialized and as the `capture` log field.
54    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    /// Whether the login shell or the registry was asked and failed.
68    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    /// The `capture_seconds` log value: the elapsed time, or the limit for
79    /// a timeout, to 0.1 s; `None` when nothing ran or nothing was timed.
80    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    /// Why the app could not read the shell's `PATH`, to follow the app
91    /// name: "could not read your PATH: /bin/zsh did not finish starting
92    /// within 10 s". `None` when the `PATH` was read or not asked for.
93    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
113/// `a, b`: directories as one log or Details value.
114pub(super) fn joined(directories: &[PathBuf]) -> String {
115    directories
116        .iter()
117        .map(|directory| directory.display().to_string())
118        .collect::<Vec<_>>()
119        .join(", ")
120}