Skip to content

Commit

Permalink
feat(trycmd): Support echo text | command
Browse files Browse the repository at this point in the history
  • Loading branch information
chrysn committed Jun 14, 2024
1 parent 20f47d2 commit eb1af6f
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
6 changes: 6 additions & 0 deletions crates/trycmd/src/bin/bin-fixture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ use std::io::Write;
use std::process;

fn run() -> Result<(), Box<dyn Error>> {
if env::var("lines-from-stdin").as_deref() == Ok("1") {
for line in std::io::stdin().lines() {
println!("read line from stdin: {}", line.unwrap());
}
}

if let Ok(text) = env::var("stdout") {
println!("{}", text);
}
Expand Down
25 changes: 24 additions & 1 deletion crates/trycmd/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,29 @@ impl TryCmd {
stdout.pop();
}

let mut stdin = None;
if cmdline.first().is_some_and(|s| s == "echo") {
// No full piping / POSIX shell implemented, but this is a frequent and
// important tool
//
// If no pipe is found, this is not processed any further: echo is then treated
// as the binary, as it would have been if there were no special handling.
if let Some(index) = cmdline.iter().position(|s| s == &"|") {
let (echo_part, actual_command) = cmdline.split_at(index);
let echo_args = &echo_part[1..];
if echo_args.first().is_some_and(|f| f == "-n")
|| echo_args.iter().any(|s| s.contains("\\"))
{
return Err(
"Behavior of echo with -n or backslashes is not definedin POSIX"
.into(),
);
}
stdin = Some(crate::Data::text(format!("{}\n", echo_args.join(" "))));
cmdline = actual_command[1..].into();
}
};

let mut env = Env::default();

let bin = loop {
Expand All @@ -310,7 +333,7 @@ impl TryCmd {
bin: Some(Bin::Name(bin)),
args: cmdline,
env,
stdin: None,
stdin,
stderr_to_stdout: true,
expected_status_source,
expected_status,
Expand Down
6 changes: 6 additions & 0 deletions crates/trycmd/tests/cmd/echo-stdin.trycmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
```
$ echo "hello" "second argument" | \
> lines-from-stdin=1 bin-fixture
read line from stdin: hello second argument

```

0 comments on commit eb1af6f

Please sign in to comment.