list all or by category and optionally open

This commit is contained in:
Volodymyr Patuta 2020-11-30 09:05:27 +01:00
parent a1f2acfe70
commit 8f57d4fe26
3 changed files with 72 additions and 3 deletions

View File

@ -37,8 +37,7 @@ pub fn make_app() -> App<'static, 'static> {
SubCommand::with_name("list")
.alias("l")
.alias("ls")
.about("List all notes or one note")
.arg(Arg::with_name("header").help("Name of the note."))
.about("List all notes or notes from a category")
.arg(
Arg::with_name("category")
.help("List all notes from a category.")

View File

@ -224,3 +224,64 @@ pub fn show_category(category: &str) -> Result<()> {
}
Ok(())
}
pub fn list_all() -> Result<()> {
let path = get_base_path()?;
let mut files: Vec<String> = Vec::new();
for (_, file) in WalkDir::new(path)
.into_iter()
.filter_map(|file| file.ok())
.enumerate()
{
if file.metadata()?.is_file() {
let p = file.path().to_str().unwrap_or("");
if !p.is_empty() {
files.push(p.to_owned());
}
}
}
let selection = Select::with_theme(&ColorfulTheme::default())
.with_prompt("Optionally choose a note")
.default(0)
.items(&files)
.interact_opt()?;
if let Some(selection) = selection {
let editor = std::env::var("EDITOR")?;
std::process::Command::new(editor)
.arg(files.remove(selection))
.status()?;
}
Ok(())
}
pub fn list_category(category: &str) -> Result<()> {
let base = get_base_path()?;
let path = format!("{}{}", base, category);
let mut files: Vec<String> = Vec::new();
if std::path::Path::new(&path).exists() {
for (_, file) in WalkDir::new(path)
.into_iter()
.filter_map(|file| file.ok())
.enumerate()
{
if file.metadata()?.is_file() {
let p = file.path().to_str().unwrap_or("");
if !p.is_empty() {
files.push(p.to_owned());
}
}
}
let selection = Select::with_theme(&ColorfulTheme::default())
.with_prompt("Optionally choose a note")
.default(0)
.items(&files)
.interact_opt()?;
if let Some(selection) = selection {
let editor = std::env::var("EDITOR")?;
std::process::Command::new(editor)
.arg(files.remove(selection))
.status()?;
}
}
Ok(())
}

View File

@ -40,7 +40,16 @@ pub fn edit(matches: &ArgMatches) -> Result<()> {
}
pub fn list(matches: &ArgMatches) -> Result<()> {
unimplemented!("list all notes, one note or category {:?}", matches);
match matches.is_present("category") {
true => {
let s: String = Input::with_theme(&ColorfulTheme::default())
.with_prompt("Category:")
.interact_text()?;
notes::list_category(&s)?;
}
false => notes::list_all()?,
}
Ok(())
}
pub fn search(matches: &ArgMatches) -> Result<()> {