use std::convert::TryFrom; use std::io::{BufRead, Write}; use clap::ArgMatches; use crate::error::{Error, Result}; use crate::database::Database; use crate::interactive::ask; use crate::io::Streams; use super::{Command, Facts}; #[derive(Debug)] pub enum Args { Id(u64), Sheet(String), } impl<'a> TryFrom<&'a ArgMatches<'a>> for Args { type Error = Error; fn try_from(args: &'a ArgMatches) -> Result { Ok(args.value_of("id").map(|v| { Args::Id(v.parse().unwrap()) }).unwrap_or_else(|| { Args::Sheet(args.value_of("sheet").unwrap().to_owned()) })) } } pub struct KillCommand; impl<'a> Command<'a> for KillCommand { type Args = Args; fn handle(args: Args, streams: &mut Streams, _facts: &Facts) -> Result<()> where D: Database, I: BufRead, O: Write, E: Write, { match args { Args::Id(id) => { if let Some(entry) = streams.db.entry_by_id(id)? { if ask(streams, &format!("are you sure you want to delete entry {}? ({})", entry.id, entry.note.unwrap_or_else(|| "".into())))? { streams.db.delete_entry_by_id(id)?; writeln!(streams.out, "It's dead")?; } else { writeln!(streams.out, "Don't worry, it's still there")?; } } else { writeln!(streams.out, "There's no entry with id {}. Someone found it before we did.", id)?; } }, Args::Sheet(sheet) => { let n = streams.db.entries_by_sheet(&sheet, None, None)?.len(); if ask(streams, &format!("are you sure you want to delete {} entries on sheet \"{}\"?", n, sheet))? { streams.db.delete_entries_in_sheet(&sheet)?; writeln!(streams.out, "They're gone")?; } else { writeln!(streams.out, "Don't worry, they're still there")?; } } } Ok(()) } }