standout-input 7.6.1

Declarative input collection for CLI applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
//! Test injection for interactive prompts.
//!
//! Wizard / setup-helper / REPL flows that build on the `.prompt()` shortcut
//! on every interactive source ([`InquireText`](crate::InquireText),
//! [`InquireSelect`](crate::InquireSelect), [`TextPromptSource`](crate::TextPromptSource),
//! and friends) are otherwise untestable in process — the inquire backends
//! reach for raw stdin and the simple-prompts and editor sources need a TTY.
//!
//! [`PromptResponder`] is the test seam: every `.prompt()` call consults a
//! process-global responder first, and falls through to the real backend
//! only when none is installed. Tests install a [`ScriptedResponder`] with
//! a queue of typed [`PromptResponse`] values; the production wizard code
//! is unchanged.
//!
//! # Why responses are typed by *kind*, not by message text
//!
//! For finite-choice prompts ([`Select`](PromptKind::Select),
//! [`MultiSelect`](PromptKind::MultiSelect), [`Confirm`](PromptKind::Confirm))
//! the response is the *position* (or boolean) — never the option's display
//! label. Renaming "Production" to "Live" doesn't break a test that picked
//! `Choice(2)`. Same for confirm: a test asserts on `true`/`false`, not on
//! the prompt copy.
//!
//! Open prompts ([`Text`](PromptKind::Text), [`Password`](PromptKind::Password),
//! [`Editor`](PromptKind::Editor)) take a `String`, since the value *is* the
//! free-form answer.
//!
//! See the "Testing Wizards" section in the
//! [Interactive Flows topic](../../docs/topics/interactive-flows.md) for a
//! full example.

use std::sync::Arc;

use once_cell::sync::Lazy;
use std::sync::Mutex;

/// The kind of prompt being responded to.
///
/// The interactive source passes its kind to the responder; the responder
/// returns a [`PromptResponse`]. A scripted responder uses the kind to
/// validate that the next queued response matches what the source actually
/// asked for, panicking with a descriptive message on mismatch (a wizard-
/// reorder bug surfaces at the test, not as a silent wrong-data assert
/// downstream).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PromptKind {
    /// Free-form text input ([`InquireText`](crate::InquireText),
    /// [`TextPromptSource`](crate::TextPromptSource)).
    Text,
    /// Masked password input ([`InquirePassword`](crate::InquirePassword)).
    Password,
    /// Editor-based multi-line input ([`EditorSource`](crate::EditorSource),
    /// [`InquireEditor`](crate::InquireEditor)).
    Editor,
    /// Yes/no ([`InquireConfirm`](crate::InquireConfirm),
    /// [`ConfirmPromptSource`](crate::ConfirmPromptSource)).
    Confirm,
    /// Single selection from a list ([`InquireSelect`](crate::InquireSelect)).
    Select,
    /// Multi-selection from a list ([`InquireMultiSelect`](crate::InquireMultiSelect)).
    MultiSelect,
}

impl std::fmt::Display for PromptKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Text => write!(f, "text"),
            Self::Password => write!(f, "password"),
            Self::Editor => write!(f, "editor"),
            Self::Confirm => write!(f, "confirm"),
            Self::Select => write!(f, "select"),
            Self::MultiSelect => write!(f, "multi-select"),
        }
    }
}

/// Context the source passes to a [`PromptResponder`].
///
/// Includes everything a smart responder might want: the prompt kind, the
/// human-facing message (for diagnostic / advanced matching), and — for
/// finite-choice prompts — the size of the option list so a `Choice(i)`
/// response can be range-checked.
#[derive(Debug, Clone, Copy)]
pub struct PromptContext<'a> {
    /// What kind of prompt is asking.
    pub kind: PromptKind,
    /// The human-facing prompt message (e.g. `"Pack name:"`).
    ///
    /// Mostly useful for diagnostics in panic messages and for advanced
    /// responders that want to match on text. Position-based scripted
    /// responders don't need to consult it.
    pub message: &'a str,
    /// Size of the option list, for `Select` / `MultiSelect`. `None` for
    /// open prompts and confirm.
    pub options: Option<usize>,
}

/// A response a [`PromptResponder`] can return.
#[derive(Debug, Clone)]
pub enum PromptResponse {
    /// Free-form text answer for [`Text`](PromptKind::Text),
    /// [`Password`](PromptKind::Password), and
    /// [`Editor`](PromptKind::Editor) prompts.
    Text(String),
    /// Boolean answer for [`Confirm`](PromptKind::Confirm) prompts.
    Bool(bool),
    /// Index of the chosen option for [`Select`](PromptKind::Select) prompts.
    /// Must be `< options` or the source will panic.
    Choice(usize),
    /// Indices of the chosen options for [`MultiSelect`](PromptKind::MultiSelect).
    /// Each must be `< options`.
    Choices(Vec<usize>),
    /// Surface this prompt as user cancellation
    /// ([`InputError::PromptCancelled`](crate::InputError::PromptCancelled)).
    Cancel,
    /// Surface this prompt as "no input"
    /// ([`InputError::NoInput`](crate::InputError::NoInput)) — the same path
    /// the source takes when stdin is not a TTY.
    Skip,
}

impl PromptResponse {
    /// Convenience constructor for a text response.
    pub fn text(s: impl Into<String>) -> Self {
        Self::Text(s.into())
    }

    /// Convenience constructor for a multi-select response.
    pub fn choices(indices: impl IntoIterator<Item = usize>) -> Self {
        Self::Choices(indices.into_iter().collect())
    }

    /// Returns the kind this response is *valid* for, if any. `Cancel` and
    /// `Skip` are always valid, so they return `None`.
    pub(crate) fn expected_kind(&self) -> Option<&'static [PromptKind]> {
        match self {
            Self::Text(_) => Some(&[PromptKind::Text, PromptKind::Password, PromptKind::Editor]),
            Self::Bool(_) => Some(&[PromptKind::Confirm]),
            Self::Choice(_) => Some(&[PromptKind::Select]),
            Self::Choices(_) => Some(&[PromptKind::MultiSelect]),
            Self::Cancel | Self::Skip => None,
        }
    }
}

/// Test seam for the `.prompt()` shortcut on interactive sources.
///
/// When a responder is installed via [`set_default_prompt_responder`],
/// every `prompt()` call routes through it instead of opening a real prompt.
/// Implement this trait for custom dispatch logic, or use the bundled
/// [`ScriptedResponder`].
pub trait PromptResponder: Send + Sync {
    /// Produce a response for the given prompt.
    fn respond(&self, ctx: PromptContext<'_>) -> PromptResponse;
}

/// A position-based scripted responder.
///
/// Built from a queue of [`PromptResponse`] values. Each call to
/// [`respond`](PromptResponder::respond) pops the next response and
/// validates that its kind is compatible with the prompt the source
/// actually asked for; if not, it panics with a message that names the
/// position, the prompt kind, and the response kind.
///
/// This makes wizard-reorder bugs surface as test failures at the offending
/// step rather than as silent wrong-data assertions later.
///
/// ```
/// use standout_input::{ScriptedResponder, PromptResponse};
///
/// let responder = ScriptedResponder::new([
///     PromptResponse::text("buy milk"),
///     PromptResponse::Bool(true),
///     PromptResponse::Choice(2),
/// ]);
/// ```
pub struct ScriptedResponder {
    queue: Mutex<std::collections::VecDeque<PromptResponse>>,
}

impl ScriptedResponder {
    /// Create a scripted responder from a sequence of responses.
    pub fn new(responses: impl IntoIterator<Item = PromptResponse>) -> Self {
        Self {
            queue: Mutex::new(responses.into_iter().collect()),
        }
    }

    /// Number of responses still queued.
    pub fn remaining(&self) -> usize {
        self.queue.lock().unwrap().len()
    }
}

impl PromptResponder for ScriptedResponder {
    fn respond(&self, ctx: PromptContext<'_>) -> PromptResponse {
        let response = self.queue.lock().unwrap().pop_front().unwrap_or_else(|| {
            panic!(
                "ScriptedResponder ran out of responses; \
                 next prompt was a `{}` prompt with message {:?}",
                ctx.kind, ctx.message
            )
        });

        if let Some(allowed) = response.expected_kind() {
            if !allowed.contains(&ctx.kind) {
                panic!(
                    "ScriptedResponder kind mismatch: expected response for `{}` prompt \
                     ({:?}), but got {:?}",
                    ctx.kind, ctx.message, response
                );
            }
        }

        // Range-check by reference so we don't move the response we're
        // about to return.
        if let PromptResponse::Choice(i) = &response {
            let n = ctx.options.unwrap_or(0);
            assert!(
                *i < n,
                "ScriptedResponder: Choice({i}) is out of range for select prompt \
                 with {n} option(s) ({:?})",
                ctx.message
            );
        }
        if let PromptResponse::Choices(indices) = &response {
            let n = ctx.options.unwrap_or(0);
            for &i in indices {
                assert!(
                    i < n,
                    "ScriptedResponder: Choices contains {i}, out of range for \
                     multi-select prompt with {n} option(s) ({:?})",
                    ctx.message
                );
            }
        }

        response
    }
}

impl std::fmt::Debug for ScriptedResponder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ScriptedResponder")
            .field("remaining", &self.remaining())
            .finish()
    }
}

// ============================================================================
// Process-global responder override
// ============================================================================

type SharedResponder = Arc<dyn PromptResponder>;

static RESPONDER_OVERRIDE: Lazy<Mutex<Option<SharedResponder>>> = Lazy::new(|| Mutex::new(None));

/// Installs a process-global [`PromptResponder`] that every `.prompt()` call
/// on an interactive source will route through until
/// [`reset_default_prompt_responder`] is called.
///
/// Intended for test harnesses; the `standout-test` crate's
/// `TestHarness::prompts(...)` wires this automatically. Tests using it must
/// run serially (e.g. via `#[serial]`) because the override is process-global.
pub fn set_default_prompt_responder(responder: SharedResponder) {
    *RESPONDER_OVERRIDE.lock().unwrap() = Some(responder);
}

/// Clears the override installed by [`set_default_prompt_responder`].
pub fn reset_default_prompt_responder() {
    *RESPONDER_OVERRIDE.lock().unwrap() = None;
}

/// Returns a clone of the currently installed responder, if any.
///
/// Used by source `.prompt()` implementations to decide whether to short-
/// circuit through the responder or fall through to the real backend.
#[cfg(any(feature = "editor", feature = "simple-prompts", feature = "inquire"))]
pub(crate) fn current_prompt_responder() -> Option<SharedResponder> {
    RESPONDER_OVERRIDE.lock().unwrap().clone()
}

/// Helper used by source `.prompt()` shortcuts that return a free-form
/// `String` (text / password / editor prompts).
///
/// If a responder is installed, dispatches and maps `Text(s) -> Ok(s)`,
/// `Cancel -> PromptCancelled`, `Skip -> NoInput`. Returns `Ok(None)` (i.e.
/// "fall through to the real backend") when no responder is installed, so
/// the caller can use the original `is_available` + `collect` path.
///
/// `Bool` / `Choice` / `Choices` responses against an open prompt panic
/// via `ScriptedResponder`'s validation in production tests.
#[cfg(any(feature = "editor", feature = "simple-prompts", feature = "inquire"))]
pub(crate) fn intercept_text(
    kind: PromptKind,
    message: &str,
) -> Result<Option<String>, crate::InputError> {
    let Some(responder) = current_prompt_responder() else {
        return Ok(None);
    };
    let response = responder.respond(PromptContext {
        kind,
        message,
        options: None,
    });
    match response {
        PromptResponse::Text(s) => Ok(Some(s)),
        PromptResponse::Cancel => Err(crate::InputError::PromptCancelled),
        PromptResponse::Skip => Err(crate::InputError::NoInput),
        other => panic!(
            "PromptResponder returned {other:?} for a `{kind}` prompt; \
             expected Text / Cancel / Skip"
        ),
    }
}

/// Helper for `.prompt()` shortcuts that return a `bool`
/// ([`InquireConfirm`](crate::InquireConfirm),
/// [`ConfirmPromptSource`](crate::ConfirmPromptSource)).
#[cfg(any(feature = "simple-prompts", feature = "inquire"))]
pub(crate) fn intercept_bool(
    kind: PromptKind,
    message: &str,
) -> Result<Option<bool>, crate::InputError> {
    let Some(responder) = current_prompt_responder() else {
        return Ok(None);
    };
    let response = responder.respond(PromptContext {
        kind,
        message,
        options: None,
    });
    match response {
        PromptResponse::Bool(b) => Ok(Some(b)),
        PromptResponse::Cancel => Err(crate::InputError::PromptCancelled),
        PromptResponse::Skip => Err(crate::InputError::NoInput),
        other => panic!(
            "PromptResponder returned {other:?} for a `{kind}` prompt; \
             expected Bool / Cancel / Skip"
        ),
    }
}

/// Helper for [`InquireSelect`](crate::InquireSelect)::prompt(). Returns
/// the selected *index* into the source's options vector; the caller
/// performs the `options[i].clone()` so the typed `T` flows out.
#[cfg(feature = "inquire")]
pub(crate) fn intercept_choice(
    message: &str,
    n: usize,
) -> Result<Option<usize>, crate::InputError> {
    let Some(responder) = current_prompt_responder() else {
        return Ok(None);
    };
    let response = responder.respond(PromptContext {
        kind: PromptKind::Select,
        message,
        options: Some(n),
    });
    match response {
        PromptResponse::Choice(i) => {
            assert!(
                i < n,
                "PromptResponder returned Choice({i}) for select prompt with {n} option(s)"
            );
            Ok(Some(i))
        }
        PromptResponse::Cancel => Err(crate::InputError::PromptCancelled),
        PromptResponse::Skip => Err(crate::InputError::NoInput),
        other => panic!(
            "PromptResponder returned {other:?} for a `select` prompt; \
             expected Choice / Cancel / Skip"
        ),
    }
}

/// Helper for [`InquireMultiSelect`](crate::InquireMultiSelect)::prompt().
/// Returns the selected indices.
#[cfg(feature = "inquire")]
pub(crate) fn intercept_choices(
    message: &str,
    n: usize,
) -> Result<Option<Vec<usize>>, crate::InputError> {
    let Some(responder) = current_prompt_responder() else {
        return Ok(None);
    };
    let response = responder.respond(PromptContext {
        kind: PromptKind::MultiSelect,
        message,
        options: Some(n),
    });
    match response {
        PromptResponse::Choices(indices) => {
            for &i in &indices {
                assert!(
                    i < n,
                    "PromptResponder returned Choices containing {i} for multi-select \
                     prompt with {n} option(s)"
                );
            }
            Ok(Some(indices))
        }
        PromptResponse::Cancel => Err(crate::InputError::PromptCancelled),
        PromptResponse::Skip => Err(crate::InputError::NoInput),
        other => panic!(
            "PromptResponder returned {other:?} for a `multi-select` prompt; \
             expected Choices / Cancel / Skip"
        ),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serial_test::serial;

    fn ctx(kind: PromptKind, options: Option<usize>) -> PromptContext<'static> {
        PromptContext {
            kind,
            message: "test prompt",
            options,
        }
    }

    #[test]
    fn scripted_responder_returns_in_order() {
        let r = ScriptedResponder::new([
            PromptResponse::text("first"),
            PromptResponse::Bool(true),
            PromptResponse::Choice(1),
        ]);
        assert!(
            matches!(r.respond(ctx(PromptKind::Text, None)), PromptResponse::Text(s) if s == "first")
        );
        assert!(matches!(
            r.respond(ctx(PromptKind::Confirm, None)),
            PromptResponse::Bool(true)
        ));
        assert!(matches!(
            r.respond(ctx(PromptKind::Select, Some(3))),
            PromptResponse::Choice(1)
        ));
        assert_eq!(r.remaining(), 0);
    }

    #[test]
    fn cancel_and_skip_are_kind_agnostic() {
        let r = ScriptedResponder::new([PromptResponse::Cancel, PromptResponse::Skip]);
        // Cancel is fine for any kind
        assert!(matches!(
            r.respond(ctx(PromptKind::Select, Some(2))),
            PromptResponse::Cancel
        ));
        // Skip too
        assert!(matches!(
            r.respond(ctx(PromptKind::Confirm, None)),
            PromptResponse::Skip
        ));
    }

    #[test]
    fn text_response_works_for_all_open_kinds() {
        let r = ScriptedResponder::new([
            PromptResponse::text("a"),
            PromptResponse::text("b"),
            PromptResponse::text("c"),
        ]);
        assert!(matches!(
            r.respond(ctx(PromptKind::Text, None)),
            PromptResponse::Text(_)
        ));
        assert!(matches!(
            r.respond(ctx(PromptKind::Password, None)),
            PromptResponse::Text(_)
        ));
        assert!(matches!(
            r.respond(ctx(PromptKind::Editor, None)),
            PromptResponse::Text(_)
        ));
    }

    #[test]
    #[should_panic(expected = "kind mismatch")]
    fn scripted_responder_panics_on_kind_mismatch() {
        let r = ScriptedResponder::new([PromptResponse::text("oops")]);
        // Confirm prompt with a Text response — wizard order changed and
        // the test should fail loudly here, not 3 lines later.
        let _ = r.respond(ctx(PromptKind::Confirm, None));
    }

    #[test]
    #[should_panic(expected = "out of range")]
    fn scripted_responder_panics_on_out_of_range_choice() {
        let r = ScriptedResponder::new([PromptResponse::Choice(5)]);
        let _ = r.respond(ctx(PromptKind::Select, Some(3)));
    }

    #[test]
    #[should_panic(expected = "out of range")]
    fn scripted_responder_panics_on_out_of_range_multiselect() {
        let r = ScriptedResponder::new([PromptResponse::choices([0, 7])]);
        let _ = r.respond(ctx(PromptKind::MultiSelect, Some(3)));
    }

    #[test]
    #[should_panic(expected = "ran out of responses")]
    fn scripted_responder_panics_when_exhausted() {
        let r = ScriptedResponder::new([PromptResponse::text("only")]);
        let _ = r.respond(ctx(PromptKind::Text, None));
        let _ = r.respond(ctx(PromptKind::Text, None));
    }

    // current_prompt_responder() is only compiled when at least one
    // prompt-producing feature is enabled, so the test that exercises it
    // shares the same cfg gate. Under --no-default-features the install /
    // reset path is unobservable from the public API, so there's no test
    // to write.
    #[cfg(any(feature = "editor", feature = "simple-prompts", feature = "inquire"))]
    #[test]
    #[serial(prompt_responder)]
    fn install_and_reset_default_responder() {
        assert!(current_prompt_responder().is_none());
        set_default_prompt_responder(Arc::new(ScriptedResponder::new([])));
        assert!(current_prompt_responder().is_some());
        reset_default_prompt_responder();
        assert!(current_prompt_responder().is_none());
    }
}