use std::{ io::{BufRead, Write}, path::PathBuf, }; use log::debug; pub(crate) fn do_rename( path: &std::path::Path, signature: nameme_core::sig::Signature, args: crate::NamemeApp, ) -> anyhow::Result<()> { if !args.rename && !args.auto && !args.upper { debug!("renaming disabled!"); return Ok(()); } let exts = signature.exts; if exts.is_empty() { return Ok(()); } let mut ext = exts.first().unwrap().to_lowercase(); if args.upper { ext = ext.to_uppercase(); } let new = PathBuf::from(path); let new = new.with_extension(ext.clone()); if new != path { if args.auto { debug!( "auto: renaming {} -> {}", path.to_str().unwrap(), new.to_str().unwrap() ); std::fs::rename(path, new.clone())?; if args.verbose { println!( "renamed {} -> {}", path.to_str().unwrap(), new.to_str().unwrap() ); } } else { let mut stdout = std::io::stdout(); print!("rename {}?\n", path.to_str().unwrap()); stdout.flush()?; let stdin = std::io::stdin(); let mut iterator = stdin.lock().lines(); let line = iterator.next().unwrap().unwrap(); if line.contains('Y') || line.contains('y') { if exts.len() == 1 { std::fs::rename(path, new.clone())?; if args.verbose { println!( "renamed {} -> {}", path.to_str().unwrap(), new.to_str().unwrap() ); } } else { println!("choose one of the following: "); for (i, ext) in exts.iter().enumerate() { let ext = if args.upper { ext.to_uppercase() } else { ext.to_lowercase() }; println!("[{}]: {ext}", i + 1); } println!("[0-{}/N]: ", exts.len()); let line = iterator.next().unwrap().unwrap(); if line.contains('N') || line.contains('n') { return Ok(()); } else if let Ok(i) = line.parse::() { let i = i - 1; if i >= exts.len() { return Ok(()); } let ext = if args.upper { exts[i].to_uppercase() } else { exts[i].to_lowercase() }; let new = PathBuf::from(path); let new = new.with_extension(ext.clone()); std::fs::rename(path, new.clone())?; if args.verbose { println!( "renamed {} -> {}", path.to_str().unwrap(), new.to_str().unwrap() ); } } else { anyhow::bail!("cannot parse {line} as integer!") } } } } } Ok(()) }