use std::{
env,
error::Error,
ffi::OsString,
fmt, io,
path::{Path, PathBuf},
};
pub trait EnvSource {
fn var_os(&self, key: &str) -> Option<OsString>;
fn path_exists(&self, path: &Path) -> bool {
path.exists()
}
fn temp_dir(&self) -> PathBuf {
env::temp_dir()
}
fn current_dir(&self) -> io::Result<PathBuf> {
env::current_dir()
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct SystemEnv;
impl EnvSource for SystemEnv {
fn var_os(&self, key: &str) -> Option<OsString> {
env::var_os(key)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum PathsError {
Unresolved {
directory: &'static str,
variables: &'static [&'static str],
},
RelativePath {
source: String,
path: PathBuf,
},
CurrentDir(io::Error),
InvalidUserToken,
}
impl fmt::Display for PathsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unresolved {
directory,
variables,
} => write!(
f,
"could not resolve an absolute {directory}; tried {}",
variables.join(", ")
),
Self::RelativePath { source, path } => {
write!(f, "{source} must be absolute, got {}", path.display())
}
Self::CurrentDir(error) => write!(f, "could not resolve current directory: {error}"),
Self::InvalidUserToken => f.write_str(
"connection-file user token must be non-empty and contain no path separators",
),
}
}
}
impl Error for PathsError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::CurrentDir(error) => Some(error),
_ => None,
}
}
}
#[derive(Clone, Copy)]
enum Platform {
Unix,
Windows,
}
pub struct Dirs<'a, E: EnvSource + ?Sized> {
env: &'a E,
platform: Platform,
}
pub fn with_env<E: EnvSource + ?Sized>(env: &E) -> Dirs<'_, E> {
Dirs {
env,
platform: if cfg!(windows) {
Platform::Windows
} else {
Platform::Unix
},
}
}
impl<E: EnvSource + ?Sized> Dirs<'_, E> {
fn non_empty(&self, key: &str) -> Option<OsString> {
self.env.var_os(key).filter(|value| !value.is_empty())
}
fn absolute_var(&self, key: &str) -> Option<PathBuf> {
self.non_empty(key)
.map(PathBuf::from)
.filter(|path| path.is_absolute())
}
pub fn home(&self) -> Result<PathBuf, PathsError> {
match self.platform {
Platform::Unix => self.absolute_var("HOME").ok_or(PathsError::Unresolved {
directory: "home directory",
variables: &["HOME"],
}),
Platform::Windows => {
if let Some(path) = self.absolute_var("USERPROFILE") {
return Ok(path);
}
if let (Some(drive), Some(path)) =
(self.non_empty("HOMEDRIVE"), self.non_empty("HOMEPATH"))
{
let mut home = PathBuf::from(drive);
home.push(path);
if home.is_absolute() {
return Ok(home);
}
}
self.absolute_var("HOME").ok_or(PathsError::Unresolved {
directory: "home directory",
variables: &["USERPROFILE", "HOMEDRIVE", "HOMEPATH", "HOME"],
})
}
}
}
fn base(
&self,
xdg: &'static str,
windows: &'static str,
unix_tail: &[&str],
windows_tail: &str,
) -> Result<PathBuf, PathsError> {
if let Some(path) = self.absolute_var(xdg) {
return Ok(path);
}
match self.platform {
Platform::Unix => {
let mut path = self.home().map_err(|_| PathsError::Unresolved {
directory: xdg,
variables: match xdg {
"XDG_DATA_HOME" => &["XDG_DATA_HOME", "HOME"],
"XDG_CONFIG_HOME" => &["XDG_CONFIG_HOME", "HOME"],
"XDG_STATE_HOME" => &["XDG_STATE_HOME", "HOME"],
_ => &["XDG_CACHE_HOME", "HOME"],
},
})?;
for component in unix_tail {
path.push(component);
}
Ok(path)
}
Platform::Windows => {
self.windows_base(windows, windows_tail)
.ok_or(PathsError::Unresolved {
directory: xdg,
variables: match xdg {
"XDG_DATA_HOME" => &["XDG_DATA_HOME", "LOCALAPPDATA", "USERPROFILE"],
"XDG_CONFIG_HOME" => &["XDG_CONFIG_HOME", "APPDATA", "USERPROFILE"],
"XDG_STATE_HOME" => &["XDG_STATE_HOME", "LOCALAPPDATA", "USERPROFILE"],
_ => &["XDG_CACHE_HOME", "LOCALAPPDATA", "USERPROFILE"],
},
})
}
}
}
fn windows_base(&self, variable: &str, tail: &str) -> Option<PathBuf> {
self.absolute_var(variable).or_else(|| {
self.absolute_var("USERPROFILE")
.map(|path| path.join("AppData").join(tail))
})
}
pub fn data_home(&self) -> Result<PathBuf, PathsError> {
self.base(
"XDG_DATA_HOME",
"LOCALAPPDATA",
&[".local", "share"],
"Local",
)
}
pub fn xdg_data_home(&self) -> Result<PathBuf, PathsError> {
if let Some(path) = self.absolute_var("XDG_DATA_HOME") {
return Ok(path);
}
let home = self.home().map_err(|_| PathsError::Unresolved {
directory: "XDG data home",
variables: match self.platform {
Platform::Unix => &["XDG_DATA_HOME", "HOME"],
Platform::Windows => &[
"XDG_DATA_HOME",
"USERPROFILE",
"HOMEDRIVE",
"HOMEPATH",
"HOME",
],
},
})?;
Ok(home.join(".local").join("share"))
}
pub fn config_home(&self) -> Result<PathBuf, PathsError> {
self.base("XDG_CONFIG_HOME", "APPDATA", &[".config"], "Roaming")
}
pub fn state_home(&self) -> Result<PathBuf, PathsError> {
self.base(
"XDG_STATE_HOME",
"LOCALAPPDATA",
&[".local", "state"],
"Local",
)
}
pub fn cache_home(&self) -> Result<PathBuf, PathsError> {
self.base("XDG_CACHE_HOME", "LOCALAPPDATA", &[".cache"], "Local")
}
pub fn cortexkit_data_dir(&self) -> Result<PathBuf, PathsError> {
let local = self.data_home().map(|home| home.join("cortexkit"));
if matches!(self.platform, Platform::Windows)
&& self.absolute_var("XDG_DATA_HOME").is_none()
{
if let Some(roaming) = self.windows_base("APPDATA", "Roaming") {
let legacy = roaming.join("cortexkit");
if self.env.path_exists(&legacy)
&& !local.as_ref().is_ok_and(|path| self.env.path_exists(path))
{
return Ok(legacy);
}
}
}
local
}
pub fn cortexkit_config_dir(&self) -> Result<PathBuf, PathsError> {
Ok(self.config_home()?.join("cortexkit"))
}
pub fn cortexkit_run_dir(&self) -> Result<PathBuf, PathsError> {
Ok(self.cortexkit_data_dir()?.join("run"))
}
pub fn cortexkit_state_dir(&self) -> Result<PathBuf, PathsError> {
Ok(self.state_home()?.join("cortexkit"))
}
pub fn cortexkit_cache_dir(&self) -> Result<PathBuf, PathsError> {
Ok(self.cache_home()?.join("cortexkit"))
}
pub fn connection_file_candidates(
&self,
explicit: Option<&Path>,
per_user_token: &str,
) -> Result<Vec<PathBuf>, PathsError> {
if let Some(path) = explicit {
if path.is_absolute() {
return Ok(vec![path.to_path_buf()]);
}
let cwd = self.env.current_dir().map_err(PathsError::CurrentDir)?;
return Ok(vec![require_absolute(
require_absolute(cwd, "current directory")?.join(path),
"explicit connection file",
)?]);
}
if let Some(path) = self.non_empty("SUBC_CONNECTION_FILE") {
return Ok(vec![require_absolute(
PathBuf::from(path),
"SUBC_CONNECTION_FILE",
)?]);
}
if per_user_token.is_empty() || per_user_token.contains(['/', '\\']) {
return Err(PathsError::InvalidUserToken);
}
let mut candidates = Vec::new();
if let Some(path) = self.absolute_var("XDG_RUNTIME_DIR") {
candidates.push(path.join("subc-connection.json"));
}
if let Some(path) = self.absolute_var("HOME") {
candidates.push(
path.join(".local")
.join("share")
.join("cortexkit")
.join("run")
.join("subc-connection.json"),
);
}
candidates.push(
require_absolute(self.env.temp_dir(), "temporary directory")?
.join(format!("subc-{per_user_token}.connection.json")),
);
Ok(candidates)
}
}
fn require_absolute(path: PathBuf, source: &str) -> Result<PathBuf, PathsError> {
if path.is_absolute() {
Ok(path)
} else {
Err(PathsError::RelativePath {
source: source.to_owned(),
path,
})
}
}
pub fn env_absolute_path<E: EnvSource + ?Sized>(
env: &E,
variable: &str,
) -> Result<Option<PathBuf>, PathsError> {
env.var_os(variable)
.filter(|value| !value.is_empty())
.map(|value| require_absolute(PathBuf::from(value), variable))
.transpose()
}
macro_rules! process_dirs {
($($name:ident),+ $(,)?) => {$(
#[doc = concat!("Resolve using the process environment; see [`Dirs::", stringify!($name), "`].")]
pub fn $name() -> Result<PathBuf, PathsError> { with_env(&SystemEnv).$name() }
)+};
}
process_dirs!(
home,
data_home,
xdg_data_home,
config_home,
state_home,
cache_home,
cortexkit_data_dir,
cortexkit_config_dir,
cortexkit_run_dir,
cortexkit_state_dir,
cortexkit_cache_dir
);
pub fn connection_file_candidates(
explicit: Option<&Path>,
per_user_token: &str,
) -> Result<Vec<PathBuf>, PathsError> {
with_env(&SystemEnv).connection_file_candidates(explicit, per_user_token)
}
#[cfg(test)]
mod tests;