mod file;
mod process;
use std::path::{Path, PathBuf};
pub use file::{InstallFile, install_file_path, read_install_file, write_install_file};
#[cfg(feature = "crate-config")]
pub(crate) use process::{config_dir_checked, config_dir_for_legacy_wrapper};
pub(crate) use process::{projects_root_checked, projects_root_for_legacy_wrapper};
pub use process::{try_config_dir, try_config_dir_under};
use crate::workspace_layout::{DEFAULT_WORKSPACE_DIR, WORKSPACE_ROOT_ENV, expand_tilde};
pub const TOOLS_DIR_NAME: &str = ".trusty-tools";
pub const MPM_DIR_NAME: &str = ".trusty-mpm";
pub const CONFIG_DIR_ENV: &str = "TRUSTY_MPM_CONFIG_DIR";
pub const CLAUDE_CONFIG_DIR_ENV: &str = "CLAUDE_CONFIG_DIR";
pub const CODEX_HOME_ENV: &str = "CODEX_HOME";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathSource {
Flag,
Env,
InstallFile,
Template,
Default,
}
impl std::fmt::Display for PathSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Flag => "flag",
Self::Env => "env",
Self::InstallFile => "install-file",
Self::Template => "config-template",
Self::Default => "default",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedPath {
pub path: PathBuf,
pub source: PathSource,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PathOverrides {
pub projects_root: Option<PathBuf>,
pub config_dir: Option<PathBuf>,
pub claude_config_dir: Option<PathBuf>,
pub codex_home: Option<PathBuf>,
pub projects_root_template: Option<String>,
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum InstallPathsError {
#[error("the home directory could not be determined")]
NoHome,
#[error("{key} from {origin} is empty; give an absolute path")]
Empty {
key: &'static str,
origin: PathSource,
},
#[error("{key} from {origin} must be an absolute path, got {value:?}")]
Relative {
key: &'static str,
origin: PathSource,
value: PathBuf,
},
#[error("cannot read {path:?}: {source}")]
Read {
path: PathBuf,
source: std::io::Error,
},
#[error("cannot parse {path:?}: {message}")]
Parse {
path: PathBuf,
message: String,
},
#[error("cannot write {path:?}: {source}")]
Write {
path: PathBuf,
source: std::io::Error,
},
#[error("cannot serialise the install file: {message}")]
Serialize {
message: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstallPaths {
pub projects_root: ResolvedPath,
pub config_dir: ResolvedPath,
pub claude_config_dir: Option<ResolvedPath>,
pub codex_home: Option<ResolvedPath>,
}
#[derive(Clone, Copy)]
enum Key {
ProjectsRoot,
ConfigDir,
ClaudeConfigDir,
CodexHome,
}
impl Key {
fn name(self) -> &'static str {
match self {
Self::ProjectsRoot => "projects_root",
Self::ConfigDir => "config_dir",
Self::ClaudeConfigDir => "claude_config_dir",
Self::CodexHome => "codex_home",
}
}
fn env_var(self) -> &'static str {
match self {
Self::ProjectsRoot => WORKSPACE_ROOT_ENV,
Self::ConfigDir => CONFIG_DIR_ENV,
Self::ClaudeConfigDir => CLAUDE_CONFIG_DIR_ENV,
Self::CodexHome => CODEX_HOME_ENV,
}
}
fn pick(self, o: &PathOverrides) -> Option<&PathBuf> {
match self {
Self::ProjectsRoot => o.projects_root.as_ref(),
Self::ConfigDir => o.config_dir.as_ref(),
Self::ClaudeConfigDir => o.claude_config_dir.as_ref(),
Self::CodexHome => o.codex_home.as_ref(),
}
}
fn pick_template(self, o: &PathOverrides) -> Option<&str> {
match self {
Self::ProjectsRoot => o
.projects_root_template
.as_deref()
.map(str::trim)
.filter(|t| !t.is_empty()),
Self::ConfigDir | Self::ClaudeConfigDir | Self::CodexHome => None,
}
}
fn pick_file(self, f: &InstallFile) -> Option<&PathBuf> {
match self {
Self::ProjectsRoot => f.projects_root.as_ref(),
Self::ConfigDir => f.config_dir.as_ref(),
Self::ClaudeConfigDir => f.claude_config_dir.as_ref(),
Self::CodexHome => f.codex_home.as_ref(),
}
}
fn default_for(self, home: &Path) -> Option<PathBuf> {
match self {
Self::ProjectsRoot => Some(home.join(DEFAULT_WORKSPACE_DIR)),
Self::ConfigDir => Some(home.to_path_buf()),
Self::ClaudeConfigDir | Self::CodexHome => None,
}
}
}
impl InstallPaths {
pub fn resolve() -> Result<Self, InstallPathsError> {
Self::resolve_overridden(&PathOverrides::default())
}
pub fn resolve_overridden(overrides: &PathOverrides) -> Result<Self, InstallPathsError> {
let home = dirs::home_dir().ok_or(InstallPathsError::NoHome)?;
Self::resolve_with(|name| std::env::var(name).ok(), &home, overrides)
}
pub fn resolve_with(
env: impl Fn(&str) -> Option<String>,
home: &Path,
overrides: &PathOverrides,
) -> Result<Self, InstallPathsError> {
let mut file: Option<Option<InstallFile>> = None;
let mut one = |key: Key| -> Result<Option<ResolvedPath>, InstallPathsError> {
if let Some(hit) = resolve_early(key, &env, home, overrides)? {
return Ok(Some(hit));
}
if file.is_none() {
file = Some(read_install_file(home)?);
}
resolve_late(key, file.as_ref().and_then(Option::as_ref), overrides, home)
};
let projects_root = required(Key::ProjectsRoot, one(Key::ProjectsRoot)?)?;
let config_dir = required(Key::ConfigDir, one(Key::ConfigDir)?)?;
Ok(Self {
projects_root,
config_dir,
claude_config_dir: one(Key::ClaudeConfigDir)?,
codex_home: one(Key::CodexHome)?,
})
}
pub fn tools_dir(&self) -> PathBuf {
self.config_dir.path.join(TOOLS_DIR_NAME)
}
pub fn mpm_dir(&self) -> PathBuf {
self.config_dir.path.join(MPM_DIR_NAME)
}
}
fn required(key: Key, hit: Option<ResolvedPath>) -> Result<ResolvedPath, InstallPathsError> {
hit.ok_or(InstallPathsError::Empty {
key: key.name(),
origin: PathSource::Default,
})
}
fn resolve_early(
key: Key,
env: &impl Fn(&str) -> Option<String>,
home: &Path,
overrides: &PathOverrides,
) -> Result<Option<ResolvedPath>, InstallPathsError> {
if let Some(raw) = key.pick(overrides) {
let expanded = expand_raw(raw, home);
return absolute(key, PathSource::Flag, expanded).map(Some);
}
if let Some(raw) = env(key.env_var()).filter(|v| !v.trim().is_empty()) {
let expanded = expand_tilde(raw.trim(), home);
return absolute(key, PathSource::Env, expanded).map(Some);
}
Ok(None)
}
fn resolve_late(
key: Key,
file: Option<&InstallFile>,
overrides: &PathOverrides,
home: &Path,
) -> Result<Option<ResolvedPath>, InstallPathsError> {
if let Some(path) = file.and_then(|f| key.pick_file(f)) {
return absolute(key, PathSource::InstallFile, path.clone()).map(Some);
}
if let Some(raw) = key.pick_template(overrides) {
return absolute(key, PathSource::Template, expand_tilde(raw, home)).map(Some);
}
Ok(key.default_for(home).map(|path| ResolvedPath {
path,
source: PathSource::Default,
}))
}
fn expand_raw(raw: &Path, home: &Path) -> PathBuf {
match raw.to_str() {
Some(s) => expand_tilde(s.trim(), home),
None => raw.to_path_buf(),
}
}
fn absolute(
key: Key,
origin: PathSource,
path: PathBuf,
) -> Result<ResolvedPath, InstallPathsError> {
validate(key.name(), origin, &path)?;
Ok(ResolvedPath {
path,
source: origin,
})
}
fn validate(key: &'static str, origin: PathSource, path: &Path) -> Result<(), InstallPathsError> {
if path.as_os_str().is_empty() {
return Err(InstallPathsError::Empty { key, origin });
}
if !path.is_absolute() {
return Err(InstallPathsError::Relative {
key,
origin,
value: path.to_path_buf(),
});
}
Ok(())
}
#[cfg(test)]
mod tests;