1use crate::utils::PathExt;
2use std::borrow::Cow;
3use std::ffi::{OsStr, OsString};
4use std::io::Write;
5use std::path::{Path, PathBuf};
6use std::process::{Child, ExitStatus};
7
8pub struct Command {
9 program: OsString,
11 program_args: Vec<OsString>,
13 current_dir: PathBuf,
15 child: Option<Child>,
17 stdin: Option<Vec<u8>>,
19 stdout: Vec<u8>,
21 stderr: Vec<u8>,
23 status: ExitStatus,
25 expected_success: Option<bool>,
27 expected_failure: Option<bool>,
29 expected_status: Option<i32>,
31 expected_stdout: Option<Vec<u8>>,
33 expected_stderr: Option<Vec<u8>>,
35}
36
37impl Command {
38 pub fn new(program: impl AsRef<OsStr>, caller_file: impl AsRef<str>, manifest_dir: impl AsRef<str>) -> Self {
39 let manifest_path = Path::new(manifest_dir.as_ref());
40 let caller_path = Path::new(caller_file.as_ref())
41 .parent()
42 .expect("failed to retrieve parent directory for caller file");
43 let current_dir = match manifest_path.rem(caller_path) {
44 None => caller_path.into(),
45 Some(path_buf) => {
46 if path_buf.components().count() == 0 {
47 PathBuf::from(".")
48 } else {
49 path_buf
50 }
51 }
52 };
53 Self {
54 program: program.as_ref().into(),
55 program_args: vec![],
56 current_dir,
57 child: None,
58 stdin: None,
59 stdout: vec![],
60 stderr: vec![],
61 status: ExitStatus::default(),
62 expected_success: None,
63 expected_failure: None,
64 expected_status: None,
65 expected_stdout: None,
66 expected_stderr: None,
67 }
68 }
69
70 pub fn arg(mut self, arg: impl AsRef<OsStr>) -> Self {
71 self.program_args.push(arg.as_ref().into());
72 self
73 }
74
75 pub fn success(mut self) -> Self {
76 self.expected_success = Some(true);
77 self.expected_failure = None;
78 self
79 }
80
81 pub fn failure(mut self) -> Self {
82 self.expected_failure = Some(true);
83 self.expected_success = None;
84 self
85 }
86
87 pub fn code(mut self, code: i32) -> Self {
88 self.expected_status = Some(code);
89 self
90 }
91
92 pub fn stdin(mut self, bytes: impl AsRef<[u8]>) -> Self {
93 self.stdin = Some(bytes.as_ref().to_vec());
94 self
95 }
96
97 pub fn stdout(mut self, bytes: impl AsRef<[u8]>) -> Self {
98 self.expected_stdout = Some(bytes.as_ref().to_vec());
99 self
100 }
101
102 pub fn stderr(mut self, bytes: impl AsRef<[u8]>) -> Self {
103 self.expected_stderr = Some(bytes.as_ref().to_vec());
104 self
105 }
106
107 pub fn spawn(&mut self) {
108 if self.child.is_some() {
109 panic!("command is already spawned");
110 }
111 let mut command = std::process::Command::new(self.program.clone());
112 let mut child = command
113 .args(self.program_args.clone())
114 .current_dir(self.current_dir.clone())
115 .stdin(std::process::Stdio::piped())
116 .stdout(std::process::Stdio::piped())
117 .stderr(std::process::Stdio::piped())
118 .spawn()
119 .expect("failed to spawn requested command");
120 if let Some(bytes) = &self.stdin {
121 let mut stdin = child.stdin.take().expect("failed to obtain child process stdin");
122 stdin.write_all(bytes).expect("failed to write child process stdin");
123 }
124 self.child = Some(child);
125 }
126
127 pub fn wait(&mut self) {
128 let child = self.child.take().expect("command is not spawned");
129 let output = child.wait_with_output().expect("failed to obtain child process output");
130 self.stdout = output.stdout;
131 self.stderr = output.stderr;
132 self.status = output.status;
133 self.assert();
134 }
135
136 pub fn execute(&mut self) {
137 self.spawn();
138 self.wait();
139 }
140
141 pub fn stop(&mut self) {
142 if let Some(child) = &mut self.child {
143 child.kill().expect("failed to force a child process to stop");
144 } else {
145 panic!("command is not spawned");
146 }
147 }
148
149 pub fn get_program(&self) -> &OsStr {
150 &self.program
151 }
152
153 pub fn get_current_dir(&self) -> &Path {
154 &self.current_dir
155 }
156
157 pub fn get_stdout(&'_ self) -> Cow<'_, str> {
158 String::from_utf8_lossy(&self.stdout)
159 }
160
161 pub fn get_stderr(&'_ self) -> Cow<'_, str> {
162 String::from_utf8_lossy(&self.stderr)
163 }
164
165 pub fn get_stdout_raw(&self) -> &[u8] {
166 &self.stdout
167 }
168
169 pub fn get_stderr_raw(&self) -> &[u8] {
170 &self.stderr
171 }
172
173 pub fn get_status(&self) -> ExitStatus {
174 self.status
175 }
176
177 fn assert(&self) {
179 if let Some(true) = self.expected_success {
180 if !self.status.success() {
181 panic!("expected success");
182 }
183 }
184 if let Some(true) = self.expected_failure {
185 if self.status.success() {
186 panic!("expected failure");
187 }
188 }
189 if let Some(expected) = self.expected_status {
190 let actual = self.status.code().expect("failed to retrieve status code");
191 if actual != expected {
192 println!("\nexpected status code: {}\n actual status code: {}", expected, actual);
193 panic!("unexpected status");
194 }
195 }
196 if let Some(expected) = &self.expected_stdout {
197 let actual = self.get_stdout_raw();
198 if actual != expected {
199 println!("\nexpected stdout: {:?}\n actual stdout: {:?}", expected, actual);
200 panic!("unexpected stdout");
201 }
202 }
203 if let Some(expected) = &self.expected_stderr {
204 let actual = self.get_stderr_raw();
205 if actual != expected {
206 println!("\nexpected stderr: {:?}\n actual stderr: {:?}", expected, actual);
207 panic!("unexpected stderr");
208 }
209 }
210 }
211}