standout-input 7.3.0

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
//! Integration tests for standout-input.
//!
//! These tests verify the behavior of input chains across different scenarios,
//! using mocks to ensure consistent behavior in both interactive and CI environments.

use clap::{Arg, Command};
use standout_input::{
    ArgSource, ClipboardSource, EnvSource, FlagSource, InputChain, InputError, InputSourceKind,
    MockClipboard, MockEnv, MockStdin, StdinSource,
};

fn create_test_command() -> Command {
    Command::new("test")
        .arg(Arg::new("message").long("message").short('m'))
        .arg(Arg::new("body").long("body").short('b'))
        .arg(
            Arg::new("yes")
                .long("yes")
                .short('y')
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("no-editor")
                .long("no-editor")
                .action(clap::ArgAction::SetTrue),
        )
}

// ============================================================================
// Test: The "gh pr create" pattern
// ============================================================================
// This is the most common pattern: arg → stdin → editor/default

#[test]
fn gh_pattern_arg_provided() {
    let matches = create_test_command()
        .try_get_matches_from(["test", "--body", "from argument"])
        .unwrap();

    let chain = InputChain::<String>::new()
        .try_source(ArgSource::new("body"))
        .try_source(StdinSource::with_reader(MockStdin::terminal()))
        .default("from default".to_string());

    let result = chain.resolve_with_source(&matches).unwrap();
    assert_eq!(result.value, "from argument");
    assert_eq!(result.source, InputSourceKind::Arg);
}

#[test]
fn gh_pattern_stdin_piped() {
    let matches = create_test_command()
        .try_get_matches_from(["test"]) // No --body
        .unwrap();

    let chain = InputChain::<String>::new()
        .try_source(ArgSource::new("body"))
        .try_source(StdinSource::with_reader(MockStdin::piped("from stdin")))
        .default("from default".to_string());

    let result = chain.resolve_with_source(&matches).unwrap();
    assert_eq!(result.value, "from stdin");
    assert_eq!(result.source, InputSourceKind::Stdin);
}

#[test]
fn gh_pattern_falls_through_to_default() {
    let matches = create_test_command()
        .try_get_matches_from(["test"]) // No --body
        .unwrap();

    let chain = InputChain::<String>::new()
        .try_source(ArgSource::new("body"))
        .try_source(StdinSource::with_reader(MockStdin::terminal())) // Not piped
        .default("from default".to_string());

    let result = chain.resolve_with_source(&matches).unwrap();
    assert_eq!(result.value, "from default");
    assert_eq!(result.source, InputSourceKind::Default);
}

// ============================================================================
// Test: Confirmation patterns (like `rm -i` or `gh pr merge`)
// ============================================================================

#[test]
fn confirmation_with_yes_flag() {
    let matches = create_test_command()
        .try_get_matches_from(["test", "--yes"])
        .unwrap();

    let chain = InputChain::<bool>::new()
        .try_source(FlagSource::new("yes"))
        .default(false);

    let result = chain.resolve(&matches).unwrap();
    assert!(result); // --yes provided
}

#[test]
fn confirmation_without_flag_uses_default() {
    let matches = create_test_command()
        .try_get_matches_from(["test"]) // No --yes
        .unwrap();

    let chain = InputChain::<bool>::new()
        .try_source(FlagSource::new("yes"))
        .default(false);

    let result = chain.resolve(&matches).unwrap();
    assert!(!result); // Uses default
}

#[test]
fn inverted_flag_for_no_editor() {
    let matches = create_test_command()
        .try_get_matches_from(["test", "--no-editor"])
        .unwrap();

    // "use_editor" should be false when --no-editor is provided
    let chain = InputChain::<bool>::new()
        .try_source(FlagSource::new("no-editor").inverted())
        .default(true); // Default to using editor

    let result = chain.resolve(&matches).unwrap();
    assert!(!result); // --no-editor inverted = false
}

// ============================================================================
// Test: Environment variable patterns (like API tokens)
// ============================================================================

#[test]
fn env_var_priority_over_default() {
    let matches = create_test_command()
        .try_get_matches_from(["test"])
        .unwrap();

    let env = MockEnv::new().with_var("MY_TOKEN", "secret-from-env");

    let chain = InputChain::<String>::new()
        .try_source(ArgSource::new("message")) // Not provided
        .try_source(EnvSource::with_reader("MY_TOKEN", env))
        .default("no-token".to_string());

    let result = chain.resolve_with_source(&matches).unwrap();
    assert_eq!(result.value, "secret-from-env");
    assert_eq!(result.source, InputSourceKind::Env);
}

#[test]
fn arg_overrides_env_var() {
    let matches = create_test_command()
        .try_get_matches_from(["test", "--message", "from-arg"])
        .unwrap();

    let env = MockEnv::new().with_var("MY_TOKEN", "secret-from-env");

    let chain = InputChain::<String>::new()
        .try_source(ArgSource::new("message"))
        .try_source(EnvSource::with_reader("MY_TOKEN", env))
        .default("no-token".to_string());

    let result = chain.resolve_with_source(&matches).unwrap();
    assert_eq!(result.value, "from-arg");
    assert_eq!(result.source, InputSourceKind::Arg);
}

// ============================================================================
// Test: Clipboard patterns (like padz prefill)
// ============================================================================

#[test]
fn clipboard_as_fallback() {
    let matches = create_test_command()
        .try_get_matches_from(["test"])
        .unwrap();

    let chain = InputChain::<String>::new()
        .try_source(ArgSource::new("message"))
        .try_source(StdinSource::with_reader(MockStdin::terminal()))
        .try_source(ClipboardSource::with_reader(MockClipboard::with_content(
            "clipboard content",
        )));

    let result = chain.resolve_with_source(&matches).unwrap();
    assert_eq!(result.value, "clipboard content");
    assert_eq!(result.source, InputSourceKind::Clipboard);
}

#[test]
fn empty_clipboard_falls_through() {
    let matches = create_test_command()
        .try_get_matches_from(["test"])
        .unwrap();

    let chain = InputChain::<String>::new()
        .try_source(ArgSource::new("message"))
        .try_source(ClipboardSource::with_reader(MockClipboard::empty()))
        .default("fallback".to_string());

    let result = chain.resolve_with_source(&matches).unwrap();
    assert_eq!(result.value, "fallback");
    assert_eq!(result.source, InputSourceKind::Default);
}

// ============================================================================
// Test: Validation
// ============================================================================

#[test]
fn validation_passes() {
    let matches = create_test_command()
        .try_get_matches_from(["test", "--message", "user@example.com"])
        .unwrap();

    let chain = InputChain::<String>::new()
        .try_source(ArgSource::new("message"))
        .validate(|s| s.contains('@'), "Must be an email");

    let result = chain.resolve(&matches);
    assert!(result.is_ok());
    assert_eq!(result.unwrap(), "user@example.com");
}

#[test]
fn validation_fails_with_error() {
    let matches = create_test_command()
        .try_get_matches_from(["test", "--message", "not-an-email"])
        .unwrap();

    let chain = InputChain::<String>::new()
        .try_source(ArgSource::new("message"))
        .validate(|s| s.contains('@'), "Must be an email");

    let result = chain.resolve(&matches);
    assert!(matches!(result, Err(InputError::ValidationFailed(_))));
}

#[test]
fn multiple_validations_all_pass() {
    let matches = create_test_command()
        .try_get_matches_from(["test", "--message", "hello@world.com"])
        .unwrap();

    let chain = InputChain::<String>::new()
        .try_source(ArgSource::new("message"))
        .validate(|s| !s.is_empty(), "Cannot be empty")
        .validate(|s| s.contains('@'), "Must contain @")
        .validate(|s| s.len() >= 5, "Must be at least 5 chars");

    let result = chain.resolve(&matches);
    assert!(result.is_ok());
}

#[test]
fn multiple_validations_first_fails() {
    let matches = create_test_command()
        .try_get_matches_from(["test", "--message", ""])
        .unwrap();

    // Note: empty string from arg won't be collected, so we use default
    let chain = InputChain::<String>::new()
        .try_source(ArgSource::new("message"))
        .try_source(StdinSource::with_reader(MockStdin::piped("")))
        .default("".to_string())
        .validate(|s| !s.is_empty(), "Cannot be empty");

    let result = chain.resolve(&matches);
    assert!(matches!(result, Err(InputError::ValidationFailed(_))));
}

// ============================================================================
// Test: No input available
// ============================================================================

#[test]
fn no_input_returns_error() {
    let matches = create_test_command()
        .try_get_matches_from(["test"])
        .unwrap();

    let chain = InputChain::<String>::new()
        .try_source(ArgSource::new("message"))
        .try_source(StdinSource::with_reader(MockStdin::terminal()))
        .try_source(EnvSource::with_reader("MISSING", MockEnv::new()));
    // No default!

    let result = chain.resolve(&matches);
    assert!(matches!(result, Err(InputError::NoInput)));
}

// ============================================================================
// Test: Complex multi-source chain
// ============================================================================

#[test]
fn complex_chain_priority() {
    // Tests the full priority: arg → stdin → env → clipboard → default

    // Case 1: Arg wins
    let matches = create_test_command()
        .try_get_matches_from(["test", "--message", "from-arg"])
        .unwrap();

    let chain = build_complex_chain("env-value", "clipboard-value");
    assert_eq!(chain.resolve(&matches).unwrap(), "from-arg");

    // Case 2: Stdin wins (no arg)
    let matches = create_test_command()
        .try_get_matches_from(["test"])
        .unwrap();

    let chain = InputChain::<String>::new()
        .try_source(ArgSource::new("message"))
        .try_source(StdinSource::with_reader(MockStdin::piped("from-stdin")))
        .try_source(EnvSource::with_reader(
            "MY_VAR",
            MockEnv::new().with_var("MY_VAR", "env-value"),
        ))
        .try_source(ClipboardSource::with_reader(MockClipboard::with_content(
            "clipboard-value",
        )))
        .default("default-value".to_string());

    assert_eq!(chain.resolve(&matches).unwrap(), "from-stdin");

    // Case 3: Env wins (no arg, terminal stdin)
    let chain = InputChain::<String>::new()
        .try_source(ArgSource::new("message"))
        .try_source(StdinSource::with_reader(MockStdin::terminal()))
        .try_source(EnvSource::with_reader(
            "MY_VAR",
            MockEnv::new().with_var("MY_VAR", "env-value"),
        ))
        .try_source(ClipboardSource::with_reader(MockClipboard::with_content(
            "clipboard-value",
        )))
        .default("default-value".to_string());

    assert_eq!(chain.resolve(&matches).unwrap(), "env-value");

    // Case 4: Clipboard wins (no arg, terminal stdin, no env)
    let chain = InputChain::<String>::new()
        .try_source(ArgSource::new("message"))
        .try_source(StdinSource::with_reader(MockStdin::terminal()))
        .try_source(EnvSource::with_reader("MY_VAR", MockEnv::new()))
        .try_source(ClipboardSource::with_reader(MockClipboard::with_content(
            "clipboard-value",
        )))
        .default("default-value".to_string());

    assert_eq!(chain.resolve(&matches).unwrap(), "clipboard-value");

    // Case 5: Default wins (nothing else available)
    let chain = InputChain::<String>::new()
        .try_source(ArgSource::new("message"))
        .try_source(StdinSource::with_reader(MockStdin::terminal()))
        .try_source(EnvSource::with_reader("MY_VAR", MockEnv::new()))
        .try_source(ClipboardSource::with_reader(MockClipboard::empty()))
        .default("default-value".to_string());

    assert_eq!(chain.resolve(&matches).unwrap(), "default-value");
}

fn build_complex_chain(env_value: &str, clipboard_value: &str) -> InputChain<String> {
    InputChain::<String>::new()
        .try_source(ArgSource::new("message"))
        .try_source(StdinSource::with_reader(MockStdin::terminal()))
        .try_source(EnvSource::with_reader(
            "MY_VAR",
            MockEnv::new().with_var("MY_VAR", env_value),
        ))
        .try_source(ClipboardSource::with_reader(MockClipboard::with_content(
            clipboard_value,
        )))
        .default("default-value".to_string())
}

// ============================================================================
// Test: CI/non-TTY environment behavior
// ============================================================================
// These tests verify that the mocks allow testing behavior that would normally
// depend on terminal state, making tests reliable in CI environments.

#[test]
fn mock_ensures_consistent_behavior_in_ci() {
    // This test would behave differently in a real terminal vs CI without mocks.
    // With MockStdin, we get consistent behavior everywhere.

    let matches = create_test_command()
        .try_get_matches_from(["test"])
        .unwrap();

    // Simulate CI environment: stdin is terminal (not piped)
    let ci_stdin = MockStdin::terminal();
    let chain = InputChain::<String>::new()
        .try_source(StdinSource::with_reader(ci_stdin))
        .default("ci-default".to_string());

    assert_eq!(chain.resolve(&matches).unwrap(), "ci-default");

    // Simulate piped input
    let piped_stdin = MockStdin::piped("piped-content");
    let chain = InputChain::<String>::new()
        .try_source(StdinSource::with_reader(piped_stdin))
        .default("ci-default".to_string());

    assert_eq!(chain.resolve(&matches).unwrap(), "piped-content");
}

#[test]
fn mock_stdin_preserves_whitespace_when_configured() {
    let matches = create_test_command()
        .try_get_matches_from(["test"])
        .unwrap();

    // With trim (default)
    let chain = InputChain::<String>::new()
        .try_source(StdinSource::with_reader(MockStdin::piped("  hello  \n")));
    assert_eq!(chain.resolve(&matches).unwrap(), "hello");

    // Without trim
    let chain = InputChain::<String>::new()
        .try_source(StdinSource::with_reader(MockStdin::piped("  hello  \n")).trim(false));
    assert_eq!(chain.resolve(&matches).unwrap(), "  hello  \n");
}