Move responsibility for extracting names from paths lower

This commit is contained in:
Lucien Greathouse
2021-08-24 17:59:53 -04:00
parent d484098781
commit 8954def25c
8 changed files with 86 additions and 68 deletions

View File

@@ -1,5 +1,7 @@
use std::path::Path;
use anyhow::Context;
/// If the given string ends up with the given suffix, returns the portion of
/// the string before the suffix.
pub fn match_trailing<'a>(input: &'a str, suffix: &str) -> Option<&'a str> {
@@ -11,10 +13,31 @@ pub fn match_trailing<'a>(input: &'a str, suffix: &str) -> Option<&'a str> {
}
}
/// If the given path has a file name, and that file name ends with the given
/// suffix, returns the portion of the file name before the given suffix.
pub fn match_file_name<'a>(path: &'a Path, suffix: &str) -> Option<&'a str> {
let file_name = path.file_name()?.to_str()?;
match_trailing(&file_name, suffix)
pub trait PathExt {
fn file_name_ends_with(&self, suffix: &str) -> bool;
fn file_name_trim_end<'a>(&'a self, suffix: &str) -> anyhow::Result<&'a str>;
}
impl<P> PathExt for P
where
P: AsRef<Path>,
{
fn file_name_ends_with(&self, suffix: &str) -> bool {
self.as_ref()
.file_name()
.and_then(|name| name.to_str())
.map(|name| name.ends_with(suffix))
.unwrap_or(false)
}
fn file_name_trim_end<'a>(&'a self, suffix: &str) -> anyhow::Result<&'a str> {
let path = self.as_ref();
let file_name = path
.file_name()
.and_then(|name| name.to_str())
.with_context(|| format!("Path did not have a file name: {}", path.display()))?;
match_trailing(&file_name, suffix)
.with_context(|| format!("Path did not end in {}: {}", suffix, path.display()))
}
}