1use std::{
27 env,
28 error::Error,
29 ffi::OsString,
30 fmt, io,
31 path::{Path, PathBuf},
32};
33
34pub trait EnvSource {
39 fn var_os(&self, key: &str) -> Option<OsString>;
41
42 fn path_exists(&self, path: &Path) -> bool {
45 path.exists()
46 }
47
48 fn temp_dir(&self) -> PathBuf {
51 env::temp_dir()
52 }
53
54 fn current_dir(&self) -> io::Result<PathBuf> {
57 env::current_dir()
58 }
59}
60
61#[derive(Clone, Copy, Debug, Default)]
63pub struct SystemEnv;
64
65impl EnvSource for SystemEnv {
66 fn var_os(&self, key: &str) -> Option<OsString> {
67 env::var_os(key)
68 }
69}
70
71#[derive(Debug)]
73#[non_exhaustive]
74pub enum PathsError {
75 Unresolved {
77 directory: &'static str,
79 variables: &'static [&'static str],
81 },
82 RelativePath {
84 source: String,
86 path: PathBuf,
88 },
89 CurrentDir(io::Error),
91 InvalidUserToken,
93}
94
95impl fmt::Display for PathsError {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 match self {
98 Self::Unresolved {
99 directory,
100 variables,
101 } => write!(
102 f,
103 "could not resolve an absolute {directory}; tried {}",
104 variables.join(", ")
105 ),
106 Self::RelativePath { source, path } => {
107 write!(f, "{source} must be absolute, got {}", path.display())
108 }
109 Self::CurrentDir(error) => write!(f, "could not resolve current directory: {error}"),
110 Self::InvalidUserToken => f.write_str(
111 "connection-file user token must be non-empty and contain no path separators",
112 ),
113 }
114 }
115}
116
117impl Error for PathsError {
118 fn source(&self) -> Option<&(dyn Error + 'static)> {
119 match self {
120 Self::CurrentDir(error) => Some(error),
121 _ => None,
122 }
123 }
124}
125
126#[derive(Clone, Copy)]
127enum Platform {
128 Unix,
129 Windows,
130}
131
132pub struct Dirs<'a, E: EnvSource + ?Sized> {
134 env: &'a E,
135 platform: Platform,
136}
137
138pub fn with_env<E: EnvSource + ?Sized>(env: &E) -> Dirs<'_, E> {
140 Dirs {
141 env,
142 platform: if cfg!(windows) {
143 Platform::Windows
144 } else {
145 Platform::Unix
146 },
147 }
148}
149
150impl<E: EnvSource + ?Sized> Dirs<'_, E> {
151 fn non_empty(&self, key: &str) -> Option<OsString> {
152 self.env.var_os(key).filter(|value| !value.is_empty())
153 }
154
155 fn absolute_var(&self, key: &str) -> Option<PathBuf> {
156 self.non_empty(key)
157 .map(PathBuf::from)
158 .filter(|path| path.is_absolute())
159 }
160
161 pub fn home(&self) -> Result<PathBuf, PathsError> {
165 match self.platform {
166 Platform::Unix => self.absolute_var("HOME").ok_or(PathsError::Unresolved {
167 directory: "home directory",
168 variables: &["HOME"],
169 }),
170 Platform::Windows => {
171 if let Some(path) = self.absolute_var("USERPROFILE") {
172 return Ok(path);
173 }
174 if let (Some(drive), Some(path)) =
175 (self.non_empty("HOMEDRIVE"), self.non_empty("HOMEPATH"))
176 {
177 let mut home = PathBuf::from(drive);
178 home.push(path);
179 if home.is_absolute() {
180 return Ok(home);
181 }
182 }
183 self.absolute_var("HOME").ok_or(PathsError::Unresolved {
184 directory: "home directory",
185 variables: &["USERPROFILE", "HOMEDRIVE", "HOMEPATH", "HOME"],
186 })
187 }
188 }
189 }
190
191 fn base(
192 &self,
193 xdg: &'static str,
194 windows: &'static str,
195 unix_tail: &[&str],
196 windows_tail: &str,
197 ) -> Result<PathBuf, PathsError> {
198 if let Some(path) = self.absolute_var(xdg) {
199 return Ok(path);
200 }
201 match self.platform {
202 Platform::Unix => {
203 let mut path = self.home().map_err(|_| PathsError::Unresolved {
204 directory: xdg,
205 variables: match xdg {
206 "XDG_DATA_HOME" => &["XDG_DATA_HOME", "HOME"],
207 "XDG_CONFIG_HOME" => &["XDG_CONFIG_HOME", "HOME"],
208 "XDG_STATE_HOME" => &["XDG_STATE_HOME", "HOME"],
209 _ => &["XDG_CACHE_HOME", "HOME"],
210 },
211 })?;
212 for component in unix_tail {
213 path.push(component);
214 }
215 Ok(path)
216 }
217 Platform::Windows => {
218 self.windows_base(windows, windows_tail)
219 .ok_or(PathsError::Unresolved {
220 directory: xdg,
221 variables: match xdg {
222 "XDG_DATA_HOME" => &["XDG_DATA_HOME", "LOCALAPPDATA", "USERPROFILE"],
223 "XDG_CONFIG_HOME" => &["XDG_CONFIG_HOME", "APPDATA", "USERPROFILE"],
224 "XDG_STATE_HOME" => &["XDG_STATE_HOME", "LOCALAPPDATA", "USERPROFILE"],
225 _ => &["XDG_CACHE_HOME", "LOCALAPPDATA", "USERPROFILE"],
226 },
227 })
228 }
229 }
230 }
231
232 fn windows_base(&self, variable: &str, tail: &str) -> Option<PathBuf> {
233 self.absolute_var(variable).or_else(|| {
234 self.absolute_var("USERPROFILE")
235 .map(|path| path.join("AppData").join(tail))
236 })
237 }
238
239 pub fn data_home(&self) -> Result<PathBuf, PathsError> {
243 self.base(
244 "XDG_DATA_HOME",
245 "LOCALAPPDATA",
246 &[".local", "share"],
247 "Local",
248 )
249 }
250
251 pub fn xdg_data_home(&self) -> Result<PathBuf, PathsError> {
256 if let Some(path) = self.absolute_var("XDG_DATA_HOME") {
257 return Ok(path);
258 }
259 let home = self.home().map_err(|_| PathsError::Unresolved {
260 directory: "XDG data home",
261 variables: match self.platform {
262 Platform::Unix => &["XDG_DATA_HOME", "HOME"],
263 Platform::Windows => &[
264 "XDG_DATA_HOME",
265 "USERPROFILE",
266 "HOMEDRIVE",
267 "HOMEPATH",
268 "HOME",
269 ],
270 },
271 })?;
272 Ok(home.join(".local").join("share"))
273 }
274
275 pub fn config_home(&self) -> Result<PathBuf, PathsError> {
277 self.base("XDG_CONFIG_HOME", "APPDATA", &[".config"], "Roaming")
278 }
279
280 pub fn state_home(&self) -> Result<PathBuf, PathsError> {
282 self.base(
283 "XDG_STATE_HOME",
284 "LOCALAPPDATA",
285 &[".local", "state"],
286 "Local",
287 )
288 }
289
290 pub fn cache_home(&self) -> Result<PathBuf, PathsError> {
292 self.base("XDG_CACHE_HOME", "LOCALAPPDATA", &[".cache"], "Local")
293 }
294
295 pub fn cortexkit_data_dir(&self) -> Result<PathBuf, PathsError> {
298 let local = self.data_home().map(|home| home.join("cortexkit"));
299 if matches!(self.platform, Platform::Windows)
300 && self.absolute_var("XDG_DATA_HOME").is_none()
301 {
302 if let Some(roaming) = self.windows_base("APPDATA", "Roaming") {
303 let legacy = roaming.join("cortexkit");
304 if self.env.path_exists(&legacy)
305 && !local.as_ref().is_ok_and(|path| self.env.path_exists(path))
306 {
307 return Ok(legacy);
308 }
309 }
310 }
311 local
312 }
313
314 pub fn cortexkit_config_dir(&self) -> Result<PathBuf, PathsError> {
316 Ok(self.config_home()?.join("cortexkit"))
317 }
318
319 pub fn cortexkit_run_dir(&self) -> Result<PathBuf, PathsError> {
323 Ok(self.cortexkit_data_dir()?.join("run"))
324 }
325
326 pub fn cortexkit_state_dir(&self) -> Result<PathBuf, PathsError> {
328 Ok(self.state_home()?.join("cortexkit"))
329 }
330
331 pub fn cortexkit_cache_dir(&self) -> Result<PathBuf, PathsError> {
333 Ok(self.cache_home()?.join("cortexkit"))
334 }
335
336 pub fn connection_file_candidates(
354 &self,
355 explicit: Option<&Path>,
356 per_user_token: &str,
357 ) -> Result<Vec<PathBuf>, PathsError> {
358 if let Some(path) = explicit {
359 if path.is_absolute() {
360 return Ok(vec![path.to_path_buf()]);
361 }
362 let cwd = self.env.current_dir().map_err(PathsError::CurrentDir)?;
363 return Ok(vec![require_absolute(
364 require_absolute(cwd, "current directory")?.join(path),
365 "explicit connection file",
366 )?]);
367 }
368 if let Some(path) = self.non_empty("SUBC_CONNECTION_FILE") {
369 return Ok(vec![require_absolute(
370 PathBuf::from(path),
371 "SUBC_CONNECTION_FILE",
372 )?]);
373 }
374 if per_user_token.is_empty() || per_user_token.contains(['/', '\\']) {
375 return Err(PathsError::InvalidUserToken);
376 }
377 let mut candidates = Vec::new();
378 if let Some(path) = self.absolute_var("XDG_RUNTIME_DIR") {
379 candidates.push(path.join("subc-connection.json"));
380 }
381 if let Some(path) = self.absolute_var("HOME") {
382 candidates.push(
383 path.join(".local")
384 .join("share")
385 .join("cortexkit")
386 .join("run")
387 .join("subc-connection.json"),
388 );
389 }
390 candidates.push(
391 require_absolute(self.env.temp_dir(), "temporary directory")?
392 .join(format!("subc-{per_user_token}.connection.json")),
393 );
394 Ok(candidates)
395 }
396}
397
398fn require_absolute(path: PathBuf, source: &str) -> Result<PathBuf, PathsError> {
399 if path.is_absolute() {
400 Ok(path)
401 } else {
402 Err(PathsError::RelativePath {
403 source: source.to_owned(),
404 path,
405 })
406 }
407}
408
409pub fn env_absolute_path<E: EnvSource + ?Sized>(
415 env: &E,
416 variable: &str,
417) -> Result<Option<PathBuf>, PathsError> {
418 env.var_os(variable)
419 .filter(|value| !value.is_empty())
420 .map(|value| require_absolute(PathBuf::from(value), variable))
421 .transpose()
422}
423
424macro_rules! process_dirs {
425 ($($name:ident),+ $(,)?) => {$(
426 #[doc = concat!("Resolve using the process environment; see [`Dirs::", stringify!($name), "`].")]
427 pub fn $name() -> Result<PathBuf, PathsError> { with_env(&SystemEnv).$name() }
428 )+};
429}
430
431process_dirs!(
432 home,
433 data_home,
434 xdg_data_home,
435 config_home,
436 state_home,
437 cache_home,
438 cortexkit_data_dir,
439 cortexkit_config_dir,
440 cortexkit_run_dir,
441 cortexkit_state_dir,
442 cortexkit_cache_dir
443);
444
445pub fn connection_file_candidates(
447 explicit: Option<&Path>,
448 per_user_token: &str,
449) -> Result<Vec<PathBuf>, PathsError> {
450 with_env(&SystemEnv).connection_file_candidates(explicit, per_user_token)
451}
452
453#[cfg(test)]
454mod tests;