fader_master/config/src/paths.rs

135 lines
4.7 KiB
Rust

use std::{fs, os::unix::fs::PermissionsExt, path::PathBuf};
use fader_core::ProfileId;
use crate::{ConfigError, PersistenceError, StateLoad, files::load_state};
/// Relevant XDG environment values, separated from process globals for tests.
#[derive(Clone, Debug)]
pub struct XdgEnvironment {
/// User home used only for XDG fallbacks.
pub home: PathBuf,
/// `$XDG_CONFIG_HOME`; relative values are ignored by the XDG specification.
pub config_home: Option<PathBuf>,
/// `$XDG_STATE_HOME`; relative values are ignored by the XDG specification.
pub state_home: Option<PathBuf>,
/// `$XDG_RUNTIME_DIR`; no shared temporary-directory fallback is invented.
pub runtime_dir: Option<PathBuf>,
}
impl XdgEnvironment {
/// Captures relevant process environment without applying path policy yet.
pub fn from_process() -> Result<Self, ConfigError> {
let home = std::env::var_os("HOME").map(PathBuf::from).ok_or_else(|| {
ConfigError::validation("HOME", "is required when resolving XDG fallbacks")
})?;
Ok(Self {
home,
config_home: std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from),
state_home: std::env::var_os("XDG_STATE_HOME").map(PathBuf::from),
runtime_dir: std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from),
})
}
}
/// Resolved per-user configuration, state, and optional runtime paths.
#[derive(Clone, Debug)]
pub struct XdgPaths {
config_dir: PathBuf,
state_dir: PathBuf,
runtime_dir: Option<PathBuf>,
}
impl XdgPaths {
/// Resolves absolute XDG roots and specification-defined home fallbacks.
pub fn resolve(environment: &XdgEnvironment) -> Result<Self, ConfigError> {
if !environment.home.is_absolute() {
return Err(ConfigError::validation("HOME", "must be an absolute path"));
}
let config_root = absolute_or(&environment.config_home, || {
environment.home.join(".config")
});
let state_root = absolute_or(&environment.state_home, || {
environment.home.join(".local/state")
});
let runtime_dir = environment
.runtime_dir
.as_ref()
.filter(|path| path.is_absolute())
.map(|path| path.join("fader_master"));
Ok(Self {
config_dir: config_root.join("fader_master"),
state_dir: state_root.join("fader_master"),
runtime_dir,
})
}
/// Root containing the global config, profiles, and device documents.
pub fn config_dir(&self) -> &std::path::Path {
&self.config_dir
}
/// Global active-profile configuration document.
pub fn config_file(&self) -> PathBuf {
self.config_dir.join("config.toml")
}
/// Durable state checkpoint document.
pub fn state_file(&self) -> PathBuf {
self.state_dir.join("state.toml")
}
/// Optional private runtime directory; absent when XDG provides none.
pub fn runtime_dir(&self) -> Option<&std::path::Path> {
self.runtime_dir.as_deref()
}
/// Resolves a validated stable profile ID without accepting path syntax.
pub fn profile_file(&self, id: &str) -> Result<PathBuf, ConfigError> {
let id = ProfileId::new(id).map_err(|error| {
ConfigError::validation("profile ID", format!("unsafe profile ID: {error}"))
})?;
Ok(self
.config_dir
.join("profiles")
.join(format!("{}.toml", id.as_str())))
}
/// Creates application-owned directories with mode `0700`.
pub fn create_layout(&self) -> Result<(), PersistenceError> {
for directory in [
self.config_dir.clone(),
self.config_dir.join("profiles"),
self.config_dir.join("devices"),
self.state_dir.clone(),
]
.into_iter()
.chain(self.runtime_dir.iter().cloned())
{
create_private_dir(&directory)?;
}
Ok(())
}
/// Reads state without treating absence or malformed cached data as fatal.
pub fn load_state(&self) -> Result<StateLoad, PersistenceError> {
load_state(&self.state_file())
}
}
fn absolute_or(value: &Option<PathBuf>, fallback: impl FnOnce() -> PathBuf) -> PathBuf {
value
.as_ref()
.filter(|path| path.is_absolute())
.cloned()
.unwrap_or_else(fallback)
}
fn create_private_dir(path: &std::path::Path) -> Result<(), PersistenceError> {
fs::create_dir_all(path)
.map_err(|source| PersistenceError::io("create directory", path, source))?;
super::files::check_owned_not_symlink(path)?;
fs::set_permissions(path, fs::Permissions::from_mode(0o700))
.map_err(|source| PersistenceError::io("set directory permissions", path, source))
}