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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
use std::path;
use std::process;
use error::*;
use format;
use msg::*;
pub struct CargoRun {
bin_path: path::PathBuf,
}
impl CargoRun {
pub(crate) fn from_message(
msgs: CommandMessages,
is_bin: bool,
is_example: bool,
) -> CargoResult<Self> {
let kind = match (is_bin, is_example) {
(true, true) => {
return Err(CargoError::new(ErrorKind::CommandFailed)
.set_context("Ambiguous which binary is intended, multiple selected"));
}
(false, true) => "example",
_ => "bin",
};
let bin_path = extract_binary_path(msgs, kind)?;
Ok(Self { bin_path })
}
pub fn path(&self) -> &path::Path {
&self.bin_path
}
pub fn command(&self) -> process::Command {
process::Command::new(self.path())
}
}
fn extract_bin<'a>(msg: &'a format::Message, desired_kind: &str) -> Option<&'a path::Path> {
match msg {
format::Message::CompilerArtifact(art) => {
if !art.profile.test
&& art.target.crate_types == ["bin"]
&& art.target.kind == [desired_kind]
{
Some(art.filenames.iter().next().expect("files must exist"))
} else {
None
}
}
_ => None,
}
}
fn transpose<T, E>(r: Result<Option<T>, E>) -> Option<Result<T, E>> {
match r {
Ok(Some(x)) => Some(Ok(x)),
Ok(None) => None,
Err(e) => Some(Err(e)),
}
}
fn extract_binary_paths(
msgs: CommandMessages,
kind: &'static str,
) -> impl Iterator<Item = Result<path::PathBuf, CargoError>> {
msgs.filter_map(move |m| {
let m = m.and_then(|m| {
let m = m.decode()?;
format::log_message(&m);
let p = extract_bin(&m, kind).map(|p| p.to_path_buf());
Ok(p)
});
transpose(m)
})
}
fn extract_binary_path(
msgs: CommandMessages,
kind: &'static str,
) -> Result<path::PathBuf, CargoError> {
let bins: Result<Vec<_>, CargoError> = extract_binary_paths(msgs, kind).collect();
let bins = bins?;
if bins.is_empty() {
return Err(CargoError::new(ErrorKind::CommandFailed).set_context("No binaries in crate"));
} else if bins.len() != 1 {
return Err(
CargoError::new(ErrorKind::CommandFailed).set_context(std::format!(
"Ambiguous which binary is intended: {:?}",
bins
)),
);
}
Ok(bins.into_iter().next().expect("already validated"))
}