Skip to main content

rust_analyzer/
command.rs

1//! Utilities for running a cargo command like `cargo check` or `cargo test` in a separate thread
2//! and parse its stdout/stderr.
3
4use 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
19/// This trait abstracts parsing one line of JSON output into a Rust
20/// data type.
21///
22/// This is useful for `cargo check` output, `cargo test` output, as
23/// well as custom discover commands.
24pub(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        // We manually read a line at a time, instead of using serde's
52        // stream deserializers, because the deserializer cannot recover
53        // from an error, resulting in it getting stuck, because we try to
54        // be resilient against failures.
55        //
56        // Because cargo only outputs one JSON object per line, we can
57        // simply skip a line if it doesn't parse, which just ignores any
58        // erroneous output.
59
60        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            // Try to deserialize a message from Cargo or Rustc.
75            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
122/// 'Join On Drop' wrapper for a child process.
123///
124/// This wrapper kills the process when the wrapper is dropped.
125struct 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
134/// A handle to a shell command, such as cargo for diagnostics (flycheck).
135pub(crate) struct CommandHandle<T> {
136    /// The handle to the actual child process. As we cannot cancel directly from with
137    /// a read syscall dropping and therefore terminating the process is our best option.
138    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                // We have an exit code.
211                true
212            }
213            Ok(None) => {
214                // Hasn't exited yet.
215                false
216            }
217            Err(_) => {
218                // Couldn't get an exit code. Assume that we've
219                // exited.
220                true
221            }
222        }
223    }
224}