Skip to content

Commit 40c23ca

Browse files
committed
Remove dependency on pipe, unless parallel
1 parent 2b52daf commit 40c23ca

File tree

6 files changed

+105
-304
lines changed

6 files changed

+105
-304
lines changed

Cargo.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@ rust-version = "1.53"
2222
[target.'cfg(unix)'.dependencies]
2323
# Don't turn on the feature "std" for this, see https://github.com/rust-lang/cargo/issues/4866
2424
# which is still an issue with `resolver = "1"`.
25-
libc = { version = "0.2.62", default-features = false }
25+
libc = { version = "0.2.62", default-features = false, optional = true }
2626

2727
[features]
28-
parallel = []
28+
parallel = ["libc"]
2929

3030
[dev-dependencies]
3131
tempfile = "3"

src/command_helpers.rs

+76-94
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,12 @@ use std::{
44
collections::hash_map,
55
ffi::OsString,
66
fmt::Display,
7-
fs::{self, File},
7+
fs,
88
hash::Hasher,
9-
io::{self, BufRead, BufReader, Read, Write},
9+
io::{self, BufRead, BufReader, Read, Stdout, Write},
1010
path::Path,
1111
process::{Child, Command, Stdio},
1212
sync::Arc,
13-
thread::{self, JoinHandle},
1413
};
1514

1615
use crate::{Error, ErrorKind, Object};
@@ -41,83 +40,51 @@ impl CargoOutput {
4140
}
4241
}
4342

44-
pub(crate) fn print_thread(&self) -> Result<Option<PrintThread>, Error> {
45-
self.warnings.then(PrintThread::new).transpose()
43+
fn stdio_for_warnings(&self) -> Stdio {
44+
if self.warnings {
45+
Stdio::piped()
46+
} else {
47+
Stdio::null()
48+
}
4649
}
4750
}
4851

49-
pub(crate) struct PrintThread {
50-
handle: Option<JoinHandle<()>>,
51-
pipe_writer: Option<File>,
52+
pub(crate) fn reader_for_stderr_as_warnings(
53+
child: &mut Child,
54+
) -> Option<BufReader<std::process::ChildStderr>> {
55+
child
56+
.stderr
57+
.take()
58+
.map(|stderr| BufReader::with_capacity(100, stderr))
5259
}
5360

54-
impl PrintThread {
55-
pub(crate) fn new() -> Result<Self, Error> {
56-
let (pipe_reader, pipe_writer) = crate::os_pipe::pipe()?;
57-
58-
// Capture the standard error coming from compilation, and write it out
59-
// with cargo:warning= prefixes. Note that this is a bit wonky to avoid
60-
// requiring the output to be UTF-8, we instead just ship bytes from one
61-
// location to another.
62-
let print = thread::spawn(move || {
63-
let mut stderr = BufReader::with_capacity(4096, pipe_reader);
64-
let mut line = Vec::with_capacity(20);
65-
let stdout = io::stdout();
66-
67-
// read_until returns 0 on Eof
68-
while stderr.read_until(b'\n', &mut line).unwrap() != 0 {
69-
{
70-
let mut stdout = stdout.lock();
71-
72-
stdout.write_all(b"cargo:warning=").unwrap();
73-
stdout.write_all(&line).unwrap();
74-
stdout.write_all(b"\n").unwrap();
75-
}
76-
77-
// read_until does not clear the buffer
78-
line.clear();
79-
}
80-
});
81-
82-
Ok(Self {
83-
handle: Some(print),
84-
pipe_writer: Some(pipe_writer),
85-
})
86-
}
87-
88-
/// # Panics
89-
///
90-
/// Will panic if the pipe writer has already been taken.
91-
pub(crate) fn take_pipe_writer(&mut self) -> File {
92-
self.pipe_writer.take().unwrap()
93-
}
61+
fn forward_all_stderr_as_warnings(
62+
child_stderr_reader: &mut Option<BufReader<std::process::ChildStderr>>,
63+
) {
64+
if let Some(stderr) = child_stderr_reader.as_mut() {
65+
let mut line = Vec::new();
66+
let stdout = io::stdout();
9467

95-
/// # Panics
96-
///
97-
/// Will panic if the pipe writer has already been taken.
98-
pub(crate) fn clone_pipe_writer(&self) -> Result<File, Error> {
99-
self.try_clone_pipe_writer().map(Option::unwrap)
100-
}
68+
// read_until returns 0 on Eof
69+
while stderr.read_until(b'\n', &mut line).unwrap_or_default() != 0 {
70+
write_warning(&stdout, &line);
10171

102-
pub(crate) fn try_clone_pipe_writer(&self) -> Result<Option<File>, Error> {
103-
self.pipe_writer
104-
.as_ref()
105-
.map(File::try_clone)
106-
.transpose()
107-
.map_err(From::from)
72+
// read_until does not clear the buffer
73+
line.clear();
74+
}
10875
}
10976
}
11077

111-
impl Drop for PrintThread {
112-
fn drop(&mut self) {
113-
// Drop pipe_writer first to avoid deadlock
114-
self.pipe_writer.take();
78+
fn write_warning(stdout: &Stdout, line: &[u8]) {
79+
let mut stdout = stdout.lock();
11580

116-
self.handle.take().unwrap().join().unwrap();
117-
}
81+
stdout.write_all(b"cargo:warning=").unwrap();
82+
stdout.write_all(line).unwrap();
83+
stdout.write_all(b"\n").unwrap();
11884
}
11985

12086
fn wait_on_child(cmd: &Command, program: &str, child: &mut Child) -> Result<(), Error> {
87+
forward_all_stderr_as_warnings(&mut reader_for_stderr_as_warnings(child));
12188
let status = match child.wait() {
12289
Ok(s) => s,
12390
Err(e) => {
@@ -193,20 +160,13 @@ pub(crate) fn objects_from_files(files: &[Arc<Path>], dst: &Path) -> Result<Vec<
193160
Ok(objects)
194161
}
195162

196-
fn run_inner(cmd: &mut Command, program: &str, pipe_writer: Option<File>) -> Result<(), Error> {
197-
let mut child = spawn(cmd, program, pipe_writer)?;
198-
wait_on_child(cmd, program, &mut child)
199-
}
200-
201163
pub(crate) fn run(
202164
cmd: &mut Command,
203165
program: &str,
204-
print: Option<&PrintThread>,
166+
cargo_output: &CargoOutput,
205167
) -> Result<(), Error> {
206-
let pipe_writer = print.map(PrintThread::clone_pipe_writer).transpose()?;
207-
run_inner(cmd, program, pipe_writer)?;
208-
209-
Ok(())
168+
let mut child = spawn(cmd, program, cargo_output)?;
169+
wait_on_child(cmd, program, &mut child)
210170
}
211171

212172
pub(crate) fn run_output(
@@ -216,12 +176,7 @@ pub(crate) fn run_output(
216176
) -> Result<Vec<u8>, Error> {
217177
cmd.stdout(Stdio::piped());
218178

219-
let mut print = cargo_output.print_thread()?;
220-
let mut child = spawn(
221-
cmd,
222-
program,
223-
print.as_mut().map(PrintThread::take_pipe_writer),
224-
)?;
179+
let mut child = spawn(cmd, program, cargo_output)?;
225180

226181
let mut stdout = vec![];
227182
child
@@ -239,7 +194,7 @@ pub(crate) fn run_output(
239194
pub(crate) fn spawn(
240195
cmd: &mut Command,
241196
program: &str,
242-
pipe_writer: Option<File>,
197+
cargo_output: &CargoOutput,
243198
) -> Result<Child, Error> {
244199
struct ResetStderr<'cmd>(&'cmd mut Command);
245200

@@ -254,10 +209,7 @@ pub(crate) fn spawn(
254209
println!("running: {:?}", cmd);
255210

256211
let cmd = ResetStderr(cmd);
257-
let child = cmd
258-
.0
259-
.stderr(pipe_writer.map_or_else(Stdio::null, Stdio::from))
260-
.spawn();
212+
let child = cmd.0.stderr(cargo_output.stdio_for_warnings()).spawn();
261213
match child {
262214
Ok(child) => Ok(child),
263215
Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
@@ -301,15 +253,41 @@ pub(crate) fn command_add_output_file(
301253
}
302254
}
303255

256+
#[cfg(feature = "parallel")]
257+
fn forward_available_stderr_as_warnings(
258+
child_stderr_reader: &mut Option<BufReader<std::process::ChildStderr>>,
259+
) {
260+
if let Some(child_stderr_reader) = child_stderr_reader.as_mut() {
261+
if let Ok(available) = child_stderr_reader.fill_buf() {
262+
let stdout = io::stdout();
263+
let mut consumed = 0;
264+
for line in available.split_inclusive(|&b| b == b'\n') {
265+
// Only forward complete lines, leave the rest in the buffer.
266+
if let Some((b'\n', line)) = line.split_last() {
267+
consumed += line.len() + 1;
268+
write_warning(&stdout, line);
269+
}
270+
}
271+
child_stderr_reader.consume(consumed);
272+
}
273+
}
274+
}
275+
304276
#[cfg(feature = "parallel")]
305277
pub(crate) fn try_wait_on_child(
306278
cmd: &Command,
307279
program: &str,
308280
child: &mut Child,
309281
stdout: &mut dyn io::Write,
282+
child_stderr_reader: &mut Option<BufReader<std::process::ChildStderr>>,
310283
) -> Result<Option<()>, Error> {
284+
forward_available_stderr_as_warnings(child_stderr_reader);
285+
311286
match child.try_wait() {
312287
Ok(Some(status)) => {
288+
// Flush any remaining stderr messages.
289+
forward_all_stderr_as_warnings(child_stderr_reader);
290+
313291
let _ = writeln!(stdout, "{}", status);
314292

315293
if status.success() {
@@ -325,12 +303,16 @@ pub(crate) fn try_wait_on_child(
325303
}
326304
}
327305
Ok(None) => Ok(None),
328-
Err(e) => Err(Error::new(
329-
ErrorKind::ToolExecError,
330-
format!(
331-
"Failed to wait on spawned child process, command {:?} with args {:?}: {}.",
332-
cmd, program, e
333-
),
334-
)),
306+
Err(e) => {
307+
// Flush any remaining stderr messages.
308+
forward_all_stderr_as_warnings(child_stderr_reader);
309+
Err(Error::new(
310+
ErrorKind::ToolExecError,
311+
format!(
312+
"Failed to wait on spawned child process, command {:?} with args {:?}: {}.",
313+
cmd, program, e
314+
),
315+
))
316+
}
335317
}
336318
}

0 commit comments

Comments
 (0)