use anyhow::{Context, Result};
use std::path::{Path, PathBuf};
mod replacement;
pub(crate) fn ensure_dst_not_inside_src(src: &Path, dst: &Path) -> Result<()> {
if src == dst {
anyhow::bail!(
"Source and destination are the same path {:?}; refusing to copy",
src
);
}
let src_canon = src
.canonicalize()
.with_context(|| format!("Source {:?} does not exist or is not accessible", src))?;
let dst_is_link = std::fs::symlink_metadata(dst)
.map(|meta| meta.file_type().is_symlink())
.unwrap_or(false);
let lexical_dst = || -> Option<PathBuf> {
let parent = dst.parent()?.canonicalize().ok()?;
let name = dst.file_name()?;
Some(parent.join(name))
};
let dst_canon: Option<PathBuf> = if dst_is_link {
lexical_dst()
} else {
dst.canonicalize().ok().or_else(lexical_dst)
};
if dst_is_link {
let lexical_src = || -> Option<PathBuf> {
let parent = src.parent()?.canonicalize().ok()?;
Some(parent.join(src.file_name()?))
};
if let (Some(a), Some(b)) = (lexical_src(), dst_canon.as_ref()) {
if a == *b {
anyhow::bail!(
"Source and destination are the same path {:?}; refusing to copy",
src
);
}
}
}
if let Some(dst_canon) = dst_canon {
if dst_canon.starts_with(&src_canon) {
anyhow::bail!(
"Destination {:?} is inside source {:?}; refusing to copy to avoid infinite recursion",
dst,
src
);
}
if src_canon.starts_with(&dst_canon) {
anyhow::bail!(
"Source {:?} is inside destination {:?}; refusing to avoid deleting the source",
src,
dst
);
}
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TargetState {
Absent,
LinkToSource,
ForeignLink,
RealDir,
RealFile,
}
#[derive(Debug, Clone, Copy)]
pub enum ReplacePolicy<'a> {
NoClobber,
Recorded { mode: &'a str },
UserConfirmed,
}
impl ReplacePolicy<'_> {
fn permits(&self, state: TargetState) -> bool {
match state {
TargetState::Absent | TargetState::LinkToSource => true,
TargetState::ForeignLink => match self {
ReplacePolicy::NoClobber => false,
ReplacePolicy::Recorded { mode } => *mode == "symlink",
ReplacePolicy::UserConfirmed => true,
},
TargetState::RealDir => match self {
ReplacePolicy::NoClobber => false,
ReplacePolicy::Recorded { mode } => *mode == "copy",
ReplacePolicy::UserConfirmed => true,
},
TargetState::RealFile => matches!(self, ReplacePolicy::UserConfirmed),
}
}
fn describe(&self) -> &'static str {
match self {
ReplacePolicy::NoClobber => "不由 AgentHub 管理",
ReplacePolicy::Recorded { .. } => "与已记录的部署不一致",
ReplacePolicy::UserConfirmed => "无法被替换",
}
}
}
#[derive(Debug)]
pub struct ReplaceRefused {
pub target: PathBuf,
pub reason: &'static str,
}
pub fn refusal_message(target: &Path, reason: &str) -> String {
format!(
"拒绝替换 {target:?}:该路径{reason}。已有内容未被修改——\
请先将其导入技能库或移至其他位置后重试。"
)
}
impl std::fmt::Display for ReplaceRefused {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&refusal_message(&self.target, self.reason))
}
}
impl std::error::Error for ReplaceRefused {}
fn authorize_replacement(
source: &Path,
target: &Path,
policy: ReplacePolicy<'_>,
) -> Result<TargetState> {
let state = classify_target(target, Some(source))?;
if !policy.permits(state) {
return Err(ReplaceRefused {
target: target.to_path_buf(),
reason: policy.describe(),
}
.into());
}
Ok(state)
}
pub fn preflight_replace(
source: &Path,
target: &Path,
mode: SyncMode,
policy: ReplacePolicy<'_>,
) -> Result<()> {
if is_target_current(source, target, mode, None, None) {
return Ok(());
}
authorize_replacement(source, target, policy).map(|_| ())
}
pub fn classify_target(target: &Path, source: Option<&Path>) -> Result<TargetState> {
let metadata = match std::fs::symlink_metadata(target) {
Ok(metadata) => metadata,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(TargetState::Absent),
Err(err) => {
return Err(anyhow::Error::from(err)
.context(format!("Cannot inspect existing target {:?}", target)));
}
};
if metadata.file_type().is_symlink() {
if source.is_some_and(|source| symlink_points_to(target, source)) {
return Ok(TargetState::LinkToSource);
}
return Ok(TargetState::ForeignLink);
}
if metadata.is_dir() {
Ok(TargetState::RealDir)
} else {
Ok(TargetState::RealFile)
}
}
#[derive(Debug, Clone, Copy)]
pub enum SyncMode {
Symlink,
Copy,
}
impl SyncMode {
pub fn as_str(&self) -> &'static str {
match self {
SyncMode::Symlink => "symlink",
SyncMode::Copy => "copy",
}
}
}
pub fn sync_mode_for_tool(_tool_key: &str, configured_mode: Option<&str>) -> SyncMode {
match configured_mode {
Some("copy") => SyncMode::Copy,
Some("symlink") => SyncMode::Symlink,
_ => SyncMode::Symlink,
}
}
pub fn target_dir_name(central_path: &Path, skill_name: &str) -> String {
central_path
.file_name()
.and_then(|name| name.to_str())
.filter(|name| !name.is_empty())
.map(ToString::to_string)
.unwrap_or_else(|| skill_name.to_string())
}
pub fn sync_skill(
source: &Path,
target: &Path,
mode: SyncMode,
policy: ReplacePolicy<'_>,
) -> Result<SyncMode> {
if is_target_current(source, target, mode, None, None) {
return Ok(mode);
}
let state = authorize_replacement(source, target, policy)?;
crate::core::file_watcher::mute_self_writes(target);
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("Failed to create parent dir {:?}", parent))?;
}
ensure_dst_not_inside_src(source, target)?;
replacement::replace(source, target, mode, policy, state)
}
pub(crate) fn is_library_entry(path: &Path) -> bool {
let root = super::central_repo::skills_dir();
let Ok(root) = root.canonicalize() else {
return false;
};
path == root
|| path
.parent()
.and_then(|parent| parent.canonicalize().ok())
.is_some_and(|parent| parent.starts_with(&root))
}
pub(crate) fn uses_library_directly(source: &Path, target: &Path) -> bool {
is_library_entry(target)
&& source.is_dir()
&& source
.canonicalize()
.ok()
.zip(target.canonicalize().ok())
.is_some_and(|(a, b)| a == b)
}
pub fn is_target_current(
source: &Path,
target: &Path,
mode: SyncMode,
last_synced_source_hash: Option<&str>,
current_source_hash: Option<&str>,
) -> bool {
if uses_library_directly(source, target) {
return true;
}
match mode {
SyncMode::Symlink => symlink_points_to(target, source),
SyncMode::Copy => match (last_synced_source_hash, current_source_hash) {
(Some(stored), Some(current)) if stored == current => {
std::fs::symlink_metadata(target).is_ok()
}
_ => false,
},
}
}
fn symlink_points_to(target: &Path, source: &Path) -> bool {
let Ok(metadata) = std::fs::symlink_metadata(target) else {
return false;
};
if !metadata.file_type().is_symlink() {
return false;
}
let Ok(link_target) = std::fs::read_link(target) else {
return false;
};
let resolved_link_target = if link_target.is_absolute() {
link_target
} else {
target
.parent()
.unwrap_or_else(|| Path::new(""))
.join(link_target)
};
if resolved_link_target == source {
return true;
}
match (resolved_link_target.canonicalize(), source.canonicalize()) {
(Ok(link), Ok(src)) => link == src,
_ => false,
}
}
pub fn remove_classified_target(target: &Path, state: TargetState) -> Result<()> {
match state {
TargetState::Absent => Ok(()),
TargetState::LinkToSource | TargetState::ForeignLink => {
crate::core::file_watcher::mute_self_writes(target);
remove_link(target)
}
TargetState::RealFile => {
crate::core::file_watcher::mute_self_writes(target);
std::fs::remove_file(target).map_err(Into::into)
}
TargetState::RealDir => {
crate::core::file_watcher::mute_self_writes(target);
std::fs::remove_dir_all(target).map_err(Into::into)
}
}
}
pub fn remove_recorded_target(target: &Path, recorded_mode: &str) -> Result<bool> {
if is_library_entry(target) {
return Ok(false);
}
let state = classify_target(target, None)?;
let policy = ReplacePolicy::Recorded {
mode: recorded_mode,
};
if !policy.permits(state) {
return Ok(false);
}
remove_classified_target(target, state)?;
Ok(true)
}
pub fn remove_recorded_target_or_warn(target: &Path, recorded_mode: &str) -> bool {
match remove_recorded_target(target, recorded_mode) {
Ok(true) => true,
Ok(false) => {
log::warn!(
"Preserving {}: no longer matches its recorded {recorded_mode} deployment; \
removing the record only",
target.display()
);
false
}
Err(e) => {
log::warn!("Failed to remove sync target {}: {e}", target.display());
false
}
}
}
pub fn matches_recorded_deployment(target: &Path, recorded_mode: &str) -> Result<bool> {
let state = classify_target(target, None)?;
if state == TargetState::Absent {
return Ok(false);
}
let policy = ReplacePolicy::Recorded {
mode: recorded_mode,
};
Ok(policy.permits(state))
}
pub(crate) fn remove_link(target: &Path) -> Result<()> {
#[cfg(windows)]
{
use std::os::windows::fs::FileTypeExt;
let metadata = match std::fs::symlink_metadata(target) {
Ok(metadata) => metadata,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(err) => return Err(err.into()),
};
if !metadata.file_type().is_symlink() {
anyhow::bail!(
"Refusing to remove {:?}: expected a link but found a real file or directory",
target
);
}
if metadata.file_type().is_symlink_dir() {
std::fs::remove_dir(target)?;
} else {
std::fs::remove_file(target)?;
}
Ok(())
}
#[cfg(not(windows))]
{
match std::fs::remove_file(target) {
Ok(()) => Ok(()),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(err) => Err(err.into()),
}
}
}
pub fn remove_target(target: &Path) -> Result<()> {
let metadata = match std::fs::symlink_metadata(target) {
Ok(metadata) => metadata,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(err) => return Err(err.into()),
};
crate::core::file_watcher::mute_self_writes(target);
if metadata.file_type().is_symlink() {
#[cfg(windows)]
{
use std::os::windows::fs::FileTypeExt;
if metadata.file_type().is_symlink_dir() {
std::fs::remove_dir(target)?;
} else {
std::fs::remove_file(target)?;
}
}
#[cfg(not(windows))]
{
std::fs::remove_file(target)?;
}
} else if metadata.is_dir() {
std::fs::remove_dir_all(target)?;
} else {
std::fs::remove_file(target)?;
}
Ok(())
}
fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
std::fs::create_dir_all(dst)?;
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let ft = entry.file_type()?;
let dest_path = dst.join(entry.file_name());
if ft.is_dir() {
let name = entry.file_name();
if name == ".git" {
continue;
}
copy_dir_recursive(&entry.path(), &dest_path)?;
} else {
std::fs::copy(entry.path(), &dest_path)?;
}
}
Ok(())
}
#[cfg(test)]
#[path = "sync_engine/replacement_tests.rs"]
mod replacement_tests;
#[cfg(test)]
mod tests;