auths_core/paths.rs
1//! Shared path resolution for the Auths home directory.
2//!
3//! All code that needs the `~/.auths` directory should call [`auths_home_with_config`]
4//! (or the legacy shim [`auths_home`]) instead of hardcoding
5//! `dirs::home_dir().join(".auths")`. This enables multi-agent simulation and CI
6//! overrides via the `AUTHS_HOME` env var.
7
8use std::path::PathBuf;
9
10use crate::config::EnvironmentConfig;
11
12/// Resolves the Auths home directory from an injected `EnvironmentConfig`.
13///
14/// Uses `config.auths_home` when set; otherwise falls back to `~/.auths`.
15/// Prefer this over `auths_home()` for new code — it keeps env-var reads at the
16/// process boundary.
17///
18/// Args:
19/// * `config` - The environment configuration to source the home path from.
20///
21/// Usage:
22/// ```ignore
23/// let env = auths_core::config::EnvironmentConfig::from_env();
24/// let dir = auths_core::paths::auths_home_with_config(&env)?;
25/// ```
26#[allow(clippy::disallowed_methods)] // INVARIANT: designated home-dir resolution boundary — dirs::home_dir is the OS-level fallback
27pub fn auths_home_with_config(config: &EnvironmentConfig) -> Result<PathBuf, AuthsHomeError> {
28 if let Some(ref home) = config.auths_home {
29 return Ok(home.clone());
30 }
31 let home = dirs::home_dir().ok_or(AuthsHomeError::NoHomeDir)?;
32 Ok(home.join(".auths"))
33}
34
35/// Resolves the Auths home directory.
36///
37/// Reads `AUTHS_HOME` from the environment (via `EnvironmentConfig::from_env()`),
38/// then falls back to `~/.auths`.
39///
40/// Prefer `auths_home_with_config` for new code.
41///
42/// Usage:
43/// ```ignore
44/// let dir = auths_core::paths::auths_home()?;
45/// let keys = dir.join("keys.enc");
46/// ```
47pub fn auths_home() -> Result<PathBuf, AuthsHomeError> {
48 auths_home_with_config(&EnvironmentConfig::from_env())
49}
50
51/// Error returned when the Auths home directory cannot be resolved.
52#[derive(Debug, thiserror::Error)]
53#[non_exhaustive]
54pub enum AuthsHomeError {
55 /// The user's home directory could not be determined.
56 #[error("Could not determine home directory")]
57 NoHomeDir,
58}
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63
64 #[test]
65 fn explicit_home_overrides_default() {
66 let env = EnvironmentConfig::builder()
67 .auths_home(std::path::PathBuf::from("/tmp/custom-auths"))
68 .build();
69 assert_eq!(
70 auths_home_with_config(&env).unwrap(),
71 std::path::PathBuf::from("/tmp/custom-auths")
72 );
73 }
74
75 #[test]
76 fn no_override_falls_back_to_default() {
77 let env = EnvironmentConfig::builder().build();
78 let path = auths_home_with_config(&env).unwrap();
79 assert!(path.ends_with(".auths"));
80 }
81}