use std::ffi::OsString;
use std::path::PathBuf;
use std::sync::OnceLock;
use std::time::Duration;
use chrono::{DateTime, Utc};
use super::cache::{CachedPath, PathCache, read_cache};
use super::capture::{Capture, joined};
use super::entries::{distinct, merge, missing_variables};
use super::fallback::{self, Probe, env_var};
use super::{DISABLE_ENV, DISABLE_ENV_ALIAS, save, shell_timeout};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Source {
LoginShell(PathBuf),
Registry,
Inherited(String),
}
impl Source {
pub fn describe(&self) -> String {
match self {
Source::LoginShell(shell) => format!("login shell {}", shell.display()),
Source::Registry => "Windows registry".to_string(),
Source::Inherited(reason) => format!("inherited ({reason})"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct CaptureError {
pub(super) capture: Capture,
pub(super) message: String,
}
pub(super) struct Found {
pub(super) path: OsString,
pub(super) source: Source,
pub(super) capture: Capture,
pub(super) network: Vec<(String, String)>,
}
#[derive(Debug, Clone)]
pub struct Resolved {
pub path: OsString,
pub source: Source,
pub capture: Capture,
pub added: usize,
pub fallback: Vec<PathBuf>,
pub cached: Option<CachedPath>,
pub changed: bool,
pub network: Vec<(String, String)>,
}
impl Resolved {
fn inherited_path(path: OsString, reason: &str, capture: Capture) -> Self {
Self {
path,
source: Source::Inherited(reason.to_string()),
capture,
added: 0,
fallback: Vec::new(),
cached: None,
changed: false,
network: Vec::new(),
}
}
fn merged(path: OsString, found: Found, current: &OsString) -> Self {
Self {
added: distinct(&path).len() - distinct(current).len(),
changed: path != *current,
path,
source: found.source,
capture: found.capture,
fallback: Vec::new(),
cached: None,
network: missing_variables(found.network, |name| std::env::var_os(name).is_some()),
}
}
fn append(&mut self, directories: &[PathBuf], current: &OsString) {
if directories.is_empty() {
return;
}
let mut entries = distinct(&self.path);
entries.extend(directories.iter().cloned());
if let Ok(path) = std::env::join_paths(&entries) {
self.path = path;
self.added = distinct(&self.path)
.len()
.saturating_sub(distinct(current).len());
self.changed = self.path != *current;
}
}
fn use_cache(&mut self, cache: &PathCache, probe: &Probe<'_>, current: &OsString) {
let directories =
fallback::missing_directories(&distinct(&self.path), cache.path.clone(), probe);
self.append(&directories, current);
self.cached = Some(CachedPath {
saved_at: cache.saved_at,
source: cache.source.clone(),
version: cache.version.clone(),
added: directories.len(),
});
}
pub fn capture_failed(&self) -> bool {
self.capture.failed()
}
pub fn path_from(&self) -> &'static str {
match &self.capture {
Capture::Captured { .. } => "login_shell",
Capture::Registry => "registry",
Capture::Terminal => "terminal",
Capture::Disabled => "disabled",
_ if self.cached.as_ref().is_some_and(|cached| cached.added > 0) => "cache",
_ => "fallback",
}
}
pub fn log_fields(&self, now: DateTime<Utc>) -> Vec<(&'static str, String)> {
let cache_age = self.cached.as_ref().map_or_else(
|| "-".to_string(),
|cached| (now - cached.saved_at).num_seconds().max(0).to_string(),
);
vec![
("source", self.source.describe()),
("capture", self.capture.label().to_string()),
(
"capture_seconds",
self.capture.seconds().unwrap_or_else(|| "-".to_string()),
),
("path_from", self.path_from().to_string()),
("cache_age", cache_age),
("added", self.added.to_string()),
("fallback", joined(&self.fallback)),
("changed", self.changed.to_string()),
("network_variables", self.network.len().to_string()),
]
}
}
#[derive(Debug, Clone)]
pub struct Startup {
pub cache_file: Option<PathBuf>,
pub force: bool,
}
static APPLIED: OnceLock<Resolved> = OnceLock::new();
pub fn applied() -> Option<&'static Resolved> {
APPLIED.get()
}
static SEARCH_FOLDERS: OnceLock<Vec<PathBuf>> = OnceLock::new();
pub(super) fn search_folders() -> Option<&'static [PathBuf]> {
SEARCH_FOLDERS.get().map(Vec::as_slice)
}
pub unsafe fn apply(startup: Startup) -> &'static Resolved {
let cache = startup.cache_file.as_deref().and_then(read_cache);
let folders = fallback::startup_folders(&Probe::from_env(&env_var));
let resolved = resolve(startup.force, cache.as_ref(), folders.clone());
unsafe { set_environment(&resolved, reader_still_running()) };
let _ = SEARCH_FOLDERS.set(folders);
save::save(startup.cache_file, &resolved, cache, Utc::now());
APPLIED.get_or_init(|| resolved)
}
unsafe fn set_environment(resolved: &Resolved, reader_running: bool) {
if reader_running {
return;
}
if resolved.changed {
unsafe { std::env::set_var("PATH", &resolved.path) };
}
for (name, value) in &resolved.network {
unsafe { std::env::set_var(name, value) };
}
}
fn resolve(force: bool, cache: Option<&PathCache>, folders: Vec<PathBuf>) -> Resolved {
resolve_with(Inputs {
current: std::env::var_os("PATH").unwrap_or_default(),
disabled: disabled_by(&env_var),
terminal: terminal_start(force),
capture: platform_path,
cache,
fallback: folders,
probe: Probe::from_env(&env_var),
inherited_first: cfg!(windows),
})
}
pub(super) fn disabled_by(lookup: &dyn Fn(&str) -> Option<String>) -> Option<&'static str> {
[DISABLE_ENV, DISABLE_ENV_ALIAS]
.into_iter()
.find(|name| lookup(name).as_deref() == Some("0"))
}
pub(super) struct Inputs<'a, C> {
pub(super) current: OsString,
pub(super) disabled: Option<&'static str>,
pub(super) terminal: bool,
pub(super) capture: C,
pub(super) cache: Option<&'a PathCache>,
pub(super) fallback: Vec<PathBuf>,
pub(super) probe: Probe<'a>,
pub(super) inherited_first: bool,
}
pub(super) fn resolve_with<C>(inputs: Inputs<'_, C>) -> Resolved
where
C: FnOnce(Duration) -> Result<Found, CaptureError>,
{
let current = inputs.current;
if let Some(name) = inputs.disabled {
return Resolved::inherited_path(current, &format!("{name}=0"), Capture::Disabled);
}
if inputs.terminal {
return Resolved::inherited_path(current, "started from a terminal", Capture::Terminal);
}
let timeout = shell_timeout(inputs.cache.is_some());
let mut resolved = captured(
(inputs.capture)(timeout),
current.clone(),
inputs.inherited_first,
);
if resolved.capture_failed()
&& let Some(cache) = inputs.cache
{
resolved.use_cache(cache, &inputs.probe, ¤t);
}
let directories =
fallback::missing_directories(&distinct(&resolved.path), inputs.fallback, &inputs.probe);
resolved.append(&directories, ¤t);
resolved.fallback = directories;
resolved
}
fn captured(
outcome: Result<Found, CaptureError>,
current: OsString,
inherited_first: bool,
) -> Resolved {
match outcome {
Ok(found) => {
let path = if inherited_first {
merge(¤t, &found.path)
} else {
merge(&found.path, ¤t)
};
Resolved::merged(path, found, ¤t)
}
Err(error) => Resolved::inherited_path(current, &error.message, error.capture),
}
}
#[cfg(unix)]
use super::shell::{platform_path, reader_still_running, terminal_start};
#[cfg(windows)]
use super::registry::platform_path;
#[cfg(not(unix))]
fn terminal_start(_force: bool) -> bool {
false
}
#[cfg(not(unix))]
fn reader_still_running() -> bool {
false
}
#[cfg(not(any(unix, windows)))]
fn platform_path(_timeout: Duration) -> Result<Found, CaptureError> {
Err(CaptureError {
capture: Capture::Other {
reason: "unsupported platform".to_string(),
},
message: "unsupported platform".to_string(),
})
}
#[cfg(test)]
mod log_tests;
#[cfg(test)]
mod tests;