Skip to main content

systemprompt_cli/
interactive.rs

1//! Interactive prompting helpers shared across commands.
2//!
3//! [`Prompter`] is the single seam over operator interaction: production code
4//! uses [`DialoguerPrompter`] (terminal prompts via `dialoguer`), tests use
5//! [`ScriptedPrompter`] with queued answers. The flag-bridging helpers
6//! ([`require_confirmation`], [`resolve_required`], …) keep their behaviour:
7//! interactive mode prompts, non-interactive mode falls back to a default or
8//! fails with a "flag required" error.
9
10use std::collections::VecDeque;
11use std::sync::Mutex;
12
13use crate::CliConfig;
14use anyhow::{Result, anyhow};
15use dialoguer::theme::ColorfulTheme;
16use dialoguer::{Confirm, Input, Password, Select};
17
18pub trait Prompter: Send + Sync {
19    fn confirm(&self, message: &str, default: bool) -> Result<bool>;
20    fn input(&self, prompt: &str) -> Result<String>;
21    fn input_with_default(&self, prompt: &str, default: &str) -> Result<String>;
22    fn select(&self, prompt: &str, items: &[String]) -> Result<usize>;
23    fn password(&self, prompt: &str) -> Result<String>;
24}
25
26#[derive(Debug, Clone, Copy, Default)]
27pub struct DialoguerPrompter;
28
29impl Prompter for DialoguerPrompter {
30    fn confirm(&self, message: &str, default: bool) -> Result<bool> {
31        Ok(Confirm::with_theme(&ColorfulTheme::default())
32            .with_prompt(message)
33            .default(default)
34            .interact()?)
35    }
36
37    fn input(&self, prompt: &str) -> Result<String> {
38        Ok(Input::<String>::with_theme(&ColorfulTheme::default())
39            .with_prompt(prompt)
40            .interact_text()?)
41    }
42
43    fn input_with_default(&self, prompt: &str, default: &str) -> Result<String> {
44        Ok(Input::<String>::with_theme(&ColorfulTheme::default())
45            .with_prompt(prompt)
46            .default(default.to_owned())
47            .interact_text()?)
48    }
49
50    fn select(&self, prompt: &str, items: &[String]) -> Result<usize> {
51        Ok(Select::with_theme(&ColorfulTheme::default())
52            .with_prompt(prompt)
53            .items(items)
54            .default(0)
55            .interact()?)
56    }
57
58    fn password(&self, prompt: &str) -> Result<String> {
59        Ok(Password::with_theme(&ColorfulTheme::default())
60            .with_prompt(prompt)
61            .interact()?)
62    }
63}
64
65#[derive(Debug, Default)]
66pub struct ScriptedPrompter {
67    answers: Mutex<VecDeque<String>>,
68}
69
70impl ScriptedPrompter {
71    #[must_use]
72    pub fn new(answers: impl IntoIterator<Item = impl Into<String>>) -> Self {
73        Self {
74            answers: Mutex::new(answers.into_iter().map(Into::into).collect()),
75        }
76    }
77
78    fn next_answer(&self, prompt: &str) -> Result<String> {
79        self.answers
80            .lock()
81            .map_err(|e| anyhow!("Scripted prompter lock poisoned: {e}"))?
82            .pop_front()
83            .ok_or_else(|| anyhow!("Scripted prompter exhausted at prompt: {prompt}"))
84    }
85}
86
87impl Prompter for ScriptedPrompter {
88    fn confirm(&self, message: &str, _default: bool) -> Result<bool> {
89        let answer = self.next_answer(message)?;
90        Ok(matches!(
91            answer.to_lowercase().as_str(),
92            "y" | "yes" | "true"
93        ))
94    }
95
96    fn input(&self, prompt: &str) -> Result<String> {
97        self.next_answer(prompt)
98    }
99
100    fn input_with_default(&self, prompt: &str, default: &str) -> Result<String> {
101        match self.next_answer(prompt) {
102            Ok(answer) if answer.is_empty() => Ok(default.to_owned()),
103            other => other,
104        }
105    }
106
107    fn select(&self, prompt: &str, items: &[String]) -> Result<usize> {
108        let answer = self.next_answer(prompt)?;
109        let idx: usize = answer
110            .parse()
111            .map_err(|e| anyhow!("Scripted select answer '{answer}' is not an index: {e}"))?;
112        if idx >= items.len() {
113            return Err(anyhow!(
114                "Scripted select index {idx} out of range for {} items",
115                items.len()
116            ));
117        }
118        Ok(idx)
119    }
120
121    fn password(&self, prompt: &str) -> Result<String> {
122        self.next_answer(prompt)
123    }
124}
125
126pub fn require_confirmation(
127    message: &str,
128    skip_confirmation: bool,
129    config: &CliConfig,
130) -> Result<()> {
131    require_confirmation_with(
132        &DialoguerPrompter,
133        message,
134        skip_confirmation,
135        false,
136        config,
137    )
138}
139
140pub fn require_confirmation_default_yes(
141    message: &str,
142    skip_confirmation: bool,
143    config: &CliConfig,
144) -> Result<()> {
145    require_confirmation_with(&DialoguerPrompter, message, skip_confirmation, true, config)
146}
147
148pub fn require_confirmation_with(
149    prompter: &dyn Prompter,
150    message: &str,
151    skip_confirmation: bool,
152    default: bool,
153    config: &CliConfig,
154) -> Result<()> {
155    if skip_confirmation {
156        return Ok(());
157    }
158
159    if !config.is_interactive() {
160        return Err(anyhow!("--yes is required in non-interactive mode"));
161    }
162
163    if prompter.confirm(message, default)? {
164        Ok(())
165    } else {
166        Err(anyhow!("Operation cancelled"))
167    }
168}
169
170pub fn resolve_required<T, F>(
171    value: Option<T>,
172    flag_name: &str,
173    config: &CliConfig,
174    prompt_fn: F,
175) -> Result<T>
176where
177    F: FnOnce() -> Result<T>,
178{
179    match value {
180        Some(v) => Ok(v),
181        None if config.is_interactive() => prompt_fn(),
182        None => Err(anyhow!(
183            "--{} is required in non-interactive mode",
184            flag_name
185        )),
186    }
187}
188
189pub fn select_from_list<T: ToString + Clone>(
190    prompt: &str,
191    items: &[T],
192    flag_name: &str,
193    config: &CliConfig,
194) -> Result<T> {
195    if items.is_empty() {
196        return Err(anyhow!("No items available for selection"));
197    }
198
199    if !config.is_interactive() {
200        return Err(anyhow!(
201            "--{} is required in non-interactive mode",
202            flag_name
203        ));
204    }
205
206    let display: Vec<String> = items.iter().map(ToString::to_string).collect();
207    let idx = DialoguerPrompter.select(prompt, &display)?;
208    Ok(items[idx].clone())
209}
210
211pub fn select_index(prompt: &str, items: &[&str], config: &CliConfig) -> Result<Option<usize>> {
212    if !config.is_interactive() {
213        return Ok(None);
214    }
215
216    let display: Vec<String> = items.iter().map(|s| (*s).to_owned()).collect();
217    Ok(Some(DialoguerPrompter.select(prompt, &display)?))
218}
219
220pub fn prompt_input(prompt: &str, flag_name: &str, config: &CliConfig) -> Result<String> {
221    if !config.is_interactive() {
222        return Err(anyhow!(
223            "--{} is required in non-interactive mode",
224            flag_name
225        ));
226    }
227
228    DialoguerPrompter.input(prompt)
229}
230
231pub fn prompt_input_with_default(
232    prompt: &str,
233    default: &str,
234    config: &CliConfig,
235) -> Result<String> {
236    if !config.is_interactive() {
237        return Ok(default.to_owned());
238    }
239
240    DialoguerPrompter.input_with_default(prompt, default)
241}
242
243pub fn confirm_optional(message: &str, default: bool, config: &CliConfig) -> Result<bool> {
244    if !config.is_interactive() {
245        return Ok(default);
246    }
247
248    DialoguerPrompter.confirm(message, default)
249}