use std::collections::HashSet;
use std::path::{Path, PathBuf};
use soft_canonicalize::soft_canonicalize;
use typed_path::Utf8UnixPathBuf;
use crate::Result;
use crate::protocol::{FileKind, LinkKind, TargetOs};
use crate::sync::filter::FilterSet;
use crate::sync::linkpolicy::{
LinkClass, classify_link, compute_exec_hint, final_mode, rewrite_internal_target,
};
use crate::sync::wire::{file_source, wire_str};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileEntry {
pub relative_path: String,
pub size: u64,
pub mode: u32,
pub mtime_sec: i64,
pub mtime_nsec: u32,
pub file_hash: Option<[u8; 32]>,
pub is_dir: bool,
pub link_target: Option<String>,
pub link_kind: LinkKind,
pub inode: Option<u64>,
pub kind: FileKind,
pub rdev: Option<u64>,
pub uid: Option<u32>,
pub gid: Option<u32>,
pub atime_sec: i64,
pub atime_nsec: u32,
pub xattrs: Option<Vec<(String, Vec<u8>)>>,
pub source_path: Option<PathBuf>,
pub dereferenced: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Manifest {
pub root: PathBuf,
pub files: Vec<FileEntry>,
pub total_bytes: u64,
pub skipped: Vec<String>,
}
impl Manifest {
#[must_use]
pub fn new(root: PathBuf) -> Self {
Self {
root,
files: Vec::new(),
total_bytes: 0,
skipped: Vec::new(),
}
}
#[must_use]
pub fn len(&self) -> usize {
self.files.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.files.is_empty()
}
}
#[derive(Debug, Clone)]
#[expect(clippy::struct_excessive_bools)]
pub struct ScanOptions {
pub hash: bool,
pub hash_workers: usize,
pub filter: Option<FilterSet>,
pub recursive: bool,
pub preserve_links: bool,
pub follow_links: bool,
pub literal_links: bool,
pub literal_internal_links: bool,
pub literal_external_file_links: bool,
pub literal_external_dir_links: bool,
pub target_os: TargetOs,
pub is_source_scan: bool,
pub no_perms: bool,
pub source_os: TargetOs,
pub archive: bool,
pub xattrs: bool,
pub include_root_component: bool,
pub source_link_paths: Option<HashSet<String>>,
}
impl Default for ScanOptions {
fn default() -> Self {
Self {
hash: false,
hash_workers: num_cpus::get(),
filter: None,
recursive: true,
preserve_links: true,
follow_links: false,
literal_links: false,
literal_internal_links: false,
literal_external_file_links: false,
literal_external_dir_links: false,
target_os: TargetOs::Unix,
is_source_scan: true,
no_perms: false,
source_os: local_os(),
source_link_paths: None,
archive: false,
xattrs: false,
include_root_component: false,
}
}
}
#[must_use]
pub(crate) fn include_root_component(path: &str) -> bool {
if path.is_empty() {
return false;
}
if path.ends_with(['/', '\\']) {
return false;
}
match path.rsplit(['/', '\\']).next() {
Some(comp) => !comp.is_empty() && comp != "." && comp != "..",
None => false,
}
}
#[must_use]
pub(crate) fn local_os() -> TargetOs {
if cfg!(windows) {
TargetOs::Windows
} else {
TargetOs::Unix
}
}
#[derive(Debug, Clone)]
pub struct Scanner {
options: ScanOptions,
}
impl Scanner {
#[must_use]
pub fn new(options: ScanOptions) -> Self {
Self { options }
}
pub async fn scan(&self, root: &Path) -> Result<Manifest> {
let canonical = tokio::fs::canonicalize(root)
.await
.map_err(crate::Error::Io)?;
let mut entries = Vec::new();
if canonical.is_file() {
let rel = wire_str(
&canonical
.file_name()
.unwrap_or(canonical.as_os_str())
.to_string_lossy(),
);
if self.options.filter.as_ref().is_none_or(|f| f.passes(&rel)) {
let meta = tokio::fs::metadata(&canonical)
.await
.map_err(crate::Error::Io)?;
entries.push(file_entry(rel, &meta, None));
}
if self.options.hash {
let parent = canonical.parent().unwrap_or(&canonical);
self.hash_files(parent, &mut entries).await?;
}
self.apply_permission_matrix(&mut entries);
self.collect_entry_xattrs(
canonical.parent().unwrap_or(&canonical),
&mut entries,
);
let total_bytes = entries.iter().map(|f| f.size).sum();
return Ok(Manifest {
root: canonical
.parent()
.unwrap_or(&canonical)
.to_path_buf(),
files: entries,
total_bytes,
skipped: Vec::new(),
});
}
let ctx = self.context(&canonical);
let root_for_walk = canonical.clone();
let (mut entries, skipped): (Vec<FileEntry>, Vec<String>) =
tokio::task::spawn_blocking(move || {
walk_tree(&ctx, &root_for_walk)
})
.await
.map_err(|e| crate::Error::Other(format!("Scan task panicked: {e}")))??;
entries.sort_by(|a, b| a.relative_path.cmp(&b.relative_path));
if self.options.hash {
self.hash_files(&canonical, &mut entries).await?;
}
self.apply_permission_matrix(&mut entries);
self.collect_entry_xattrs(&canonical, &mut entries);
let root = if self.options.include_root_component
&& let Some(dir_name) = canonical.file_name()
{
let prefix = dir_name.to_string_lossy().into_owned();
for entry in &mut entries {
let mut wire = Utf8UnixPathBuf::new();
wire.push(&prefix);
wire.push(&entry.relative_path);
entry.relative_path = wire.to_string();
}
canonical
.parent()
.unwrap_or(&canonical)
.to_path_buf()
} else {
canonical.clone()
};
let total_bytes = entries.iter().map(|f| f.size).sum();
Ok(Manifest {
root,
files: entries,
total_bytes,
skipped,
})
}
pub async fn scan_multi(&self, base: &Path, roots: &[PathBuf]) -> Result<Manifest> {
let mut entries = Vec::new();
let mut skipped = Vec::new();
let mut roots = roots.to_vec();
roots.sort();
let mut accepted: Vec<PathBuf> = Vec::new();
let ctx_base = if base.as_os_str().is_empty() {
Path::new(".")
} else {
base
};
let canonical_base = tokio::fs::canonicalize(ctx_base).await.map_err(crate::Error::Io)?;
let ctx = self.context(&canonical_base);
for root in &roots {
if accepted.iter().any(|r| root.starts_with(r)) {
continue;
}
let rel_os = root.strip_prefix(base).map_err(|_| {
crate::Error::Other(format!(
"internal glob error: {} is not under {}",
root.display(),
base.display()
))
})?;
let rel = wire_str(&rel_os.to_string_lossy());
let rel = rel.strip_prefix("./").unwrap_or(&rel).to_string();
if self
.options
.filter
.as_ref()
.is_none_or(|f| f.passes(&rel))
{
self.scan_match(root, &rel, &ctx, &mut entries, &mut skipped)
.await?;
accepted.push(root.clone());
}
}
entries.sort_by(|a, b| a.relative_path.cmp(&b.relative_path));
self.apply_permission_matrix(&mut entries);
self.collect_entry_xattrs(base, &mut entries);
let total_bytes = entries.iter().map(|f| f.size).sum();
Ok(Manifest {
root: base.to_path_buf(),
files: entries,
total_bytes,
skipped,
})
}
async fn scan_match(
&self,
root: &Path,
rel: &str,
ctx: &ScanContext,
entries: &mut Vec<FileEntry>,
skipped: &mut Vec<String>,
) -> Result<()> {
let lmeta = std::fs::symlink_metadata(root).map_err(crate::Error::Io)?;
let file_type = lmeta.file_type();
if file_type.is_symlink() {
let target = std::fs::read_link(root)
.map(|t| wire_str(&t.to_string_lossy()))
.unwrap_or_default();
let mut visited = HashSet::new();
scan_link(ctx, root, rel, &target, Some(&lmeta), entries, skipped, &mut visited);
return Ok(());
}
if !file_type.is_dir() && !file_type.is_file() {
if let Some(kind) = special_kind(&lmeta) {
entries.push(special_entry(rel.to_string(), &lmeta, kind));
}
return Ok(());
}
if file_type.is_file() && ctx.source_is_windows && !ctx.literal_links && is_lnk_file(root) {
let mut visited = HashSet::new();
scan_lnk(ctx, root, rel, &lmeta, entries, skipped, &mut visited);
return Ok(());
}
let manifest = self.scan(root).await?;
if file_type.is_dir() {
let meta = tokio::fs::metadata(root).await.map_err(crate::Error::Io)?;
entries.push(dir_entry(rel.to_string(), &meta));
for mut entry in manifest.files {
entry.relative_path = wire_str(
&PathBuf::from(rel)
.join(&entry.relative_path)
.to_string_lossy(),
);
entries.push(entry);
}
} else if let Some(mut file) = manifest.files.into_iter().next() {
file.relative_path = rel.to_string();
entries.push(file);
}
Ok(())
}
pub async fn scan_targeted(&self, root: &Path, source: &Manifest) -> Result<Manifest> {
let canonical = tokio::fs::canonicalize(root)
.await
.map_err(crate::Error::Io)?;
let mut paths: Vec<String> = source
.files
.iter()
.map(|f| f.relative_path.clone())
.collect();
paths.sort_unstable();
paths.dedup();
let source_links: HashSet<String> = source
.files
.iter()
.filter(|f| f.link_target.is_some())
.map(|f| f.relative_path.clone())
.collect();
let ctx = std::sync::Arc::new(ScanContext {
is_source: false,
follow_links: false,
warn: false,
source_link_paths: (!source_links.is_empty()).then_some(source_links),
..self.context(&canonical)
});
let workers = self.options.hash_workers.max(1);
let chunk_size = paths.len().div_ceil(workers).max(1);
let mut handles = Vec::new();
while !paths.is_empty() {
let take = chunk_size.min(paths.len());
let chunk: Vec<String> = paths.drain(..take).collect();
let root = canonical.clone();
let ctx = std::sync::Arc::clone(&ctx);
handles.push(tokio::task::spawn_blocking(move || {
let mut entries: Vec<FileEntry> = Vec::new();
let mut visited = HashSet::new();
for rel in chunk {
let full = root.join(&rel);
let result = std::fs::symlink_metadata(&full);
match result {
Ok(meta) => {
let file_type = meta.file_type();
if file_type.is_dir() {
entries.push(dir_entry(rel.clone(), &meta));
} else if file_type.is_file() {
if ctx.source_is_windows && is_lnk_entry(&full, &rel, &ctx) {
scan_lnk(
&ctx,
&full,
&rel,
&meta,
&mut entries,
&mut Vec::new(),
&mut visited,
);
} else {
entries.push(file_entry(rel.clone(), &meta, None));
}
} else if file_type.is_symlink() {
let target = std::fs::read_link(&full)
.map(|t| wire_str(&t.to_string_lossy()))
.unwrap_or_default();
scan_link(
&ctx,
&full,
&rel,
&target,
Some(&meta),
&mut entries,
&mut Vec::new(),
&mut visited,
);
} else if let Some(kind) = special_kind(&meta) {
entries.push(special_entry(rel.clone(), &meta, kind));
}
}
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::NotFound
| std::io::ErrorKind::NotADirectory
) || is_symlink_loop(&e) =>
{
}
Err(e) => return Err(crate::Error::Io(e)),
}
}
Ok::<_, crate::Error>(entries)
}));
}
let mut entries: Vec<FileEntry> = Vec::new();
for handle in handles {
entries.extend(
handle
.await
.map_err(|_| crate::Error::Other("Probe task panicked".to_string()))??,
);
}
entries.sort_by(|a, b| a.relative_path.cmp(&b.relative_path));
if self.options.hash {
self.hash_files(&canonical, &mut entries).await?;
}
let total_bytes = entries.iter().map(|f| f.size).sum();
Ok(Manifest {
root: canonical,
files: entries,
total_bytes,
skipped: Vec::new(),
})
}
async fn hash_files(&self, root: &Path, entries: &mut [FileEntry]) -> Result<()> {
use tokio::io::AsyncReadExt;
let workers = self.options.hash_workers.max(1);
let semaphore = std::sync::Arc::new(tokio::sync::Semaphore::new(workers));
let root = std::sync::Arc::new(root.to_path_buf());
let mut handles = Vec::new();
for (idx, entry) in entries.iter().enumerate() {
if entry.is_dir || entry.link_target.is_some() || entry.kind != FileKind::File {
continue; }
let permit = semaphore.clone().acquire_owned().await;
let path = entry_source(&root, entry);
handles.push(tokio::spawn(async move {
let _permit = permit;
let display = path.display().to_string();
let mut file = tokio::fs::File::open(&path)
.await
.map_err(|e| crate::Error::Other(format!("Failed to hash {display}: {e}")))?;
let mut hasher = blake3::Hasher::new();
let mut buf = vec![0u8; 256 * 1024];
loop {
let n = file.read(&mut buf).await.map_err(|e| {
crate::Error::Other(format!("Failed to hash {display}: {e}"))
})?;
if n == 0 {
break;
}
hasher.update(&buf[..n]);
}
Ok::<_, crate::Error>((idx, *hasher.finalize().as_bytes()))
}));
}
for handle in handles {
let (idx, hash) = handle
.await
.map_err(|_| crate::Error::Other("Hash task panicked".to_string()))??;
entries[idx].file_hash = Some(hash);
}
Ok(())
}
fn context(&self, root: &Path) -> ScanContext {
ScanContext {
root: root.to_path_buf(),
filter: self.options.filter.clone(),
recursive: self.options.recursive,
preserve_links: self.options.preserve_links,
follow_links: self.options.follow_links,
literal_links: self.options.literal_links,
literal_internal_links: self.options.literal_internal_links,
literal_external_file_links: self.options.literal_external_file_links,
literal_external_dir_links: self.options.literal_external_dir_links,
target_os: self.options.target_os,
is_source: self.options.is_source_scan,
source_is_windows: self.options.source_os == TargetOs::Windows,
source_link_paths: self.options.source_link_paths.clone(),
warn: self.options.is_source_scan,
}
}
fn apply_permission_matrix(&self, entries: &mut [FileEntry]) {
if !self.options.is_source_scan {
return;
}
let source_os = self.options.source_os;
let no_perms = self.options.no_perms;
let archive = self.options.archive;
for entry in entries {
if entry.link_target.is_some() {
entry.mode = 0;
continue;
}
let exec_hint = compute_exec_hint(Path::new(&entry.relative_path));
entry.mode = final_mode(
source_os,
self.options.target_os,
entry.mode,
entry.is_dir,
exec_hint,
no_perms,
archive,
);
}
}
fn collect_entry_xattrs(&self, root: &Path, entries: &mut [FileEntry]) {
if !self.options.xattrs || !self.options.is_source_scan {
return;
}
for entry in entries {
if matches!(entry.kind, FileKind::File | FileKind::Dir) {
let path = entry_source(root, entry);
entry.xattrs = Some(crate::platform::fs::collect_xattrs(&path));
}
}
}
}
#[derive(Debug, Clone)]
#[expect(clippy::struct_excessive_bools)]
struct ScanContext {
root: PathBuf,
filter: Option<FilterSet>,
recursive: bool,
preserve_links: bool,
follow_links: bool,
literal_links: bool,
literal_internal_links: bool,
literal_external_file_links: bool,
literal_external_dir_links: bool,
target_os: TargetOs,
is_source: bool,
source_is_windows: bool,
source_link_paths: Option<HashSet<String>>,
warn: bool,
}
impl ScanContext {
fn skip(&self, rel: &str, reason: &str, skipped: &mut Vec<String>) {
if self.warn {
tracing::warn!("skipping {rel}: {reason}");
}
skipped.push(rel.to_string());
}
}
fn walk_tree(ctx: &ScanContext, root: &Path) -> crate::Result<(Vec<FileEntry>, Vec<String>)> {
let walk_root = root.to_path_buf();
let filter_root = walk_root.clone();
let filter = ctx.filter.clone();
let recursive = ctx.recursive;
let mut walker = jwalk::WalkDir::new(root)
.skip_hidden(false) .min_depth(1) .max_depth(if recursive { usize::MAX } else { 1 });
walker = walker.process_read_dir(move |_parent, _dir_path, _state, dir_entries| {
if let Some(filter) = &filter {
dir_entries.retain(|e| match e {
Ok(entry) => {
let path = entry.path();
let rel = path.strip_prefix(&filter_root).unwrap_or(&path);
filter.passes(&rel.to_string_lossy())
}
Err(_) => true, });
}
});
let mut out = Vec::new();
let mut skipped = Vec::new();
let mut visited: HashSet<PathBuf> = HashSet::new();
for entry in walker {
let entry = entry
.map_err(|e| crate::Error::Other(format!("walk error: {e}")))?;
let path = entry.path();
let rel = path
.strip_prefix(&walk_root)
.unwrap_or(&path)
.to_string_lossy()
.replace('\\', "/");
let file_type = entry.file_type();
if file_type.is_dir() {
if !recursive {
continue;
}
let meta = entry
.metadata()
.map_err(|e| crate::Error::Other(format!("metadata: {e}")))?;
out.push(dir_entry(rel, &meta));
} else if file_type.is_file() {
if ctx.source_is_windows && is_lnk_entry(&path, &rel, ctx) {
let lmeta = entry
.metadata()
.map_err(|e| crate::Error::Other(format!("metadata: {e}")))?;
scan_lnk(ctx, &path, &rel, &lmeta, &mut out, &mut skipped, &mut visited);
} else {
let meta = entry
.metadata()
.map_err(|e| crate::Error::Other(format!("metadata: {e}")))?;
out.push(file_entry(rel, &meta, None));
}
} else if file_type.is_symlink() {
let target = std::fs::read_link(&path)
.map(|t| wire_str(&t.to_string_lossy()))
.unwrap_or_default();
let lmeta = std::fs::symlink_metadata(&path).ok();
scan_link(
ctx,
&path,
&rel,
&target,
lmeta.as_ref(),
&mut out,
&mut skipped,
&mut visited,
);
} else if let Some(lmeta) = std::fs::symlink_metadata(&path).ok()
&& let Some(kind) = special_kind(&lmeta)
{
out.push(special_entry(rel, &lmeta, kind));
}
}
Ok((out, skipped))
}
#[expect(clippy::too_many_arguments)]
fn scan_link(
ctx: &ScanContext,
link_path: &Path,
rel: &str,
target: &str,
lmeta: Option<&std::fs::Metadata>,
entries: &mut Vec<FileEntry>,
skipped: &mut Vec<String>,
visited: &mut HashSet<PathBuf>,
) {
if !ctx.preserve_links {
if ctx.is_source {
ctx.skip(rel, "link skipped (--skip-links)", skipped);
} else {
entries.push(symlink_entry(
rel.to_string(),
target.to_string(),
LinkKind::Symlink,
lmeta,
));
}
return;
}
if ctx.follow_links {
if ctx.is_source {
match std::fs::metadata(link_path) {
Ok(meta) if meta.is_file() => {
entries.push(file_entry(rel.to_string(), &meta, None));
}
Ok(meta) if meta.is_dir() => {
walk_external(ctx, link_path, rel, entries, skipped, visited);
}
_ => {
ctx.skip(rel, "unreadable or special link target (--follow-links)", skipped);
}
}
} else {
entries.push(symlink_entry(
rel.to_string(),
target.to_string(),
LinkKind::Symlink,
lmeta,
));
}
return;
}
if ctx.literal_links {
let kind = if ctx.target_os == TargetOs::Windows {
LinkKind::Lnk
} else {
LinkKind::Symlink
};
entries.push(symlink_entry(rel.to_string(), target.to_string(), kind, lmeta));
return;
}
match classify_link(link_path, target, &ctx.root) {
LinkClass::Internal => {
if ctx.is_source {
let resolved = crate::sync::linkpolicy::resolve_target(link_path, target);
let self_link = crate::sync::linkpolicy::lexical_normalize(link_path);
if crate::sync::linkpolicy::lexical_normalize(&resolved) == self_link {
ctx.skip(rel, "loop detected", skipped);
return;
}
}
let kind = if ctx.target_os == TargetOs::Windows {
LinkKind::Lnk
} else {
LinkKind::Symlink
};
if ctx.literal_internal_links {
entries.push(symlink_entry(rel.to_string(), target.to_string(), kind, lmeta));
return;
}
let target_rel = rel_of_internal_target(link_path, target, &ctx.root);
let rewritten = rewrite_internal_target(rel, &target_rel);
entries.push(symlink_entry(rel.to_string(), rewritten, kind, lmeta));
}
LinkClass::ExternalFile => {
if !ctx.is_source {
entries.push(symlink_entry(
rel.to_string(),
target.to_string(),
LinkKind::Symlink,
lmeta,
));
} else if ctx.literal_external_file_links && ctx.target_os == TargetOs::Unix {
entries.push(symlink_entry(
rel.to_string(),
target.to_string(),
LinkKind::Symlink,
lmeta,
));
} else {
if let Ok(meta) = std::fs::metadata(link_path)
&& meta.is_file()
{
entries.push(file_entry(rel.to_string(), &meta, None));
} else {
ctx.skip(rel, "unreadable external file link", skipped);
}
}
}
LinkClass::ExternalDir => {
if ctx.literal_external_dir_links {
let kind = if ctx.target_os == TargetOs::Windows {
LinkKind::Lnk
} else {
LinkKind::Symlink
};
entries.push(symlink_entry(rel.to_string(), target.to_string(), kind, lmeta));
} else if ctx.is_source {
ctx.skip(
rel,
"external directory link (--literal-external-dir-links to keep)",
skipped,
);
}
}
LinkClass::DanglingExternal => {
if ctx.is_source {
ctx.skip(rel, "dangling external link", skipped);
}
}
}
}
fn walk_external(
ctx: &ScanContext,
link_path: &Path,
rel: &str,
entries: &mut Vec<FileEntry>,
skipped: &mut Vec<String>,
visited: &mut HashSet<PathBuf>,
) {
let Ok(canonical_dir) = std::fs::canonicalize(link_path) else {
ctx.skip(rel, "external directory link unreadable", skipped);
return;
};
if !visited.insert(canonical_dir.clone()) {
ctx.skip(rel, "loop detected", skipped);
return;
}
if let Ok(meta) = std::fs::metadata(&canonical_dir) {
entries.push(dir_entry(rel.to_string(), &meta));
}
walk_dir_contents(ctx, &canonical_dir, rel, entries, skipped, visited);
}
fn walk_dir_contents(
ctx: &ScanContext,
dir: &Path,
rel_prefix: &str,
entries: &mut Vec<FileEntry>,
skipped: &mut Vec<String>,
visited: &mut HashSet<PathBuf>,
) {
let mut children: Vec<_> = match std::fs::read_dir(dir) {
Ok(it) => it.filter_map(std::result::Result::ok).collect(),
Err(e) => {
if ctx.warn {
tracing::warn!("cannot read {}: {e}", dir.display());
}
return;
}
};
children.sort_by_key(std::fs::DirEntry::file_name);
for child in children {
let name = child.file_name().to_string_lossy().into_owned();
let child_path = child.path();
let rel = if rel_prefix.is_empty() {
name
} else {
format!("{rel_prefix}/{name}")
};
if ctx.filter.as_ref().is_some_and(|f| !f.passes(&rel)) {
continue;
}
let Ok(lmeta) = std::fs::symlink_metadata(&child_path) else {
continue;
};
let file_type = lmeta.file_type();
if file_type.is_dir() {
if !ctx.recursive {
continue;
}
entries.push(dir_entry(rel.clone(), &lmeta));
walk_dir_contents(ctx, &child_path, &rel, entries, skipped, visited);
} else if file_type.is_file() {
if ctx.source_is_windows && !ctx.literal_links && is_lnk_file(&child_path) {
scan_lnk(ctx, &child_path, &rel, &lmeta, entries, skipped, visited);
} else {
let mut entry = file_entry(rel.clone(), &lmeta, None);
entry.source_path = Some(child_path.clone());
entry.dereferenced = true;
entries.push(entry);
}
} else if file_type.is_symlink() {
let target = std::fs::read_link(&child_path)
.map(|t| wire_str(&t.to_string_lossy()))
.unwrap_or_default();
scan_link(ctx, &child_path, &rel, &target, Some(&lmeta), entries, skipped, visited);
} else if let Some(kind) = special_kind(&lmeta) {
let mut entry = special_entry(rel.clone(), &lmeta, kind);
entry.dereferenced = true;
entries.push(entry);
}
}
}
fn rel_of_internal_target(link_path: &Path, target: &str, root: &Path) -> String {
let resolved = crate::sync::linkpolicy::resolve_target(link_path, target);
if let Ok(rel) = resolved.strip_prefix(root) {
return wire_str(&rel.to_string_lossy());
}
let Ok(canon) = std::fs::canonicalize(&resolved) else {
let normalized = soft_canonicalize(&resolved)
.unwrap_or_else(|_| crate::sync::linkpolicy::lexical_normalize(&resolved));
return wire_str(&normalized.strip_prefix(root).unwrap_or(&resolved).to_string_lossy());
};
wire_str(&canon.strip_prefix(root).unwrap_or(&canon).to_string_lossy())
}
fn entry_source(root: &Path, entry: &FileEntry) -> PathBuf {
file_source(root, entry.source_path.as_deref(), Path::new(&entry.relative_path))
}
fn is_lnk_entry(path: &Path, rel: &str, ctx: &ScanContext) -> bool {
if ctx.is_source {
return !ctx.literal_links && is_lnk_file(path);
}
ctx.source_link_paths
.as_ref()
.is_some_and(|links| links.contains(rel))
&& lnk_magic_of(path)
}
fn is_lnk_file(path: &Path) -> bool {
path.extension()
.is_some_and(|e| e.eq_ignore_ascii_case("lnk"))
&& lnk_magic_of(path)
}
fn lnk_magic_of(path: &Path) -> bool {
use std::io::Read;
let Ok(mut file) = std::fs::File::open(path) else {
return false;
};
let mut head = [0u8; 4];
let n = file.read(&mut head).unwrap_or(0);
crate::sync::linkpolicy::is_lnk_magic(&head[..n])
}
fn extract_lnk_target(path: &Path) -> Option<String> {
let link = lnk::ShellLink::open(path, lnk::encoding::UTF_16LE)
.or_else(|_| lnk::ShellLink::open(path, lnk::encoding::WINDOWS_1252))
.ok()?;
if let Some(target) = link.link_target() {
return Some(target);
}
link.string_data().relative_path().clone()
}
fn scan_lnk(
ctx: &ScanContext,
link_path: &Path,
rel: &str,
lmeta: &std::fs::Metadata,
entries: &mut Vec<FileEntry>,
skipped: &mut Vec<String>,
visited: &mut HashSet<PathBuf>,
) {
if !ctx.preserve_links {
if ctx.is_source {
ctx.skip(rel, "shortcut skipped (--skip-links)", skipped);
} else {
match extract_lnk_target(link_path) {
Some(t) => entries.push(symlink_entry(
rel.to_string(),
wire_str(&t),
LinkKind::Lnk,
Some(lmeta),
)),
None => entries.push(file_entry(rel.to_string(), lmeta, None)),
}
}
return;
}
let Some(target) = extract_lnk_target(link_path) else {
entries.push(file_entry(rel.to_string(), lmeta, None));
return;
};
if ctx.follow_links {
if ctx.is_source {
let resolved = crate::sync::linkpolicy::resolve_target(link_path, &target);
match std::fs::metadata(&resolved) {
Ok(meta) if meta.is_file() => {
let mut entry = file_entry(rel.to_string(), &meta, None);
entry.source_path = Some(resolved);
entry.dereferenced = true;
entries.push(entry);
}
Ok(meta) if meta.is_dir() => {
walk_external(ctx, &resolved, rel, entries, skipped, visited);
}
_ => {
ctx.skip(rel, "directory or unreadable .lnk target (--follow-links)", skipped);
}
}
} else {
entries.push(symlink_entry(
rel.to_string(),
wire_str(&target),
LinkKind::Lnk,
Some(lmeta),
));
}
return;
}
if ctx.literal_links {
entries.push(symlink_entry(
rel.to_string(),
wire_str(&target),
LinkKind::Lnk,
Some(lmeta),
));
return;
}
match classify_link(link_path, &target, &ctx.root) {
LinkClass::Internal => {
let kind = if ctx.target_os == TargetOs::Windows {
LinkKind::Lnk
} else {
LinkKind::Symlink
};
if ctx.literal_internal_links {
entries.push(symlink_entry(rel.to_string(), wire_str(&target), kind, Some(lmeta)));
return;
}
let target_rel = rel_of_internal_target(link_path, &target, &ctx.root);
let rewritten = rewrite_internal_target(rel, &target_rel);
entries.push(symlink_entry(rel.to_string(), rewritten, kind, Some(lmeta)));
}
_ => {
entries.push(file_entry(rel.to_string(), lmeta, None));
}
}
}
fn mode_from_meta(meta: &std::fs::Metadata) -> u32 {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
meta.permissions().mode()
}
#[cfg(not(unix))]
{
let _ = meta;
0o644
}
}
#[cfg(unix)]
#[expect(clippy::unnecessary_wraps)]
fn rdev_of(meta: &std::fs::Metadata) -> Option<u64> {
use std::os::unix::fs::MetadataExt;
Some(meta.rdev())
}
#[cfg(not(unix))]
fn rdev_of(_meta: &std::fs::Metadata) -> Option<u64> {
None
}
#[cfg(unix)]
fn special_kind(meta: &std::fs::Metadata) -> Option<FileKind> {
use std::os::unix::fs::MetadataExt;
let mode = libc::mode_t::try_from(meta.mode()).expect("mode fits mode_t");
match mode & libc::S_IFMT {
libc::S_IFIFO => Some(FileKind::Fifo),
libc::S_IFSOCK => Some(FileKind::Socket),
libc::S_IFBLK => Some(FileKind::BlockDevice),
libc::S_IFCHR => Some(FileKind::CharDevice),
_ => None,
}
}
#[cfg(not(unix))]
fn special_kind(_meta: &std::fs::Metadata) -> Option<FileKind> {
None
}
#[allow(clippy::unnecessary_wraps)]
fn inode_of(meta: &std::fs::Metadata) -> Option<u64> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
Some(meta.ino())
}
#[cfg(not(unix))]
{
let _ = meta;
None
}
}
fn mtime_secs(meta: &std::fs::Metadata) -> i64 {
i64::try_from(crate::platform::fs::mtime_secs(meta)).unwrap_or(i64::MAX)
}
fn mtime_nsecs(meta: &std::fs::Metadata) -> u32 {
crate::platform::fs::mtime_nsecs(meta)
}
fn atime_secs(meta: &std::fs::Metadata) -> i64 {
i64::try_from(crate::platform::fs::atime_secs(meta)).unwrap_or(i64::MAX)
}
fn atime_nsecs(meta: &std::fs::Metadata) -> u32 {
crate::platform::fs::atime_nsecs(meta)
}
#[allow(clippy::unnecessary_wraps)]
fn uid_of(meta: &std::fs::Metadata) -> Option<u32> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
Some(meta.uid())
}
#[cfg(not(unix))]
{
let _ = meta;
None
}
}
#[allow(clippy::unnecessary_wraps)]
fn gid_of(meta: &std::fs::Metadata) -> Option<u32> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
Some(meta.gid())
}
#[cfg(not(unix))]
{
let _ = meta;
None
}
}
#[cfg(unix)]
fn is_symlink_loop(e: &std::io::Error) -> bool {
e.raw_os_error() == Some(libc::ELOOP)
}
#[cfg(not(unix))]
fn is_symlink_loop(_e: &std::io::Error) -> bool {
false
}
fn file_entry(rel: String, meta: &std::fs::Metadata, hash: Option<[u8; 32]>) -> FileEntry {
FileEntry {
relative_path: rel,
size: meta.len(),
mode: mode_from_meta(meta),
mtime_sec: mtime_secs(meta),
mtime_nsec: mtime_nsecs(meta),
file_hash: hash,
is_dir: false,
link_target: None,
link_kind: LinkKind::Symlink,
inode: inode_of(meta),
kind: FileKind::File,
rdev: None,
uid: uid_of(meta),
gid: gid_of(meta),
atime_sec: atime_secs(meta),
atime_nsec: atime_nsecs(meta),
xattrs: None,
source_path: None,
dereferenced: false,
}
}
fn dir_entry(rel: String, meta: &std::fs::Metadata) -> FileEntry {
FileEntry {
relative_path: rel,
size: 0,
mode: mode_from_meta(meta),
mtime_sec: mtime_secs(meta),
mtime_nsec: mtime_nsecs(meta),
file_hash: None,
is_dir: true,
link_target: None,
link_kind: LinkKind::Symlink,
inode: inode_of(meta),
kind: FileKind::Dir,
rdev: None,
uid: uid_of(meta),
gid: gid_of(meta),
atime_sec: atime_secs(meta),
atime_nsec: atime_nsecs(meta),
xattrs: None,
source_path: None,
dereferenced: false,
}
}
fn symlink_entry(
rel: String,
target: String,
kind: LinkKind,
lmeta: Option<&std::fs::Metadata>,
) -> FileEntry {
FileEntry {
relative_path: rel,
size: 0,
mode: 0,
mtime_sec: lmeta.map_or(0, mtime_secs),
mtime_nsec: lmeta.map_or(0, mtime_nsecs),
file_hash: None,
is_dir: false,
link_target: Some(target),
link_kind: kind,
inode: None,
kind: FileKind::Symlink,
rdev: None,
uid: lmeta.and_then(uid_of),
gid: lmeta.and_then(gid_of),
atime_sec: lmeta.map_or(0, atime_secs),
atime_nsec: lmeta.map_or(0, atime_nsecs),
xattrs: None,
source_path: None,
dereferenced: false,
}
}
fn special_entry(rel: String, meta: &std::fs::Metadata, kind: FileKind) -> FileEntry {
FileEntry {
relative_path: rel,
size: 0,
mode: mode_from_meta(meta),
mtime_sec: mtime_secs(meta),
mtime_nsec: mtime_nsecs(meta),
file_hash: None,
is_dir: false,
link_target: None,
link_kind: LinkKind::Symlink,
inode: inode_of(meta),
kind,
rdev: rdev_of(meta),
uid: uid_of(meta),
gid: gid_of(meta),
atime_sec: atime_secs(meta),
atime_nsec: atime_nsecs(meta),
xattrs: None,
source_path: None,
dereferenced: false,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn scan_empty_dir() {
let dir = tempfile::tempdir().unwrap();
let manifest = Scanner::new(ScanOptions::default())
.scan(dir.path())
.await
.unwrap();
assert!(manifest.is_empty());
assert_eq!(manifest.len(), 0);
}
#[tokio::test]
async fn scan_files_and_nested() {
let dir = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("a.txt"), b"aaa")
.await
.unwrap();
tokio::fs::create_dir(dir.path().join("sub")).await.unwrap();
tokio::fs::write(dir.path().join("sub/b.txt"), b"bbbb")
.await
.unwrap();
let manifest = Scanner::new(ScanOptions::default())
.scan(dir.path())
.await
.unwrap();
assert_eq!(manifest.len(), 3);
assert_eq!(manifest.total_bytes, 7);
assert_eq!(manifest.files[0].relative_path, "a.txt");
assert_eq!(manifest.files[0].size, 3);
assert!(!manifest.files[0].is_dir);
assert_eq!(manifest.files[1].relative_path, "sub");
assert!(manifest.files[1].is_dir);
assert_eq!(manifest.files[2].relative_path, "sub/b.txt");
assert_eq!(manifest.files[2].size, 4);
}
#[test]
fn include_root_component_helper() {
assert!(include_root_component("dir"));
assert!(include_root_component("./dir"));
assert!(include_root_component("/abs/dir"));
assert!(include_root_component("C:\\path\\dir"));
assert!(include_root_component("user@host:backup"));
assert!(!include_root_component("dir/"));
assert!(!include_root_component("dir\\"));
assert!(!include_root_component(""));
assert!(!include_root_component("."));
assert!(!include_root_component("dir/."));
assert!(!include_root_component("dir/.."));
assert!(!include_root_component("/"));
}
#[tokio::test]
async fn scan_include_root_component_prefixes_entries() {
let dir = tempfile::tempdir().unwrap();
let name = dir.path().file_name().unwrap().to_string_lossy().into_owned();
tokio::fs::write(dir.path().join("a.txt"), b"aaa")
.await
.unwrap();
tokio::fs::create_dir(dir.path().join("sub")).await.unwrap();
tokio::fs::write(dir.path().join("sub/b.txt"), b"bbbb")
.await
.unwrap();
let manifest = Scanner::new(ScanOptions {
include_root_component: true,
..ScanOptions::default()
})
.scan(dir.path())
.await
.unwrap();
let canon_dir = dir.path().canonicalize().unwrap();
assert_eq!(manifest.root, canon_dir.parent().unwrap().to_path_buf());
assert!(manifest
.files
.iter()
.any(|f| f.relative_path == format!("{name}/a.txt")));
assert!(manifest
.files
.iter()
.any(|f| f.relative_path == format!("{name}/sub/b.txt")));
assert!(manifest
.files
.iter()
.all(|f| f.relative_path.starts_with(&format!("{name}/"))));
}
#[tokio::test]
async fn scan_with_hash() {
let dir = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("a.txt"), b"hello")
.await
.unwrap();
let manifest = Scanner::new(ScanOptions {
hash: true,
hash_workers: 2,
filter: None,
..ScanOptions::default()
})
.scan(dir.path())
.await
.unwrap();
assert_eq!(manifest.len(), 1);
let hash = manifest.files[0].file_hash.unwrap();
assert_eq!(hash, *blake3::hash(b"hello").as_bytes());
}
#[tokio::test]
async fn scan_single_file() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("single.txt");
tokio::fs::write(&file, b"xyz").await.unwrap();
let manifest = Scanner::new(ScanOptions::default())
.scan(&file)
.await
.unwrap();
assert_eq!(manifest.len(), 1);
assert_eq!(manifest.files[0].relative_path, "single.txt");
}
#[tokio::test]
async fn scan_single_file_with_hash() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("single.bin");
tokio::fs::write(&file, b"hello").await.unwrap();
let manifest = Scanner::new(ScanOptions {
hash: true,
hash_workers: 2,
filter: None,
..ScanOptions::default()
})
.scan(&file)
.await
.unwrap();
assert_eq!(manifest.len(), 1);
assert_eq!(
manifest.files[0].file_hash,
Some(*blake3::hash(b"hello").as_bytes())
);
}
#[tokio::test]
async fn scan_applies_filter() {
let dir = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("a.tmp"), b"x")
.await
.unwrap();
tokio::fs::write(dir.path().join("b.txt"), b"y")
.await
.unwrap();
tokio::fs::create_dir(dir.path().join("node_modules"))
.await
.unwrap();
tokio::fs::write(dir.path().join("node_modules/pkg.js"), b"z")
.await
.unwrap();
let filter = Some(crate::sync::FilterSet {
excludes: vec!["*.tmp".to_string(), "node_modules".to_string()],
includes: vec![],
});
let manifest = Scanner::new(ScanOptions {
hash: false,
hash_workers: 1,
filter,
..ScanOptions::default()
})
.scan(dir.path())
.await
.unwrap();
assert_eq!(manifest.len(), 1);
assert_eq!(manifest.files[0].relative_path, "b.txt");
}
#[cfg(unix)]
#[tokio::test]
async fn scan_symlink_records_target() {
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("target.txt"), b"data")
.await
.unwrap();
symlink("target.txt", dir.path().join("link.txt")).unwrap();
let manifest = Scanner::new(ScanOptions::default())
.scan(dir.path())
.await
.unwrap();
let link = manifest
.files
.iter()
.find(|f| f.relative_path == "link.txt")
.unwrap();
assert_eq!(link.link_target.as_deref(), Some("target.txt"));
assert!(!link.is_dir);
assert_eq!(link.size, 0);
let target = manifest
.files
.iter()
.find(|f| f.relative_path == "target.txt")
.unwrap();
assert!(target.link_target.is_none());
assert_eq!(target.size, 4);
}
#[cfg(unix)]
#[tokio::test]
async fn scan_hardlinks_share_inode() {
let dir = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("orig.txt"), b"same content")
.await
.unwrap();
std::fs::hard_link(dir.path().join("orig.txt"), dir.path().join("dup.txt")).unwrap();
let manifest = Scanner::new(ScanOptions::default())
.scan(dir.path())
.await
.unwrap();
let orig = manifest
.files
.iter()
.find(|f| f.relative_path == "orig.txt")
.unwrap();
let dup = manifest
.files
.iter()
.find(|f| f.relative_path == "dup.txt")
.unwrap();
assert!(orig.inode.is_some());
assert_eq!(orig.inode, dup.inode);
}
#[cfg(unix)]
#[tokio::test]
async fn scan_self_loop_link_skipped() {
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("a.txt"), b"x")
.await
.unwrap();
symlink("l", dir.path().join("l")).unwrap();
tokio::fs::create_dir(dir.path().join("sub")).await.unwrap();
symlink("../sub/l", dir.path().join("sub/l")).unwrap();
let manifest = Scanner::new(ScanOptions::default())
.scan(dir.path())
.await
.unwrap();
assert!(
manifest
.files
.iter()
.all(|f| f.relative_path != "l" && f.relative_path != "sub/l"),
"self-looping links must not appear as entries"
);
assert!(manifest.skipped.contains(&"l".to_string()));
assert!(manifest.skipped.contains(&"sub/l".to_string()));
let rels: Vec<&str> = manifest
.files
.iter()
.map(|f| f.relative_path.as_str())
.collect();
assert_eq!(rels, vec!["a.txt", "sub"]);
}
#[cfg(unix)]
#[tokio::test]
async fn scan_captures_owner_and_nsec_mtime() {
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::MetadataExt;
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("a.txt");
tokio::fs::write(&file, b"x").await.unwrap();
let c = std::ffi::CString::new(file.as_os_str().as_bytes()).unwrap();
let times = [
libc::timespec {
tv_sec: 1_600_000_000,
tv_nsec: 123_456_789,
},
libc::timespec {
tv_sec: 1_600_000_000,
tv_nsec: 123_456_789,
},
];
assert_eq!(
unsafe { libc::utimensat(libc::AT_FDCWD, c.as_ptr(), times.as_ptr(), 0) },
0
);
let manifest = Scanner::new(ScanOptions::default())
.scan(dir.path())
.await
.unwrap();
let entry = &manifest.files[0];
let meta = std::fs::metadata(&file).unwrap();
assert_eq!(entry.uid, Some(meta.uid()), "owner uid is captured");
assert_eq!(entry.gid, Some(meta.gid()), "owner gid is captured");
assert_eq!(entry.mtime_sec, 1_600_000_000);
assert_eq!(entry.mtime_nsec, 123_456_789, "nsec remainder is captured");
assert_eq!(
entry.atime_sec, 1_600_000_000,
"the atime is always captured (restored only under -U)"
);
assert_eq!(entry.atime_nsec, 123_456_789);
}
#[cfg(unix)]
#[tokio::test]
async fn scan_captures_xattrs_when_enabled() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("a.txt");
tokio::fs::write(&file, b"x").await.unwrap();
crate::platform::fs::apply_xattrs(&file, &[("user.cp2_scan".to_string(), b"v".to_vec())])
.expect("set the source xattr");
let manifest = Scanner::new(ScanOptions::default())
.scan(dir.path())
.await
.unwrap();
assert_eq!(manifest.files[0].xattrs, None, "-X off carries nothing");
let manifest = Scanner::new(ScanOptions {
xattrs: true,
..ScanOptions::default()
})
.scan(dir.path())
.await
.unwrap();
let xattrs = manifest.files[0].xattrs.as_deref().unwrap();
let (_, v) = xattrs
.iter()
.find(|(n, _)| n == "user.cp2_scan")
.expect("the set attribute is collected");
assert_eq!(v, b"v");
}
#[tokio::test]
async fn scan_multi_merges_roots_under_base() {
let dir = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("a.txt"), b"aaa")
.await
.unwrap();
tokio::fs::create_dir(dir.path().join("sub")).await.unwrap();
tokio::fs::write(dir.path().join("sub/b.txt"), b"bbbb")
.await
.unwrap();
tokio::fs::create_dir(dir.path().join("empty")).await.unwrap();
let roots = vec![
dir.path().join("a.txt"),
dir.path().join("sub"),
dir.path().join("empty"),
];
let manifest = Scanner::new(ScanOptions::default())
.scan_multi(dir.path(), &roots)
.await
.unwrap();
let rels: Vec<&str> = manifest
.files
.iter()
.map(|f| f.relative_path.as_str())
.collect();
assert_eq!(rels, vec!["a.txt", "empty", "sub", "sub/b.txt"]);
assert_eq!(manifest.total_bytes, 7);
assert!(
manifest
.files
.iter()
.find(|f| f.relative_path == "empty")
.unwrap()
.is_dir
);
assert!(
manifest
.files
.iter()
.find(|f| f.relative_path == "sub")
.unwrap()
.is_dir
);
}
#[tokio::test]
async fn scan_multi_drops_whole_matches_the_filter_rejects() {
let dir = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("keep.txt"), b"k")
.await
.unwrap();
tokio::fs::write(dir.path().join("skip.tmp"), b"s")
.await
.unwrap();
let filter = Some(crate::sync::FilterSet {
excludes: vec!["*.tmp".to_string()],
includes: vec![],
});
let roots = vec![dir.path().join("keep.txt"), dir.path().join("skip.tmp")];
let manifest = Scanner::new(ScanOptions {
hash: false,
hash_workers: 1,
filter,
..ScanOptions::default()
})
.scan_multi(dir.path(), &roots)
.await
.unwrap();
let rels: Vec<&str> = manifest
.files
.iter()
.map(|f| f.relative_path.as_str())
.collect();
assert_eq!(rels, vec!["keep.txt"]);
}
#[tokio::test]
async fn scan_multi_rebases_deep_matches() {
let dir = tempfile::tempdir().unwrap();
tokio::fs::create_dir(dir.path().join("a")).await.unwrap();
tokio::fs::write(dir.path().join("a/x.rs"), b"1")
.await
.unwrap();
tokio::fs::write(dir.path().join("x.rs"), b"2").await.unwrap();
let roots = vec![dir.path().join("a/x.rs"), dir.path().join("x.rs")];
let manifest = Scanner::new(ScanOptions::default())
.scan_multi(dir.path(), &roots)
.await
.unwrap();
let rels: Vec<&str> = manifest
.files
.iter()
.map(|f| f.relative_path.as_str())
.collect();
assert_eq!(rels, vec!["a/x.rs", "x.rs"]);
}
#[cfg(unix)]
#[tokio::test]
async fn scan_multi_keeps_symlink_match_as_link() {
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("real.txt"), b"data")
.await
.unwrap();
symlink("real.txt", dir.path().join("link.txt")).unwrap();
let roots = vec![dir.path().join("link.txt")];
let manifest = Scanner::new(ScanOptions::default())
.scan_multi(dir.path(), &roots)
.await
.unwrap();
assert_eq!(manifest.len(), 1);
let link = &manifest.files[0];
assert_eq!(link.relative_path, "link.txt");
assert_eq!(link.link_target.as_deref(), Some("real.txt"));
assert!(!link.is_dir);
}
#[tokio::test]
async fn scan_multi_dedupes_overlapping_roots() {
let dir = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("a.txt"), b"a")
.await
.unwrap();
tokio::fs::create_dir(dir.path().join("sub")).await.unwrap();
tokio::fs::write(dir.path().join("sub/b.txt"), b"b")
.await
.unwrap();
let roots = vec![
dir.path().join("sub"),
dir.path().join("sub/b.txt"),
dir.path().join("a.txt"),
dir.path().join("a.txt"),
];
let manifest = Scanner::new(ScanOptions::default())
.scan_multi(dir.path(), &roots)
.await
.unwrap();
let rels: Vec<&str> = manifest
.files
.iter()
.map(|f| f.relative_path.as_str())
.collect();
assert_eq!(rels, vec!["a.txt", "sub", "sub/b.txt"]);
}
#[cfg(unix)]
#[tokio::test]
async fn scan_records_specials() {
use std::os::unix::ffi::OsStrExt;
let dir = tempfile::tempdir().unwrap();
let pipe = dir.path().join("pipe");
let c = std::ffi::CString::new(pipe.as_os_str().as_bytes()).unwrap();
assert_eq!(unsafe { libc::mkfifo(c.as_ptr(), 0o640) }, 0);
tokio::fs::write(dir.path().join("a.txt"), b"x")
.await
.unwrap();
let manifest = Scanner::new(ScanOptions::default())
.scan(dir.path())
.await
.unwrap();
let pipe_entry = manifest
.files
.iter()
.find(|f| f.relative_path == "pipe")
.unwrap();
assert_eq!(pipe_entry.kind, crate::protocol::FileKind::Fifo);
assert_eq!(pipe_entry.size, 0);
let file_entry = manifest
.files
.iter()
.find(|f| f.relative_path == "a.txt")
.unwrap();
assert_eq!(file_entry.kind, crate::protocol::FileKind::File);
}
async fn source_with(files: &[(&str, &[u8])], dirs: &[&str]) -> Manifest {
let dir = tempfile::tempdir().unwrap();
for name in dirs {
tokio::fs::create_dir(dir.path().join(name)).await.unwrap();
}
for (name, content) in files {
tokio::fs::write(dir.path().join(name), content)
.await
.unwrap();
}
Scanner::new(ScanOptions::default())
.scan(dir.path())
.await
.unwrap()
}
#[tokio::test]
async fn scan_targeted_probes_only_source_paths() {
let dest = tempfile::tempdir().unwrap();
tokio::fs::write(dest.path().join("a.txt"), b"aaa")
.await
.unwrap();
tokio::fs::write(dest.path().join("decoy.txt"), b"decoy")
.await
.unwrap();
tokio::fs::create_dir(dest.path().join("sub")).await.unwrap();
tokio::fs::write(dest.path().join("sub/b.txt"), b"bbbb")
.await
.unwrap();
tokio::fs::write(dest.path().join("sub/extra.txt"), b"extra")
.await
.unwrap();
tokio::fs::create_dir(dest.path().join("untouched"))
.await
.unwrap();
tokio::fs::write(dest.path().join("untouched/deep.txt"), b"deep")
.await
.unwrap();
let source = source_with(&[("a.txt", b"aaa"), ("sub/b.txt", b"bbbb")], &["sub"]).await;
let manifest = Scanner::new(ScanOptions::default())
.scan_targeted(dest.path(), &source)
.await
.unwrap();
let rels: Vec<&str> = manifest
.files
.iter()
.map(|f| f.relative_path.as_str())
.collect();
assert_eq!(rels, vec!["a.txt", "sub", "sub/b.txt"]);
assert_eq!(manifest.files[0].size, 3);
assert!(!manifest.files[0].is_dir);
assert_eq!(manifest.files[2].size, 4);
assert_eq!(manifest.total_bytes, 7);
}
#[tokio::test]
async fn scan_targeted_prunes_absent_subtrees() {
let dest = tempfile::tempdir().unwrap();
tokio::fs::write(dest.path().join("keep.txt"), b"k")
.await
.unwrap();
let source = source_with(&[("keep.txt", b"k"), ("gone/x.txt", b"x")], &["gone"]).await;
let manifest = Scanner::new(ScanOptions::default())
.scan_targeted(dest.path(), &source)
.await
.unwrap();
let rels: Vec<&str> = manifest
.files
.iter()
.map(|f| f.relative_path.as_str())
.collect();
assert_eq!(rels, vec!["keep.txt"]);
}
#[tokio::test]
async fn scan_targeted_records_type_mismatches() {
let dest = tempfile::tempdir().unwrap();
tokio::fs::create_dir(dest.path().join("x")).await.unwrap();
tokio::fs::write(dest.path().join("y"), b"file").await.unwrap();
let source = source_with(&[("x", b"data")], &["y"]).await;
let manifest = Scanner::new(ScanOptions::default())
.scan_targeted(dest.path(), &source)
.await
.unwrap();
assert_eq!(manifest.len(), 2);
let x = manifest
.files
.iter()
.find(|f| f.relative_path == "x")
.unwrap();
assert!(x.is_dir, "dest has a dir where the source has a file");
let y = manifest
.files
.iter()
.find(|f| f.relative_path == "y")
.unwrap();
assert!(!y.is_dir, "dest has a file where the source has a dir");
assert_eq!(y.size, 4);
}
#[tokio::test]
async fn scan_targeted_empty_source_yields_empty_manifest() {
let dest = tempfile::tempdir().unwrap();
tokio::fs::write(dest.path().join("only-in-dest.txt"), b"x")
.await
.unwrap();
let source = source_with(&[], &[]).await;
let manifest = Scanner::new(ScanOptions::default())
.scan_targeted(dest.path(), &source)
.await
.unwrap();
assert!(manifest.is_empty());
}
#[tokio::test]
async fn scan_targeted_hashes_matched_files() {
let dest = tempfile::tempdir().unwrap();
tokio::fs::write(dest.path().join("a.txt"), b"hello")
.await
.unwrap();
tokio::fs::write(dest.path().join("decoy.txt"), b"ignored")
.await
.unwrap();
let source = source_with(&[("a.txt", b"hello")], &[]).await;
let manifest = Scanner::new(ScanOptions {
hash: true,
hash_workers: 2,
filter: None,
..ScanOptions::default()
})
.scan_targeted(dest.path(), &source)
.await
.unwrap();
assert_eq!(manifest.len(), 1);
assert_eq!(
manifest.files[0].file_hash,
Some(*blake3::hash(b"hello").as_bytes())
);
}
#[cfg(unix)]
#[tokio::test]
async fn scan_targeted_symlink_preserve_records_target() {
use std::os::unix::fs::symlink;
let dest = tempfile::tempdir().unwrap();
tokio::fs::write(dest.path().join("target.txt"), b"data")
.await
.unwrap();
symlink("target.txt", dest.path().join("link.txt")).unwrap();
let source = {
let s = tempfile::tempdir().unwrap();
tokio::fs::write(s.path().join("target.txt"), b"data")
.await
.unwrap();
symlink("target.txt", s.path().join("link.txt")).unwrap();
Scanner::new(ScanOptions::default())
.scan(s.path())
.await
.unwrap()
};
let manifest = Scanner::new(ScanOptions::default())
.scan_targeted(dest.path(), &source)
.await
.unwrap();
let link = manifest
.files
.iter()
.find(|f| f.relative_path == "link.txt")
.unwrap();
assert_eq!(link.link_target.as_deref(), Some("target.txt"));
assert!(!link.is_dir);
}
#[cfg(unix)]
#[tokio::test]
async fn scan_targeted_records_links_faithfully_under_follow() {
use std::os::unix::fs::symlink;
let dest = tempfile::tempdir().unwrap();
tokio::fs::write(dest.path().join("target.txt"), b"12345")
.await
.unwrap();
symlink("target.txt", dest.path().join("link.txt")).unwrap();
let source = {
let s = tempfile::tempdir().unwrap();
tokio::fs::write(s.path().join("target.txt"), b"12345")
.await
.unwrap();
symlink("target.txt", s.path().join("link.txt")).unwrap();
Scanner::new(ScanOptions {
follow_links: true,
..ScanOptions::default()
})
.scan(s.path())
.await
.unwrap()
};
let src_link = source
.files
.iter()
.find(|f| f.relative_path == "link.txt")
.unwrap();
assert!(
src_link.link_target.is_none(),
"the source scan dereferences under --follow-links"
);
let manifest = Scanner::new(ScanOptions::default())
.scan_targeted(dest.path(), &source)
.await
.unwrap();
let link = manifest
.files
.iter()
.find(|f| f.relative_path == "link.txt")
.unwrap();
assert_eq!(link.link_target.as_deref(), Some("target.txt"));
assert!(!link.is_dir);
assert_eq!(link.size, 0);
}
#[cfg(unix)]
#[tokio::test]
async fn scan_internal_link_to_windows_target_emits_lnk_kind() {
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("target.txt"), b"x")
.await
.unwrap();
symlink("target.txt", dir.path().join("link.txt")).unwrap();
let manifest = Scanner::new(ScanOptions {
target_os: TargetOs::Windows,
..ScanOptions::default()
})
.scan(dir.path())
.await
.unwrap();
let link = manifest
.files
.iter()
.find(|f| f.relative_path == "link.txt")
.unwrap();
assert_eq!(link.link_kind, LinkKind::Lnk);
assert_eq!(link.link_target.as_deref(), Some("target.txt"));
}
fn write_lnk_fixture(path: &Path, target: &str) {
let mut link = lnk::ShellLink::default().with_encoding(&lnk::StringEncoding::Unicode);
link.set_relative_path(Some(target.to_string()));
link.save(path).expect("write .lnk fixture");
}
#[test]
fn lnk_fixture_roundtrips_through_extract() {
let dir = tempfile::tempdir().unwrap();
let lnk_path = dir.path().join("shortcut.lnk");
write_lnk_fixture(&lnk_path, r"..\sub\target.txt");
let bytes = std::fs::read(&lnk_path).unwrap();
assert!(crate::sync::linkpolicy::is_lnk_magic(&bytes));
assert_eq!(
extract_lnk_target(&lnk_path).as_deref(),
Some(r"..\sub\target.txt"),
"the relative path must survive the write→parse roundtrip"
);
}
#[tokio::test]
async fn scan_lnk_internal_target_becomes_link_entry() {
let dir = tempfile::tempdir().unwrap();
tokio::fs::create_dir(dir.path().join("sub")).await.unwrap();
tokio::fs::write(dir.path().join("sub/target.txt"), b"x")
.await
.unwrap();
write_lnk_fixture(&dir.path().join("shortcut.lnk"), r"sub\target.txt");
let manifest = Scanner::new(ScanOptions {
source_os: TargetOs::Windows,
..ScanOptions::default()
})
.scan(dir.path())
.await
.unwrap();
let link = manifest
.files
.iter()
.find(|f| f.relative_path == "shortcut.lnk")
.unwrap();
assert!(
link.link_target.is_some(),
"an internal .lnk must become a link entry"
);
assert_eq!(link.link_target.as_deref(), Some("sub/target.txt"));
assert_eq!(link.size, 0);
}
#[tokio::test]
async fn follow_links_dereferences_lnk_file_targets() {
let dir = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("target.txt"), b"payload")
.await
.unwrap();
write_lnk_fixture(&dir.path().join("shortcut.lnk"), r"target.txt");
let manifest = Scanner::new(ScanOptions {
follow_links: true,
source_os: TargetOs::Windows,
..ScanOptions::default()
})
.scan(dir.path())
.await
.unwrap();
let entry = manifest
.files
.iter()
.find(|f| f.relative_path == "shortcut.lnk")
.unwrap();
assert!(
entry.link_target.is_none(),
"a dereferenced .lnk is a regular file"
);
assert_eq!(entry.size, 7);
assert!(entry.dereferenced, "the target is not ours to remove");
assert_eq!(
entry.source_path.as_ref().map(|p| p.canonicalize().unwrap()),
Some(dir.path().join("target.txt").canonicalize().unwrap()),
"content is read from the target, not the .lnk body"
);
}
#[tokio::test]
async fn skip_links_skips_lnk_shortcuts() {
let dir = tempfile::tempdir().unwrap();
write_lnk_fixture(&dir.path().join("shortcut.lnk"), r"target.txt");
let manifest = Scanner::new(ScanOptions {
preserve_links: false,
source_os: TargetOs::Windows,
..ScanOptions::default()
})
.scan(dir.path())
.await
.unwrap();
assert!(
manifest.files.iter().all(|f| f.relative_path != "shortcut.lnk"),
"a skipped .lnk is not part of the transfer"
);
assert!(
manifest.skipped.iter().any(|p| p == "shortcut.lnk"),
"the skipped shortcut is recorded for --delete protection"
);
}
#[cfg(unix)]
#[tokio::test]
async fn scan_targeted_recognizes_extensionless_lnk_when_source_says_link() {
use std::os::unix::fs::symlink;
let dest = tempfile::tempdir().unwrap();
tokio::fs::create_dir(dest.path().join("sub")).await.unwrap();
tokio::fs::write(dest.path().join("sub/t.txt"), b"x")
.await
.unwrap();
tokio::fs::create_dir(dest.path().join("links")).await.unwrap();
write_lnk_fixture(&dest.path().join("links/l"), r"..\sub\t.txt");
let src = tempfile::tempdir().unwrap();
tokio::fs::create_dir(src.path().join("sub")).await.unwrap();
tokio::fs::write(src.path().join("sub/t.txt"), b"x")
.await
.unwrap();
tokio::fs::create_dir(src.path().join("links")).await.unwrap();
symlink("../sub/t.txt", src.path().join("links/l")).unwrap();
let source = Scanner::new(ScanOptions {
target_os: TargetOs::Windows,
..ScanOptions::default()
})
.scan(src.path())
.await
.unwrap();
let src_link = source
.files
.iter()
.find(|f| f.relative_path == "links/l")
.unwrap();
assert!(src_link.link_target.is_some());
let manifest = Scanner::new(ScanOptions {
source_os: TargetOs::Windows,
..ScanOptions::default()
})
.scan_targeted(dest.path(), &source)
.await
.unwrap();
let probe_link = manifest
.files
.iter()
.find(|f| f.relative_path == "links/l")
.unwrap();
assert!(
probe_link.link_target.is_some(),
"an extensionless .lnk must be recognized on the destination probe"
);
assert_eq!(
probe_link.link_target, src_link.link_target,
"the probe and the source must rewrite the target identically"
);
assert_eq!(probe_link.size, 0);
}
#[tokio::test]
async fn full_walk_dest_scan_recognizes_extensionless_lnk_from_source_key() {
let dest = tempfile::tempdir().unwrap();
tokio::fs::create_dir(dest.path().join("sub")).await.unwrap();
tokio::fs::write(dest.path().join("sub/t.txt"), b"x")
.await
.unwrap();
tokio::fs::create_dir(dest.path().join("links")).await.unwrap();
write_lnk_fixture(&dest.path().join("links/l"), r"..\sub\t.txt");
let manifest = Scanner::new(ScanOptions {
source_os: TargetOs::Windows,
is_source_scan: false,
source_link_paths: Some(["links/l".to_string()].into_iter().collect()),
..ScanOptions::default()
})
.scan(dest.path())
.await
.unwrap();
let link = manifest
.files
.iter()
.find(|f| f.relative_path == "links/l")
.unwrap();
assert!(link.link_target.is_some());
let file = manifest
.files
.iter()
.find(|f| f.relative_path == "sub/t.txt")
.unwrap();
assert!(file.link_target.is_none(), "a data file is never sniffed");
}
#[cfg(unix)]
#[tokio::test]
async fn literal_scan_keeps_literal_targets_and_all_links() {
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("real.txt"), b"x")
.await
.unwrap();
tokio::fs::create_dir(dir.path().join("links")).await.unwrap();
let abs_target = dir.path().join("real.txt");
symlink(&abs_target, dir.path().join("links/l_abs")).unwrap();
let ext = tempfile::tempdir().unwrap();
symlink(ext.path(), dir.path().join("links/l_ext_dir")).unwrap();
symlink("l_loop", dir.path().join("links/l_loop")).unwrap();
let manifest = Scanner::new(ScanOptions {
literal_links: true,
..ScanOptions::default()
})
.scan(dir.path())
.await
.unwrap();
let l_abs = manifest
.files
.iter()
.find(|f| f.relative_path == "links/l_abs")
.unwrap();
assert_eq!(
l_abs.link_target.as_deref(),
Some(abs_target.to_str().unwrap()),
"an internal link keeps its literal absolute target under --literal-links"
);
assert_eq!(l_abs.link_kind, LinkKind::Symlink);
let l_ext = manifest
.files
.iter()
.find(|f| f.relative_path == "links/l_ext_dir")
.unwrap();
assert!(
l_ext.link_target.is_some(),
"an external directory link is kept as a link under --literal-links"
);
let l_loop = manifest
.files
.iter()
.find(|f| f.relative_path == "links/l_loop")
.unwrap();
assert_eq!(
l_loop.link_target.as_deref(),
Some("l_loop"),
"a self-referential link is kept as-is under --literal-links"
);
assert!(
manifest.skipped.is_empty(),
"--literal-links never skips a link"
);
}
#[cfg(unix)]
#[tokio::test]
async fn literal_internal_links_keeps_only_internal_target() {
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
let ext = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("real.txt"), b"x")
.await
.unwrap();
tokio::fs::write(ext.path().join("e.txt"), b"y")
.await
.unwrap();
let abs_target = dir.path().join("real.txt");
symlink(&abs_target, dir.path().join("l_internal")).unwrap();
symlink(ext.path().join("e.txt"), dir.path().join("l_ext_file")).unwrap();
let manifest = Scanner::new(ScanOptions {
literal_internal_links: true,
..ScanOptions::default()
})
.scan(dir.path())
.await
.unwrap();
let internal = manifest
.files
.iter()
.find(|f| f.relative_path == "l_internal")
.unwrap();
assert_eq!(
internal.link_target.as_deref(),
Some(abs_target.to_str().unwrap()),
"--literal-internal-links keeps the internal link's literal target"
);
let ext_file = manifest
.files
.iter()
.find(|f| f.relative_path == "l_ext_file")
.unwrap();
assert!(
ext_file.link_target.is_none(),
"the external file link is still dereferenced (default policy)"
);
}
#[cfg(unix)]
#[tokio::test]
async fn literal_external_file_links_keeps_external_file_target() {
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
let ext = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("real.txt"), b"x")
.await
.unwrap();
tokio::fs::write(ext.path().join("e.txt"), b"y")
.await
.unwrap();
symlink("real.txt", dir.path().join("l_internal")).unwrap();
let abs_ext = ext.path().join("e.txt");
symlink(&abs_ext, dir.path().join("l_ext_file")).unwrap();
let manifest = Scanner::new(ScanOptions {
literal_external_file_links: true,
..ScanOptions::default()
})
.scan(dir.path())
.await
.unwrap();
let ext_file = manifest
.files
.iter()
.find(|f| f.relative_path == "l_ext_file")
.unwrap();
assert_eq!(
ext_file.link_target.as_deref(),
Some(abs_ext.to_str().unwrap()),
"--literal-external-file-links keeps the literal absolute target"
);
let internal = manifest
.files
.iter()
.find(|f| f.relative_path == "l_internal")
.unwrap();
assert_eq!(
internal.link_target.as_deref(),
Some("real.txt"),
"internal links are still rewritten/kept per the default policy"
);
}
#[cfg(unix)]
#[tokio::test]
async fn literal_external_dir_links_keeps_external_dir_link() {
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
let ext = tempfile::tempdir().unwrap();
tokio::fs::write(ext.path().join("inner.txt"), b"y")
.await
.unwrap();
let abs_ext = ext.path();
symlink(abs_ext, dir.path().join("l_ext_dir")).unwrap();
let manifest = Scanner::new(ScanOptions {
literal_external_dir_links: true,
..ScanOptions::default()
})
.scan(dir.path())
.await
.unwrap();
let ext_dir = manifest
.files
.iter()
.find(|f| f.relative_path == "l_ext_dir")
.unwrap();
assert_eq!(
ext_dir.link_target.as_deref(),
Some(abs_ext.to_str().unwrap()),
"--literal-external-dir-links keeps the external directory link"
);
assert!(
manifest.skipped.is_empty(),
"no skip is recorded for a kept external directory link"
);
}
#[cfg(unix)]
#[tokio::test]
async fn follow_links_dereferences_everything() {
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
let ext = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("real.txt"), b"x")
.await
.unwrap();
tokio::fs::write(ext.path().join("inner.txt"), b"y")
.await
.unwrap();
symlink("real.txt", dir.path().join("l_internal")).unwrap();
symlink(ext.path(), dir.path().join("l_ext_dir")).unwrap();
let manifest = Scanner::new(ScanOptions {
follow_links: true,
..ScanOptions::default()
})
.scan(dir.path())
.await
.unwrap();
let internal = manifest
.files
.iter()
.find(|f| f.relative_path == "l_internal")
.unwrap();
assert!(
internal.link_target.is_none(),
"--follow-links dereferences the internal link into a file"
);
assert_eq!(internal.size, 1);
let recursed = manifest
.files
.iter()
.find(|f| f.relative_path == "l_ext_dir/inner.txt")
.unwrap();
assert!(
recursed.dereferenced,
"the recursed entry lives outside the root and is marked"
);
}
#[cfg(unix)]
#[tokio::test]
async fn skip_links_skips_all_links() {
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("real.txt"), b"x")
.await
.unwrap();
symlink("real.txt", dir.path().join("l_file")).unwrap();
symlink("real.txt", dir.path().join("l_file2")).unwrap();
let manifest = Scanner::new(ScanOptions {
preserve_links: false,
..ScanOptions::default()
})
.scan(dir.path())
.await
.unwrap();
assert!(
manifest.files.iter().all(|f| f.link_target.is_none()),
"--skip-links keeps no link in the transfer list"
);
assert_eq!(manifest.skipped.len(), 2, "every link is recorded as skipped");
}
#[tokio::test]
async fn literal_windows_source_lnk_copied_as_opaque_data() {
let dir = tempfile::tempdir().unwrap();
write_lnk_fixture(&dir.path().join("shortcut.lnk"), r"target.txt");
let manifest = Scanner::new(ScanOptions {
source_os: TargetOs::Windows,
literal_links: true,
..ScanOptions::default()
})
.scan(dir.path())
.await
.unwrap();
let entry = manifest
.files
.iter()
.find(|f| f.relative_path == "shortcut.lnk")
.unwrap();
assert!(
entry.link_target.is_none(),
"a literal .lnk is a regular file, not a link entry"
);
assert!(
entry.size > 0,
"the shortcut body is copied verbatim"
);
}
#[cfg(unix)]
#[tokio::test]
async fn literal_dest_probe_records_literal_lnk_target() {
use std::os::unix::fs::symlink;
let src = tempfile::tempdir().unwrap();
tokio::fs::create_dir(src.path().join("sub")).await.unwrap();
tokio::fs::write(src.path().join("sub/t.txt"), b"x")
.await
.unwrap();
tokio::fs::create_dir(src.path().join("links")).await.unwrap();
symlink("sub/../sub/t.txt", src.path().join("links/l")).unwrap();
let source = Scanner::new(ScanOptions {
target_os: TargetOs::Windows,
literal_links: true,
..ScanOptions::default()
})
.scan(src.path())
.await
.unwrap();
let src_link = source
.files
.iter()
.find(|f| f.relative_path == "links/l")
.unwrap();
assert_eq!(
src_link.link_target.as_deref(),
Some("sub/../sub/t.txt"),
"the source keeps the literal target — no DEST-relative rewrite"
);
let dest = tempfile::tempdir().unwrap();
tokio::fs::create_dir(dest.path().join("sub")).await.unwrap();
tokio::fs::write(dest.path().join("sub/t.txt"), b"x")
.await
.unwrap();
tokio::fs::create_dir(dest.path().join("links")).await.unwrap();
write_lnk_fixture(&dest.path().join("links/l"), r"sub\..\sub\t.txt");
let manifest = Scanner::new(ScanOptions {
source_os: TargetOs::Windows,
literal_links: true,
..ScanOptions::default()
})
.scan_targeted(dest.path(), &source)
.await
.unwrap();
let probe_link = manifest
.files
.iter()
.find(|f| f.relative_path == "links/l")
.unwrap();
assert_eq!(
probe_link.link_target, src_link.link_target,
"the probe must recover the same literal the source recorded"
);
assert_eq!(probe_link.size, 0);
}
#[cfg(unix)]
#[tokio::test]
async fn skip_links_overrides_literal() {
use std::os::unix::fs::symlink;
let dir = tempfile::tempdir().unwrap();
tokio::fs::write(dir.path().join("real.txt"), b"payload")
.await
.unwrap();
symlink("real.txt", dir.path().join("l")).unwrap();
let manifest = Scanner::new(ScanOptions {
preserve_links: false,
literal_links: true,
..ScanOptions::default()
})
.scan(dir.path())
.await
.unwrap();
assert!(
manifest.files.iter().all(|f| f.relative_path != "l"),
"--skip-links skips the link even under --literal-links"
);
assert!(
manifest.skipped.iter().any(|p| p == "l"),
"the skipped link is recorded for --delete protection"
);
}
}