use std::path::PathBuf;
pub fn filter_markdown_files(
files: Vec<PathBuf>,
include: Option<Vec<&str>>,
exclude: Option<Vec<&str>>,
) -> Vec<PathBuf> {
let mut markdown_files: Vec<PathBuf> = files
.into_iter()
.filter(|file| file.extension().and_then(|ext| ext.to_str()) == Some("md"))
.collect();
if let Some(include) = include {
if !include.is_empty() {
let include_with_md: Vec<String> = add_md_ext(include);
markdown_files.retain(|file| {
include_with_md.contains(&file.file_name().unwrap().to_string_lossy().to_string())
});
}
}
if let Some(exclude) = exclude {
if !exclude.is_empty() {
let exclude_with_md: Vec<String> = add_md_ext(exclude);
markdown_files.retain(|file| {
!exclude_with_md.contains(&file.file_name().unwrap().to_string_lossy().to_string())
});
}
}
markdown_files
}
fn add_md_ext(paths: Vec<&str>) -> Vec<String> {
paths
.into_iter()
.map(|path| {
if path.ends_with(".md") {
path.to_string()
} else {
format!("{}.md", path)
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_filter_markdown_files() {
let files = vec![
PathBuf::from("file1.md"),
PathBuf::from("file2.txt"),
PathBuf::from("file3.md"),
PathBuf::from("file4.md"),
];
let result = filter_markdown_files(files.clone(), None, None);
assert_eq!(
result,
vec![
PathBuf::from("file1.md"),
PathBuf::from("file3.md"),
PathBuf::from("file4.md")
]
);
let include = Some(vec!["file1", "file3"]);
let result = filter_markdown_files(files.clone(), include, None);
assert_eq!(
result,
vec![PathBuf::from("file1.md"), PathBuf::from("file3.md")]
);
let exclude = Some(vec!["file3"]);
let result = filter_markdown_files(files.clone(), None, exclude);
assert_eq!(
result,
vec![PathBuf::from("file1.md"), PathBuf::from("file4.md")]
);
let include = Some(vec!["file1", "file4"]);
let exclude = Some(vec!["file4"]);
let result = filter_markdown_files(files, include, exclude);
assert_eq!(result, vec![PathBuf::from("file1.md")]);
}
#[test]
fn test_add_md_ext() {
let paths = vec!["file1", "file2", "file3"];
let result = add_md_ext(paths);
assert_eq!(
result,
vec![
"file1.md".to_string(),
"file2.md".to_string(),
"file3.md".to_string()
]
);
let paths = vec!["file1.md", "file2", "file3.md"];
let result = add_md_ext(paths);
assert_eq!(
result,
vec![
"file1.md".to_string(),
"file2.md".to_string(),
"file3.md".to_string()
]
);
}
}