Skip to main content

pitchfork_cli/
env.rs

1use once_cell::sync::Lazy;
2pub use std::env::*;
3use std::path::PathBuf;
4
5pub static PITCHFORK_BIN: Lazy<PathBuf> = Lazy::new(|| {
6    current_exe()
7        .and_then(|p| p.canonicalize())
8        .unwrap_or_else(|e| {
9            eprintln!("Warning: Could not determine pitchfork binary path: {e}");
10            args()
11                .next()
12                .map(PathBuf::from)
13                .unwrap_or_else(|| PathBuf::from("pitchfork"))
14        })
15});
16pub static CWD: Lazy<PathBuf> = Lazy::new(|| current_dir().unwrap_or_else(|_| PathBuf::from(".")));
17
18pub static HOME_DIR: Lazy<PathBuf> = Lazy::new(|| {
19    // When running under `sudo`, HOME points to /var/root (macOS) or /root (Linux).
20    // Resolve the *original* user's home via SUDO_USER so all derived paths
21    // (state file, IPC socket, config, logs) remain consistent with the
22    // non-sudo invocation. This prevents a second supervisor instance from
23    // being spawned in a separate directory tree.
24    //
25    // Guard: only honour SUDO_USER when the effective UID is 0 (i.e. we are
26    // actually running as root). SUDO_USER can leak into non-sudo environments
27    // (e.g. inherited env, containers) and would misdirect all state paths.
28    #[cfg(unix)]
29    if nix::unistd::Uid::effective().is_root()
30        && let Ok(sudo_user) = std::env::var("SUDO_USER")
31        && let Some(home) = home_dir_for_user(&sudo_user)
32    {
33        return home;
34    }
35    dirs::home_dir().unwrap_or_else(|| {
36        eprintln!("Warning: Could not determine home directory");
37        PathBuf::from("/tmp")
38    })
39});
40pub static PITCHFORK_CONFIG_DIR: Lazy<PathBuf> = Lazy::new(|| {
41    var_path("PITCHFORK_CONFIG_DIR").unwrap_or(HOME_DIR.join(".config").join("pitchfork"))
42});
43pub static PITCHFORK_GLOBAL_CONFIG_USER: Lazy<PathBuf> =
44    Lazy::new(|| PITCHFORK_CONFIG_DIR.join("config.toml"));
45pub static PITCHFORK_GLOBAL_CONFIG_SYSTEM: Lazy<PathBuf> =
46    Lazy::new(|| PathBuf::from("/etc/pitchfork/config.toml"));
47pub static PITCHFORK_STATE_DIR: Lazy<PathBuf> = Lazy::new(|| {
48    if let Some(p) = var_path("PITCHFORK_STATE_DIR") {
49        return p;
50    }
51    #[cfg(unix)]
52    if nix::unistd::Uid::effective().is_root()
53        && let Some(home) = configured_supervisor_user_home_dir()
54    {
55        return home.join(".local").join("state").join("pitchfork");
56    }
57    // Under sudo, dirs::state_dir() would resolve against root's HOME,
58    // bypassing our SUDO_USER correction. Use HOME_DIR directly instead.
59    #[cfg(unix)]
60    if nix::unistd::Uid::effective().is_root() {
61        return HOME_DIR.join(".local").join("state").join("pitchfork");
62    }
63    dirs::state_dir()
64        .unwrap_or_else(|| HOME_DIR.join(".local").join("state"))
65        .join("pitchfork")
66});
67pub static PITCHFORK_STATE_FILE: Lazy<PathBuf> =
68    Lazy::new(|| PITCHFORK_STATE_DIR.join("state.toml"));
69pub static PITCHFORK_LOG: Lazy<log::LevelFilter> =
70    Lazy::new(|| var_log_level("PITCHFORK_LOG").unwrap_or(log::LevelFilter::Info));
71pub static PITCHFORK_LOG_FILE_LEVEL: Lazy<log::LevelFilter> =
72    Lazy::new(|| var_log_level("PITCHFORK_LOG_FILE_LEVEL").unwrap_or(*PITCHFORK_LOG));
73pub static PITCHFORK_LOGS_DIR: Lazy<PathBuf> =
74    Lazy::new(|| var_path("PITCHFORK_LOGS_DIR").unwrap_or(PITCHFORK_STATE_DIR.join("logs")));
75pub static PITCHFORK_LOG_FILE: Lazy<PathBuf> =
76    Lazy::new(|| PITCHFORK_LOGS_DIR.join("pitchfork").join("pitchfork.log"));
77// pub static PITCHFORK_EXEC: Lazy<bool> = Lazy::new(|| var_true("PITCHFORK_EXEC"));
78
79pub static IPC_SOCK_DIR: Lazy<PathBuf> = Lazy::new(|| PITCHFORK_STATE_DIR.join("sock"));
80pub static IPC_SOCK_MAIN: Lazy<PathBuf> = Lazy::new(|| IPC_SOCK_DIR.join("main.sock"));
81
82// Capture the PATH at startup so daemons can find user tools
83pub static ORIGINAL_PATH: Lazy<Option<String>> = Lazy::new(|| var("PATH").ok());
84pub static IPC_JSON: Lazy<bool> = Lazy::new(|| !var_false("IPC_JSON"));
85
86/// Expand a leading `~` path component to the current Pitchfork user's home.
87///
88/// This intentionally supports only `~` and `~/...`, not `~user` or shell
89/// expansions such as `$HOME`. Pitchfork's home resolution accounts for the
90/// original user when running under `sudo`.
91pub fn expand_tilde(path: impl AsRef<std::path::Path>) -> PathBuf {
92    expand_tilde_for_user(path, None)
93}
94
95/// Expand a leading `~` to the home directory of `user`.
96///
97/// When `user` is `None`, empty, or the system lookup fails, falls back to
98/// `HOME_DIR` (the supervisor's home). This matches Unix semantics where `~`
99/// in a process's working directory refers to that process's effective user.
100///
101/// Only `~` and `~/...` are supported — not `~user` or shell expansions.
102pub fn expand_tilde_for_user(path: impl AsRef<std::path::Path>, user: Option<&str>) -> PathBuf {
103    let path = path.as_ref();
104    match path.strip_prefix("~") {
105        Ok(rest) => home_dir_for_effective_user(user).join(rest),
106        Err(_) => path.to_path_buf(),
107    }
108}
109
110fn var_path(name: &str) -> Option<PathBuf> {
111    var(name).map(expand_tilde).ok()
112}
113
114fn var_log_level(name: &str) -> Option<log::LevelFilter> {
115    var(name).ok().and_then(|level| level.parse().ok())
116}
117
118fn var_false(name: &str) -> bool {
119    var(name)
120        .map(|val| val.to_lowercase())
121        .map(|val| val == "false" || val == "0")
122        .unwrap_or(false)
123}
124
125// fn var_true(name: &str) -> bool {
126//     var(name)
127//         .map(|val| val.to_lowercase())
128//         .map(|val| val == "true" || val == "1")
129//         .unwrap_or(false)
130// }
131
132/// Look up a user's home directory via the system password database.
133/// Returns `None` if the user does not exist or the lookup fails.
134#[cfg(unix)]
135fn home_dir_for_user(username: &str) -> Option<PathBuf> {
136    nix::unistd::User::from_name(username)
137        .ok()
138        .flatten()
139        .map(|u| u.dir)
140}
141
142/// Look up a home directory by username or numeric UID string.
143#[cfg(unix)]
144fn home_dir_by_user_spec(user: &str) -> Option<PathBuf> {
145    if user.chars().all(|c| c.is_ascii_digit()) {
146        let uid = user.parse::<u32>().ok()?;
147        nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))
148            .ok()
149            .flatten()
150            .map(|u| u.dir)
151    } else {
152        home_dir_for_user(user)
153    }
154}
155
156/// Resolve the home directory for an effective daemon user.
157///
158/// Returns `HOME_DIR` when `user` is `None`, empty, or the lookup fails.
159#[cfg(unix)]
160pub(crate) fn home_dir_for_effective_user(user: Option<&str>) -> PathBuf {
161    let user = user.map(str::trim).filter(|u| !u.is_empty());
162    match user {
163        Some(u) => home_dir_by_user_spec(u).unwrap_or_else(|| HOME_DIR.clone()),
164        None => HOME_DIR.clone(),
165    }
166}
167
168#[cfg(not(unix))]
169pub(crate) fn home_dir_for_effective_user(_user: Option<&str>) -> PathBuf {
170    HOME_DIR.clone()
171}
172
173#[cfg(unix)]
174fn configured_supervisor_user_home_dir() -> Option<PathBuf> {
175    let s = crate::settings::settings();
176    let user = s.supervisor.user.trim();
177    if user.is_empty() {
178        return None;
179    }
180    home_dir_by_user_spec(user)
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186    use std::path::Path;
187
188    #[test]
189    fn expand_tilde_replaces_home_prefix() {
190        assert_eq!(
191            expand_tilde("~/projects/api"),
192            HOME_DIR.join("projects/api")
193        );
194        assert_eq!(expand_tilde("~"), *HOME_DIR);
195    }
196
197    #[test]
198    fn expand_tilde_leaves_other_paths_unchanged() {
199        assert_eq!(
200            expand_tilde("/srv/projects/api"),
201            Path::new("/srv/projects/api")
202        );
203        assert_eq!(expand_tilde("projects/api"), Path::new("projects/api"));
204        assert_eq!(expand_tilde("~other/api"), Path::new("~other/api"));
205    }
206
207    #[test]
208    fn expand_tilde_for_user_none_uses_supervisor_home() {
209        assert_eq!(expand_tilde_for_user("~/data", None), HOME_DIR.join("data"));
210    }
211
212    #[test]
213    fn expand_tilde_for_user_empty_uses_supervisor_home() {
214        assert_eq!(
215            expand_tilde_for_user("~/data", Some("")),
216            HOME_DIR.join("data")
217        );
218    }
219
220    #[test]
221    fn expand_tilde_for_user_nonexistent_falls_back_to_supervisor_home() {
222        assert_eq!(
223            expand_tilde_for_user("~/data", Some("nonexistent_user_xyz")),
224            HOME_DIR.join("data")
225        );
226    }
227
228    #[test]
229    fn expand_tilde_for_user_leaves_non_tilde_unchanged() {
230        assert_eq!(
231            expand_tilde_for_user("/srv/api", Some("postgres")),
232            Path::new("/srv/api")
233        );
234    }
235}