use crate::ArchiveError;
use crate::IoContext;
use crate::Result;
use crate::Skip;
use crate::SkipKind;
use crate::Skips;
use crate::creation::config::CreationConfig;
use crate::creation::filters;
use crate::creation::source::source_error;
use crate::creation::source::walk_error;
use crate::creation::staged::ExcludedOutput;
use crate::pattern::PatternList;
use std::collections::HashMap;
use std::fs::Metadata;
use std::ops::Deref;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use walkdir::WalkDir;
pub(crate) struct FilteredWalker<'a> {
root: &'a Path,
config: &'a CreationConfig,
excluded: &'a ExcludedOutput,
exclude_patterns: PatternList,
}
static NOTHING_EXCLUDED: ExcludedOutput = ExcludedOutput::none();
impl<'a> FilteredWalker<'a> {
#[must_use]
pub(crate) fn new(root: &'a Path, config: &'a CreationConfig) -> Self {
Self {
root,
config,
excluded: &NOTHING_EXCLUDED,
exclude_patterns: filters::exclude_list(config),
}
}
#[must_use]
pub(crate) const fn excluding(mut self, excluded: &'a ExcludedOutput) -> Self {
self.excluded = excluded;
self
}
pub(crate) fn walk(&self) -> impl Iterator<Item = Result<WalkItem>> + '_ {
let mut walker = WalkDir::new(self.root)
.follow_links(self.config.follow_symlinks)
.into_iter();
std::iter::from_fn(move || {
loop {
let entry = match walker.next()? {
Ok(entry) => entry,
Err(e) => return Some(Err(walk_error(e, self.root))),
};
if self.is_hidden_directory(&entry) {
walker.skip_current_dir();
let shown = entry
.path()
.strip_prefix(self.root)
.unwrap_or_else(|_| entry.path());
return Some(Ok(WalkItem::Skipped(Skip::new(SkipKind::Hidden, shown))));
}
if let Some(item) = self.visit(&entry).transpose() {
return Some(item);
}
}
})
}
fn is_hidden_directory(&self, entry: &walkdir::DirEntry) -> bool {
!self.config.include_hidden
&& entry.depth() > 0
&& entry.file_type().is_dir()
&& filters::is_hidden(entry.path())
}
fn visit(&self, entry: &walkdir::DirEntry) -> Result<Option<WalkItem>> {
if self.excluded.excludes(entry.path()) {
return Ok(None);
}
let relative = filters::compute_archive_path(entry.path(), self.root, self.config)?;
match ArchiveEntryName::from_relative(&relative) {
Some(name) => filters::skip_reason(&name, self.config, &self.exclude_patterns)
.map_or_else(
|| self.build_filtered_entry(entry, relative),
|kind| Ok(Some(WalkItem::Skipped(Skip::new(kind, name.to_path_buf())))),
),
None if !self.config.include_hidden && filters::is_hidden(entry.path()) => Ok(None),
None => self.build_filtered_entry(entry, relative),
}
}
fn build_filtered_entry(
&self,
entry: &walkdir::DirEntry,
relative: PathBuf,
) -> Result<Option<WalkItem>> {
let path = entry.path().to_path_buf();
let metadata = entry.metadata().map_err(|e| walk_error(e, &path))?;
let entry_type = if metadata.is_symlink() {
let target = std::fs::read_link(&path).map_err(|e| source_error(&path, e))?;
EntryType::Symlink { target }
} else if metadata.is_dir() {
EntryType::Directory
} else {
EntryType::File
};
let size = get_file_size(&metadata);
if entry_type == EntryType::File && !self.config.max_file_size.admits(size) {
let shown = if relative.is_empty() { path } else { relative };
return Ok(Some(WalkItem::Skipped(Skip::new(
SkipKind::OverMaxFileSize,
shown,
))));
}
let Some(archive_path) = entry_name(&path, &relative, entry_type == EntryType::Directory)?
else {
return Ok(None);
};
Ok(Some(WalkItem::Entry(FilteredEntry {
path,
archive_path,
entry_type,
size,
})))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum WalkItem {
Entry(FilteredEntry),
Skipped(Skip),
}
#[derive(Debug, Default)]
pub(crate) struct Collected {
pub entries: Vec<FilteredEntry>,
pub skipped: Skips,
}
#[derive(Debug, Default)]
struct ClaimedNames(HashMap<PathBuf, PathBuf>);
impl ClaimedNames {
fn claim(&mut self, entry: &FilteredEntry) -> Result<()> {
use std::collections::hash_map::Entry;
match self.0.entry(entry.archive_path.to_path_buf()) {
Entry::Vacant(slot) => {
slot.insert(entry.path.clone());
Ok(())
}
Entry::Occupied(first) => Err(ArchiveError::InvalidConfiguration {
setting: crate::ConfigSetting::SourcePaths,
problem: crate::ConfigProblem::EntryNameCollision {
name: entry.archive_path.display().to_string(),
first: first.get().clone(),
second: entry.path.clone(),
},
}),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ArchiveEntryName(PathBuf);
impl ArchiveEntryName {
#[must_use]
pub(crate) fn from_relative(path: &Path) -> Option<Self> {
let mut components = path.components().peekable();
components.peek()?;
components
.all(|component| matches!(component, Component::Normal(_)))
.then(|| Self(path.to_path_buf()))
}
}
impl Deref for ArchiveEntryName {
type Target = Path;
fn deref(&self) -> &Path {
&self.0
}
}
fn entry_name(path: &Path, relative: &Path, is_dir: bool) -> Result<Option<ArchiveEntryName>> {
match (ArchiveEntryName::from_relative(relative), is_dir) {
(Some(name), _) => Ok(Some(name)),
(None, true) => Ok(None),
(None, false) => Err(ArchiveError::InvalidConfiguration {
setting: crate::ConfigSetting::StripPrefix,
problem: crate::ConfigProblem::RemovesWholeName {
path: path.to_path_buf(),
},
}),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FilteredEntry {
pub path: PathBuf,
pub archive_path: ArchiveEntryName,
pub entry_type: EntryType,
pub size: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum EntryType {
File,
Directory,
Symlink {
target: PathBuf,
},
}
pub(crate) fn collect_entries<P: AsRef<Path>>(
sources: &[P],
config: &CreationConfig,
excluded: &ExcludedOutput,
) -> Result<Collected> {
let mut collected = Collected::default();
let mut names = ClaimedNames::default();
for source in sources {
let path = source.as_ref();
let metadata = path.symlink_metadata().map_err(|e| source_error(path, e))?;
if metadata.is_dir() || (config.follow_symlinks && path.is_dir()) {
let walker = FilteredWalker::new(path, config).excluding(excluded);
for item in walker.walk() {
match item? {
WalkItem::Entry(entry) => {
names.claim(&entry)?;
collected.entries.push(entry);
}
WalkItem::Skipped(skip) => collected.skipped.record(skip)?,
}
}
} else {
let size = if metadata.is_file() {
metadata.len()
} else {
0
};
let entry_type = if metadata.is_symlink() {
let target = std::fs::read_link(path).map_err(|e| source_error(path, e))?;
EntryType::Symlink { target }
} else {
EntryType::File
};
let relative = if let Some(parent) = path.parent() {
filters::compute_archive_path(path, parent, config)?
} else {
path.file_name()
.ok_or_else(|| {
ArchiveError::Io(std::io::Error::other(IoContext::new(
"cannot determine filename for source path",
crate::path_text(path),
)))
})?
.into()
};
if !excluded.excludes(path)
&& let Some(archive_path) = entry_name(path, &relative, false)?
{
let entry = FilteredEntry {
path: path.to_path_buf(),
archive_path,
entry_type,
size,
};
names.claim(&entry)?;
collected.entries.push(entry);
}
}
}
Ok(collected)
}
#[cfg(unix)]
fn get_file_size(metadata: &Metadata) -> u64 {
use std::os::unix::fs::MetadataExt;
metadata.size()
}
#[cfg(not(unix))]
fn get_file_size(metadata: &Metadata) -> u64 {
metadata.len()
}
#[cfg(test)]
#[allow(clippy::unwrap_used)] mod tests {
use super::*;
use crate::pattern::EntryPattern;
use std::assert_matches;
use std::fs;
use tempfile::TempDir;
fn walked_items(walker: &FilteredWalker<'_>) -> Vec<WalkItem> {
walker.walk().collect::<Result<Vec<_>>>().unwrap()
}
fn walked_entries(walker: &FilteredWalker<'_>) -> Vec<FilteredEntry> {
walked_items(walker)
.into_iter()
.filter_map(|item| match item {
WalkItem::Entry(entry) => Some(entry),
WalkItem::Skipped(_) => None,
})
.collect()
}
#[test]
fn test_walker_ignores_patterns_matching_the_ancestors_of_the_root() {
let temp = TempDir::new().unwrap();
let root = temp.path().join("job.tmp").join("src");
fs::create_dir_all(&root).unwrap();
fs::write(root.join("a.txt"), "a").unwrap();
fs::write(root.join("b.rs"), "b").unwrap();
let config = CreationConfig::default();
let collected =
collect_entries(&[root.as_path()], &config, &ExcludedOutput::none()).unwrap();
assert_eq!(collected.entries.len(), 2);
assert!(collected.skipped.is_empty());
}
#[test]
fn test_walker_counts_what_the_filters_leave_out() {
let temp = TempDir::new().unwrap();
let root = temp.path();
fs::write(root.join("keep.txt"), "keep").unwrap();
fs::write(root.join("skip.tmp"), "x").unwrap();
fs::write(root.join(".secret"), "x").unwrap();
fs::write(root.join("big.bin"), "a".repeat(1000)).unwrap();
let config = CreationConfig::default().with_max_file_size(crate::non_zero!(100));
let collected = collect_entries(&[root], &config, &ExcludedOutput::none()).unwrap();
assert_eq!(collected.entries.len(), 1);
assert_eq!(collected.skipped.count(SkipKind::Excluded), 1);
assert_eq!(collected.skipped.count(SkipKind::Hidden), 1);
assert_eq!(collected.skipped.count(SkipKind::OverMaxFileSize), 1);
let mut sample: Vec<_> = collected
.skipped
.sample()
.iter()
.map(|skip| skip.path.clone())
.collect();
sample.sort();
assert_eq!(
sample,
[".secret", "big.bin", "skip.tmp"].map(PathBuf::from)
);
}
#[test]
fn test_walker_path_pattern_excludes_the_subtree_by_archive_path() {
let temp = TempDir::new().unwrap();
let root = temp.path();
fs::create_dir_all(root.join("build/out")).unwrap();
fs::write(root.join("build/out/app"), "bin").unwrap();
fs::write(root.join("build/keep.txt"), "k").unwrap();
let config = CreationConfig::default()
.with_exclude_patterns(vec![EntryPattern::try_from("build/out").unwrap()]);
let collected = collect_entries(&[root], &config, &ExcludedOutput::none()).unwrap();
let paths: Vec<_> = collected
.entries
.iter()
.map(|e| e.archive_path.to_path_buf())
.collect();
assert!(paths.contains(&PathBuf::from("build/keep.txt")));
assert!(!paths.iter().any(|p| p.starts_with("build/out")));
assert_eq!(collected.skipped.count(SkipKind::Excluded), 2);
}
#[test]
fn test_walker_basic_directory() {
let temp = TempDir::new().unwrap();
let root = temp.path();
fs::write(root.join("file1.txt"), "content1").unwrap();
fs::write(root.join("file2.rs"), "content2").unwrap();
fs::create_dir(root.join("subdir")).unwrap();
fs::write(root.join("subdir/file3.txt"), "content3").unwrap();
let config = CreationConfig::default()
.with_include_hidden(true)
.with_exclude_patterns(vec![]);
let walker = FilteredWalker::new(root, &config);
let entries = walked_entries(&walker);
assert_eq!(entries.len(), 4, "expected exactly 4 entries");
let paths: Vec<_> = entries
.iter()
.map(|e| e.archive_path.to_str().unwrap())
.collect();
assert!(paths.iter().any(|p| p.contains("file1.txt")));
assert!(paths.iter().any(|p| p.contains("file2.rs")));
assert!(paths.iter().any(|p| p.contains("subdir")));
assert!(paths.iter().any(|p| p.contains("file3.txt")));
}
#[test]
fn test_walker_skips_hidden_files() {
let temp = TempDir::new().unwrap();
let root = temp.path();
fs::write(root.join("visible.txt"), "content").unwrap();
fs::write(root.join(".hidden"), "secret").unwrap();
let config = CreationConfig::default(); let walker = FilteredWalker::new(root, &config);
let entries = walked_entries(&walker);
let paths: Vec<_> = entries
.iter()
.map(|e| e.archive_path.to_str().unwrap())
.collect();
assert!(paths.iter().any(|p| p.contains("visible.txt")));
assert!(!paths.iter().any(|p| p.contains(".hidden")));
}
#[test]
fn test_walker_includes_hidden_when_configured() {
let temp = TempDir::new().unwrap();
let root = temp.path();
fs::write(root.join("visible.txt"), "content").unwrap();
fs::write(root.join(".hidden"), "secret").unwrap();
let config = CreationConfig::default().with_include_hidden(true);
let walker = FilteredWalker::new(root, &config);
let entries = walked_entries(&walker);
let paths: Vec<_> = entries
.iter()
.map(|e| e.archive_path.to_str().unwrap())
.collect();
assert!(paths.iter().any(|p| p.contains("visible.txt")));
assert!(paths.iter().any(|p| p.contains(".hidden")));
}
#[test]
fn test_walker_skips_excluded_patterns() {
let temp = TempDir::new().unwrap();
let root = temp.path();
fs::write(root.join("keep.txt"), "keep").unwrap();
fs::write(root.join("skip.tmp"), "skip").unwrap();
fs::write(root.join("also.log"), "skip").unwrap();
let config = CreationConfig::default().with_exclude_patterns(vec![
EntryPattern::try_from("*.tmp").unwrap(),
EntryPattern::try_from("*.log").unwrap(),
]);
let walker = FilteredWalker::new(root, &config);
let entries = walked_entries(&walker);
let paths: Vec<_> = entries
.iter()
.map(|e| e.archive_path.to_str().unwrap())
.collect();
assert!(paths.iter().any(|p| p.contains("keep.txt")));
assert!(!paths.iter().any(|p| p.contains("skip.tmp")));
assert!(!paths.iter().any(|p| p.contains("also.log")));
}
#[cfg(unix)]
#[test]
fn test_walker_handles_symlinks() {
let temp = TempDir::new().unwrap();
let root = temp.path();
fs::write(root.join("target.txt"), "content").unwrap();
std::os::unix::fs::symlink(root.join("target.txt"), root.join("link.txt")).unwrap();
let config = CreationConfig::default();
let walker = FilteredWalker::new(root, &config);
let entries = walked_entries(&walker);
let link_entry = entries
.iter()
.find(|e| e.archive_path.to_str().unwrap().contains("link.txt"));
assert!(link_entry.is_some());
if let Some(entry) = link_entry {
assert_matches!(entry.entry_type, EntryType::Symlink { .. });
}
}
#[cfg(unix)]
#[test]
fn test_walker_detects_symlink_cycles() {
let temp = TempDir::new().unwrap();
let root = temp.path();
fs::create_dir(root.join("dir1")).unwrap();
fs::create_dir(root.join("dir1/dir2")).unwrap();
std::os::unix::fs::symlink(root.join("dir1"), root.join("dir1/dir2/link")).unwrap();
let config = CreationConfig::default().with_follow_symlinks(true);
let walker = FilteredWalker::new(root, &config);
let results: Vec<_> = walker.walk().collect();
let successes = results.iter().filter(|r| r.is_ok()).count();
assert!(successes > 0, "should have some entries before cycle");
let has_cycle_error = results.iter().any(|r| {
if let Err(e) = r {
e.to_string().contains("File system loop")
|| e.to_string().contains("walkdir error")
} else {
false
}
});
assert!(has_cycle_error, "should detect symlink cycle");
}
#[test]
fn test_walker_respects_max_file_size() {
let temp = TempDir::new().unwrap();
let root = temp.path();
fs::write(root.join("small.txt"), "tiny").unwrap(); fs::write(root.join("large.txt"), "a".repeat(1000)).unwrap();
let config = CreationConfig::default().with_max_file_size(crate::non_zero!(100));
let walker = FilteredWalker::new(root, &config);
let entries = walked_entries(&walker);
let paths: Vec<_> = entries
.iter()
.map(|e| e.archive_path.to_str().unwrap())
.collect();
assert!(paths.iter().any(|p| p.contains("small.txt")));
assert!(!paths.iter().any(|p| p.contains("large.txt")));
}
#[test]
fn test_walker_computes_archive_paths() {
let temp = TempDir::new().unwrap();
let root = temp.path();
fs::create_dir(root.join("src")).unwrap();
fs::write(root.join("src/main.rs"), "code").unwrap();
let config = CreationConfig::default();
let walker = FilteredWalker::new(root, &config);
let entries = walked_entries(&walker);
let main_entry = entries
.iter()
.find(|e| e.archive_path.to_str().unwrap().contains("main.rs"));
assert!(main_entry.is_some());
if let Some(entry) = main_entry {
assert_eq!(&*entry.archive_path, Path::new("src/main.rs"));
}
}
#[test]
fn test_walker_strip_prefix() {
let temp = TempDir::new().unwrap();
let root = temp.path();
fs::create_dir(root.join("project")).unwrap();
fs::create_dir(root.join("project/src")).unwrap();
fs::write(root.join("project/src/main.rs"), "code").unwrap();
let config = CreationConfig::default().with_strip_prefix(Some(PathBuf::from("project")));
let walker = FilteredWalker::new(root, &config);
let entries = walked_entries(&walker);
let main_entry = entries
.iter()
.find(|e| e.archive_path.to_str().unwrap().contains("main.rs"));
assert!(main_entry.is_some());
if let Some(entry) = main_entry {
assert_eq!(&*entry.archive_path, Path::new("src/main.rs"));
}
}
#[test]
fn test_filtered_entry_file() {
let entry = FilteredEntry {
path: PathBuf::from("/tmp/file.txt"),
archive_path: ArchiveEntryName::from_relative(Path::new("file.txt")).unwrap(),
entry_type: EntryType::File,
size: 1024,
};
assert_eq!(entry.path, Path::new("/tmp/file.txt"));
assert_eq!(&*entry.archive_path, Path::new("file.txt"));
assert_matches!(entry.entry_type, EntryType::File);
assert_eq!(entry.size, 1024);
}
#[test]
fn test_filtered_entry_directory() {
let entry = FilteredEntry {
path: PathBuf::from("/tmp/dir"),
archive_path: ArchiveEntryName::from_relative(Path::new("dir")).unwrap(),
entry_type: EntryType::Directory,
size: 0,
};
assert_matches!(entry.entry_type, EntryType::Directory);
assert_eq!(entry.size, 0);
}
#[test]
fn test_filtered_entry_symlink() {
let entry = FilteredEntry {
path: PathBuf::from("/tmp/link"),
archive_path: ArchiveEntryName::from_relative(Path::new("link")).unwrap(),
entry_type: EntryType::Symlink {
target: PathBuf::from("target.txt"),
},
size: 0,
};
match &entry.entry_type {
EntryType::Symlink { target } => {
assert_eq!(target, Path::new("target.txt"));
}
_ => panic!("expected symlink"),
}
}
#[test]
fn test_entry_type_equality() {
assert_eq!(EntryType::File, EntryType::File);
assert_eq!(EntryType::Directory, EntryType::Directory);
assert_eq!(
EntryType::Symlink {
target: PathBuf::from("a")
},
EntryType::Symlink {
target: PathBuf::from("a")
}
);
assert_ne!(EntryType::File, EntryType::Directory);
assert_ne!(
EntryType::Symlink {
target: PathBuf::from("a")
},
EntryType::Symlink {
target: PathBuf::from("b")
}
);
}
#[test]
fn test_collect_entries_empty_sources() {
let config = CreationConfig::default();
let sources: Vec<&Path> = vec![];
let entries = collect_entries(&sources, &config, &ExcludedOutput::none())
.unwrap()
.entries;
assert_eq!(entries.len(), 0);
}
fn colliding_sources() -> (tempfile::TempDir, PathBuf, PathBuf) {
let temp = tempfile::TempDir::new().unwrap();
let first = temp.path().join("proj");
let second = temp.path().join("other");
for dir in [&first, &second] {
std::fs::create_dir(dir).unwrap();
std::fs::write(dir.join("a.txt"), "x").unwrap();
}
(temp, first.join("a.txt"), second.join("a.txt"))
}
#[test]
fn test_collect_entries_refuses_sources_with_the_same_entry_name() {
let (_temp, first, second) = colliding_sources();
let config = CreationConfig::default();
let error = collect_entries(
&[first.as_path(), second.as_path()],
&config,
&ExcludedOutput::none(),
)
.unwrap_err();
assert_matches!(
error,
ArchiveError::InvalidConfiguration {
setting: crate::ConfigSetting::SourcePaths,
problem: crate::ConfigProblem::EntryNameCollision { name, first: f, second: s },
} if name == "a.txt" && f == first && s == second
);
}
#[test]
fn test_collect_entries_refuses_colliding_files_inside_directories() {
let (temp, _, _) = colliding_sources();
let config = CreationConfig::default();
let proj = temp.path().join("proj");
let other = temp.path().join("other");
let error = collect_entries(
&[proj.as_path(), other.as_path()],
&config,
&ExcludedOutput::none(),
);
assert_matches!(
error,
Err(ArchiveError::InvalidConfiguration {
problem: crate::ConfigProblem::EntryNameCollision { .. },
..
})
);
}
#[test]
fn test_collect_entries_accepts_distinct_entry_names() {
let (temp, first, _) = colliding_sources();
let config = CreationConfig::default();
let other = temp.path().join("other");
fs::rename(other.join("a.txt"), other.join("b.txt")).unwrap();
let collected = collect_entries(
&[first.as_path(), other.as_path()],
&config,
&ExcludedOutput::none(),
)
.unwrap();
assert_eq!(collected.entries.len(), 2);
}
#[test]
fn test_collect_entries_nonexistent_source() {
let config = CreationConfig::default();
let sources = [Path::new("/nonexistent/path/that/does/not/exist")];
let result = collect_entries(&sources, &config, &ExcludedOutput::none());
assert!(result.is_err());
assert_matches!(result.unwrap_err(), ArchiveError::SourceNotFound { .. });
}
#[test]
fn test_collect_entries_mixed_files_and_directories() {
let temp = TempDir::new().unwrap();
let root = temp.path();
fs::write(root.join("single_file.txt"), "standalone").unwrap();
fs::create_dir(root.join("dir1")).unwrap();
fs::write(root.join("dir1/file1.txt"), "content1").unwrap();
fs::write(root.join("dir1/file2.txt"), "content2").unwrap();
fs::create_dir(root.join("dir2")).unwrap();
fs::write(root.join("dir2/file3.txt"), "content3").unwrap();
let config = CreationConfig::default().with_include_hidden(true);
let sources = [
root.join("single_file.txt"),
root.join("dir1"),
root.join("dir2"),
];
let entries = collect_entries(&sources, &config, &ExcludedOutput::none())
.unwrap()
.entries;
assert_eq!(entries.len(), 4);
let paths: Vec<_> = entries
.iter()
.map(|e| e.archive_path.to_str().unwrap())
.collect();
assert!(paths.iter().any(|p| p.contains("single_file.txt")));
assert!(paths.iter().any(|p| p.contains("file1.txt")));
assert!(paths.iter().any(|p| p.contains("file2.txt")));
assert!(paths.iter().any(|p| p.contains("file3.txt")));
}
#[test]
fn test_collect_entries_large_directory_count() {
let temp = TempDir::new().unwrap();
let root = temp.path();
for i in 0..50 {
fs::write(root.join(format!("file_{i}.txt")), format!("content {i}")).unwrap();
}
fs::create_dir(root.join("subdir")).unwrap();
for i in 0..30 {
fs::write(
root.join(format!("subdir/file_{i}.txt")),
format!("sub content {i}"),
)
.unwrap();
}
let config = CreationConfig::default().with_include_hidden(true);
let sources = [root];
let entries = collect_entries(&sources, &config, &ExcludedOutput::none())
.unwrap()
.entries;
assert!(
entries.len() >= 80,
"Expected at least 80 entries, got {}",
entries.len()
);
}
#[test]
fn test_collect_entries_single_file() {
let temp = TempDir::new().unwrap();
let file_path = temp.path().join("test.txt");
fs::write(&file_path, "content").unwrap();
let config = CreationConfig::default();
let sources = [&file_path];
let entries = collect_entries(&sources, &config, &ExcludedOutput::none())
.unwrap()
.entries;
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].entry_type, EntryType::File);
assert!(
entries[0]
.archive_path
.to_str()
.unwrap()
.contains("test.txt")
);
}
#[cfg(unix)]
#[test]
fn test_collect_entries_single_file_symlink_not_dereferenced() {
let temp = TempDir::new().unwrap();
let target_path = temp.path().join("target.txt");
let link_path = temp.path().join("evil_link");
fs::write(&target_path, "content").unwrap();
std::os::unix::fs::symlink(&target_path, &link_path).unwrap();
let config = CreationConfig::default();
let sources = [&link_path];
let entries = collect_entries(&sources, &config, &ExcludedOutput::none())
.unwrap()
.entries;
assert_eq!(entries.len(), 1);
assert_eq!(
entries[0].entry_type,
EntryType::Symlink {
target: target_path,
}
);
assert!(
entries[0]
.archive_path
.to_str()
.unwrap()
.contains("evil_link")
);
}
#[cfg(unix)]
#[test]
fn test_collect_entries_dangling_symlink_source_not_rejected() {
let temp = TempDir::new().unwrap();
let missing_target = temp.path().join("nowhere.txt");
let link_path = temp.path().join("dangling_link");
std::os::unix::fs::symlink(&missing_target, &link_path).unwrap();
let config = CreationConfig::default();
let sources = [&link_path];
let entries = collect_entries(&sources, &config, &ExcludedOutput::none())
.unwrap()
.entries;
assert_eq!(entries.len(), 1);
assert_eq!(
entries[0].entry_type,
EntryType::Symlink {
target: missing_target,
}
);
assert!(
entries[0]
.archive_path
.to_str()
.unwrap()
.contains("dangling_link")
);
}
#[cfg(unix)]
#[test]
fn test_collect_entries_dir_symlink_source_classified_as_symlink() {
let temp = TempDir::new().unwrap();
let target_dir = temp.path().join("target_dir");
let link_path = temp.path().join("dirlink");
fs::create_dir(&target_dir).unwrap();
fs::write(target_dir.join("inner.txt"), "content").unwrap();
std::os::unix::fs::symlink(&target_dir, &link_path).unwrap();
let config = CreationConfig::default();
let sources = [&link_path];
let entries = collect_entries(&sources, &config, &ExcludedOutput::none())
.unwrap()
.entries;
assert_eq!(entries.len(), 1);
assert_eq!(
entries[0].entry_type,
EntryType::Symlink { target: target_dir }
);
assert!(
entries[0]
.archive_path
.to_str()
.unwrap()
.contains("dirlink")
);
}
#[test]
fn test_collect_entries_respects_filters() {
let temp = TempDir::new().unwrap();
let root = temp.path();
fs::write(root.join("keep.txt"), "keep").unwrap();
fs::write(root.join("skip.tmp"), "skip").unwrap();
fs::write(root.join(".hidden"), "hidden").unwrap();
let config = CreationConfig::default()
.with_exclude_patterns(vec![EntryPattern::try_from("*.tmp").unwrap()])
.with_include_hidden(false);
let sources = [root];
let entries = collect_entries(&sources, &config, &ExcludedOutput::none())
.unwrap()
.entries;
let paths: Vec<_> = entries
.iter()
.map(|e| e.archive_path.to_str().unwrap())
.collect();
assert!(paths.iter().any(|p| p.contains("keep.txt")));
assert!(!paths.iter().any(|p| p.contains("skip.tmp")));
assert!(!paths.iter().any(|p| p.contains(".hidden")));
}
}