use std::collections::HashSet;
use std::ffi::OsString;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use walkdir::{DirEntry, WalkDir};
pub const EXTENSIONS: [&str; 20] = [
"flac", "wav", "aif", "aiff", "aifc", "caf", "m4a", "mp4", "alac", "mp3", "aac", "ogg", "oga",
"opus", "mka", "webm", "wv", "ape", "dsf", "dff",
];
pub struct Problem {
pub path: PathBuf,
pub why: String,
pub unread: bool,
}
#[derive(Default)]
pub struct Inputs {
pub files: Vec<PathBuf>,
pub problems: Vec<Problem>,
}
impl Inputs {
pub fn gather(
paths: &[PathBuf],
stdin: &mut impl Read,
null: bool,
follow: bool,
) -> io::Result<Self> {
let mut inputs = Self::default();
for path in paths {
if path.as_os_str() == "-" {
for listed in listed(stdin, null)? {
inputs.add(&listed, follow);
}
} else {
inputs.add(path, follow);
}
}
let mut seen = HashSet::new();
inputs.files.retain(|file| seen.insert(file.clone()));
Ok(inputs)
}
fn add(&mut self, path: &Path, follow: bool) {
if !path.is_dir() {
self.files.push(path.to_path_buf());
return;
}
let walk = WalkDir::new(path)
.follow_links(follow)
.sort_by_file_name()
.into_iter()
.filter_entry(|entry| entry.depth() == 0 || !hidden(entry));
for entry in walk {
match entry {
Ok(entry) if entry.file_type().is_file() && audio(entry.path()) => {
self.files.push(entry.into_path());
}
Ok(_) => {}
Err(e) => self.problems.push(Problem {
path: e.path().unwrap_or(path).to_path_buf(),
why: match (e.loop_ancestor(), e.io_error()) {
(Some(ancestor), _) => format!("the link loops back to {}", ancestor.display()),
(None, Some(io)) => io.to_string(),
(None, None) => e.to_string(),
},
unread: e.loop_ancestor().is_none(),
}),
}
}
}
}
fn hidden(entry: &DirEntry) -> bool {
entry.file_name().as_encoded_bytes().first() == Some(&b'.')
}
fn audio(path: &Path) -> bool {
path.extension().is_some_and(|extension| {
EXTENSIONS
.iter()
.any(|known| extension.eq_ignore_ascii_case(known))
})
}
fn listed(stdin: &mut impl Read, null: bool) -> io::Result<Vec<PathBuf>> {
let mut bytes = Vec::new();
stdin.read_to_end(&mut bytes)?;
bytes
.split(|byte| *byte == if null { 0 } else { b'\n' })
.map(|path| if null { path } else { without_return(path) })
.filter(|path| !path.is_empty())
.map(|path| os_string(path).map(PathBuf::from))
.collect()
}
#[cfg(windows)]
fn without_return(line: &[u8]) -> &[u8] {
line.strip_suffix(b"\r").unwrap_or(line)
}
#[cfg(not(windows))]
fn without_return(line: &[u8]) -> &[u8] {
line
}
#[cfg(unix)]
fn os_string(bytes: &[u8]) -> io::Result<OsString> {
use std::os::unix::ffi::OsStringExt;
Ok(OsString::from_vec(bytes.to_vec()))
}
#[cfg(not(unix))]
fn os_string(bytes: &[u8]) -> io::Result<OsString> {
String::from_utf8(bytes.to_vec())
.map(OsString::from)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}