use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::process::Command;
use crate::daemon;
const CONFIG_DIR_VAR: &str = "CLAUDE_CONFIG_DIR";
const MCP_CONFIG: &str = ".claude.json";
pub(crate) fn config_dir(raw: Option<OsString>) -> Option<PathBuf> {
raw.filter(|dir| !dir.is_empty()).map(PathBuf::from)
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Profile {
pub(crate) dir: PathBuf,
pub(crate) mcp_config: PathBuf,
reach: Reach,
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum Reach {
Current,
Unset,
Set,
}
impl Profile {
pub(crate) fn is_current(&self) -> bool {
self.reach == Reach::Current
}
pub(crate) fn apply(&self, cmd: &mut Command) {
match self.reach {
Reach::Current => {}
Reach::Unset => {
cmd.env_remove(CONFIG_DIR_VAR);
}
Reach::Set => {
cmd.env(CONFIG_DIR_VAR, &self.dir);
}
}
}
pub(crate) fn shell_prefix(&self) -> String {
match self.reach {
Reach::Current => String::new(),
Reach::Unset => format!("env -u {CONFIG_DIR_VAR} "),
Reach::Set => format!(
"{CONFIG_DIR_VAR}={} ",
daemon::shell_word(&self.dir.to_string_lossy())
),
}
}
fn unset(home: &Path) -> Self {
Profile {
dir: home.join(".claude"),
mcp_config: home.join(MCP_CONFIG),
reach: Reach::Unset,
}
}
fn set(dir: PathBuf, reach: Reach) -> Self {
Profile {
mcp_config: dir.join(MCP_CONFIG),
dir,
reach,
}
}
#[cfg(test)]
pub(crate) fn current(home: &Path, config_dir: Option<&Path>) -> Self {
match config_dir {
Some(dir) => Profile::set(dir.to_path_buf(), Reach::Current),
None => Profile {
reach: Reach::Current,
..Profile::unset(home)
},
}
}
#[cfg(test)]
pub(crate) fn default_unset(home: &Path) -> Self {
Profile::unset(home)
}
#[cfg(test)]
pub(crate) fn named(dir: &Path) -> Self {
Profile::set(dir.to_path_buf(), Reach::Set)
}
}
pub(crate) fn profiles(home: &Path, config_dir: Option<&Path>) -> Vec<Profile> {
let mut named: Vec<PathBuf> = std::fs::read_dir(home)
.into_iter()
.flatten()
.flatten()
.filter(|entry| entry.file_name().to_string_lossy().starts_with(".claude-"))
.map(|entry| entry.path())
.filter(|dir| dir.join("projects").is_dir())
.collect();
named.sort();
let current = match config_dir {
Some(dir) => Profile::set(dir.to_path_buf(), Reach::Current),
None => Profile {
reach: Reach::Current,
..Profile::unset(home)
},
};
let mut out = vec![current];
let others = std::iter::once(Profile::unset(home))
.chain(named.into_iter().map(|dir| Profile::set(dir, Reach::Set)));
for profile in others {
if out.iter().all(|p| p.mcp_config != profile.mcp_config) {
out.push(profile);
}
}
out
}
pub(crate) fn locate(
search_path: Option<&OsStr>,
home: &Path,
profiles: &[Profile],
) -> Option<PathBuf> {
let on_path = search_path
.into_iter()
.flat_map(std::env::split_paths)
.filter(|dir| dir.is_absolute())
.map(|dir| dir.join("claude"));
let installed = [
home.join(".local").join("bin").join("claude"),
home.join(".claude").join("local").join("claude"),
];
let in_profiles = profiles.iter().map(|p| p.dir.join("local").join("claude"));
on_path
.chain(installed)
.chain(in_profiles)
.find(|candidate| daemon::program_usable(candidate).is_ok())
}
#[derive(Debug, Clone)]
pub(crate) struct Claude {
pub(crate) program: PathBuf,
pub(crate) profile: Profile,
}
impl Claude {
pub(crate) fn current(
search_path: Option<&OsStr>,
home: &Path,
config_dir: Option<&Path>,
) -> Self {
let mut found = profiles(home, config_dir);
let program = locate(search_path, home, &found).unwrap_or_else(|| PathBuf::from("claude"));
Claude {
program,
profile: found.swap_remove(0),
}
}
pub(crate) fn command(&self) -> Command {
let mut cmd = Command::new(&self.program);
self.profile.apply(&mut cmd);
cmd
}
}
#[cfg(test)]
mod tests {
use std::ffi::OsString;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use super::*;
fn install(path: &Path, mode: u32) {
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, "#!/bin/sh\n").unwrap();
fs::set_permissions(path, fs::Permissions::from_mode(mode)).unwrap();
}
fn env_of(profile: &Profile) -> Option<Option<OsString>> {
let mut cmd = Command::new("claude");
profile.apply(&mut cmd);
cmd.get_envs()
.find(|(key, _)| *key == CONFIG_DIR_VAR)
.map(|(_, value)| value.map(OsStr::to_os_string))
}
#[test]
fn profiles_list_current_then_default_then_named_profiles_with_transcripts() {
let home = tempfile::tempdir().unwrap();
let home = home.path();
fs::create_dir_all(home.join(".claude-b/projects")).unwrap();
fs::create_dir_all(home.join(".claude-a/projects")).unwrap();
fs::create_dir_all(home.join(".claude-tool")).unwrap();
fs::write(home.join(".claude-file"), "").unwrap();
let current = home.join(".claude");
let dirs: Vec<PathBuf> = profiles(home, None).into_iter().map(|p| p.dir).collect();
assert_eq!(
dirs,
[current, home.join(".claude-a"), home.join(".claude-b")]
);
}
#[test]
fn profiles_under_claude_config_dir_reach_the_default_by_unsetting_it() {
let home = tempfile::tempdir().unwrap();
let home = home.path();
fs::create_dir_all(home.join(".claude-a/projects")).unwrap();
let active = home.join(".claude-a");
let found = profiles(home, Some(&active));
let dirs: Vec<&Path> = found.iter().map(|p| p.dir.as_path()).collect();
assert_eq!(dirs, [active.as_path(), &home.join(".claude")]);
assert!(found[0].is_current());
assert_eq!(env_of(&found[0]), None);
assert_eq!(found[0].shell_prefix(), "");
assert_eq!(env_of(&found[1]), Some(None));
assert_eq!(found[1].shell_prefix(), "env -u CLAUDE_CONFIG_DIR ");
}
#[test]
fn named_profiles_are_reached_by_setting_claude_config_dir() {
let home = tempfile::tempdir().unwrap();
let home = home.path();
let work = home.join("my work");
fs::create_dir_all(work.join("projects")).unwrap();
let profile = Profile::named(&work);
assert_eq!(env_of(&profile), Some(Some(work.clone().into_os_string())));
assert_eq!(
profile.shell_prefix(),
format!("CLAUDE_CONFIG_DIR='{}' ", work.display())
);
}
#[test]
fn locate_prefers_path_then_local_bin_then_profile_installs() {
let home = tempfile::tempdir().unwrap();
let home = home.path();
let bin = home.join("path-bin");
let work = home.join(".claude-work");
let profiles = vec![Profile::current(home, None), Profile::named(&work)];
let path = std::env::join_paths([home.join("empty"), bin.clone()]).unwrap();
assert_eq!(locate(Some(&path), home, &profiles), None);
install(&work.join("local/claude"), 0o755);
assert_eq!(
locate(Some(&path), home, &profiles),
Some(work.join("local/claude"))
);
install(&home.join(".claude/local/claude"), 0o755);
assert_eq!(
locate(Some(&path), home, &profiles),
Some(home.join(".claude/local/claude"))
);
install(&home.join(".local/bin/claude"), 0o755);
assert_eq!(
locate(Some(&path), home, &profiles),
Some(home.join(".local/bin/claude"))
);
install(&bin.join("claude"), 0o755);
assert_eq!(
locate(Some(&path), home, &profiles),
Some(bin.join("claude"))
);
}
#[test]
fn locate_skips_files_that_cannot_run_and_relative_path_entries() {
let home = tempfile::tempdir().unwrap();
let home = home.path();
install(&home.join("bin/claude"), 0o644);
fs::create_dir_all(home.join(".local/bin/claude")).unwrap();
let path = std::env::join_paths([home.join("bin"), PathBuf::from(".")]).unwrap();
assert_eq!(locate(Some(&path), home, &[]), None);
assert_eq!(locate(None, home, &[]), None);
}
#[test]
fn current_runs_the_located_claude_against_the_shells_own_profile() {
let home = tempfile::tempdir().unwrap();
let home = home.path();
install(&home.join(".local/bin/claude"), 0o755);
let active = home.join(".claude-a");
let claude = Claude::current(None, home, Some(&active));
assert_eq!(claude.program, home.join(".local/bin/claude"));
assert_eq!(claude.profile.dir, active);
assert!(claude.profile.is_current());
assert_eq!(env_of(&claude.profile), None);
}
#[test]
fn current_without_claude_anywhere_runs_a_bare_claude() {
let home = tempfile::tempdir().unwrap();
let home = home.path();
let claude = Claude::current(None, home, None);
assert_eq!(claude.program, PathBuf::from("claude"));
}
#[test]
fn claude_config_dir_set_to_the_default_dir_is_a_profile_apart_from_the_unset_default() {
let home = tempfile::tempdir().unwrap();
let home = home.path();
let default = home.join(".claude");
let found = profiles(home, Some(&default));
let configs: Vec<&Path> = found.iter().map(|p| p.mcp_config.as_path()).collect();
assert_eq!(
configs,
[
default.join(".claude.json").as_path(),
&home.join(".claude.json")
]
);
assert!(found.iter().all(|p| p.dir == default));
assert_eq!(env_of(&found[0]), None);
assert_eq!(env_of(&found[1]), Some(None));
}
#[test]
fn profiles_without_claude_config_dir_read_the_mcp_config_beside_home() {
let home = tempfile::tempdir().unwrap();
let home = home.path();
fs::create_dir_all(home.join(".claude-a/projects")).unwrap();
let found = profiles(home, None);
let configs: Vec<PathBuf> = found.into_iter().map(|p| p.mcp_config).collect();
assert_eq!(
configs,
[
home.join(".claude.json"),
home.join(".claude-a/.claude.json")
]
);
}
#[test]
fn an_empty_claude_config_dir_is_unset() {
assert_eq!(config_dir(Some(OsString::new())), None);
assert_eq!(config_dir(None), None);
assert_eq!(
config_dir(Some(OsString::from("/srv/claude"))),
Some(PathBuf::from("/srv/claude"))
);
}
}