Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(trycmd): Support echo text | command #344

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 defined in 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

```