pub mod signal;
#[cfg(windows)]
pub mod win;
#[cfg(target_os = "linux")]
pub mod linux;
use crate::predicate::{EntryMeta, EntryType};
use crate::syntax::{CodePoint, decode};
use std::fs;
use std::io;
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FileId {
pub volume: u64,
pub id: u128,
}
#[derive(Clone, Debug)]
pub struct DirEntry {
pub name: Vec<CodePoint>,
pub entry_type: EntryType,
pub is_reparse: bool,
pub reparse_tag: u32,
pub attributes: u32,
pub size: u64,
pub btime: i64,
pub mtime: i64,
pub atime: i64,
pub ctime: i64,
pub file_id: FileId,
}
impl DirEntry {
pub fn meta(&self, depth: u32) -> EntryMeta<'_> {
EntryMeta {
name: &self.name,
depth,
entry_type: self.entry_type,
is_reparse: self.is_reparse,
reparse_tag: self.reparse_tag,
attributes: self.attributes,
size: self.size,
btime: self.btime,
mtime: self.mtime,
atime: self.atime,
ctime: self.ctime,
}
}
}
pub struct DirScan {
pub entries: Vec<DirEntry>,
pub entry_errors: Vec<EntryFailure>,
}
pub struct EntryFailure {
pub name: Option<Vec<CodePoint>>,
pub source: io::Error,
}
#[derive(Clone, Copy, Debug)]
pub struct EnumPlan {
pub want_stat: bool,
pub want_file_id: bool,
pub want_reparse_file_id: bool,
}
impl EnumPlan {
pub const FULL: EnumPlan = EnumPlan {
want_stat: true,
want_file_id: true,
want_reparse_file_id: true,
};
pub fn wants_any_file_id(&self) -> bool {
self.want_file_id || self.want_reparse_file_id
}
pub fn wants_file_id_for(&self, is_reparse: bool) -> bool {
self.want_file_id || (is_reparse && self.want_reparse_file_id)
}
}
pub fn enumerate(path: &Path, plan: EnumPlan) -> io::Result<DirScan> {
#[cfg(windows)]
{
win::enumerate_dir_native(path, plan)
}
#[cfg(target_os = "linux")]
{
linux::enumerate_dir_native(path, plan)
}
#[cfg(not(any(windows, target_os = "linux")))]
{
enumerate_dir(path, plan)
}
}
pub fn enumerate_dir(path: &Path, plan: EnumPlan) -> io::Result<DirScan> {
let mut entries = Vec::new();
let mut entry_errors = Vec::new();
for entry in fs::read_dir(path)? {
match read_one_entry(entry, plan) {
Ok(e) => entries.push(e),
Err(failure) => entry_errors.push(failure),
}
}
Ok(DirScan {
entries,
entry_errors,
})
}
fn read_one_entry(
entry: io::Result<fs::DirEntry>,
plan: EnumPlan,
) -> Result<DirEntry, EntryFailure> {
let entry = entry.map_err(|source| EntryFailure { name: None, source })?;
let name = decode_name(&entry.file_name());
let ft = entry.file_type().map_err(|source| EntryFailure {
name: Some(name.clone()),
source,
})?;
let entry_type = if ft.is_dir() {
EntryType::Dir
} else if ft.is_file() {
EntryType::File
} else {
EntryType::Other
};
if !(plan.want_stat || plan.wants_file_id_for(ft.is_symlink())) {
return Ok(DirEntry {
name,
entry_type,
is_reparse: ft.is_symlink(),
reparse_tag: 0,
attributes: 0,
size: 0,
btime: 0,
mtime: 0,
atime: 0,
ctime: 0,
file_id: FileId { volume: 0, id: 0 },
});
}
let md = entry.metadata().map_err(|source| EntryFailure {
name: Some(name.clone()),
source,
})?; let (attributes, is_reparse, file_id, ctime) = platform_extra(&md, &ft);
Ok(DirEntry {
name,
entry_type,
is_reparse,
reparse_tag: 0,
attributes,
size: md.len(),
btime: nanos(md.created()),
mtime: nanos(md.modified()),
atime: nanos(md.accessed()),
ctime,
file_id,
})
}
fn nanos(t: io::Result<SystemTime>) -> i64 {
let Ok(st) = t else { return 0 };
match st.duration_since(UNIX_EPOCH) {
Ok(d) => i64::try_from(d.as_nanos()).unwrap_or(i64::MAX),
Err(e) => i64::try_from(e.duration().as_nanos())
.map(|n| -n)
.unwrap_or(i64::MIN),
}
}
pub(crate) fn decode_name(os: &std::ffi::OsStr) -> Vec<CodePoint> {
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt;
let units: Vec<u16> = os.encode_wide().collect();
decode::decode_utf16(&units)
}
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
decode::decode_bytes(os.as_bytes())
}
#[cfg(not(any(windows, unix)))]
{
decode::decode_str(&os.to_string_lossy())
}
}
pub(crate) fn encode_os_name(cps: &[CodePoint]) -> std::ffi::OsString {
#[cfg(windows)]
{
use std::os::windows::ffi::OsStringExt;
let mut units: Vec<u16> = Vec::with_capacity(cps.len());
for &cp in cps {
if cp > 0xFFFF {
let c = cp - 0x1_0000;
units.push(0xD800 + ((c >> 10) as u16));
units.push(0xDC00 + ((c & 0x3FF) as u16));
} else {
units.push(cp as u16);
}
}
std::ffi::OsString::from_wide(&units)
}
#[cfg(unix)]
{
use std::os::unix::ffi::OsStringExt;
let mut bytes: Vec<u8> = Vec::with_capacity(cps.len());
for &cp in cps {
if (0xDC80..=0xDCFF).contains(&cp) {
bytes.push((cp - 0xDC00) as u8);
} else if let Some(c) = char::from_u32(cp) {
let mut buf = [0u8; 4];
bytes.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
} else {
bytes.extend_from_slice("\u{FFFD}".as_bytes());
}
}
std::ffi::OsString::from_vec(bytes)
}
#[cfg(not(any(windows, unix)))]
{
cps.iter()
.filter_map(|&c| char::from_u32(c))
.collect::<String>()
.into()
}
}
#[cfg(windows)]
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;
#[cfg(windows)]
fn platform_extra(md: &fs::Metadata, ft: &fs::FileType) -> (u32, bool, FileId, i64) {
use std::os::windows::fs::MetadataExt;
let attrs = md.file_attributes();
let is_reparse = attrs & FILE_ATTRIBUTE_REPARSE_POINT != 0 || ft.is_symlink();
(attrs, is_reparse, FileId { volume: 0, id: 0 }, 0)
}
#[cfg(unix)]
fn platform_extra(md: &fs::Metadata, ft: &fs::FileType) -> (u32, bool, FileId, i64) {
use std::os::unix::fs::MetadataExt;
let ctime = md
.ctime()
.saturating_mul(1_000_000_000)
.saturating_add(md.ctime_nsec());
(
0,
ft.is_symlink(),
FileId {
volume: md.dev(),
id: u128::from(md.ino()),
},
ctime,
)
}
#[cfg(not(any(windows, unix)))]
fn platform_extra(_md: &fs::Metadata, ft: &fs::FileType) -> (u32, bool, FileId, i64) {
(0, ft.is_symlink(), FileId { volume: 0, id: 0 }, 0)
}