Refactor FileMatcher to use OsString
This commit is contained in:
parent
faf4e47cac
commit
d1924aa758
22
src/file.rs
22
src/file.rs
@ -1,5 +1,7 @@
|
||||
use std::error::Error;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::path::PathBuf;
|
||||
|
||||
//TODO this whole structure should probably use OsString instead of String
|
||||
@ -83,40 +85,40 @@ impl Display for FileInfoError {
|
||||
|
||||
impl Error for FileInfoError {}
|
||||
|
||||
//TODO this structure should probably work with OsString instead of String
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FileMatcher {
|
||||
name: String,
|
||||
extension: Option<String>,
|
||||
name: OsString,
|
||||
extension: Option<OsString>,
|
||||
}
|
||||
|
||||
impl FileMatcher {
|
||||
pub fn from<S>(name: S) -> Self
|
||||
where
|
||||
S: ToString,
|
||||
S: AsRef<OsStr>,
|
||||
{
|
||||
Self {
|
||||
name: name.to_string(),
|
||||
name: name.as_ref().to_owned(),
|
||||
extension: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn and_extension<S>(self, extension: S) -> Self
|
||||
where
|
||||
S: ToString,
|
||||
S: AsRef<OsStr>,
|
||||
{
|
||||
Self {
|
||||
extension: Some(extension.to_string()),
|
||||
extension: Some(extension.as_ref().to_owned()),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn matches(&self, file_name: &str) -> bool {
|
||||
file_name.starts_with(&self.name)
|
||||
pub fn matches<S>(&self, file_name: S) -> bool where S: AsRef<OsStr> {
|
||||
let file_name = file_name.as_ref();
|
||||
file_name.as_bytes().starts_with(self.name.as_bytes())
|
||||
&& self
|
||||
.extension
|
||||
.as_ref()
|
||||
.is_none_or(|extension| file_name.ends_with(extension))
|
||||
.is_none_or(|extension| file_name.as_bytes().ends_with(extension.as_bytes()))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -359,7 +359,7 @@ fn main() -> Result<(), String> {
|
||||
//TODO avoid lossy match
|
||||
present_file_names
|
||||
.iter()
|
||||
.filter(|file| file_matcher.matches(&file.to_string_lossy()))
|
||||
.filter(|file| file_matcher.matches(file))
|
||||
.map(|file| {
|
||||
FileAction::new(
|
||||
file,
|
||||
@ -377,7 +377,7 @@ fn main() -> Result<(), String> {
|
||||
OldVersionPolicy::Delete => {
|
||||
//TODO avoid lossy match
|
||||
let mut actions = present_file_names.iter()
|
||||
.filter(|file| file_matcher.matches(&file.to_string_lossy()))
|
||||
.filter(|file| file_matcher.matches(file))
|
||||
.map(|file| {
|
||||
//special case -> file has the same name as current file, then we just need to replace it
|
||||
if *file == file_name {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user