1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
|
use std::io;
use std::io::BufRead;
use std::io::Read;
use std::process;
use crate::error::*;
use crate::format;
/// Messages returned from a cargo sub-command.
pub struct CommandMessages(InnerCommandMessages);
struct InnerCommandMessages {
done: bool,
child: process::Child,
stdout: io::BufReader<process::ChildStdout>,
stderr: io::BufReader<process::ChildStderr>,
}
impl CommandMessages {
/// Run the command, allowing iteration over ndjson messages.
pub fn with_command(mut cmd: process::Command) -> CargoResult<Self> {
let mut child = cmd
.stdout(process::Stdio::piped())
.stderr(process::Stdio::piped())
.spawn()
.map_err(|e| CargoError::new(ErrorKind::InvalidCommand).set_cause(e))?;
let stdout = child.stdout.take().expect("piped above");
let stdout = io::BufReader::new(stdout);
let stderr = child.stderr.take().expect("piped above");
let stderr = io::BufReader::new(stderr);
let msgs = InnerCommandMessages {
done: false,
child,
stdout,
stderr,
};
Ok(CommandMessages(msgs))
}
#[inline]
fn next_msg(&mut self) -> CargoResult<Option<Message>> {
#![allow(clippy::branches_sharing_code)]
let mut content = String::new();
let len = self
.0
.stdout
.read_line(&mut content)
.map_err(|e| CargoError::new(ErrorKind::InvalidOutput).set_cause(e))?;
if 0 < len {
Ok(Some(Message(content)))
} else {
let status = self
.0
.child
.wait()
.map_err(|e| CargoError::new(ErrorKind::InvalidOutput).set_cause(e))?;
if !status.success() && !self.0.done {
self.0.done = true;
let mut data = vec![];
self.0
.stderr
.read_to_end(&mut data)
.map_err(|e| CargoError::new(ErrorKind::InvalidOutput).set_cause(e))?;
let err = CargoError::new(ErrorKind::CommandFailed)
.set_context(String::from_utf8_lossy(&data));
Err(err)
} else {
self.0.done = true;
Ok(None)
}
}
}
}
impl Drop for CommandMessages {
fn drop(&mut self) {
if !self.0.done {
let _ = self.0.child.wait();
}
}
}
impl Iterator for CommandMessages {
type Item = CargoResult<Message>;
#[inline]
fn next(&mut self) -> Option<CargoResult<Message>> {
match self.next_msg() {
Ok(Some(x)) => Some(Ok(x)),
Ok(None) => None,
Err(e) => Some(Err(e)),
}
}
}
/// An individual message from a cargo sub-command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Message(String);
impl Message {
/// Deserialize the message.
pub fn decode(&self) -> CargoResult<format::Message<'_>> {
self.decode_custom()
}
/// Deserialize the message.
pub fn decode_custom<'a, T>(&'a self) -> CargoResult<T>
where
T: serde::Deserialize<'a>,
{
let data = serde_json::from_str(self.0.as_str())
.map_err(|e| CargoError::new(ErrorKind::InvalidOutput).set_cause(e))?;
Ok(data)
}
}
|