extract ask() into a function and a module

This commit is contained in:
Abraham Toriz 2021-08-11 20:24:42 -05:00
parent d7e98e51a3
commit 73a0b62c75
3 changed files with 19 additions and 15 deletions

View File

@ -1,5 +1,5 @@
use std::convert::TryFrom;
use std::io::{self, Write};
use std::io::Write;
use clap::ArgMatches;
use chrono::{DateTime, Utc};
@ -7,15 +7,10 @@ use chrono::{DateTime, Utc};
use crate::error::{Error, Result};
use crate::database::Database;
use crate::config::Config;
use crate::interactive::ask;
use super::Command;
fn read_line() -> String {
let mut pre_n = String::new();
io::stdin().read_line(&mut pre_n).unwrap();
pre_n
}
#[derive(Debug)]
pub enum Args {
Id(u64),
@ -48,10 +43,7 @@ impl<'a> Command<'a> for KillCommand {
match args {
Args::Id(id) => {
if let Some(entry) = db.entry_by_id(id)? {
write!(out, "are you sure you want to delete entry {}? ({}) [y/n] ", entry.id, entry.note.unwrap_or_else(|| "".into()))?;
io::stdout().flush()?;
if read_line().to_lowercase().starts_with('y') {
if ask(out, &format!("are you sure you want to delete entry {}? ({})", entry.id, entry.note.unwrap_or_else(|| "".into())))? {
db.delete_entry_by_id(id)?;
writeln!(out, "It's dead")?;
} else {
@ -64,10 +56,7 @@ impl<'a> Command<'a> for KillCommand {
Args::Sheet(sheet) => {
let n = db.entries_by_sheet(&sheet, None, None)?.len();
write!(out, "are you sure you want to delete {} entries on sheet \"{}\"? [y/n] ", n, sheet)?;
io::stdout().flush()?;
if read_line().to_lowercase().starts_with('y') {
if ask(out, &format!("are you sure you want to delete {} entries on sheet \"{}\"?", n, sheet))? {
db.delete_entries_in_sheet(&sheet)?;
writeln!(out, "They're gone")?;
} else {

14
src/interactive.rs Normal file
View File

@ -0,0 +1,14 @@
use std::io::{self, Write};
fn read_line() -> io::Result<String> {
let mut pre_n = String::new();
io::stdin().read_line(&mut pre_n)?;
Ok(pre_n)
}
pub fn ask<W: Write>(out: &mut W, question: &str) -> io::Result<bool> {
write!(out, "{} [y/N] ", question)?;
out.flush()?;
Ok(read_line()?.to_lowercase().starts_with('y'))
}

View File

@ -12,6 +12,7 @@ pub mod timeparse;
pub mod regex;
pub mod tabulate;
pub mod old;
pub mod interactive;
#[cfg(test)]
pub mod test_utils;