use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use super::{InstallPathsError, PathSource, TOOLS_DIR_NAME, validate};
use crate::workspace_layout::expand_tilde;
pub const INSTALL_FILE_NAME: &str = "install.toml";
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InstallFile {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub projects_root: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub config_dir: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub claude_config_dir: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub codex_home: Option<PathBuf>,
}
pub fn install_file_path(home: &Path) -> PathBuf {
home.join(TOOLS_DIR_NAME).join(INSTALL_FILE_NAME)
}
pub fn read_install_file(home: &Path) -> Result<Option<InstallFile>, InstallPathsError> {
let path = install_file_path(home);
let raw = match std::fs::read_to_string(&path) {
Ok(raw) => raw,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(source) => return Err(InstallPathsError::Read { path, source }),
};
toml::from_str(&raw).map(Some).map_err(|e| {
let at = e.span().and_then(|s| raw.get(..s.start)).map(|b| {
let col = b.len() - b.rfind('\n').map_or(0, |i| i + 1) + 1;
format!(" (line {}, column {col})", b.matches('\n').count() + 1)
});
InstallPathsError::Parse {
path,
message: format!("{}{}", e.message(), at.unwrap_or_default()),
}
})
}
pub fn write_install_file(
home: &Path,
values: &InstallFile,
) -> Result<(PathBuf, InstallFile), InstallPathsError> {
let stored = InstallFile {
projects_root: normalise("projects_root", values.projects_root.as_ref(), home)?,
config_dir: normalise("config_dir", values.config_dir.as_ref(), home)?,
claude_config_dir: normalise("claude_config_dir", values.claude_config_dir.as_ref(), home)?,
codex_home: normalise("codex_home", values.codex_home.as_ref(), home)?,
};
let body = toml::to_string(&stored).map_err(|e| InstallPathsError::Serialize {
message: e.to_string(),
})?;
let path = install_file_path(home);
let write_err = |source| InstallPathsError::Write {
path: path.clone(),
source,
};
let dir = path.parent().unwrap_or(home);
std::fs::create_dir_all(dir).map_err(write_err)?;
let tmp = dir.join(format!(".{INSTALL_FILE_NAME}.{}.tmp", std::process::id()));
std::fs::write(&tmp, body).map_err(write_err)?;
if let Err(source) = std::fs::rename(&tmp, &path) {
let _ = std::fs::remove_file(&tmp);
return Err(write_err(source));
}
Ok((path, stored))
}
fn normalise(
key: &'static str,
value: Option<&PathBuf>,
home: &Path,
) -> Result<Option<PathBuf>, InstallPathsError> {
let Some(raw) = value else {
return Ok(None);
};
let expanded = match raw.to_str() {
Some(s) => expand_tilde(s.trim(), home),
None => raw.clone(),
};
validate(key, PathSource::InstallFile, &expanded)?;
Ok(Some(expanded))
}