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
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
# Input Sources

`standout-input` provides a unified way to acquire input before your handler runs. This enables interactive workflows like:

- Opening an editor for commit messages
- Prompting for confirmation ("Delete 5 items?")
- Selecting from a list of options
- Reading piped stdin for scripting
- Pre-filling from clipboard

All without polluting your handler logic.

---

## Why Input Sources?

CLI commands often need content that doesn't fit in command-line arguments. The `gh pr create` pattern is common:

```bash
# Option 1: Inline (awkward for long text)
gh pr create --body "Long description..."

# Option 2: Editor (interactive)
gh pr create --editor

# Option 3: Piped (scriptable)
echo "Description" | gh pr create --body-file -
```

Your CLI should support these patterns, but the logic doesn't belong in handlers:

- **Separation of concerns**: Handlers produce results, input acquisition is a setup concern
- **Testability**: Handlers remain pure functions that receive data
- **Composability**: Different commands can mix input sources

Standout's input system integrates as a pre-handler phase, running *before* your handler executes. Your handler receives resolved content—input acquisition is transparent.

---

## Source Types

Input sources fall into two categories:

### Non-Interactive Sources

These work in scripts and CI pipelines:

| Source | Use Case |
|--------|----------|
| **Arg** | Short content as CLI arguments |
| **Stdin** | Piped content (`cat file \| cmd`) |
| **Clipboard** | Pre-filled content from clipboard |
| **Env** | Environment variable |
| **Default** | Hardcoded fallback |

### Interactive Sources

These require a TTY and user interaction:

| Source | Use Case | Output Type |
|--------|----------|-------------|
| **Editor** | Long-form text (commit messages) | `String` |
| **Text** | Short text input ("Enter name:") | `String` |
| **Confirm** | Yes/no questions ("Proceed?") | `bool` |
| **Select** | Pick one from list | `T` |
| **MultiSelect** | Pick many from list | `Vec<T>` |
| **Password** | Hidden text input | `String` |

---

## Non-Interactive Sources

### Arg Source

Read directly from a clap argument:

```rust
InputSource::arg("message")
```

### Stdin Source

Read piped content when stdin is not a TTY:

```rust
InputSource::stdin()
```

Only reads if stdin is actually piped. Returns `None` if stdin is a terminal.

### Clipboard Source

Read from system clipboard:

```rust
InputSource::clipboard()
```

### Env Source

Read from environment variable:

```rust
InputSource::env("MY_APP_TOKEN")
```

---

## Interactive Sources

### Editor Source

Open the user's preferred editor:

```rust
InputSource::editor()
    .initial("# Enter your message\n\n")
    .extension(".md")
    .require_save(true)
```

Use for multi-line content like commit messages or descriptions.

### Text Prompt

Prompt for short text input:

```rust
InputSource::text("Enter your name:")
    .default("Anonymous")
    .placeholder("John Doe")
```

### Confirm Prompt

Ask a yes/no question:

```rust
InputSource::confirm("Delete 5 items?")
    .default(false)  // Default to "no"
```

Returns `bool`. In chains, use with `#[input]` on a `bool` parameter.

### Select Prompt

Pick one from a list:

```rust
InputSource::select("Choose format:")
    .option("json", "JSON output")
    .option("yaml", "YAML output")
    .option("csv", "CSV output")
    .default("json")
```

### Multi-Select Prompt

Pick multiple from a list:

```rust
InputSource::multi_select("Select features:")
    .option("auth", "Authentication")
    .option("logging", "Request logging")
    .option("cache", "Response caching")
```

### Password Prompt

Hidden text input:

```rust
InputSource::password("Enter API token:")
    .confirm("Confirm token:")  // Optional confirmation
```

---

## Quick Start

The simplest integration uses the handler macro:

```rust
use standout_macros::handler;

#[handler]
pub fn create(
    #[input(fallback = "editor")] message: String,
    #[flag] verbose: bool,
) -> Result<CreateResult, Error> {
    // `message` is resolved from: arg → stdin → editor
    Ok(CreateResult { message, verbose })
}
```

Or use the builder API for more control:

```rust
let app = App::builder()
    .command_with("create", handlers::create, |cfg| {
        cfg.template("create.jinja")
           .input("message", InputSource::chain()
               .try_arg("message")
               .try_stdin()
               .fallback_editor(EditorConfig::new()
                   .initial("# Enter message")
                   .extension(".md")))
    })
    .build()?;
```

---

## Input Chains

Chain multiple sources with fallback behavior:

```rust
InputSource::chain()
    .try_arg("body")           // First: try CLI arg
    .try_stdin()               // Second: try piped stdin
    .fallback_editor(config)   // Third: open editor
```

The chain stops at the first source that provides content. This enables the `gh pr create` pattern:

- `gh pr create --body "text"` → uses arg
- `echo "text" | gh pr create` → uses stdin
- `gh pr create` → opens editor

### Chain with Skip Flag

Some commands want `--no-editor` to skip interactive input:

```rust
InputSource::chain()
    .try_arg("body")
    .try_stdin()
    .fallback_editor_unless("no-editor", config)
    .default("")  // If --no-editor and no other source, use empty
```

---

## API Reference

### Macro Attributes

| Attribute | Behavior |
|-----------|----------|
| `#[input]` | Resolve from arg of same name |
| `#[input(fallback = "editor")]` | Arg → stdin → editor chain |
| `#[input(fallback = "stdin")]` | Arg → stdin chain |
| `#[input(source = "editor")]` | Editor only |

### Builder Methods

```rust
// Single sources
InputSource::arg("name")      // From CLI argument
InputSource::stdin()          // From piped stdin
InputSource::editor()         // Always open editor
InputSource::clipboard()      // From system clipboard

// Editor configuration
InputSource::editor()
    .initial("prefilled content")
    .extension(".md")          // For syntax highlighting
    .require_save(true)        // Abort if user doesn't save
    .trim_newlines(true)       // Strip trailing newlines

// Chains
InputSource::chain()
    .try_arg("message")
    .try_stdin()
    .fallback_editor(config)
    .default("fallback value")

// With validation
InputSource::chain()
    .try_arg("message")
    .validate(|s| !s.is_empty(), "Message cannot be empty")
```

### Low-Level API

For standalone use without the framework:

```rust
use standout_input::{Editor, detect_editor, read_stdin_if_piped};

// Detect preferred editor
let editor = detect_editor()?;  // Checks: VISUAL, EDITOR, then fallbacks

// Read stdin only if piped
let piped: Option<String> = read_stdin_if_piped()?;

// Open editor with content
let content = Editor::new()
    .executable(&editor)
    .initial("# Enter message\n")
    .extension(".md")
    .edit()?;  // Returns Option<String>, None if user aborted
```

---

## Editor Detection

Editor detection follows established conventions:

| Priority | Source | Example |
|----------|--------|---------|
| 1 | `VISUAL` env var | `VISUAL=code` |
| 2 | `EDITOR` env var | `EDITOR=vim` |
| 3 | Platform default | `vim` (Unix), `notepad` (Windows) |

For apps that want custom precedence (like `gh` with `GH_EDITOR`):

```rust
let editor = detect_editor_with_precedence(&[
    "GH_EDITOR",    // App-specific first
    "VISUAL",
    "EDITOR",
])?;
```

---

## Integration with Handlers

Resolved input is injected into `CommandContext.extensions`:

```rust
// Framework resolves input before handler runs
// Handler receives it via #[input] attribute or ctx.extensions

#[handler]
pub fn create(
    #[input(fallback = "editor")] body: String,
    #[ctx] ctx: &CommandContext,
) -> Result<Pad, Error> {
    // `body` is already resolved
    // Can also access: ctx.extensions.get::<ResolvedInput<"body">>()
}
```

For complex cases that need the resolution metadata:

```rust
fn create(matches: &ArgMatches, ctx: &CommandContext) -> HandlerResult<Pad> {
    let input = ctx.extensions.get_required::<ResolvedInput>()?;

    match input.source {
        InputSourceKind::Arg => log::debug!("Got body from --body arg"),
        InputSourceKind::Stdin => log::debug!("Got body from piped stdin"),
        InputSourceKind::Editor => log::debug!("Got body from editor"),
    }

    let body = input.content;
    // ...
}
```

---

## Direct Use in Handlers

For commands with complex input logic (like padz's "smart create"), use the library directly:

```rust
use standout_input::{Editor, read_stdin_if_piped, read_clipboard};

fn create(matches: &ArgMatches, ctx: &CommandContext) -> HandlerResult<Pad> {
    let no_editor = matches.get_flag("no-editor");
    let title_arg = matches.get_one::<String>("title");

    let content = if let Some(piped) = read_stdin_if_piped()? {
        // Piped input takes precedence
        piped
    } else if let Some(title) = title_arg {
        if no_editor {
            // Title only, no body
            title.clone()
        } else {
            // Title provided, open editor for body
            let body = Editor::new()
                .initial(&format!("# {}\n\n", title))
                .extension(".md")
                .edit()?
                .unwrap_or_default();
            format!("{}\n\n{}", title, body)
        }
    } else if no_editor {
        // No input and no editor - error
        return Err(anyhow!("No content provided. Use --title or pipe input."));
    } else {
        // No args - prefill from clipboard, open editor
        let clipboard = read_clipboard().unwrap_or_default();
        Editor::new()
            .initial(&clipboard)
            .edit()?
            .ok_or_else(|| anyhow!("Editor cancelled"))?
    };

    // ... rest of handler
}
```

This gives full control while still using standardized primitives.

---

## Clipboard Integration

Read from system clipboard as an input source:

```rust
// As part of a chain
InputSource::chain()
    .try_arg("content")
    .try_clipboard()
    .fallback_editor(config)

// Or for prefilling editor
let initial = read_clipboard().unwrap_or_default();
Editor::new().initial(&initial).edit()?
```

Platform support:

| Platform | Read Command |
|----------|--------------|
| macOS | `pbpaste` |
| Linux | `xclip -selection clipboard -o` |
| Windows | PowerShell `Get-Clipboard` |

---

## Comparison with Output Piping

Input sources and output piping are symmetric but opposite:

| Aspect | Input Sources | Output Piping |
|--------|---------------|---------------|
| Direction | External → Handler | Handler → External |
| Pipeline position | Pre-handler | Post-output |
| Interactive | Can be (editor) | Never |
| Purpose | Acquire content | Transform/route output |

```
              INPUT SOURCES                    OUTPUT PIPING
              ↓                                ↓
[Arg/Stdin/Editor] → Handler → Render → [jq/tee/clipboard]
```

---

## Error Handling

Input errors are returned before handler execution:

```rust
// Editor not found
// Error: No editor found. Set VISUAL or EDITOR environment variable.

// User cancelled editor (with require_save)
// Error: Editor cancelled without saving.

// Stdin read failed
// Error: Failed to read from stdin: <io error>

// Validation failed
// Error: Input validation failed: Message cannot be empty
```

---

## Security Considerations

**Editor execution**: The editor command is resolved from environment variables. Ensure `VISUAL`/`EDITOR` are set by the user, not from untrusted sources.

**Temp file handling**: Editor content is written to a temp file. The file is deleted after reading. Content may briefly exist on disk.

```rust
// Files are created in system temp directory with random names
// e.g., /tmp/standout-input-a7b3c9.md
```

---

## Summary

| Feature | Method/Attribute |
|---------|------------------|
| From CLI arg | `InputSource::arg("name")` |
| From piped stdin | `InputSource::stdin()` |
| From editor | `InputSource::editor()` |
| From clipboard | `InputSource::clipboard()` |
| Chain with fallback | `InputSource::chain().try_arg().fallback_editor()` |
| Prefill editor | `.initial("content")` |
| File extension | `.extension(".md")` |
| Require save | `.require_save(true)` |
| Validation | `.validate(fn, "error message")` |