Skip to content

Commit bf1d020

Browse files
committed
feat(trycmd): Support echo text | command
Closes: #172
1 parent 20f47d2 commit bf1d020

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

crates/trycmd/src/bin/bin-fixture.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@ use std::io::Write;
55
use std::process;
66

77
fn run() -> Result<(), Box<dyn Error>> {
8+
if env::var("lines-from-stdin").as_deref() == Ok("1") {
9+
for line in std::io::stdin().lines() {
10+
println!("read line from stdin: {}", line.unwrap());
11+
}
12+
}
13+
814
if let Ok(text) = env::var("stdout") {
915
println!("{}", text);
1016
}

crates/trycmd/src/schema.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,29 @@ impl TryCmd {
292292
stdout.pop();
293293
}
294294

295+
let mut stdin = None;
296+
if cmdline.first().is_some_and(|s| s == "echo") {
297+
// No full piping / POSIX shell implemented, but this is a frequent and
298+
// important tool
299+
//
300+
// If no pipe is found, this is not processed any further: echo is then treated
301+
// as the binary, as it would have been if there were no special handling.
302+
if let Some(index) = cmdline.iter().position(|s| s == &"|") {
303+
let (echo_part, actual_command) = cmdline.split_at(index);
304+
let echo_args = &echo_part[1..];
305+
if echo_args.first().is_some_and(|f| f == "-n")
306+
|| echo_args.iter().any(|s| s.contains("\\"))
307+
{
308+
return Err(
309+
"Behavior of echo with -n or backslashes is not defined in POSIX"
310+
.into(),
311+
);
312+
}
313+
stdin = Some(crate::Data::text(format!("{}\n", echo_args.join(" "))));
314+
cmdline = actual_command[1..].into();
315+
}
316+
};
317+
295318
let mut env = Env::default();
296319

297320
let bin = loop {
@@ -310,7 +333,7 @@ impl TryCmd {
310333
bin: Some(Bin::Name(bin)),
311334
args: cmdline,
312335
env,
313-
stdin: None,
336+
stdin,
314337
stderr_to_stdout: true,
315338
expected_status_source,
316339
expected_status,
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
```
2+
$ echo "hello" "second argument" | \
3+
> lines-from-stdin=1 bin-fixture
4+
read line from stdin: hello second argument
5+
6+
```

0 commit comments

Comments
 (0)