1use std::{
5 ffi::OsString,
6 fmt,
7 io::{self, BufWriter, Write},
8 marker::PhantomData,
9 path::PathBuf,
10 process::{ChildStderr, ChildStdout, Command, Stdio},
11};
12
13use anyhow::Context;
14use crossbeam_channel::Sender;
15use paths::Utf8PathBuf;
16use process_wrap::std::{ChildWrapper, CommandWrap};
17use stdx::process::streaming_output;
18
19pub(crate) trait JsonLinesParser<T>: Send + 'static {
25 fn from_line(&self, line: &str, error: &mut String) -> Option<T>;
26 fn from_stderr_line(&self, line: &str, error: &mut String) -> Option<T>;
27 fn from_eof(&self) -> Option<T>;
28}
29
30struct CommandActor<T> {
31 parser: Box<dyn JsonLinesParser<T>>,
32 sender: Sender<T>,
33 stdout: ChildStdout,
34 stderr: ChildStderr,
35}
36
37impl<T: Sized + Send + 'static> CommandActor<T> {
38 fn new(
39 parser: impl JsonLinesParser<T>,
40 sender: Sender<T>,
41 stdout: ChildStdout,
42 stderr: ChildStderr,
43 ) -> Self {
44 let parser = Box::new(parser);
45 CommandActor { parser, sender, stdout, stderr }
46 }
47}
48
49impl<T: Sized + Send + 'static> CommandActor<T> {
50 fn run(self, outfile: Option<Utf8PathBuf>) -> io::Result<(bool, String)> {
51 let mut stdout = outfile.as_ref().and_then(|path| {
61 _ = std::fs::create_dir_all(path);
62 Some(BufWriter::new(std::fs::File::create(path.join("stdout")).ok()?))
63 });
64 let mut stderr = outfile.as_ref().and_then(|path| {
65 _ = std::fs::create_dir_all(path);
66 Some(BufWriter::new(std::fs::File::create(path.join("stderr")).ok()?))
67 });
68
69 let mut stdout_errors = String::new();
70 let mut stderr_errors = String::new();
71 let mut read_at_least_one_stdout_message = false;
72 let mut read_at_least_one_stderr_message = false;
73 let process_line = |line: &str, error: &mut String| {
74 if let Some(t) = self.parser.from_line(line, error) {
76 self.sender.send(t).unwrap();
77 true
78 } else {
79 false
80 }
81 };
82 let output = streaming_output(
83 self.stdout,
84 self.stderr,
85 &mut |line| {
86 if let Some(stdout) = &mut stdout {
87 _ = stdout.write_all(line.as_bytes());
88 _ = stdout.write_all(b"\n");
89 }
90 if process_line(line, &mut stdout_errors) {
91 read_at_least_one_stdout_message = true;
92 }
93 },
94 &mut |line| {
95 if let Some(stderr) = &mut stderr {
96 _ = stderr.write_all(line.as_bytes());
97 _ = stderr.write_all(b"\n");
98 }
99 if let Some(t) = self.parser.from_stderr_line(line, &mut stderr_errors) {
100 self.sender.send(t).unwrap();
101 read_at_least_one_stderr_message = true;
102 }
103 },
104 &mut || {
105 if let Some(t) = self.parser.from_eof() {
106 self.sender.send(t).unwrap();
107 }
108 },
109 );
110
111 let read_at_least_one_message =
112 read_at_least_one_stdout_message || read_at_least_one_stderr_message;
113 let mut error = stdout_errors;
114 error.push_str(&stderr_errors);
115 match output {
116 Ok(_) => Ok((read_at_least_one_message, error)),
117 Err(e) => Err(io::Error::new(e.kind(), format!("{e:?}: {error}"))),
118 }
119 }
120}
121
122struct JodGroupChild(Box<dyn ChildWrapper>);
126
127impl Drop for JodGroupChild {
128 fn drop(&mut self) {
129 _ = self.0.kill();
130 _ = self.0.wait();
131 }
132}
133
134pub(crate) struct CommandHandle<T> {
136 child: JodGroupChild,
139 thread: stdx::thread::JoinHandle<io::Result<(bool, String)>>,
140 program: OsString,
141 arguments: Vec<OsString>,
142 current_dir: Option<PathBuf>,
143 _phantom: PhantomData<T>,
144}
145
146impl<T> fmt::Debug for CommandHandle<T> {
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 f.debug_struct("CommandHandle")
149 .field("program", &self.program)
150 .field("arguments", &self.arguments)
151 .field("current_dir", &self.current_dir)
152 .finish()
153 }
154}
155
156impl<T: Sized + Send + 'static> CommandHandle<T> {
157 pub(crate) fn spawn(
158 mut command: Command,
159 parser: impl JsonLinesParser<T>,
160 sender: Sender<T>,
161 out_file: Option<Utf8PathBuf>,
162 ) -> anyhow::Result<Self> {
163 command.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::null());
164
165 let program = command.get_program().into();
166 let arguments = command.get_args().map(|arg| arg.into()).collect::<Vec<OsString>>();
167 let current_dir = command.get_current_dir().map(|arg| arg.to_path_buf());
168
169 let mut child = CommandWrap::from(command);
170 #[cfg(unix)]
171 child.wrap(process_wrap::std::ProcessSession);
172 #[cfg(windows)]
173 child.wrap(process_wrap::std::JobObject);
174 let mut child = child
175 .spawn()
176 .map(JodGroupChild)
177 .with_context(|| format!("Failed to spawn command: {child:?}"))?;
178
179 let stdout = child.0.stdout().take().unwrap();
180 let stderr = child.0.stderr().take().unwrap();
181
182 let actor = CommandActor::<T>::new(parser, sender, stdout, stderr);
183 let thread =
184 stdx::thread::Builder::new(stdx::thread::ThreadIntent::Worker, "CommandHandle")
185 .spawn(move || actor.run(out_file))
186 .expect("failed to spawn thread");
187 Ok(CommandHandle { program, arguments, current_dir, child, thread, _phantom: PhantomData })
188 }
189
190 pub(crate) fn cancel(mut self) {
191 let _ = self.child.0.kill();
192 let _ = self.child.0.wait();
193 }
194
195 pub(crate) fn join(mut self) -> io::Result<()> {
196 let exit_status = self.child.0.wait()?;
197 let (read_at_least_one_message, error) = self.thread.join()?;
198 if read_at_least_one_message || exit_status.success() {
199 Ok(())
200 } else {
201 Err(io::Error::other(format!(
202 "Cargo watcher failed, the command produced no valid metadata (exit code: {exit_status:?}):\n{error}"
203 )))
204 }
205 }
206
207 pub(crate) fn has_exited(&mut self) -> bool {
208 match self.child.0.try_wait() {
209 Ok(Some(_exit_code)) => {
210 true
212 }
213 Ok(None) => {
214 false
216 }
217 Err(_) => {
218 true
221 }
222 }
223 }
224}