use std::collections::BTreeMap;
use rho_protocol::{
Ask, DefaultStyle, InputAnswer, InputRequest, InputRequestId, Question, QuestionAsk, Selection,
};
use super::console::one_line;
use crate::{
control_chars::{escape_controls, LineBreaks},
permission::PermissionMode,
};
pub(super) struct Prompt {
id: InputRequestId,
kind: Kind,
}
enum Kind {
Pick {
preface: Option<String>,
options: Vec<(String, InputAnswer)>,
},
Questions {
ask: QuestionAsk,
answers: BTreeMap<String, Vec<String>>,
index: usize,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum Reply {
Answer(InputAnswer),
Next,
Retry(String),
}
impl Prompt {
pub(super) fn new(request: &InputRequest) -> Option<Self> {
let kind = match &request.ask {
Ask::Approval(_) => Kind::Pick {
preface: None,
options: vec![
("allow once".to_owned(), InputAnswer::AllowOnce),
("allow for session".to_owned(), InputAnswer::AllowForSession),
("deny".to_owned(), InputAnswer::Deny { reason: None }),
],
},
Ask::PlanApproval(plan) => {
let mut options: Vec<_> = plan
.modes
.iter()
.filter_map(|&wire| {
let mode = PermissionMode::try_from(wire).ok()?;
Some((
format!("approve in {}", mode.as_str()),
InputAnswer::ApprovePlan {
mode: wire,
feedback: None,
},
))
})
.collect();
options.push((
"keep planning".to_owned(),
InputAnswer::KeepPlanning { feedback: None },
));
Kind::Pick {
preface: Some(escape_controls(plan.plan.trim_end(), LineBreaks::Keep)),
options,
}
}
Ask::Question(ask) if !ask.questions.is_empty() => Kind::Questions {
ask: ask.clone(),
answers: BTreeMap::new(),
index: 0,
},
_ => return None,
};
Some(Self {
id: request.id,
kind,
})
}
pub(super) fn id(&self) -> InputRequestId {
self.id
}
pub(super) fn opening(&self) -> String {
match &self.kind {
Kind::Pick {
preface: Some(preface),
..
} => format!("{preface}\n{}", self.asking()),
Kind::Pick { preface: None, .. } | Kind::Questions { .. } => self.asking(),
}
}
pub(super) fn asking(&self) -> String {
match &self.kind {
Kind::Pick { options, .. } => {
let options: Vec<String> = (1..)
.zip(options)
.map(|(n, (label, _))| format!("{n} {label}"))
.collect();
format!(" {}\n", options.join(" · "))
}
Kind::Questions { ask, index, .. } => question_text(ask, *index),
}
}
pub(super) fn reply(&mut self, line: &str) -> Reply {
let line = line.trim();
match &mut self.kind {
Kind::Pick { options, .. } => match line
.parse::<usize>()
.ok()
.and_then(|n| options.get(n.checked_sub(1)?))
{
Some((_, answer)) => Reply::Answer(answer.clone()),
None => Reply::Retry(format!("answer a number from 1 to {}", options.len())),
},
Kind::Questions {
ask,
answers,
index,
} => {
match line {
"/decline" => return Reply::Answer(InputAnswer::Decline),
"/dismiss" => return Reply::Answer(InputAnswer::Dismiss),
_ => {}
}
let question = &ask.questions[*index];
match picked(question, line) {
Ok(Some(values)) => {
answers.insert(question.id.clone(), values);
}
Ok(None) => {}
Err(why) => return Reply::Retry(why),
}
*index += 1;
if *index < ask.questions.len() {
Reply::Next
} else {
Reply::Answer(InputAnswer::Answers {
answers: std::mem::take(answers),
})
}
}
}
}
}
fn text_only(question: &Question) -> bool {
question.allow_other && matches!(question.choices.as_slice(), [only] if only.value == "other")
}
fn picked(question: &Question, line: &str) -> Result<Option<Vec<String>>, String> {
if line.is_empty() {
return match &question.default {
Some(default) if default.style == DefaultStyle::Selected => {
Ok(Some(distinct(default.values.iter())))
}
_ if question.required => Err("this question needs an answer".to_owned()),
_ => Ok(None),
};
}
if text_only(question) {
return Ok(Some(vec![line.to_owned()]));
}
let numbers: Option<Vec<usize>> = line
.split([',', ' '])
.filter(|part| !part.is_empty())
.map(|part| part.parse().ok())
.collect();
let choice = |n: usize| question.choices.get(n.checked_sub(1)?);
match numbers {
Some(numbers) if !numbers.is_empty() && numbers.iter().all(|&n| choice(n).is_some()) => {
if numbers.len() > 1 && question.selection != Selection::Many {
return Err("pick one".to_owned());
}
Ok(Some(distinct(
numbers.into_iter().filter_map(choice).map(|c| &c.value),
)))
}
_ if question.allow_other => Ok(Some(vec![line.to_owned()])),
Some(numbers) => match numbers.into_iter().find(|&n| choice(n).is_none()) {
Some(missing) => Err(format!("there is no choice {missing}")),
None => Err("pick by number".to_owned()),
},
None => Err("pick by number".to_owned()),
}
}
fn distinct<'a>(values: impl Iterator<Item = &'a String>) -> Vec<String> {
let mut distinct = Vec::new();
for value in values {
if !distinct.contains(value) {
distinct.push(value.clone());
}
}
distinct
}
fn question_text(ask: &QuestionAsk, index: usize) -> String {
let question = &ask.questions[index];
let mut text = format!(" {}/{} ", index + 1, ask.questions.len());
if let Some(header) = &question.header {
text.push_str(&format!("{}: ", one_line(header)));
}
text.push_str(&one_line(&question.prompt));
if !question.required {
text.push_str(" (optional)");
}
text.push('\n');
if let Some(help) = &question.help {
text.push_str(&format!(" {}\n", one_line(help)));
}
let mut how = Vec::new();
if text_only(question) {
how.push("type your answer".to_owned());
} else {
for (n, choice) in (1..).zip(&question.choices) {
text.push_str(&format!(" {n} {}", one_line(&choice.label)));
if let Some(description) = &choice.description {
text.push_str(&format!(" — {}", one_line(description)));
}
text.push('\n');
}
match (question.choices.is_empty(), question.selection) {
(true, _) => {}
(false, Selection::Many) => how.push("pick any, like 1,3".to_owned()),
(false, _) => how.push("pick one".to_owned()),
}
if question.allow_other {
how.push("or type your own answer".to_owned());
}
}
match &question.default {
Some(default) if default.style == DefaultStyle::Selected => {
how.push(format!("Enter takes {}", labels(question, &default.values)));
}
Some(default) => {
how.push(format!("suggested: {}", labels(question, &default.values)));
if !question.required {
how.push("Enter skips".to_owned());
}
}
None if !question.required => how.push("Enter skips".to_owned()),
None => {}
}
how.push("/decline or /dismiss closes the questions".to_owned());
text.push_str(&format!(" {}\n", how.join("; ")));
text
}
fn labels(question: &Question, values: &[String]) -> String {
distinct(values.iter())
.iter()
.map(|value| {
question
.choices
.iter()
.find(|choice| &choice.value == value)
.map_or(value.as_str(), |choice| choice.label.as_str())
})
.map(one_line)
.collect::<Vec<_>>()
.join(", ")
}
#[cfg(test)]
#[path = "prompt_tests.rs"]
mod tests;