use std::path::{Path, PathBuf};
pub fn duplicate_file_impl(path: &Path) -> Result<PathBuf, String> {
if !path.is_file() {
return Err(format!("File not found: {}", path.display()));
}
let parent = path.parent().unwrap_or(Path::new("."));
let file_name = path.file_name().and_then(|n| n.to_str()).ok_or_else(|| "Invalid filename".to_string())?;
let (stem, ext) = match file_name.rsplit_once('.') {
Some((s, e)) => (s.to_string(), format!(".{}", e)),
None => (file_name.to_string(), String::new()),
};
let mut new_name = format!("{} copy{}", stem, ext);
let mut new_path = parent.join(&new_name);
let mut counter = 2;
while new_path.exists() && counter <= 100 {
new_name = format!("{} copy ({}){}", stem, counter, ext);
new_path = parent.join(&new_name);
counter += 1;
}
if counter > 100 {
return Err("Could not find available filename after 100 attempts".to_string());
}
std::fs::copy(path, &new_path).map_err(|e| format!("Failed to copy file: {}", e))?;
Ok(new_path)
}
#[tauri::command]
pub async fn duplicate_file(path: String) -> Result<String, String> {
let p = PathBuf::from(&path);
duplicate_file_impl(&p).map(|pb| pb.to_string_lossy().into_owned())
}
pub fn create_markdown_note_impl(folder: &Path, name: &str) -> Result<PathBuf, String> {
if name.trim().is_empty() {
return Err("Note name cannot be empty".to_string());
}
if !folder.is_dir() {
return Err(format!("Folder not found: {}", folder.display()));
}
let note_path = folder.join(name);
if note_path.exists() {
return Err(format!("File already exists: {}", note_path.display()));
}
std::fs::write(¬e_path, "").map_err(|e| format!("Failed to create file: {}", e))?;
Ok(note_path)
}
#[tauri::command]
pub async fn create_markdown_note(folder: String, name: String) -> Result<String, String> {
let f = PathBuf::from(&folder);
create_markdown_note_impl(&f, &name).map(|pb| pb.to_string_lossy().into_owned())
}