use std::fs::{read, read_dir, DirEntry};
use std::path::{Path, PathBuf};
use resvg::usvg::{Options, Tree};
use crate::error::SpreetResult;
fn is_hidden(entry: &DirEntry) -> bool {
entry
.file_name()
.to_str()
.map_or(false, |s| s.starts_with('.'))
}
fn is_svg_file(entry: &DirEntry) -> bool {
entry.path().is_file() && entry.path().extension().map_or(false, |s| s == "svg")
}
fn is_useful_input(entry: &DirEntry) -> bool {
!is_hidden(entry) && is_svg_file(entry)
}
pub fn get_svg_input_paths<P: AsRef<Path>>(path: P, recursive: bool) -> SpreetResult<Vec<PathBuf>> {
Ok(read_dir(path)?
.filter_map(|entry| {
if let Ok(entry) = entry {
let path_buf = entry.path();
if recursive && path_buf.is_dir() {
get_svg_input_paths(path_buf, true).ok()
} else if is_useful_input(&entry) {
Some(vec![path_buf])
} else {
None
}
} else {
None
}
})
.flatten()
.collect())
}
pub fn load_svg<P: AsRef<Path>>(path: P) -> SpreetResult<Tree> {
let resources_dir = std::fs::canonicalize(&path)
.ok()
.and_then(|p| p.parent().map(Path::to_path_buf));
let options = Options {
resources_dir,
..Options::default()
};
Ok(Tree::from_data(&read(path)?, &options)?)
}