From 40926ccba4fc332480f62398f2211d586dd3f444 Mon Sep 17 00:00:00 2001 From: Bnyro Date: Fri, 11 Oct 2024 15:30:07 +0200 Subject: [PATCH] refactor: extract fix_file_name function --- crates/typos-cli/src/file.rs | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/crates/typos-cli/src/file.rs b/crates/typos-cli/src/file.rs index c7f377c..0a9b914 100644 --- a/crates/typos-cli/src/file.rs +++ b/crates/typos-cli/src/file.rs @@ -127,11 +127,7 @@ impl FileChecker for FixTypos { } } if !fixes.is_empty() { - let file_name = file_name.to_owned().into_bytes(); - let new_name = fix_buffer(file_name, fixes.into_iter()); - let new_name = - String::from_utf8(new_name).expect("corrections are valid utf-8"); - let new_path = path.with_file_name(new_name); + let new_path = fix_file_name(path, file_name, fixes.into_iter())?; std::fs::rename(path, new_path)?; } } @@ -205,11 +201,7 @@ impl FileChecker for DiffTypos { } } if !fixes.is_empty() { - let file_name = file_name.to_owned().into_bytes(); - let new_name = fix_buffer(file_name, fixes.into_iter()); - let new_name = - String::from_utf8(new_name).expect("corrections are valid utf-8"); - new_path = Some(path.with_file_name(new_name)); + new_path = fix_file_name(path, file_name, fixes.into_iter()).ok(); } } } @@ -650,7 +642,7 @@ fn is_fixable(typo: &typos::Typo<'_>) -> bool { extract_fix(typo).is_some() } -fn fix_buffer(mut buffer: Vec, typos: impl Iterator>) -> Vec { +fn fix_buffer<'a>(mut buffer: Vec, typos: impl Iterator>) -> Vec { let mut offset = 0isize; for typo in typos { let fix = extract_fix(&typo).expect("Caller only provides fixable typos"); @@ -664,6 +656,18 @@ fn fix_buffer(mut buffer: Vec, typos: impl Iterator( + path: &std::path::Path, + file_name: &'a str, + fixes: impl Iterator>, +) -> Result { + let file_name = file_name.to_owned().into_bytes(); + let new_name = fix_buffer(file_name, fixes); + let new_name = String::from_utf8(new_name).expect("corrections are valid utf-8"); + let new_path = path.with_file_name(new_name); + Ok(new_path) +} + pub fn walk_path( walk: ignore::Walk, checks: &dyn FileChecker,