use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use parking_lot::Mutex;
use crate::capability::WorktreeRoutingPolicy;
use crate::protocol::edit_hooks::{EditContext, EditHook};
pub const WORKTREE_ROUTING_ENV: &str = "SYMFORGE_WORKTREE_AWARE";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorktreeEntry {
pub path: PathBuf,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedTarget {
pub target_path: PathBuf,
pub indexed_path: PathBuf,
pub rerouted: bool,
}
#[derive(Debug, thiserror::Error)]
pub enum WorktreeError {
#[error(
"WorkingDirectoryNotARecognizedWorktree: working_directory `{}` is not a recognized worktree of `{}` — {hint}",
cwd.display(), indexed_root.display()
)]
WorkingDirectoryNotARecognizedWorktree {
cwd: PathBuf,
indexed_root: PathBuf,
hint: String,
},
#[error("TargetFileMissing: target file `{}` does not exist — {hint}", path.display())]
TargetFileMissing { path: PathBuf, hint: String },
#[error("TargetPathRefused: rerouted target `{}` is refused — {reason}", path.display())]
TargetPathRefused { path: PathBuf, reason: String },
#[error(
"PathOutsideIndexedRoot: indexed path `{}` is not under the indexed root `{}`",
path.display(), indexed_root.display()
)]
PathOutsideIndexedRoot {
path: PathBuf,
indexed_root: PathBuf,
},
#[error("NetworkPathRefused: working_directory `{}` is a network path and is never used", cwd.display())]
NetworkPathRefused { cwd: PathBuf },
#[error("filesystem error: {0}")]
Io(#[from] std::io::Error),
#[error("`git worktree list` failed: {0}")]
GitWorktreeList(String),
#[error(
"WorktreeRoutingDisabledByPolicy: working_directory `{}` requested worktree routing, but worktree routing is disabled by policy — {hint}",
cwd.display()
)]
WorktreeRoutingDisabledByPolicy { cwd: PathBuf, hint: String },
}
pub fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
dunce::canonicalize(path)
}
pub fn refuse_network_working_directories<'a>(
directories: impl IntoIterator<Item = Option<&'a Path>>,
) -> Result<(), WorktreeError> {
match directories
.into_iter()
.flatten()
.find(|directory| crate::paths::is_network_path(directory))
{
Some(directory) => Err(WorktreeError::NetworkPathRefused {
cwd: directory.to_path_buf(),
}),
None => Ok(()),
}
}
fn canonicalize_or_identity(path: &Path) -> PathBuf {
canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}
#[derive(Debug, Default)]
pub struct WorktreeCache {
roots: HashMap<PathBuf, RootWorktrees>,
}
#[derive(Debug, Default)]
struct RootWorktrees {
entries: HashMap<PathBuf, WorktreeEntry>,
last_refreshed: Option<Instant>,
}
impl WorktreeCache {
pub fn new() -> Self {
Self::default()
}
fn root_key(indexed_root: &Path) -> PathBuf {
canonicalize_or_identity(indexed_root)
}
pub fn insert(&mut self, indexed_root: &Path, path: PathBuf) {
self.roots
.entry(Self::root_key(indexed_root))
.or_default()
.entries
.insert(path.clone(), WorktreeEntry { path });
}
pub fn len(&self) -> usize {
self.roots.values().map(|slice| slice.entries.len()).sum()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn last_refreshed(&self) -> Option<Instant> {
self.roots
.values()
.filter_map(|slice| slice.last_refreshed)
.max()
}
pub fn lookup(
&mut self,
dir: &Path,
indexed_root: &Path,
) -> Result<Option<WorktreeEntry>, WorktreeError> {
let canon = canonicalize(dir)?;
let key = Self::root_key(indexed_root);
if let Some(entry) = self
.roots
.get(&key)
.and_then(|slice| slice.entries.get(&canon))
{
return Ok(Some(entry.clone()));
}
self.refresh(indexed_root)?;
Ok(self
.roots
.get(&key)
.and_then(|slice| slice.entries.get(&canon).cloned()))
}
pub fn refresh(&mut self, indexed_root: &Path) -> Result<(), WorktreeError> {
let paths = list_worktrees(indexed_root)?;
let slice = self.roots.entry(Self::root_key(indexed_root)).or_default();
slice.entries.clear();
for path in paths {
slice.entries.insert(path.clone(), WorktreeEntry { path });
}
slice.last_refreshed = Some(Instant::now());
Ok(())
}
pub fn paths(&self) -> impl Iterator<Item = &Path> {
self.roots
.values()
.flat_map(|slice| slice.entries.keys().map(|p| p.as_path()))
}
}
pub fn resolve_target_path(
indexed_abs: &Path,
indexed_root: &Path,
working_directory: Option<&Path>,
cache: &mut WorktreeCache,
) -> Result<ResolvedTarget, WorktreeError> {
let Some(raw_wd) = working_directory else {
return Ok(ResolvedTarget {
target_path: indexed_abs.to_path_buf(),
indexed_path: indexed_abs.to_path_buf(),
rerouted: false,
});
};
refuse_network_working_directories([Some(raw_wd)])?;
let canonical_indexed_abs = canonicalize_or_identity(indexed_abs);
let canonical_indexed_root = canonicalize(indexed_root)?;
let canonical_wd = match canonicalize(raw_wd) {
Ok(p) => p,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Err(WorktreeError::WorkingDirectoryNotARecognizedWorktree {
cwd: raw_wd.to_path_buf(),
indexed_root: canonical_indexed_root,
hint: "pass a path that is the root of a `git worktree list` entry, or omit to write to the indexed root".to_string(),
});
}
Err(e) => return Err(WorktreeError::Io(e)),
};
refuse_network_working_directories([Some(canonical_wd.as_path())])?;
if canonical_wd == canonical_indexed_root {
return Ok(ResolvedTarget {
target_path: canonical_indexed_abs.clone(),
indexed_path: canonical_indexed_abs,
rerouted: false,
});
}
let relative = canonical_indexed_abs
.strip_prefix(&canonical_indexed_root)
.map_err(|_| WorktreeError::PathOutsideIndexedRoot {
path: canonical_indexed_abs.clone(),
indexed_root: canonical_indexed_root.clone(),
})?;
let entry = cache.lookup(&canonical_wd, &canonical_indexed_root)?;
if entry.is_none() {
return Err(WorktreeError::WorkingDirectoryNotARecognizedWorktree {
cwd: canonical_wd,
indexed_root: canonical_indexed_root,
hint: "pass a path that is the root of a `git worktree list` entry, or omit to write to the indexed root".to_string(),
});
}
let target_path = canonical_wd.join(relative);
match crate::discovery::resolve_repo_path(&canonical_wd, &relative.to_string_lossy()) {
Ok(Some(_)) => {}
Ok(None) => {
return Err(WorktreeError::TargetFileMissing {
path: target_path,
hint: "the worktree may be at a commit where this file does not yet exist; check `git ls-tree HEAD <relative_path>` in the worktree".to_string(),
});
}
Err(refusal) => {
return Err(WorktreeError::TargetPathRefused {
path: target_path,
reason: format!("{refusal:?}"),
});
}
}
Ok(ResolvedTarget {
target_path,
indexed_path: canonical_indexed_abs,
rerouted: true,
})
}
fn list_worktrees(indexed_root: &Path) -> Result<Vec<PathBuf>, WorktreeError> {
let output = crate::process_util::hidden_command("git")
.arg("-C")
.arg(indexed_root)
.arg("worktree")
.arg("list")
.arg("--porcelain")
.output()
.map_err(|e| WorktreeError::GitWorktreeList(format!("spawn failed: {e}")))?;
if !output.status.success() {
return Err(WorktreeError::GitWorktreeList(format!(
"exit {}: {}",
output.status,
String::from_utf8_lossy(&output.stderr).trim()
)));
}
Ok(parse_porcelain(&String::from_utf8_lossy(&output.stdout)))
}
fn parse_porcelain(input: &str) -> Vec<PathBuf> {
let mut out = Vec::new();
for line in input.lines() {
let Some(rest) = line.strip_prefix("worktree ") else {
continue;
};
let raw = PathBuf::from(rest.trim());
match canonicalize(&raw) {
Ok(canon) => out.push(canon),
Err(_) => out.push(raw),
}
}
out
}
pub struct WorktreeAwareEditHook {
cache: Mutex<WorktreeCache>,
}
impl WorktreeAwareEditHook {
pub fn new() -> Self {
Self {
cache: Mutex::new(WorktreeCache::new()),
}
}
}
impl Default for WorktreeAwareEditHook {
fn default() -> Self {
Self::new()
}
}
impl EditHook for WorktreeAwareEditHook {
fn resolve_target_path(&self, ctx: &EditContext) -> Result<ResolvedTarget, String> {
if let Some(cwd) = ctx.working_directory
&& routing_policy_from_env() == WorktreeRoutingPolicy::Disabled
{
return Err(WorktreeError::WorktreeRoutingDisabledByPolicy {
cwd: cwd.to_path_buf(),
hint: format!(
"unset {WORKTREE_ROUTING_ENV} or set it to `1`/`true`/`on` to allow explicit call-time routing"
),
}
.to_string());
}
let mut cache = self.cache.lock();
resolve_target_path(
ctx.indexed_absolute_path,
ctx.repo_root,
ctx.working_directory,
&mut cache,
)
.map_err(|e| e.to_string())
}
}
pub fn routing_policy_from_env() -> WorktreeRoutingPolicy {
match std::env::var(WORKTREE_ROUTING_ENV) {
Ok(value) => match value.trim().to_ascii_lowercase().as_str() {
"" | "1" | "true" | "yes" | "on" | "explicit" | "explicit-call-time"
| "explicit_call_time" => WorktreeRoutingPolicy::ExplicitCallTime,
"0" | "false" | "no" | "off" | "disabled" | "disable" => {
WorktreeRoutingPolicy::Disabled
}
_ => WorktreeRoutingPolicy::Disabled,
},
Err(std::env::VarError::NotPresent) => WorktreeRoutingPolicy::ExplicitCallTime,
Err(std::env::VarError::NotUnicode(_)) => WorktreeRoutingPolicy::Disabled,
}
}
pub fn register_if_feature_enabled() {
static REGISTERED: OnceLock<()> = OnceLock::new();
REGISTERED.get_or_init(|| {
crate::protocol::edit_hooks::register(Box::new(WorktreeAwareEditHook::new()));
});
}
const MISUSE_WINDOW: Duration = Duration::from_secs(3600);
#[derive(Debug)]
pub struct WorktreeMisuseCounter {
count: AtomicU64,
window_start: Mutex<Instant>,
}
impl WorktreeMisuseCounter {
pub fn new() -> Self {
Self {
count: AtomicU64::new(0),
window_start: Mutex::new(Instant::now()),
}
}
pub fn record_missing_working_directory(&self) {
self.maybe_reset_window();
self.count.fetch_add(1, Ordering::Relaxed);
}
pub fn current_window_count(&self) -> u64 {
self.maybe_reset_window();
self.count.load(Ordering::Relaxed)
}
fn maybe_reset_window(&self) {
let mut start = self.window_start.lock();
if start.elapsed() >= MISUSE_WINDOW {
*start = Instant::now();
self.count.store(0, Ordering::Relaxed);
}
}
}
impl Default for WorktreeMisuseCounter {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn run_git(args: &[&str], cwd: &Path) {
let output = crate::process_util::hidden_command("git")
.args(args)
.current_dir(cwd)
.output()
.expect("git command");
assert!(
output.status.success(),
"git {args:?} failed: {}",
String::from_utf8_lossy(&output.stderr)
);
}
fn make_repo_with_worktree() -> (tempfile::TempDir, PathBuf, PathBuf) {
let dir = tempfile::tempdir().expect("tempdir");
let main_root = dir.path().join("main");
let worktree_root = dir.path().join("wt");
fs::create_dir_all(&main_root).unwrap();
run_git(&["init", "-q"], &main_root);
run_git(&["config", "user.email", "t@t.test"], &main_root);
run_git(&["config", "user.name", "t"], &main_root);
run_git(&["config", "commit.gpgsign", "false"], &main_root);
fs::create_dir_all(main_root.join("src")).unwrap();
fs::write(main_root.join("src/file.rs"), "fn main() {}\n").unwrap();
run_git(&["add", "."], &main_root);
run_git(&["commit", "-q", "-m", "init"], &main_root);
run_git(
&[
"worktree",
"add",
"-q",
worktree_root.to_str().unwrap(),
"-b",
"feature",
],
&main_root,
);
let main_canon = canonicalize(&main_root).unwrap();
let wt_canon = canonicalize(&worktree_root).unwrap();
(dir, main_canon, wt_canon)
}
#[cfg(windows)]
#[test]
fn working_directory_network_path_is_refused_without_filesystem_access() {
let mut cache = WorktreeCache::new();
for unc in [
r"\\nonexistent-host.invalid\share",
"//nonexistent-host.invalid/share",
r"\\?\UNC\nonexistent-host.invalid\share",
r"\\.\UNC\nonexistent-host.invalid\share",
"//./UNC/nonexistent-host.invalid/share",
r"\??\UNC\nonexistent-host.invalid\share",
r"\\?\GLOBALROOT\Device\Mup\nonexistent-host.invalid\share",
"//?/GLOBALROOT/Device/Mup/nonexistent-host.invalid/share",
r"\\?\Global\UNC\nonexistent-host.invalid\share",
] {
let started = std::time::Instant::now();
let err = resolve_target_path(
Path::new(r"C:\repo\a.rs"),
Path::new(r"C:\repo"),
Some(Path::new(unc)),
&mut cache,
)
.unwrap_err();
assert!(
matches!(err, WorktreeError::NetworkPathRefused { .. }),
"{unc}: {err}"
);
assert!(started.elapsed() < std::time::Duration::from_millis(250));
}
}
#[test]
fn canonicalize_strips_trailing_separator() {
let tmp = tempfile::tempdir().unwrap();
let canon = canonicalize(tmp.path()).unwrap();
let with_sep = {
let mut s = tmp.path().to_string_lossy().into_owned();
if !s.ends_with(std::path::MAIN_SEPARATOR) {
s.push(std::path::MAIN_SEPARATOR);
}
canonicalize(Path::new(&s)).unwrap()
};
assert_eq!(canon, with_sep);
let s = canon.to_string_lossy();
assert!(
!s.ends_with('/') && !s.ends_with('\\'),
"canonicalized path kept trailing separator: {s}"
);
}
#[test]
#[cfg(windows)]
fn canonicalize_normalizes_windows_slash_direction() {
let tmp = tempfile::tempdir().unwrap();
let forward = tmp.path().to_string_lossy().replace('\\', "/");
let back = tmp.path().to_string_lossy().replace('/', "\\");
let a = canonicalize(Path::new(&forward)).unwrap();
let b = canonicalize(Path::new(&back)).unwrap();
assert_eq!(a, b);
}
#[test]
#[cfg(windows)]
fn canonicalize_does_not_produce_unc_prefix() {
let tmp = tempfile::tempdir().unwrap();
let canon = canonicalize(tmp.path()).unwrap();
let s = canon.to_string_lossy();
assert!(
!s.starts_with(r"\\?\"),
"dunce should have stripped the UNC prefix, got: {s}"
);
}
#[test]
fn parse_porcelain_extracts_worktree_paths() {
let sample = "worktree /tmp/main\nHEAD abc123\nbranch refs/heads/main\n\nworktree /tmp/wt\nHEAD def456\nbranch refs/heads/feature\n";
let paths = parse_porcelain(sample);
assert_eq!(paths.len(), 2, "expected two worktrees, got {paths:?}");
}
#[test]
fn parse_porcelain_ignores_blank_and_attribute_lines() {
let sample = "\nworktree /only/one\nbare\n\n";
let paths = parse_porcelain(sample);
assert_eq!(paths.len(), 1);
}
#[test]
fn new_cache_is_empty() {
let cache = WorktreeCache::new();
assert!(cache.is_empty());
assert_eq!(cache.len(), 0);
assert!(cache.last_refreshed().is_none());
}
#[test]
fn insert_adds_entry_without_refresh() {
let mut cache = WorktreeCache::new();
let tmp = tempfile::tempdir().unwrap();
let root = tempfile::tempdir().unwrap();
let canon = canonicalize(tmp.path()).unwrap();
cache.insert(root.path(), canon.clone());
assert_eq!(cache.len(), 1);
let paths: Vec<&Path> = cache.paths().collect();
assert!(paths.contains(&canon.as_path()));
}
#[test]
fn refresh_lists_main_and_linked_worktrees() {
let (_tmp, main_root, wt_root) = make_repo_with_worktree();
let mut cache = WorktreeCache::new();
cache.refresh(&main_root).expect("refresh");
assert!(cache.last_refreshed().is_some());
assert_eq!(cache.len(), 2, "expected main + linked worktree");
let paths: Vec<PathBuf> = cache.paths().map(Path::to_path_buf).collect();
assert!(paths.contains(&main_root), "missing main in {paths:?}");
assert!(paths.contains(&wt_root), "missing linked wt in {paths:?}");
}
#[test]
fn lookup_returns_known_worktree() {
let (_tmp, main_root, wt_root) = make_repo_with_worktree();
let mut cache = WorktreeCache::new();
let entry = cache
.lookup(&wt_root, &main_root)
.expect("lookup")
.expect("entry");
assert_eq!(entry.path, wt_root);
}
#[test]
fn lookup_refreshes_on_miss() {
let (_tmp, main_root, wt_root) = make_repo_with_worktree();
let mut cache = WorktreeCache::new();
assert!(cache.is_empty());
let entry = cache.lookup(&wt_root, &main_root).expect("lookup");
assert!(
entry.is_some(),
"expected cache to refresh and find worktree"
);
assert!(!cache.is_empty(), "refresh should have populated cache");
}
#[test]
fn lookup_returns_none_for_unknown_directory() {
let (_tmp, main_root, _wt_root) = make_repo_with_worktree();
let stray = tempfile::tempdir().unwrap();
let stray_canon = canonicalize(stray.path()).unwrap();
let mut cache = WorktreeCache::new();
let entry = cache.lookup(&stray_canon, &main_root).expect("lookup");
assert!(
entry.is_none(),
"unrelated tempdir must not match a known worktree, got {entry:?}"
);
}
#[test]
fn resolve_returns_indexed_path_when_working_directory_omitted() {
let (_tmp, main_root, _wt) = make_repo_with_worktree();
let indexed_abs = main_root.join("src/file.rs");
let mut cache = WorktreeCache::new();
let resolved =
resolve_target_path(&indexed_abs, &main_root, None, &mut cache).expect("resolve");
assert!(!resolved.rerouted);
assert_eq!(resolved.target_path, indexed_abs);
assert_eq!(resolved.target_path, resolved.indexed_path);
}
#[test]
fn resolve_omitted_working_directory_does_not_touch_filesystem() {
let missing_root =
std::env::temp_dir().join(format!("symforge-missing-root-{}", std::process::id()));
let indexed_abs = missing_root.join("src/file.rs");
let mut cache = WorktreeCache::new();
let resolved = resolve_target_path(&indexed_abs, &missing_root, None, &mut cache)
.expect("omitted working_directory should not canonicalize repo root");
assert!(!resolved.rerouted);
assert_eq!(resolved.target_path, indexed_abs);
assert_eq!(resolved.target_path, resolved.indexed_path);
}
#[test]
fn resolve_returns_indexed_path_when_working_directory_is_indexed_root() {
let (_tmp, main_root, _wt) = make_repo_with_worktree();
let indexed_abs = main_root.join("src/file.rs");
let mut cache = WorktreeCache::new();
let resolved = resolve_target_path(&indexed_abs, &main_root, Some(&main_root), &mut cache)
.expect("resolve");
assert!(!resolved.rerouted, "indexed root should not reroute");
}
#[test]
fn resolve_reroutes_to_known_worktree() {
let (_tmp, main_root, wt_root) = make_repo_with_worktree();
let indexed_abs = main_root.join("src/file.rs");
let mut cache = WorktreeCache::new();
let resolved = resolve_target_path(&indexed_abs, &main_root, Some(&wt_root), &mut cache)
.expect("resolve");
assert!(resolved.rerouted);
assert_eq!(resolved.target_path, wt_root.join("src/file.rs"));
assert_eq!(resolved.indexed_path, canonicalize(&indexed_abs).unwrap());
}
#[test]
fn resolve_errors_on_unknown_working_directory() {
let (_tmp, main_root, _wt) = make_repo_with_worktree();
let stray = tempfile::tempdir().unwrap();
let indexed_abs = main_root.join("src/file.rs");
let mut cache = WorktreeCache::new();
let err = resolve_target_path(&indexed_abs, &main_root, Some(stray.path()), &mut cache)
.expect_err("should reject unknown dir");
assert!(
matches!(
err,
WorktreeError::WorkingDirectoryNotARecognizedWorktree { .. }
),
"got {err:?}"
);
}
#[test]
fn worktree_hits_are_fenced_to_the_requesting_indexed_root() {
let (_tmp_a, main_a, wt_a) = make_repo_with_worktree();
let (_tmp_b, main_b, _wt_b) = make_repo_with_worktree();
let mut cache = WorktreeCache::new();
let indexed_abs_a = main_a.join("src/file.rs");
let resolved = resolve_target_path(&indexed_abs_a, &main_a, Some(&wt_a), &mut cache)
.expect("A's own worktree reroutes");
assert!(resolved.rerouted);
let indexed_abs_b = main_b.join("src/file.rs");
let err = resolve_target_path(&indexed_abs_b, &main_b, Some(&wt_a), &mut cache)
.expect_err("a foreign root's cached worktree must not authorize B's reroute");
assert!(
matches!(
err,
WorktreeError::WorkingDirectoryNotARecognizedWorktree { .. }
),
"got {err:?}"
);
}
#[test]
fn resolve_refuses_an_aliased_or_linked_reroute_target() {
let tmp = tempfile::tempdir().unwrap();
fs::create_dir_all(tmp.path().join("main/src")).unwrap();
fs::create_dir_all(tmp.path().join("wt/src")).unwrap();
let main_root = canonicalize(&tmp.path().join("main")).unwrap();
let wt_root = canonicalize(&tmp.path().join("wt")).unwrap();
fs::write(main_root.join("src/file.rs"), "fn main() {}\n").unwrap();
#[cfg(windows)]
fs::write(wt_root.join("src/FILE.rs"), "fn main() {}\n").unwrap();
#[cfg(unix)]
{
let outside = tmp.path().join("outside.rs");
fs::write(&outside, "placeholder\n").unwrap();
std::os::unix::fs::symlink(&outside, wt_root.join("src/file.rs")).unwrap();
}
let mut cache = WorktreeCache::new();
cache.insert(&main_root, wt_root.clone());
let result = resolve_target_path(
&main_root.join("src/file.rs"),
&main_root,
Some(&wt_root),
&mut cache,
);
assert!(
result
.as_ref()
.is_err_and(|err| err.to_string().starts_with("TargetPathRefused")),
"got {result:?}"
);
}
#[test]
fn resolve_errors_when_target_file_missing() {
let (_tmp, main_root, wt_root) = make_repo_with_worktree();
fs::remove_file(wt_root.join("src/file.rs")).unwrap();
let indexed_abs = main_root.join("src/file.rs");
let mut cache = WorktreeCache::new();
let err = resolve_target_path(&indexed_abs, &main_root, Some(&wt_root), &mut cache)
.expect_err("should report missing target");
assert!(
matches!(err, WorktreeError::TargetFileMissing { .. }),
"got {err:?}"
);
}
#[test]
fn resolve_errors_when_indexed_path_outside_indexed_root() {
let (_tmp, main_root, wt_root) = make_repo_with_worktree();
let outside = tempfile::tempdir().unwrap();
let outside_canon = canonicalize(outside.path()).unwrap();
let stray_indexed = outside_canon.join("file.rs");
fs::write(&stray_indexed, "x").unwrap();
let mut cache = WorktreeCache::new();
let err = resolve_target_path(&stray_indexed, &main_root, Some(&wt_root), &mut cache)
.expect_err("should reject path outside indexed root");
assert!(
matches!(err, WorktreeError::PathOutsideIndexedRoot { .. }),
"got {err:?}"
);
}
#[test]
#[cfg(windows)]
fn resolve_normalizes_windows_slash_variants() {
let (_tmp, main_root, wt_root) = make_repo_with_worktree();
let indexed_abs = main_root.join("src/file.rs");
let wt_forward = PathBuf::from(wt_root.to_string_lossy().replace('\\', "/"));
let wt_back = PathBuf::from(wt_root.to_string_lossy().replace('/', "\\"));
let mut cache = WorktreeCache::new();
let a = resolve_target_path(&indexed_abs, &main_root, Some(&wt_forward), &mut cache)
.expect("resolve forward");
let b = resolve_target_path(&indexed_abs, &main_root, Some(&wt_back), &mut cache)
.expect("resolve back");
assert_eq!(a, b);
assert!(a.rerouted);
}
}