command-stream 0.18.2

Modern shell command execution library with streaming, async iteration, and event support
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
# Best Practices for command-stream (Rust)

This document covers best practices, common patterns, and pitfalls to avoid when using the command-stream Rust library.

## Table of Contents

- [Argument Handling with Macros]#argument-handling-with-macros
- [String Interpolation]#string-interpolation
- [Security Best Practices]#security-best-practices
- [Error Handling]#error-handling
- [Async Patterns]#async-patterns
- [Common Pitfalls]#common-pitfalls

---

## Argument Handling with Macros

### Using the cmd!/s!/sh! Macros

The command-stream macros (`cmd!`, `s!`, `sh!`, `cs!`) provide safe interpolation similar to JavaScript's `$` template literal:

```rust
use command_stream::s;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Simple command
    let result = s!("echo hello world").await?;

    // With interpolation (automatically quoted)
    let name = "world";
    let result = s!("echo hello {}", name).await?;

    // Multiple arguments
    let file = "test.txt";
    let flag = "--verbose";
    let result = s!("cat {} {}", file, flag).await?;

    Ok(())
}
```

### Handling Multiple Arguments

When you have a collection of arguments, handle them correctly:

```rust
use command_stream::{run, quote};

// CORRECT: Use quote::quote_all for multiple arguments
let args = vec!["file.txt", "--public", "--verbose"];
let quoted_args = quote::quote_all(&args);
let result = run(format!("command {}", quoted_args)).await?;

// CORRECT: Build command with individual quotes
let args = vec!["file.txt", "--public", "--verbose"];
let cmd = format!("command {}",
    args.iter()
        .map(|a| quote::quote(a))
        .collect::<Vec<_>>()
        .join(" ")
);
let result = run(cmd).await?;
```

### Vec/Slice Handling Patterns

Unlike JavaScript where arrays are handled automatically in template literals, Rust requires explicit handling:

```rust
use command_stream::quote;

// Pattern 1: quote_all function
let args = vec!["file.txt", "--verbose"];
let args_str = quote::quote_all(&args);
// Result: "file.txt --verbose" (each arg properly quoted)

// Pattern 2: Manual iteration
let args = vec!["file with spaces.txt", "--verbose"];
let args_str = args.iter()
    .map(|a| quote::quote(a))
    .collect::<Vec<_>>()
    .join(" ");
// Result: "'file with spaces.txt' --verbose"

// Pattern 3: Format with multiple placeholders
let file = "data.txt";
let flag1 = "--verbose";
let flag2 = "--force";
let result = s!("cmd {} {} {}", file, flag1, flag2).await?;
```

---

## String Interpolation

### Safe Interpolation (Default)

The `quote` function automatically escapes dangerous characters:

```rust
use command_stream::quote::quote;

let dangerous = "'; rm -rf /; echo '";
let safe = quote(dangerous);
// Result: "''\\'' rm -rf /; echo '\\'''"
// Shell will treat this as a literal string
```

### Interpolating Inside Your Own Quotes

The macros track the quoting context of the format string. A value that lands
inside quotes you wrote yourself is spliced in as escaped literal text rather
than wrapped in another pair of quotes, exactly like `"$var"` in a POSIX shell:

```rust,no_run
use command_stream::s;

# async fn example() -> Result<(), command_stream::Error> {
let script = "for f in *.js; do echo \"Processing: $f\"; done";
// Runs the script, like: bash -c "$script"
let result = s!("bash -c \"{}\"", script).await?;
# Ok(())
# }
```

The same rules are available directly:

```rust
use command_stream::{quote_for_context, QuoteContext};

assert_eq!(quote_for_context("hello world", QuoteContext::Unquoted), "'hello world'");
assert_eq!(quote_for_context("hello world", QuoteContext::Double), "hello world");
assert_eq!(quote_for_context("it's", QuoteContext::Single), "it'\\''s");
```

Set `COMMAND_STREAM_QUOTE_CONTEXT=0` to restore the previous behavior of always
quoting every interpolated value.

### Multiline Text and Exact File Writes

Multiline interpolations are one literal argument, like a quoted shell
variable. Backticks, dollar signs, quotes, backslashes, and newlines in the
value are data rather than shell syntax:

```rust,no_run
use command_stream::s;

# async fn example() -> Result<(), command_stream::Error> {
let content = "# Generated\n\nLiteral: `code`, $HOME, ${name}, and C:\\Tools";
let result = s!("printf '%s' {}", content).await?;
assert_eq!(result.stdout, content);
# Ok(())
# }
```

`echo` adds its normal trailing newline and its option/escape handling varies
between shells. Use `printf '%s'` when exact captured text matters, and use
`std::fs::write` when no shell command is needed.

### Paths With Spaces

Interpolate the path as-is. An interpolated value always becomes exactly one
argument, so spaces and other special characters need no help from you - the
same guarantee as `"$path"` in a shell script:

```rust
use command_stream::quote::quote;

assert_eq!(
    quote("/Users/john/My Documents/report.txt"),
    "'/Users/john/My Documents/report.txt'"
);
```

Never pre-quote the value: quote characters you add become part of the file
name, exactly as `sh` would treat them. Before v0.18 a value that started and
ended with a matching quote was spliced in as shell syntax; set
`COMMAND_STREAM_PREQUOTED_PASSTHROUGH=1` if you still depend on that.

### When Quoting is Applied

```rust
use command_stream::quote::{quote, needs_quoting};

// Safe strings pass through unchanged
assert_eq!(quote("hello"), "hello");
assert_eq!(quote("/path/to/file"), "/path/to/file");

// Dangerous strings are quoted
assert_eq!(quote("hello world"), "'hello world'");
assert_eq!(quote("$var"), "'$var'");

// Check if quoting is needed
assert!(!needs_quoting("hello"));
assert!(needs_quoting("hello world"));
```

---

## Security Best Practices

### Never Trust User Input

```rust
use command_stream::{run, quote};

async fn process_file(user_filename: &str) -> Result<(), Box<dyn std::error::Error>> {
    // CORRECT: Quote user input
    let safe_filename = quote::quote(user_filename);
    let result = run(format!("cat {}", safe_filename)).await?;

    // ALSO CORRECT: Use macro interpolation
    let result = s!("cat {}", user_filename).await?;

    Ok(())
}
```

### Validate Before Execution

```rust
use command_stream::run;
use std::path::Path;

async fn delete_file(filename: &str) -> Result<(), Box<dyn std::error::Error>> {
    // Validate: no path traversal
    if filename.contains("..") || filename.starts_with('/') {
        return Err("Invalid filename".into());
    }

    // Validate: file exists and is a file (not directory)
    let path = Path::new(filename);
    if !path.is_file() {
        return Err("Not a file".into());
    }

    run(format!("rm {}", quote::quote(filename))).await?;
    Ok(())
}
```

---

## Error Handling

### Check Results

```rust
use command_stream::run;

async fn example() -> Result<(), Box<dyn std::error::Error>> {
    let result = run("ls nonexistent").await?;

    match result.code {
        0 => println!("Success: {}", result.stdout),
        2 => eprintln!("File not found"),
        127 => eprintln!("Command not found"),
        code => eprintln!("Unknown error (code {})", code),
    }

    Ok(())
}
```

### Using the ? Operator

```rust
use command_stream::{run, Result};

async fn critical_operation() -> Result<String> {
    let result = run("important-command").await?;

    if result.code != 0 {
        return Err(command_stream::Error::CommandFailed {
            code: result.code,
            message: result.stderr,
        });
    }

    Ok(result.stdout)
}
```

---

## Async Patterns

### Basic Async Usage

```rust
use command_stream::run;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let result = run("echo hello").await?;
    println!("{}", result.stdout);
    Ok(())
}
```

### Parallel Execution

```rust
use command_stream::run;
use tokio;

async fn parallel_tasks() -> Result<(), Box<dyn std::error::Error>> {
    // Run multiple commands in parallel
    let (r1, r2, r3) = tokio::join!(
        run("task1"),
        run("task2"),
        run("task3")
    );

    println!("Task 1: {}", r1?.stdout);
    println!("Task 2: {}", r2?.stdout);
    println!("Task 3: {}", r3?.stdout);

    Ok(())
}
```

### Using ProcessRunner for Control

```rust
use command_stream::{ProcessRunner, RunOptions};

async fn controlled_execution() -> Result<(), Box<dyn std::error::Error>> {
    let options = RunOptions {
        capture: true,
        mirror: false,  // Don't print to terminal
        ..Default::default()
    };

    let mut runner = ProcessRunner::new("long-command", options);
    runner.start().await?;
    let result = runner.run().await?;

    println!("Captured: {}", result.stdout);
    Ok(())
}
```

---

## Common Pitfalls

### 1. String Formatting Without Quoting

**Problem:** Using `format!` without quoting can cause issues with special characters.

```rust
// WRONG: Spaces break the command
let filename = "my file.txt";
let cmd = format!("cat {}", filename);
// Result: "cat my file.txt" - interpreted as two args!

// CORRECT: Quote the value
let cmd = format!("cat {}", quote::quote(filename));
// Result: "cat 'my file.txt'" - single argument
```

### 2. Vec Join Without Proper Quoting

**Problem:** Joining a Vec without quoting each element.

```rust
// WRONG: join doesn't quote elements
let args = vec!["file with spaces.txt", "--flag"];
let cmd = format!("command {}", args.join(" "));
// Result: "command file with spaces.txt --flag" - BROKEN!

// CORRECT: Use quote_all
let cmd = format!("command {}", quote::quote_all(&args));
// Result: "command 'file with spaces.txt' --flag"
```

### 3. Forgetting .await

**Problem:** Async functions return futures that must be awaited.

```rust
// WRONG: Command never executes
let result = run("echo hello");  // Returns Future, not Result!

// CORRECT: Await the future
let result = run("echo hello").await?;
```

### 4. Not Handling Non-Zero Exit Codes

**Problem:** Assuming success without checking.

```rust
// RISKY: May fail silently
let result = run("risky-command").await?;
use_output(&result.stdout);

// BETTER: Check exit code
let result = run("risky-command").await?;
if result.code == 0 {
    use_output(&result.stdout);
} else {
    handle_error(&result.stderr);
}
```

### 5. Blocking in Async Context

**Problem:** Using `run_sync` in async context blocks the runtime.

```rust
// WRONG in async context
async fn bad_example() {
    // This blocks the entire runtime thread!
    let result = run_sync("slow-command");
}

// CORRECT: Use async version
async fn good_example() {
    let result = run("slow-command").await;
}
```

---

## Quick Reference

### Do's

- Use `quote::quote()` for individual values
- Use `quote::quote_all()` for Vec/slice of arguments
- Use macro interpolation (`s!`, `cmd!`) for safe templating
- Always `.await` async operations
- Check exit codes for critical operations
- Validate user input before execution

### Don'ts

- Never format user input without quoting
- Never use `args.join(" ")` without quoting each element
- Don't forget `.await` on futures
- Don't assume commands succeed
- Don't block async contexts with `run_sync`

---

## See Also

- [../js/BEST-PRACTICES.md]../js/BEST-PRACTICES.md - JavaScript best practices
- [src/quote.rs]src/quote.rs - Quote function implementation
- [src/macros.rs]src/macros.rs - Macro implementations