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 1e825fb
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 3 deletions.
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").is_ok_and(|v| v == "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
29 changes: 26 additions & 3 deletions 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 @@ -305,12 +328,12 @@ impl TryCmd {
break next;
}
};
let step = Step {
let step = dbg!(Step {
id: Some(cmd_start.to_string()),
bin: Some(Bin::Name(bin)),
args: cmdline,
env,
stdin: None,
stdin,
stderr_to_stdout: true,
expected_status_source,
expected_status,
Expand All @@ -320,7 +343,7 @@ impl TryCmd {
expected_stderr: None,
binary: false,
timeout: None,
};
});
steps.push(step);
if block_done {
break 'code;
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 1e825fb

Please sign in to comment.