1
+ use std:: fs;
1
2
use std:: io;
3
+ use std:: io:: Read ;
2
4
use std:: io:: Write ;
5
+ use std:: path;
3
6
use std:: process;
4
7
5
8
use assert:: Assert ;
@@ -22,24 +25,81 @@ pub trait CommandStdInExt {
22
25
///
23
26
/// Command::new("cat")
24
27
/// .arg("-A")
25
- /// .with_stdin("42")
28
+ /// .with_stdin()
29
+ /// .buffer("42")
26
30
/// .unwrap();
27
31
/// ```
28
- fn with_stdin < S > ( & mut self , buffer : S ) -> StdInCommand
29
- where
30
- S : Into < Vec < u8 > > ;
32
+ fn with_stdin ( & mut self ) -> StdInCommandBuilder ;
31
33
}
32
34
33
35
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
35
64
where
36
65
S : Into < Vec < u8 > > ,
37
66
{
38
67
StdInCommand {
39
- cmd : self ,
68
+ cmd : self . cmd ,
40
69
stdin : buffer. into ( ) ,
41
70
}
42
71
}
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
+ }
43
103
}
44
104
45
105
/// `Command` that carries the `stdin` buffer.
@@ -54,7 +114,8 @@ impl CommandStdInExt for process::Command {
54
114
/// use std::process::Command;
55
115
///
56
116
/// Command::new("cat")
57
- /// .with_stdin("42")
117
+ /// .with_stdin()
118
+ /// .buffer("42")
58
119
/// .unwrap();
59
120
/// ```
60
121
#[ derive( Debug ) ]
0 commit comments