1use std::ffi::OsString;
4use std::path::PathBuf;
5use std::sync::OnceLock;
6use std::time::Duration;
7
8use chrono::{DateTime, Utc};
9
10use super::cache::{CachedPath, PathCache, read_cache};
11use super::capture::{Capture, joined};
12use super::entries::{distinct, merge, missing_variables};
13use super::fallback::{self, Probe, env_var};
14use super::{DISABLE_ENV, DISABLE_ENV_ALIAS, save, shell_timeout};
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub enum Source {
19 LoginShell(PathBuf),
21 Registry,
23 Inherited(String),
25}
26
27impl Source {
28 pub fn describe(&self) -> String {
29 match self {
30 Source::LoginShell(shell) => format!("login shell {}", shell.display()),
31 Source::Registry => "Windows registry".to_string(),
32 Source::Inherited(reason) => format!("inherited ({reason})"),
33 }
34 }
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
40pub(super) struct CaptureError {
41 pub(super) capture: Capture,
42 pub(super) message: String,
43}
44
45pub(super) struct Found {
47 pub(super) path: OsString,
48 pub(super) source: Source,
49 pub(super) capture: Capture,
50 pub(super) network: Vec<(String, String)>,
51}
52
53#[derive(Debug, Clone)]
55pub struct Resolved {
56 pub path: OsString,
57 pub source: Source,
58 pub capture: Capture,
60 pub added: usize,
63 pub fallback: Vec<PathBuf>,
66 pub cached: Option<CachedPath>,
68 pub changed: bool,
71 pub network: Vec<(String, String)>,
73}
74
75impl Resolved {
76 fn inherited_path(path: OsString, reason: &str, capture: Capture) -> Self {
77 Self {
78 path,
79 source: Source::Inherited(reason.to_string()),
80 capture,
81 added: 0,
82 fallback: Vec::new(),
83 cached: None,
84 changed: false,
85 network: Vec::new(),
86 }
87 }
88
89 fn merged(path: OsString, found: Found, current: &OsString) -> Self {
90 Self {
91 added: distinct(&path).len() - distinct(current).len(),
92 changed: path != *current,
93 path,
94 source: found.source,
95 capture: found.capture,
96 fallback: Vec::new(),
97 cached: None,
98 network: missing_variables(found.network, |name| std::env::var_os(name).is_some()),
99 }
100 }
101
102 fn append(&mut self, directories: &[PathBuf], current: &OsString) {
105 if directories.is_empty() {
106 return;
107 }
108 let mut entries = distinct(&self.path);
109 entries.extend(directories.iter().cloned());
110 if let Ok(path) = std::env::join_paths(&entries) {
111 self.path = path;
112 self.added = distinct(&self.path)
113 .len()
114 .saturating_sub(distinct(current).len());
115 self.changed = self.path != *current;
116 }
117 }
118
119 fn use_cache(&mut self, cache: &PathCache, probe: &Probe<'_>, current: &OsString) {
121 let directories =
122 fallback::missing_directories(&distinct(&self.path), cache.path.clone(), probe);
123 self.append(&directories, current);
124 self.cached = Some(CachedPath {
125 saved_at: cache.saved_at,
126 source: cache.source.clone(),
127 version: cache.version.clone(),
128 added: directories.len(),
129 });
130 }
131
132 pub fn capture_failed(&self) -> bool {
134 self.capture.failed()
135 }
136
137 pub fn path_from(&self) -> &'static str {
141 match &self.capture {
142 Capture::Captured { .. } => "login_shell",
143 Capture::Registry => "registry",
144 Capture::Terminal => "terminal",
145 Capture::Disabled => "disabled",
146 _ if self.cached.as_ref().is_some_and(|cached| cached.added > 0) => "cache",
147 _ => "fallback",
148 }
149 }
150
151 pub fn log_fields(&self, now: DateTime<Utc>) -> Vec<(&'static str, String)> {
157 let cache_age = self.cached.as_ref().map_or_else(
158 || "-".to_string(),
159 |cached| (now - cached.saved_at).num_seconds().max(0).to_string(),
160 );
161 vec![
162 ("source", self.source.describe()),
163 ("capture", self.capture.label().to_string()),
164 (
165 "capture_seconds",
166 self.capture.seconds().unwrap_or_else(|| "-".to_string()),
167 ),
168 ("path_from", self.path_from().to_string()),
169 ("cache_age", cache_age),
170 ("added", self.added.to_string()),
171 ("fallback", joined(&self.fallback)),
172 ("changed", self.changed.to_string()),
173 ("network_variables", self.network.len().to_string()),
174 ]
175 }
176}
177
178#[derive(Debug, Clone)]
180pub struct Startup {
181 pub cache_file: Option<PathBuf>,
184 pub force: bool,
186}
187
188static APPLIED: OnceLock<Resolved> = OnceLock::new();
189
190pub fn applied() -> Option<&'static Resolved> {
192 APPLIED.get()
193}
194
195static SEARCH_FOLDERS: OnceLock<Vec<PathBuf>> = OnceLock::new();
196
197pub(super) fn search_folders() -> Option<&'static [PathBuf]> {
201 SEARCH_FOLDERS.get().map(Vec::as_slice)
202}
203
204pub unsafe fn apply(startup: Startup) -> &'static Resolved {
218 let cache = startup.cache_file.as_deref().and_then(read_cache);
219 let folders = fallback::startup_folders(&Probe::from_env(&env_var));
220 let resolved = resolve(startup.force, cache.as_ref(), folders.clone());
221 unsafe { set_environment(&resolved, reader_still_running()) };
224 let _ = SEARCH_FOLDERS.set(folders);
225 save::save(startup.cache_file, &resolved, cache, Utc::now());
226 APPLIED.get_or_init(|| resolved)
227}
228
229unsafe fn set_environment(resolved: &Resolved, reader_running: bool) {
238 if reader_running {
239 return;
240 }
241 if resolved.changed {
242 unsafe { std::env::set_var("PATH", &resolved.path) };
245 }
246 for (name, value) in &resolved.network {
247 unsafe { std::env::set_var(name, value) };
249 }
250}
251
252fn resolve(force: bool, cache: Option<&PathCache>, folders: Vec<PathBuf>) -> Resolved {
255 resolve_with(Inputs {
256 current: std::env::var_os("PATH").unwrap_or_default(),
257 disabled: disabled_by(&env_var),
258 terminal: terminal_start(force),
259 capture: platform_path,
260 cache,
261 fallback: folders,
262 probe: Probe::from_env(&env_var),
263 inherited_first: cfg!(windows),
264 })
265}
266
267pub(super) fn disabled_by(lookup: &dyn Fn(&str) -> Option<String>) -> Option<&'static str> {
269 [DISABLE_ENV, DISABLE_ENV_ALIAS]
270 .into_iter()
271 .find(|name| lookup(name).as_deref() == Some("0"))
272}
273
274pub(super) struct Inputs<'a, C> {
276 pub(super) current: OsString,
277 pub(super) disabled: Option<&'static str>,
278 pub(super) terminal: bool,
279 pub(super) capture: C,
280 pub(super) cache: Option<&'a PathCache>,
281 pub(super) fallback: Vec<PathBuf>,
283 pub(super) probe: Probe<'a>,
284 pub(super) inherited_first: bool,
287}
288
289pub(super) fn resolve_with<C>(inputs: Inputs<'_, C>) -> Resolved
293where
294 C: FnOnce(Duration) -> Result<Found, CaptureError>,
295{
296 let current = inputs.current;
297 if let Some(name) = inputs.disabled {
298 return Resolved::inherited_path(current, &format!("{name}=0"), Capture::Disabled);
299 }
300 if inputs.terminal {
301 return Resolved::inherited_path(current, "started from a terminal", Capture::Terminal);
302 }
303 let timeout = shell_timeout(inputs.cache.is_some());
304 let mut resolved = captured(
305 (inputs.capture)(timeout),
306 current.clone(),
307 inputs.inherited_first,
308 );
309 if resolved.capture_failed()
310 && let Some(cache) = inputs.cache
311 {
312 resolved.use_cache(cache, &inputs.probe, ¤t);
313 }
314 let directories =
315 fallback::missing_directories(&distinct(&resolved.path), inputs.fallback, &inputs.probe);
316 resolved.append(&directories, ¤t);
317 resolved.fallback = directories;
318 resolved
319}
320
321fn captured(
323 outcome: Result<Found, CaptureError>,
324 current: OsString,
325 inherited_first: bool,
326) -> Resolved {
327 match outcome {
328 Ok(found) => {
329 let path = if inherited_first {
335 merge(¤t, &found.path)
336 } else {
337 merge(&found.path, ¤t)
338 };
339 Resolved::merged(path, found, ¤t)
340 }
341 Err(error) => Resolved::inherited_path(current, &error.message, error.capture),
342 }
343}
344
345#[cfg(unix)]
346use super::shell::{platform_path, reader_still_running, terminal_start};
347
348#[cfg(windows)]
349use super::registry::platform_path;
350
351#[cfg(not(unix))]
354fn terminal_start(_force: bool) -> bool {
355 false
356}
357
358#[cfg(not(unix))]
360fn reader_still_running() -> bool {
361 false
362}
363
364#[cfg(not(any(unix, windows)))]
366fn platform_path(_timeout: Duration) -> Result<Found, CaptureError> {
367 Err(CaptureError {
368 capture: Capture::Other {
369 reason: "unsupported platform".to_string(),
370 },
371 message: "unsupported platform".to_string(),
372 })
373}
374
375#[cfg(test)]
376mod log_tests;
377#[cfg(test)]
378mod tests;