Skip to content

Commit 49dcbc5

Browse files
committed
terminal: Extend Ask default actions, prompts
Signed-off-by: Manos Pitsidianakis <[email protected]>
1 parent 2069b4d commit 49dcbc5

File tree

2 files changed

+45
-14
lines changed

2 files changed

+45
-14
lines changed

meli/src/conf.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -325,12 +325,10 @@ impl FileSettings {
325325
.set_kind(ErrorKind::Configuration));
326326
}
327327
#[cfg(not(test))]
328-
let ask = crate::terminal::Ask {
329-
message: format!(
330-
"No configuration found. Would you like to generate one in {}?",
331-
path_string
332-
),
333-
};
328+
let ask = crate::terminal::Ask::new(format!(
329+
"No configuration found. Would you like to generate one in {}?",
330+
path_string
331+
));
334332
#[cfg(not(test))]
335333
if ask.run() {
336334
create_config_file(&config_path)?;

meli/src/terminal.rs

Lines changed: 41 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -422,33 +422,66 @@ derive_csi_sequence!(
422422
(QuerySynchronizedOutputSupport, "?2026$p")
423423
);
424424

425-
pub struct Ask {
426-
pub message: String,
425+
pub struct Ask<'m> {
426+
message: Cow<'m, str>,
427+
default: Option<bool>,
427428
}
428429

429-
impl Ask {
430+
impl<'m> Ask<'m> {
431+
pub fn new<M>(m: M) -> Self
432+
where
433+
M: Into<Cow<'m, str>>,
434+
{
435+
let message = m.into();
436+
Self {
437+
message,
438+
default: Some(true),
439+
}
440+
}
441+
442+
pub fn yes_by_default(self, default: bool) -> Self {
443+
Self {
444+
default: Some(default),
445+
..self
446+
}
447+
}
448+
449+
pub fn without_default(self) -> Self {
450+
Self {
451+
default: None,
452+
..self
453+
}
454+
}
455+
430456
pub fn run(self) -> bool {
431457
let mut buffer = String::new();
432458
let stdin = std::io::stdin();
433459
let mut handle = stdin.lock();
434460

435-
print!("{} [Y/n] ", &self.message);
461+
let default = match self.default {
462+
None => "y/n",
463+
Some(true) => "Y/n",
464+
Some(false) => "y/N",
465+
};
466+
467+
print!("{} [{default}] ", self.message.as_ref());
436468
let _ = std::io::stdout().flush();
437469
loop {
438470
buffer.clear();
439471
handle
440472
.read_line(&mut buffer)
441473
.expect("Could not read from stdin.");
442474

443-
match buffer.trim() {
444-
"" | "Y" | "y" | "yes" | "YES" | "Yes" => {
475+
match (buffer.trim(), self.default) {
476+
("", Some(val)) => return val,
477+
("Y" | "y" | "yes" | "YES" | "Yes", _) => {
445478
return true;
446479
}
447-
"n" | "N" | "no" | "No" | "NO" => {
480+
("n" | "N" | "no" | "No" | "NO", _) => {
448481
return false;
449482
}
450483
_ => {
451-
print!("\n{} [Y/n] ", &self.message);
484+
print!("\n{} [{default}] ", self.message.as_ref());
452485
let _ = std::io::stdout().flush();
453486
}
454487
}

0 commit comments

Comments
 (0)