use std::fs; use std::fs::{copy, remove_file}; use std::io::{self, Write}; use std::path::PathBuf; use regex::Regex; use std::process::Command; fn get_entries_in_directory(path: &str) -> io::Result> { Ok(fs::read_dir(path)? .filter_map(|entry| entry.ok().map(|e| e.path())) .collect()) } fn find_sn_pattern(file_path: &PathBuf) -> Option { let file_name = file_path.file_name()?.to_str()?; let re = Regex::new(r"SN (\d{5,6})").unwrap(); if let Some(captures) = re.captures(file_name) { return Some(captures[1].to_string()); } None } fn find_dir_by_number(root_path: &str, number: &str) -> io::Result> { let re = Regex::new(&format!(r"{}", number)).unwrap(); let entries = fs::read_dir(root_path)?; for entry in entries { let entry = entry?; let path = entry.path(); if path.is_dir() { let dir_name = path.file_name().and_then(|os_str| os_str.to_str()); if let Some(name) = dir_name { if re.is_match(name) { return Ok(Some(path.to_path_buf())); // Возвращаем путь к родительской директории } } } } Ok(None) // Ничего не найдено } fn open_folder(path: &PathBuf) { Command::new( "explorer" ) .arg( path.to_string_lossy().replace("/", "\\")) // <- Specify the directory you'd like to open. .spawn( ) .unwrap( ); } fn main() -> io::Result<()> { let files = get_entries_in_directory("Сортировка")?; // "." - текущая директория let mut letter = String::new(); print!("Какая буква у диска: "); io::stdout().flush().unwrap(); // Очищаем буфер вывода io::stdin().read_line(&mut letter).expect("Failed to read line"); let letter = letter.trim(); let mut openned_dir : Vec = Vec::new(); for file in files{ if file.is_file(){ if let Some(sn) = find_sn_pattern(&file) { // Обрабатываем Result и Option let dir_msc = find_dir_by_number(&(letter.to_owned() + ":/Москва/"), &sn).ok().and_then(|opt| opt); //let result_msc = find_dir_by_number(&(letter.to_owned() + ":/Москва/"), &sn); let dir_oth = find_dir_by_number(&( letter.to_owned() + ":/Заказ Наряды/"), &sn).ok().and_then(|opt| opt); //let result_oth = find_dir_by_number(&( letter.to_owned() + ":/Заказ Наряды/"), &sn); if let Some(dir_msc) = dir_msc { // Извлекаем PathBuf из Option let file_name = file.file_name().expect("File name is None"); let file_name_str = file_name.to_str().expect("File name is not valid UTF-8"); let new_path = dir_msc.join(file_name_str); // Теперь dir_msc имеет тип PathBuf copy(&file, &new_path).expect("Failed to copy file"); println!("\nLOG: Файл {} перемещён в {}" , file.display(), new_path.display()); remove_file(&file).expect("Failed to remove original file"); if !(openned_dir.contains(&dir_msc)){ open_folder(&dir_msc); openned_dir.push(dir_msc); } } else if let Some(dir_oth) = dir_oth { // Извлекаем PathBuf из Option let file_name = file.file_name().expect("File name is None"); let file_name_str = file_name.to_str().expect("File name is not valid UTF-8"); let new_path = dir_oth.join(file_name_str); // Теперь dir_msc имеет тип PathBuf copy(&file, &new_path).expect("Failed to copy file"); println!("\nLOG: Файл {} перемещён в {}" , file.display(), new_path.display()); remove_file(&file).expect("Failed to remove original file"); if !(openned_dir.contains(&dir_oth)){ open_folder(&dir_oth); openned_dir.push(dir_oth); } } else{ println!("Каталог не найден для файла: {}", file.display()); print!("Где создать папку для файла ? 1 - Москва, 2 - Заказ Наряды? (1/2): "); io::stdout().flush().unwrap(); // Очищаем буфер вывода let mut choice = String::new(); io::stdin().read_line(&mut choice).expect("Failed to read line"); let choice = choice.trim(); let base_path = match choice { "1" => PathBuf::from(&( letter.to_owned() + ":/Москва/")), "2" => PathBuf::from(&( letter.to_owned() + ":/Заказ Наряды/")), _ => { println!("Invalid choice."); continue; // Переходим к следующему файлу } }; print!("Введите название для новой папки: "); io::stdout().flush().unwrap(); let mut folder_name = String::new(); io::stdin().read_line(&mut folder_name).expect("Failed to read line"); let folder_name = folder_name.trim(); let new_dir = base_path.join(folder_name); fs::create_dir_all(&new_dir).expect("Failed to create directory"); // Создаем директорию let file_name = file.file_name().expect("File name is None"); let file_name_str = file_name.to_str().expect("File name is not valid UTF-8"); let new_path = new_dir.join(file_name_str); copy(&file, &new_path).expect("Failed to copy file"); println!("\nLOG: Файл {} перемещён в {}" , file.display(), new_path.display()); remove_file(&file).expect("Failed to remove original file"); if !(openned_dir.contains(&new_dir)){ open_folder(&new_dir); openned_dir.push(new_dir); } } } } } println!("Press any key to exit..."); io::stdin().read_line(&mut String::new()).unwrap(); Ok(()) }