1use dialoguer::{Confirm, Password, theme::ColorfulTheme};
22use indicatif::{ProgressBar, ProgressStyle};
23use std::env;
24use std::io::{self, IsTerminal};
25use std::time::Duration;
26
27#[derive(Debug, Clone, Default, PartialEq, Eq)]
33#[non_exhaustive]
34pub struct InteractiveRuntime {
35 pub stdin_is_tty: bool,
37 pub stderr_is_tty: bool,
39 pub terminal: Option<String>,
41}
42
43impl InteractiveRuntime {
44 pub fn new(stdin_is_tty: bool, stderr_is_tty: bool, terminal: Option<String>) -> Self {
46 Self {
47 stdin_is_tty,
48 stderr_is_tty,
49 terminal,
50 }
51 }
52
53 pub fn detect() -> Self {
55 Self::new(
56 io::stdin().is_terminal(),
57 io::stderr().is_terminal(),
58 env::var("TERM").ok(),
59 )
60 }
61
62 pub fn allows_prompting(&self) -> bool {
79 self.stdin_is_tty && self.stderr_is_tty
80 }
81
82 pub fn allows_live_output(&self) -> bool {
95 self.stderr_is_tty && !matches!(self.terminal.as_deref(), Some("dumb"))
96 }
97}
98
99pub type InteractiveResult<T> = io::Result<T>;
101
102#[derive(Debug, Clone)]
103pub struct Interactive {
105 runtime: InteractiveRuntime,
106}
107
108impl Default for Interactive {
109 fn default() -> Self {
110 Self::detect()
111 }
112}
113
114impl Interactive {
115 pub fn detect() -> Self {
117 Self::new(InteractiveRuntime::detect())
118 }
119
120 pub fn new(runtime: InteractiveRuntime) -> Self {
136 Self { runtime }
137 }
138
139 pub fn runtime(&self) -> &InteractiveRuntime {
141 &self.runtime
142 }
143
144 pub fn confirm(&self, prompt: &str) -> InteractiveResult<bool> {
146 self.confirm_default(prompt, false)
147 }
148
149 pub fn confirm_default(&self, prompt: &str, default: bool) -> InteractiveResult<bool> {
151 self.require_prompting("confirmation prompt")?;
152 Confirm::with_theme(&ColorfulTheme::default())
153 .with_prompt(prompt)
154 .default(default)
155 .interact()
156 .map_err(io::Error::other)
157 }
158
159 pub fn password(&self, prompt: &str) -> InteractiveResult<String> {
161 self.password_with_options(prompt, false)
162 }
163
164 pub fn password_allow_empty(&self, prompt: &str) -> InteractiveResult<String> {
166 self.password_with_options(prompt, true)
167 }
168
169 pub fn spinner(&self, message: impl Into<String>) -> Spinner {
171 Spinner::with_runtime(&self.runtime, message)
172 }
173
174 fn password_with_options(&self, prompt: &str, allow_empty: bool) -> InteractiveResult<String> {
175 self.require_prompting("password prompt")?;
176 Password::with_theme(&ColorfulTheme::default())
177 .with_prompt(prompt)
178 .allow_empty_password(allow_empty)
179 .interact()
180 .map_err(io::Error::other)
181 }
182
183 fn require_prompting(&self, kind: &str) -> InteractiveResult<()> {
184 if self.runtime.allows_prompting() {
185 return Ok(());
186 }
187 Err(io::Error::other(format!(
188 "{kind} requires an interactive terminal"
189 )))
190 }
191}
192
193pub struct Spinner {
195 pb: ProgressBar,
196}
197
198impl Spinner {
199 pub fn new(message: impl Into<String>) -> Self {
204 Self::with_runtime(&InteractiveRuntime::detect(), message)
205 }
206
207 pub fn with_runtime(runtime: &InteractiveRuntime, message: impl Into<String>) -> Self {
209 Self::with_enabled(runtime.allows_live_output(), message)
210 }
211
212 pub fn with_enabled(enabled: bool, message: impl Into<String>) -> Self {
217 let pb = if enabled {
218 let pb = ProgressBar::new_spinner();
219 pb.enable_steady_tick(Duration::from_millis(120));
220 pb.set_style(
221 ProgressStyle::default_spinner()
222 .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"])
223 .template("{spinner:.cyan} {msg}")
224 .unwrap_or_else(|_| ProgressStyle::default_spinner()),
225 );
226 pb
227 } else {
228 ProgressBar::hidden()
229 };
230 pb.set_message(message.into());
231 Self { pb }
232 }
233
234 pub fn set_message(&self, message: impl Into<String>) {
236 self.pb.set_message(message.into());
237 }
238
239 pub fn suspend<F, R>(&self, f: F) -> R
241 where
242 F: FnOnce() -> R,
243 {
244 self.pb.suspend(f)
245 }
246
247 pub fn finish_success(&self, message: impl Into<String>) {
249 self.pb.finish_with_message(message.into());
250 }
251
252 pub fn finish_failure(&self, message: impl Into<String>) {
254 self.pb.abandon_with_message(message.into());
255 }
256
257 pub fn finish_with_message(&self, message: impl Into<String>) {
262 self.finish_success(message);
263 }
264
265 pub fn finish_and_clear(&self) {
267 self.pb.finish_and_clear();
268 }
269}
270
271#[cfg(test)]
272mod tests {
273 use super::{Interactive, InteractiveRuntime, Spinner};
274
275 fn runtime(
276 stdin_is_tty: bool,
277 stderr_is_tty: bool,
278 terminal: Option<&str>,
279 ) -> InteractiveRuntime {
280 InteractiveRuntime::new(stdin_is_tty, stderr_is_tty, terminal.map(str::to_string))
281 }
282
283 #[test]
284 fn runtime_capability_matrix_covers_prompting_and_live_output_unit() {
285 let cases = [
286 (runtime(true, true, Some("xterm-256color")), true, true),
287 (runtime(true, true, Some("dumb")), true, false),
288 (runtime(false, true, Some("xterm-256color")), false, true),
289 (runtime(true, false, Some("xterm-256color")), false, false),
290 (runtime(true, true, None), true, true),
291 ];
292
293 for (runtime, allows_prompting, allows_live_output) in cases {
294 assert_eq!(runtime.allows_prompting(), allows_prompting);
295 assert_eq!(runtime.allows_live_output(), allows_live_output);
296 }
297 }
298
299 #[test]
300 fn hidden_spinner_supports_full_lifecycle() {
301 let spinner = Spinner::with_enabled(false, "Working");
302 spinner.set_message("Still working");
303 spinner.suspend(|| ());
304 spinner.finish_success("Done");
305 spinner.finish_failure("Failed");
306 spinner.finish_and_clear();
307 }
308
309 #[test]
310 fn spinner_respects_runtime_policy_and_finish_alias() {
311 let live_runtime = runtime(true, true, Some("xterm-256color"));
312 let muted_runtime = runtime(true, true, Some("dumb"));
313
314 let live = Spinner::with_runtime(&live_runtime, "Working");
315 live.set_message("Still working");
316 live.finish_with_message("Done");
317
318 let muted = Spinner::with_runtime(&muted_runtime, "Muted");
319 muted.finish_with_message("Still muted");
320 }
321
322 #[test]
323 fn interactive_runtime_accessor_and_spinner_follow_runtime() {
324 let runtime = runtime(true, true, Some("xterm-256color"));
325 let interactive = Interactive::new(runtime.clone());
326
327 assert_eq!(interactive.runtime(), &runtime);
328 interactive.spinner("Working").finish_and_clear();
329 }
330
331 #[test]
332 fn prompting_helpers_fail_fast_without_interactive_terminal_unit() {
333 let interactive = Interactive::new(runtime(false, false, None));
334
335 for err in [
336 interactive
337 .confirm("Proceed?")
338 .expect_err("confirm should fail"),
339 interactive
340 .password("Password")
341 .expect_err("password should fail"),
342 interactive
343 .password_allow_empty("Password")
344 .expect_err("password prompt should still require a TTY"),
345 ] {
346 assert!(
347 err.to_string().contains("interactive terminal"),
348 "unexpected error: {err}"
349 );
350 }
351 }
352
353 #[test]
354 fn spinner_new_and_detect_paths_are_callable() {
355 let interactive = Interactive::detect();
356 interactive.spinner("Working").finish_and_clear();
357 Spinner::new("Booting").finish_and_clear();
358 }
359
360 #[test]
361 fn default_interactive_matches_detected_runtime_shape() {
362 let detected = Interactive::detect();
363 let defaulted = Interactive::default();
364
365 assert_eq!(
366 defaulted.runtime().stdin_is_tty,
367 detected.runtime().stdin_is_tty
368 );
369 assert_eq!(
370 defaulted.runtime().stderr_is_tty,
371 detected.runtime().stderr_is_tty
372 );
373 }
374}