use std::path::{Path, PathBuf};
const APP_DIR: &str = "tinyharness";
const LEGACY_DOT_DIR: &str = ".tinyharness";
const FALLBACK_CONFIG_ROOT: &str = ".config";
const FALLBACK_DATA_ROOT: &str = ".local/share";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Paths {
home: Option<PathBuf>,
config_dir: PathBuf,
data_dir: PathBuf,
project_dir: PathBuf,
}
impl Default for Paths {
fn default() -> Self {
Self::from_env(|key| std::env::var(key).ok())
}
}
impl Paths {
pub fn from_env<F>(env: F) -> Self
where
F: Fn(&str) -> Option<String>,
{
let home = env("HOME")
.or_else(|| env("USERPROFILE"))
.map(PathBuf::from)
.filter(|p| p.is_absolute());
let config_dir = xdg_dir(&env, "XDG_CONFIG_HOME")
.map(|root| root.join(APP_DIR))
.unwrap_or_else(|| {
home.as_ref()
.map(|h| h.join(FALLBACK_CONFIG_ROOT))
.unwrap_or_else(|| PathBuf::from(FALLBACK_CONFIG_ROOT))
.join(APP_DIR)
});
let data_dir = xdg_dir(&env, "XDG_DATA_HOME")
.map(|root| root.join(APP_DIR))
.unwrap_or_else(|| {
home.as_ref()
.map(|h| h.join(FALLBACK_DATA_ROOT))
.unwrap_or_else(|| PathBuf::from(FALLBACK_DATA_ROOT))
.join(APP_DIR)
});
let project_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
Paths {
home,
config_dir,
data_dir,
project_dir,
}
}
pub fn with_home(home: impl Into<PathBuf>) -> Self {
let home = home.into();
Paths {
config_dir: home.join(FALLBACK_CONFIG_ROOT).join(APP_DIR),
data_dir: home.join(FALLBACK_DATA_ROOT).join(APP_DIR),
project_dir: home.clone(),
home: Some(home),
}
}
pub fn new(config_dir: PathBuf, data_dir: PathBuf, project_dir: PathBuf) -> Self {
Paths {
home: None,
config_dir,
data_dir,
project_dir,
}
}
pub fn with_config_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.config_dir = dir.into();
self
}
pub fn with_data_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.data_dir = dir.into();
self
}
pub fn with_project_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.project_dir = dir.into();
self
}
pub fn with_legacy_home(mut self, home: impl Into<PathBuf>) -> Self {
self.home = Some(home.into());
self
}
pub fn config_dir(&self) -> &Path {
&self.config_dir
}
pub fn data_dir(&self) -> &Path {
&self.data_dir
}
pub fn project_dir(&self) -> &Path {
&self.project_dir
}
pub fn home(&self) -> Option<&Path> {
self.home.as_deref()
}
pub fn settings_file(&self) -> PathBuf {
self.config_dir.join("settings.json")
}
pub fn prompts_dir(&self) -> PathBuf {
self.config_dir.join("prompts")
}
pub fn custom_tools_file(&self) -> PathBuf {
self.config_dir.join("custom_tools.json")
}
pub fn sessions_dir(&self) -> PathBuf {
self.data_dir.join("sessions")
}
pub fn history_dir(&self) -> PathBuf {
self.data_dir.clone()
}
pub fn audit_log_file(&self) -> PathBuf {
self.data_dir.join("audit.jsonl")
}
pub fn backups_dir(&self) -> PathBuf {
self.data_dir.join("backups")
}
pub fn personal_skills_dirs(&self) -> Vec<PathBuf> {
let mut dirs = vec![self.config_dir.join("skills")];
if let Some(home) = self.home.as_deref() {
let legacy = home.join(LEGACY_DOT_DIR).join("skills");
if !dirs.contains(&legacy) {
dirs.push(legacy);
}
}
dirs
}
pub fn project_config_root(&self) -> PathBuf {
self.project_dir.join(LEGACY_DOT_DIR)
}
pub fn project_settings_file(&self) -> PathBuf {
self.project_config_root().join("config.json")
}
pub fn project_custom_tools_file(&self) -> PathBuf {
self.project_config_root().join("custom_tools.json")
}
pub fn project_skills_dir(&self) -> PathBuf {
self.project_config_root().join("skills")
}
}
fn xdg_dir<F>(env: &F, key: &str) -> Option<PathBuf>
where
F: Fn(&str) -> Option<String>,
{
env(key)
.map(|value| (value.trim().to_string(), PathBuf::from(&value)))
.filter(|(raw, path)| !raw.is_empty() && path.is_absolute())
.map(|(_, path)| path)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
fn env_map(entries: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
let map: HashMap<String, String> = entries
.iter()
.map(|(k, v)| ((*k).to_string(), (*v).to_string()))
.collect();
move |key: &str| map.get(key).cloned()
}
fn abs(path: &str) -> PathBuf {
PathBuf::from(path)
}
fn host_root(tag: &str) -> PathBuf {
std::env::current_dir()
.expect("CWD is absolute on every supported platform")
.join(format!("th-{tag}"))
}
fn env_value(root: &Path) -> &str {
root.to_str().expect("fixtures are valid UTF-8")
}
#[test]
fn home_fallback_when_no_xdg() {
let home = host_root("home");
let paths = Paths::from_env(env_map(&[("HOME", env_value(&home))]));
assert_eq!(paths.config_dir(), home.join(".config/tinyharness"));
assert_eq!(paths.data_dir(), home.join(".local/share/tinyharness"));
assert_eq!(paths.home(), Some(home.as_path()));
}
#[test]
fn xdg_roots_take_precedence_over_home() {
let home = host_root("home");
let config = host_root("xdg-config");
let data = host_root("xdg-data");
let paths = Paths::from_env(env_map(&[
("HOME", env_value(&home)),
("XDG_CONFIG_HOME", env_value(&config)),
("XDG_DATA_HOME", env_value(&data)),
]));
assert_eq!(paths.config_dir(), config.join("tinyharness"));
assert_eq!(paths.data_dir(), data.join("tinyharness"));
}
#[test]
fn empty_or_relative_xdg_is_ignored() {
let home = host_root("home");
let empty = Paths::from_env(env_map(&[
("HOME", env_value(&home)),
("XDG_CONFIG_HOME", " "),
("XDG_DATA_HOME", "relative/data"),
]));
assert_eq!(empty.config_dir(), home.join(".config/tinyharness"));
assert_eq!(empty.data_dir(), home.join(".local/share/tinyharness"));
}
#[test]
fn missing_home_uses_dot_prefixed_fallbacks() {
let paths = Paths::from_env(env_map(&[]));
assert_eq!(paths.config_dir(), abs(".config/tinyharness"));
assert_eq!(paths.data_dir(), abs(".local/share/tinyharness"));
assert_eq!(paths.home(), None);
assert_eq!(
paths.settings_file(),
abs(".config/tinyharness/settings.json")
);
}
#[test]
fn userprofile_is_home_fallback() {
let home = host_root("userprofile-home");
let paths = Paths::from_env(env_map(&[("USERPROFILE", env_value(&home))]));
assert_eq!(paths.config_dir(), home.join(".config/tinyharness"));
assert_eq!(paths.home(), Some(home.as_path()));
}
#[test]
fn home_takes_precedence_over_userprofile() {
let home = host_root("home");
let windows_home = host_root("userprofile");
let paths = Paths::from_env(env_map(&[
("HOME", env_value(&home)),
("USERPROFILE", env_value(&windows_home)),
]));
assert_eq!(paths.config_dir(), home.join(".config/tinyharness"));
assert_eq!(paths.home(), Some(home.as_path()));
}
#[test]
fn relative_home_is_rejected() {
let paths = Paths::from_env(env_map(&[("HOME", "relative/home")]));
assert_eq!(paths.home(), None);
assert_eq!(paths.config_dir(), abs(".config/tinyharness"));
}
#[test]
fn relative_home_does_not_fall_through_to_userprofile() {
let windows_home = host_root("userprofile");
let paths = Paths::from_env(env_map(&[
("HOME", "relative/home"),
("USERPROFILE", env_value(&windows_home)),
]));
assert_eq!(paths.home(), None);
assert_eq!(paths.config_dir(), abs(".config/tinyharness"));
assert_eq!(paths.data_dir(), abs(".local/share/tinyharness"));
}
#[test]
fn with_home_derives_every_location() {
let paths = Paths::with_home("/tmp/profile");
assert_eq!(
paths.settings_file(),
abs("/tmp/profile/.config/tinyharness/settings.json")
);
assert_eq!(
paths.prompts_dir(),
abs("/tmp/profile/.config/tinyharness/prompts")
);
assert_eq!(
paths.custom_tools_file(),
abs("/tmp/profile/.config/tinyharness/custom_tools.json")
);
assert_eq!(
paths.sessions_dir(),
abs("/tmp/profile/.local/share/tinyharness/sessions")
);
assert_eq!(
paths.history_dir(),
abs("/tmp/profile/.local/share/tinyharness")
);
assert_eq!(
paths.project_config_root(),
abs("/tmp/profile/.tinyharness")
);
}
#[test]
fn personal_skills_dirs_prefer_xdg_then_legacy() {
let paths = Paths::with_home("/tmp/profile");
assert_eq!(
paths.personal_skills_dirs(),
vec![
abs("/tmp/profile/.config/tinyharness/skills"),
abs("/tmp/profile/.tinyharness/skills"),
]
);
}
#[test]
fn personal_skills_dirs_dedupes_when_legacy_matches_config() {
let paths = Paths::with_home("/tmp/profile").with_config_dir("/tmp/profile/.tinyharness");
assert_eq!(
paths.personal_skills_dirs(),
vec![abs("/tmp/profile/.tinyharness/skills")]
);
}
#[test]
fn personal_skills_dirs_omit_legacy_without_home() {
let paths = Paths::new(abs("/cfg"), abs("/data"), abs("/proj"));
assert_eq!(paths.personal_skills_dirs(), vec![abs("/cfg/skills")]);
assert_eq!(paths.home(), None);
}
#[test]
fn with_legacy_home_restores_legacy_scan_only() {
let paths = Paths::new(abs("/cfg"), abs("/data"), abs("/proj")).with_legacy_home("/home/u");
assert_eq!(paths.config_dir(), abs("/cfg"));
assert_eq!(
paths.personal_skills_dirs(),
vec![abs("/cfg/skills"), abs("/home/u/.tinyharness/skills")]
);
}
#[test]
fn builders_override_individual_roots() {
let paths = Paths::with_home("/tmp/profile")
.with_config_dir("/custom/cfg")
.with_data_dir("/custom/data")
.with_project_dir("/custom/proj");
assert_eq!(paths.settings_file(), abs("/custom/cfg/settings.json"));
assert_eq!(paths.sessions_dir(), abs("/custom/data/sessions"));
assert_eq!(
paths.project_settings_file(),
abs("/custom/proj/.tinyharness/config.json")
);
assert_eq!(
paths.project_custom_tools_file(),
abs("/custom/proj/.tinyharness/custom_tools.json")
);
assert_eq!(
paths.project_skills_dir(),
abs("/custom/proj/.tinyharness/skills")
);
}
#[test]
fn overrides_re_derive_dependent_paths() {
let base = Paths::with_home("/tmp/profile");
let moved = base.clone().with_data_dir("/elsewhere/data");
assert_ne!(base.sessions_dir(), moved.sessions_dir());
assert_eq!(moved.sessions_dir(), abs("/elsewhere/data/sessions"));
}
#[test]
fn default_reads_process_env() {
let paths = Paths::default();
assert!(paths.settings_file().ends_with("settings.json"));
assert!(paths.sessions_dir().ends_with("sessions"));
assert_eq!(
paths.project_settings_file(),
paths.project_dir().join(".tinyharness/config.json")
);
assert!(!paths.personal_skills_dirs().is_empty());
}
}