use super::{FileContent, FolderContent};
use crate::{Content, ContentExtractor, ContentType, ExtractionContext, ExtractionSession, OwnedContentPtr};
use std::marker::PhantomData;
#[cfg(windows)]
fn is_link(ft: &std::fs::FileType, ent: &std::fs::DirEntry) -> bool {
use std::os::windows::fs::MetadataExt;
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
match ent.metadata() {
Ok(md) => md.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0,
Err(_) => ft.is_symlink(), }
}
#[cfg(not(windows))]
fn is_link(ft: &std::fs::FileType, _ent: &std::fs::DirEntry) -> bool {
ft.is_symlink()
}
pub struct FolderExtractor<T: ContentType> {
_marker: PhantomData<T>,
recursive: bool,
open_files_exclusively: bool,
}
impl<T: ContentType> FolderExtractor<T> {
pub fn new(recursive: bool, open_files_exclusively: bool) -> Self {
Self {
_marker: PhantomData,
recursive,
open_files_exclusively,
}
}
}
struct FolderSession<T: ContentType> {
content_type: T,
rd: std::fs::ReadDir,
entry: crate::Entry,
current_is_folder: bool,
recursive: bool,
open_files_exclusively: bool,
}
impl<T: ContentType + 'static> ContentExtractor<T> for FolderExtractor<T> {
fn create_session(&mut self, content: OwnedContentPtr<T>, _: &ExtractionContext) -> Option<Box<dyn ExtractionSession<T>>> {
let rd = std::fs::read_dir(content.path().as_path()).ok()?;
Some(Box::new(FolderSession {
content_type: content.content_type()?,
rd,
entry: crate::Entry::default(),
current_is_folder: false,
recursive: self.recursive,
open_files_exclusively: self.open_files_exclusively,
}))
}
}
impl<T: ContentType + 'static> ExtractionSession<T> for FolderSession<T> {
fn advance(&mut self) -> Option<&crate::Entry> {
loop {
let folder_ent = match self.rd.next() {
Some(Ok(ent)) => ent,
Some(Err(_)) => continue, None => return None,
};
let ft = match folder_ent.file_type() {
Ok(ft) => ft,
Err(_) => continue, };
let is_link = is_link(&ft, &folder_ent);
let mut link_target_len: Option<u64> = None;
if is_link {
match std::fs::metadata(folder_ent.path()) {
Ok(target) if target.is_dir() => continue,
Ok(target) => link_target_len = Some(target.len()),
Err(_) => continue,
}
self.current_is_folder = false;
} else {
self.current_is_folder = ft.is_dir();
}
if !self.recursive && self.current_is_folder {
continue;
}
self.entry.path.clear();
self.entry.path.set_from_os(&folder_ent.path());
self.entry.size = if self.current_is_folder {
0
} else if let Some(len) = link_target_len {
len
} else {
folder_ent.metadata().map(|m| m.len()).unwrap_or(0)
};
self.entry.skip_from_filtering = self.current_is_folder;
return Some(&self.entry);
}
}
fn extract(&mut self) -> Option<Box<dyn Content<T>>> {
if self.current_is_folder {
Some(Box::new(FolderContent::with_content_type(self.entry.path.as_path(), self.content_type)))
} else {
Some(Box::new(FileContent::with_size(
self.entry.path.as_path(),
self.entry.size,
self.open_files_exclusively,
)))
}
}
}