refactoring

This commit is contained in:
steven-omaha
2023-02-02 15:32:23 +01:00
parent 2ff6a1741d
commit 76de65f9ac
4 changed files with 25 additions and 15 deletions
+2 -2
View File
@@ -98,7 +98,7 @@ impl Pacdef {
to_install.show("install".into());
if !get_user_confirmation() {
if !get_user_confirmation()? {
return Ok(());
};
@@ -178,7 +178,7 @@ impl Pacdef {
to_remove.show("remove".into());
if !get_user_confirmation() {
if !get_user_confirmation()? {
return Ok(());
};
+1 -2
View File
@@ -1,7 +1,6 @@
use std::fmt::Write as FmtWrite;
use std::fs::{read_to_string, File};
use std::hash::Hash;
use std::io::Write as IoWrite;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::{collections::HashSet, fmt::Display};
+1 -1
View File
@@ -50,7 +50,7 @@ pub(crate) fn review(
strat.show();
}
if !get_user_confirmation() {
if !get_user_confirmation()? {
return Ok(());
}
+21 -10
View File
@@ -1,30 +1,41 @@
use std::io::{self, BufRead, Read, Write};
use std::io::{self, Read, Write};
use anyhow::Result;
use anyhow::{Context, Result};
use termios::*;
#[must_use]
pub(crate) fn get_user_confirmation() -> bool {
pub(crate) fn get_user_confirmation() -> Result<bool> {
print!("Continue? [Y/n] ");
std::io::stdout().flush().unwrap();
let reply = std::io::stdin().lock().lines().next().unwrap().unwrap();
reply.trim().is_empty() || reply.to_lowercase().contains('y')
let mut reply = String::new();
std::io::stdin()
.read_line(&mut reply)
.context("reading stdin")?;
Ok(reply.trim().is_empty() || reply.to_lowercase().contains('y'))
}
pub(crate) fn read_single_char_from_terminal() -> Result<char> {
let fd = 0; // 0 is the file descriptor for stdin
let termios = Termios::from_fd(fd)?;
// 0 is the file descriptor for stdin
let fd = 0;
let termios = Termios::from_fd(fd).context("getting stdin fd")?;
let mut new_termios = termios;
new_termios.c_lflag &= !(ICANON | ECHO);
new_termios.c_cc[VMIN] = 1;
new_termios.c_cc[VTIME] = 0;
tcsetattr(fd, TCSANOW, &new_termios).unwrap();
tcsetattr(fd, TCSANOW, &new_termios).context("setting terminal mode")?;
let mut input = [0u8; 1];
io::stdin().read_exact(&mut input[..]).unwrap();
io::stdin()
.read_exact(&mut input[..])
.context("reading one byte from stdin")?;
let result = input[0] as char;
// stdin is not echoed automatically in this terminal mode
println!("{result}");
tcsetattr(fd, TCSANOW, &termios).unwrap(); // restore previous settings
// restore previous settings
tcsetattr(fd, TCSANOW, &termios).context("restoring terminal mode")?;
Ok(result)
}