Refactor FileMatcher to use OsString

This commit is contained in:
Leonard Steppy 2025-02-03 18:01:54 +01:00
parent faf4e47cac
commit d1924aa758
2 changed files with 14 additions and 12 deletions

View File

@ -1,5 +1,7 @@
use std::error::Error; use std::error::Error;
use std::ffi::{OsStr, OsString};
use std::fmt::{Display, Formatter}; use std::fmt::{Display, Formatter};
use std::os::unix::ffi::OsStrExt;
use std::path::PathBuf; use std::path::PathBuf;
//TODO this whole structure should probably use OsString instead of String //TODO this whole structure should probably use OsString instead of String
@ -83,40 +85,40 @@ impl Display for FileInfoError {
impl Error for FileInfoError {} impl Error for FileInfoError {}
//TODO this structure should probably work with OsString instead of String
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct FileMatcher { pub struct FileMatcher {
name: String, name: OsString,
extension: Option<String>, extension: Option<OsString>,
} }
impl FileMatcher { impl FileMatcher {
pub fn from<S>(name: S) -> Self pub fn from<S>(name: S) -> Self
where where
S: ToString, S: AsRef<OsStr>,
{ {
Self { Self {
name: name.to_string(), name: name.as_ref().to_owned(),
extension: None, extension: None,
} }
} }
pub fn and_extension<S>(self, extension: S) -> Self pub fn and_extension<S>(self, extension: S) -> Self
where where
S: ToString, S: AsRef<OsStr>,
{ {
Self { Self {
extension: Some(extension.to_string()), extension: Some(extension.as_ref().to_owned()),
..self ..self
} }
} }
pub fn matches(&self, file_name: &str) -> bool { pub fn matches<S>(&self, file_name: S) -> bool where S: AsRef<OsStr> {
file_name.starts_with(&self.name) let file_name = file_name.as_ref();
file_name.as_bytes().starts_with(self.name.as_bytes())
&& self && self
.extension .extension
.as_ref() .as_ref()
.is_none_or(|extension| file_name.ends_with(extension)) .is_none_or(|extension| file_name.as_bytes().ends_with(extension.as_bytes()))
} }
} }

View File

@ -359,7 +359,7 @@ fn main() -> Result<(), String> {
//TODO avoid lossy match //TODO avoid lossy match
present_file_names present_file_names
.iter() .iter()
.filter(|file| file_matcher.matches(&file.to_string_lossy())) .filter(|file| file_matcher.matches(file))
.map(|file| { .map(|file| {
FileAction::new( FileAction::new(
file, file,
@ -377,7 +377,7 @@ fn main() -> Result<(), String> {
OldVersionPolicy::Delete => { OldVersionPolicy::Delete => {
//TODO avoid lossy match //TODO avoid lossy match
let mut actions = present_file_names.iter() let mut actions = present_file_names.iter()
.filter(|file| file_matcher.matches(&file.to_string_lossy())) .filter(|file| file_matcher.matches(file))
.map(|file| { .map(|file| {
//special case -> file has the same name as current file, then we just need to replace it //special case -> file has the same name as current file, then we just need to replace it
if *file == file_name { if *file == file_name {