use crate::core::*;
use std::fs;
use std::path::Path;
pub fn edit(vault: &Vault, category: &String, name: &String) -> Result<bool> {
check_filename(category)?;
check_filename(name)?;
let base = Path::new(&vault.notes).join(category);
fs::create_dir_all(&base)?;
let path = base.join(name).with_extension("md");
let content_before = read_safe(&path);
editor::run(&path)?;
let content_after = read_safe(&path);
let saved = content_before != content_after;
if content_after == "" && path.exists() {
fs::remove_file(&path)?;
}
if content_after == "" && base.read_dir()?.count() == 0 {
fs::remove_dir_all(&base)?;
}
Ok(saved)
}
pub fn remove(vault: &Vault, category: &String, name: &Option<String>) -> Result<()> {
check_filename(category)?;
let base = Path::new(&vault.notes).join(category);
if !base.exists() {
println!("Category [{}] was not found", category);
return Ok(())
}
match name {
Some(name) => {
check_filename(name)?;
let path = base.join(name).with_extension("md");
if path.exists() {
let question = format!("Are you sure you want to remove note [{} / {}]?", category, name);
match prompt_yes_no(question.as_str(), YesNo::No)? {
YesNo::Yes => {
fs::remove_file(&path)?;
if base.read_dir()?.count() == 0 {
fs::remove_dir_all(&base)?;
}
println!("Note [{} / {}] was successfully removed", category, name);
}
YesNo::No => println!("Nothing was removed"),
}
} else {
println!("Note [{} / {}] was not found", category, name);
}
}
None => { let question = format!("Are you sure you want to remove category [{}]?", category);
match prompt_yes_no(question.as_str(), YesNo::No)? {
YesNo::Yes => {
let question = format!("Are you ABSOLUTELY sure you want to remove category [{}]?", category);
match prompt_yes_no(question.as_str(), YesNo::No)? {
YesNo::Yes => {
fs::remove_dir_all(&base)?;
println!("Category [{}] was successfully removed", category);
}
YesNo::No => println!("Nothing was removed"),
}
}
YesNo::No => println!("Nothing was removed"),
}
},
};
Ok(())
}
pub fn remove_noprompt(vault: &Vault, category: &String, name: &String) -> Result<bool> {
check_filename(category)?;
let base = Path::new(&vault.notes).join(category);
if !base.exists() {
return Ok(true)
}
check_filename(name)?;
let path = base.join(name).with_extension("md");
if path.exists() {
fs::remove_file(&path)?;
if base.read_dir()?.count() == 0 {
fs::remove_dir_all(&base)?;
}
Ok(true)
} else {
Ok(false)
}
}
pub fn list(vault: &Vault, show_notes: bool, category: Option<String>) -> Result<()> {
let show_category = category.is_none();
for (category, notes) in vault.list_notes(show_notes, &category)? {
if show_category {
println!("{}", category);
for note in notes {
println!(" {}", note);
}
} else {
for note in notes {
println!("{}", note);
}
}
}
Ok(())
}