Skip to content

Commit ce6981a

Browse files
authored
Merge pull request #26 from epage/stdin
feat(stdin): Support piping in files
2 parents bdcdf37 + b940568 commit ce6981a

File tree

1 file changed

+68
-7
lines changed

1 file changed

+68
-7
lines changed

src/stdin.rs

Lines changed: 68 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1+
use std::fs;
12
use std::io;
3+
use std::io::Read;
24
use std::io::Write;
5+
use std::path;
36
use std::process;
47

58
use assert::Assert;
@@ -22,24 +25,81 @@ pub trait CommandStdInExt {
2225
///
2326
/// Command::new("cat")
2427
/// .arg("-A")
25-
/// .with_stdin("42")
28+
/// .with_stdin()
29+
/// .buffer("42")
2630
/// .unwrap();
2731
/// ```
28-
fn with_stdin<S>(&mut self, buffer: S) -> StdInCommand
29-
where
30-
S: Into<Vec<u8>>;
32+
fn with_stdin(&mut self) -> StdInCommandBuilder;
3133
}
3234

3335
impl CommandStdInExt for process::Command {
34-
fn with_stdin<S>(&mut self, buffer: S) -> StdInCommand
36+
fn with_stdin(&mut self) -> StdInCommandBuilder {
37+
StdInCommandBuilder { cmd: self }
38+
}
39+
}
40+
41+
/// For adding a stdin to a `Command`.
42+
#[derive(Debug)]
43+
pub struct StdInCommandBuilder<'a> {
44+
cmd: &'a mut process::Command,
45+
}
46+
47+
impl<'a> StdInCommandBuilder<'a> {
48+
/// Write `buffer` to `stdin` when the command is run.
49+
///
50+
/// # Examples
51+
///
52+
/// ```rust
53+
/// use assert_cmd::prelude::*;
54+
///
55+
/// use std::process::Command;
56+
///
57+
/// Command::new("cat")
58+
/// .arg("-A")
59+
/// .with_stdin()
60+
/// .buffer("42")
61+
/// .unwrap();
62+
/// ```
63+
pub fn buffer<S>(&mut self, buffer: S) -> StdInCommand
3564
where
3665
S: Into<Vec<u8>>,
3766
{
3867
StdInCommand {
39-
cmd: self,
68+
cmd: self.cmd,
4069
stdin: buffer.into(),
4170
}
4271
}
72+
73+
/// Write `path`s content to `stdin` when the command is run.
74+
///
75+
/// Paths are relative to the `env::current_dir` and not `Command::current_dir`.
76+
///
77+
/// # Examples
78+
///
79+
/// ```rust
80+
/// use assert_cmd::prelude::*;
81+
///
82+
/// use std::process::Command;
83+
///
84+
/// Command::new("cat")
85+
/// .arg("-A")
86+
/// .with_stdin()
87+
/// .path("Cargo.toml")
88+
/// .unwrap()
89+
/// .unwrap();
90+
/// ```
91+
pub fn path<P>(&mut self, file: P) -> io::Result<StdInCommand>
92+
where
93+
P: AsRef<path::Path>,
94+
{
95+
let file = file.as_ref();
96+
let mut buffer = Vec::new();
97+
fs::File::open(file)?.read_to_end(&mut buffer)?;
98+
Ok(StdInCommand {
99+
cmd: self.cmd,
100+
stdin: buffer,
101+
})
102+
}
43103
}
44104

45105
/// `Command` that carries the `stdin` buffer.
@@ -54,7 +114,8 @@ impl CommandStdInExt for process::Command {
54114
/// use std::process::Command;
55115
///
56116
/// Command::new("cat")
57-
/// .with_stdin("42")
117+
/// .with_stdin()
118+
/// .buffer("42")
58119
/// .unwrap();
59120
/// ```
60121
#[derive(Debug)]

0 commit comments

Comments
 (0)