use std::path::{Path, PathBuf};
use super::write_dir::NativeWriteDir;
use super::{CLAUDE_COMPAT_DIRNAME, SETTINGS_FILENAME, check_native_write_target, native_child};
pub const IMPORTED_SUBTREES: &[&str] = &["agents", "skills"];
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ImportAction {
Copy,
Refuse(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportEntry {
pub from: PathBuf,
pub to: PathBuf,
pub action: ImportAction,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ImportPlan {
pub entries: Vec<ImportEntry>,
}
impl ImportPlan {
pub fn to_copy(&self) -> impl Iterator<Item = &ImportEntry> {
self.entries
.iter()
.filter(|e| e.action == ImportAction::Copy)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ImportReport {
pub created: Vec<PathBuf>,
pub refused: Vec<(PathBuf, String)>,
}
pub fn plan_import(project_root: &Path) -> ImportPlan {
let claude_root = project_root.join(CLAUDE_COMPAT_DIRNAME);
let mut entries = Vec::new();
for subtree in IMPORTED_SUBTREES {
let dir = claude_root.join(subtree);
let mut files = Vec::new();
collect_files(&dir, &dir, subtree, &mut files);
for (relative, from) in files {
entries.push(classify(project_root, &claude_root, &relative, &from));
}
}
let settings = claude_root.join(SETTINGS_FILENAME);
if settings.is_file() {
entries.push(classify(
project_root,
&claude_root,
SETTINGS_FILENAME,
&settings,
));
}
entries.sort_by(|a, b| a.to.cmp(&b.to));
ImportPlan { entries }
}
fn collect_files(base: &Path, dir: &Path, prefix: &str, out: &mut Vec<(String, PathBuf)>) {
if !dir.is_dir() {
return;
}
let entries = match std::fs::read_dir(dir) {
Ok(entries) => entries,
Err(e) => {
tracing::warn!(
path = %dir.display(),
error = %e,
"could not read a .claude subtree while planning the trusty-code \
import; skipping it and continuing with the rest"
);
return;
}
};
for entry in entries.flatten() {
let path = entry.path();
let Ok(meta) = std::fs::symlink_metadata(&path) else {
continue;
};
if meta.is_dir() {
collect_files(base, &path, prefix, out);
} else if let Ok(rel) = path.strip_prefix(base) {
out.push((format!("{prefix}/{}", rel.display()), path.clone()));
}
}
}
fn classify(project_root: &Path, claude_root: &Path, relative: &str, from: &Path) -> ImportEntry {
let to = native_child(project_root, relative);
let refuse = |reason: String| ImportEntry {
from: from.to_path_buf(),
to: to.clone(),
action: ImportAction::Refuse(reason),
};
if let Err(e) = check_native_write_target(project_root, &to) {
return refuse(e.to_string());
}
if !source_stays_inside(claude_root, from) {
return refuse(format!(
"source resolves outside {} — refusing to import through a symlink",
claude_root.display()
));
}
if to.exists() {
return refuse(format!(
"{} already exists — an import never overwrites a user-authored file",
to.display()
));
}
if is_executable(from) {
return refuse(
"source carries the executable bit — refusing to import an executable \
into trusty-code's own configuration tree"
.to_string(),
);
}
if relative == SETTINGS_FILENAME
&& let Some(key) = settings_secret_key(from)
{
return refuse(format!(
"settings carry a secret-bearing key `{key}` — remove it, or set it \
in the environment, before importing"
));
}
ImportEntry {
from: from.to_path_buf(),
to,
action: ImportAction::Copy,
}
}
fn source_stays_inside(claude_root: &Path, from: &Path) -> bool {
match (claude_root.canonicalize(), from.canonicalize()) {
(Ok(root), Ok(file)) => file.starts_with(&root),
_ => false,
}
}
#[cfg(unix)]
fn is_executable(path: &Path) -> bool {
use std::os::unix::fs::PermissionsExt;
std::fs::metadata(path)
.map(|m| m.permissions().mode() & 0o111 != 0)
.unwrap_or(false)
}
#[cfg(not(unix))]
fn is_executable(_path: &Path) -> bool {
false
}
fn settings_secret_key(path: &Path) -> Option<String> {
let raw = match std::fs::read_to_string(path) {
Ok(raw) => raw,
Err(e) => {
tracing::warn!(
path = %path.display(),
error = %e,
"could not read .claude/settings.json while planning the import; \
refusing to import it rather than assuming it holds no secrets"
);
return Some("<unreadable>".to_string());
}
};
match serde_json::from_str::<serde_json::Value>(&raw) {
Ok(value) => super::find_secret_key(&value),
Err(e) => {
tracing::warn!(
path = %path.display(),
error = %e,
"could not parse .claude/settings.json while planning the import; \
refusing to import it rather than assuming it holds no secrets"
);
Some("<unparseable>".to_string())
}
}
}
pub fn apply_import(project_root: &Path, plan: &ImportPlan) -> ImportReport {
let mut report = ImportReport::default();
for entry in &plan.entries {
match &entry.action {
ImportAction::Refuse(reason) => {
report.refused.push((entry.from.clone(), reason.clone()));
}
ImportAction::Copy => match copy_one(project_root, &entry.from, &entry.to) {
Ok(()) => report.created.push(entry.to.clone()),
Err(e) => report
.refused
.push((entry.from.clone(), format!("copy failed: {e}"))),
},
}
}
report.created.sort();
report
}
fn copy_one(project_root: &Path, from: &Path, to: &Path) -> std::io::Result<()> {
let relative = to
.strip_prefix(super::native_config_dir(project_root))
.map_err(|_| {
std::io::Error::other(format!(
"{} is not beneath the project's own configuration directory",
to.display()
))
})?;
let (parent, name) = match (
relative.parent(),
relative.file_name().and_then(|n| n.to_str()),
) {
(Some(parent), Some(name)) => (parent, name),
_ => {
return Err(std::io::Error::other(format!(
"{} is not a usable import target",
to.display()
)));
}
};
let content = std::fs::read(from)?;
NativeWriteDir::open(project_root, parent)
.and_then(|dir| dir.create_new(name, &content))
.map_err(std::io::Error::other)
}
#[cfg(test)]
#[path = "import_tests.rs"]
mod import_tests;