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 #[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 #[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_HOSTS_FILE: Lazy<PathBuf> = Lazy::new(|| {
74 if let Some(p) = var_path("PITCHFORK_HOSTS_FILE") {
75 return p;
76 }
77 if cfg!(windows) {
78 let system_root = var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".to_string());
79 PathBuf::from(system_root)
80 .join("System32")
81 .join("drivers")
82 .join("etc")
83 .join("hosts")
84 } else {
85 PathBuf::from("/etc/hosts")
86 }
87});
88pub static PITCHFORK_LOG: Lazy<log::LevelFilter> =
89 Lazy::new(|| var_log_level("PITCHFORK_LOG").unwrap_or(log::LevelFilter::Info));
90pub static PITCHFORK_LOG_FILE_LEVEL: Lazy<log::LevelFilter> =
91 Lazy::new(|| var_log_level("PITCHFORK_LOG_FILE_LEVEL").unwrap_or(*PITCHFORK_LOG));
92pub static PITCHFORK_LOGS_DIR: Lazy<PathBuf> =
93 Lazy::new(|| var_path("PITCHFORK_LOGS_DIR").unwrap_or(PITCHFORK_STATE_DIR.join("logs")));
94pub static PITCHFORK_LOG_FILE: Lazy<PathBuf> =
95 Lazy::new(|| PITCHFORK_LOGS_DIR.join("pitchfork").join("pitchfork.log"));
96pub static IPC_SOCK_DIR: Lazy<PathBuf> = Lazy::new(|| PITCHFORK_STATE_DIR.join("sock"));
99pub static IPC_SOCK_MAIN: Lazy<PathBuf> = Lazy::new(|| IPC_SOCK_DIR.join("main.sock"));
100
101pub static ORIGINAL_PATH: Lazy<Option<String>> = Lazy::new(|| var("PATH").ok());
103pub static IPC_JSON: Lazy<bool> = Lazy::new(|| !var_false("IPC_JSON"));
104
105pub fn expand_tilde(path: impl AsRef<std::path::Path>) -> PathBuf {
111 expand_tilde_for_user(path, None)
112}
113
114pub fn expand_tilde_for_user(path: impl AsRef<std::path::Path>, user: Option<&str>) -> PathBuf {
122 let path = path.as_ref();
123 match path.strip_prefix("~") {
124 Ok(rest) => home_dir_for_effective_user(user).join(rest),
125 Err(_) => path.to_path_buf(),
126 }
127}
128
129fn var_path(name: &str) -> Option<PathBuf> {
130 var(name).map(expand_tilde).ok()
131}
132
133fn var_log_level(name: &str) -> Option<log::LevelFilter> {
134 var(name).ok().and_then(|level| level.parse().ok())
135}
136
137fn var_false(name: &str) -> bool {
138 var(name)
139 .map(|val| val.to_lowercase())
140 .map(|val| val == "false" || val == "0")
141 .unwrap_or(false)
142}
143
144#[cfg(unix)]
154fn home_dir_for_user(username: &str) -> Option<PathBuf> {
155 nix::unistd::User::from_name(username)
156 .ok()
157 .flatten()
158 .map(|u| u.dir)
159}
160
161#[cfg(unix)]
163fn home_dir_by_user_spec(user: &str) -> Option<PathBuf> {
164 if user.chars().all(|c| c.is_ascii_digit()) {
165 let uid = user.parse::<u32>().ok()?;
166 nix::unistd::User::from_uid(nix::unistd::Uid::from_raw(uid))
167 .ok()
168 .flatten()
169 .map(|u| u.dir)
170 } else {
171 home_dir_for_user(user)
172 }
173}
174
175#[cfg(unix)]
179pub(crate) fn home_dir_for_effective_user(user: Option<&str>) -> PathBuf {
180 let user = user.map(str::trim).filter(|u| !u.is_empty());
181 match user {
182 Some(u) => home_dir_by_user_spec(u).unwrap_or_else(|| HOME_DIR.clone()),
183 None => HOME_DIR.clone(),
184 }
185}
186
187#[cfg(not(unix))]
188pub(crate) fn home_dir_for_effective_user(_user: Option<&str>) -> PathBuf {
189 HOME_DIR.clone()
190}
191
192#[cfg(unix)]
193fn configured_supervisor_user_home_dir() -> Option<PathBuf> {
194 let s = crate::settings::settings();
195 let user = s.supervisor.user.trim();
196 if user.is_empty() {
197 return None;
198 }
199 home_dir_by_user_spec(user)
200}
201
202#[cfg(test)]
203mod tests {
204 use super::*;
205 use std::path::Path;
206
207 #[test]
208 fn expand_tilde_replaces_home_prefix() {
209 assert_eq!(
210 expand_tilde("~/projects/api"),
211 HOME_DIR.join("projects/api")
212 );
213 assert_eq!(expand_tilde("~"), *HOME_DIR);
214 }
215
216 #[test]
217 fn expand_tilde_leaves_other_paths_unchanged() {
218 assert_eq!(
219 expand_tilde("/srv/projects/api"),
220 Path::new("/srv/projects/api")
221 );
222 assert_eq!(expand_tilde("projects/api"), Path::new("projects/api"));
223 assert_eq!(expand_tilde("~other/api"), Path::new("~other/api"));
224 }
225
226 #[test]
227 fn expand_tilde_for_user_none_uses_supervisor_home() {
228 assert_eq!(expand_tilde_for_user("~/data", None), HOME_DIR.join("data"));
229 }
230
231 #[test]
232 fn expand_tilde_for_user_empty_uses_supervisor_home() {
233 assert_eq!(
234 expand_tilde_for_user("~/data", Some("")),
235 HOME_DIR.join("data")
236 );
237 }
238
239 #[test]
240 fn expand_tilde_for_user_nonexistent_falls_back_to_supervisor_home() {
241 assert_eq!(
242 expand_tilde_for_user("~/data", Some("nonexistent_user_xyz")),
243 HOME_DIR.join("data")
244 );
245 }
246
247 #[test]
248 fn expand_tilde_for_user_leaves_non_tilde_unchanged() {
249 assert_eq!(
250 expand_tilde_for_user("/srv/api", Some("postgres")),
251 Path::new("/srv/api")
252 );
253 }
254}