Skip to content

Commit 5b47c14

Browse files
committed
Remove dependency on pipe, unless parallel
1 parent 2b52daf commit 5b47c14

File tree

10 files changed

+234
-321
lines changed

10 files changed

+234
-321
lines changed

Cargo.toml

Lines changed: 2 additions & 2 deletions
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"

dev-tools/gen-windows-sys-binding/windows_sys.list

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
Windows.Win32.Foundation.FILETIME
2-
Windows.Win32.Foundation.INVALID_HANDLE_VALUE
32
Windows.Win32.Foundation.ERROR_NO_MORE_ITEMS
43
Windows.Win32.Foundation.ERROR_SUCCESS
54
Windows.Win32.Foundation.SysFreeString
@@ -20,7 +19,7 @@ Windows.Win32.System.Com.COINIT_MULTITHREADED
2019
Windows.Win32.System.Com.CoCreateInstance
2120
Windows.Win32.System.Com.CoInitializeEx
2221

23-
Windows.Win32.System.Pipes.CreatePipe
22+
Windows.Win32.System.Pipes.PeekNamedPipe
2423

2524
Windows.Win32.System.Registry.RegCloseKey
2625
Windows.Win32.System.Registry.RegEnumKeyExW

src/command_helpers.rs

Lines changed: 120 additions & 90 deletions
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, Read, Write},
1010
path::Path,
11-
process::{Child, Command, Stdio},
11+
process::{Child, ChildStderr, Command, Stdio},
1212
sync::Arc,
13-
thread::{self, JoinHandle},
1413
};
1514

1615
use crate::{Error, ErrorKind, Object};
@@ -41,83 +40,121 @@ 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) struct StderrForwarder {
53+
inner: Option<(ChildStderr, Vec<u8>)>,
54+
#[cfg(feature = "parallel")]
55+
is_non_blocking: bool,
5256
}
5357

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-
}
58+
const MIN_BUFFER_CAPACITY: usize = 100;
7659

77-
// read_until does not clear the buffer
78-
line.clear();
60+
impl StderrForwarder {
61+
pub(crate) fn new(child: &mut Child) -> Self {
62+
Self {
63+
inner: child
64+
.stderr
65+
.take()
66+
.map(|stderr| (stderr, Vec::with_capacity(MIN_BUFFER_CAPACITY))),
67+
#[cfg(feature = "parallel")]
68+
is_non_blocking: false,
69+
}
70+
}
71+
72+
fn forward_available(&mut self) -> bool {
73+
if let Some((stderr, buffer)) = self.inner.as_mut() {
74+
fn write_warning(line: &[u8]) {
75+
let mut stdout = io::stdout().lock();
76+
stdout.write_all(b"cargo:warning=").unwrap();
77+
stdout.write_all(line).unwrap();
78+
stdout.write_all(b"\n").unwrap();
7979
}
80-
});
8180

82-
Ok(Self {
83-
handle: Some(print),
84-
pipe_writer: Some(pipe_writer),
85-
})
81+
#[cfg(feature = "parallel")]
82+
let read_stderr = if self.is_non_blocking {
83+
crate::parallel::stderr::read_non_blocked
84+
} else {
85+
ChildStderr::read
86+
};
87+
#[cfg(not(feature = "parallel"))]
88+
let read_stderr = ChildStderr::read;
89+
90+
loop {
91+
buffer.reserve(MIN_BUFFER_CAPACITY);
92+
93+
let old_data_end = buffer.len();
94+
buffer.resize(buffer.capacity(), 0);
95+
match read_stderr(stderr, &mut buffer[old_data_end..]) {
96+
Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => {
97+
// No data currently, yield back.
98+
buffer.truncate(old_data_end);
99+
return false;
100+
}
101+
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => {
102+
// Interrupted, try again.
103+
buffer.truncate(old_data_end);
104+
}
105+
Ok(0) | Err(_) => {
106+
// End of stream: flush remaining data and bail.
107+
if old_data_end > 0 {
108+
write_warning(&buffer[..old_data_end]);
109+
}
110+
return true;
111+
}
112+
Ok(bytes_read) => {
113+
buffer.truncate(old_data_end + bytes_read);
114+
let mut consumed = 0;
115+
for line in buffer.split_inclusive(|&b| b == b'\n') {
116+
// Only forward complete lines, leave the rest in the buffer.
117+
if let Some((b'\n', line)) = line.split_last() {
118+
consumed += line.len() + 1;
119+
write_warning(line);
120+
}
121+
}
122+
buffer.drain(..consumed);
123+
}
124+
}
125+
}
126+
} else {
127+
true
128+
}
86129
}
87130

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-
}
131+
#[cfg(feature = "parallel")]
132+
pub(crate) fn set_non_blocking(&mut self) -> Result<(), Error> {
133+
assert!(!self.is_non_blocking);
94134

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-
}
135+
if let Some((stderr, _)) = self.inner.as_mut() {
136+
crate::parallel::stderr::set_non_blocking(stderr)?;
137+
}
101138

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)
139+
self.is_non_blocking = true;
140+
Ok(())
108141
}
109-
}
110142

111-
impl Drop for PrintThread {
112-
fn drop(&mut self) {
113-
// Drop pipe_writer first to avoid deadlock
114-
self.pipe_writer.take();
143+
#[cfg(feature = "parallel")]
144+
fn forward_all(&mut self) {
145+
while !self.forward_available() {}
146+
}
115147

116-
self.handle.take().unwrap().join().unwrap();
148+
#[cfg(not(feature = "parallel"))]
149+
fn forward_all(&mut self) {
150+
let forward_result = self.forward_available();
151+
assert!(forward_result, "Should have consumed all data");
117152
}
118153
}
119154

120155
fn wait_on_child(cmd: &Command, program: &str, child: &mut Child) -> Result<(), Error> {
156+
StderrForwarder::new(child).forward_all();
157+
121158
let status = match child.wait() {
122159
Ok(s) => s,
123160
Err(e) => {
@@ -193,20 +230,13 @@ pub(crate) fn objects_from_files(files: &[Arc<Path>], dst: &Path) -> Result<Vec<
193230
Ok(objects)
194231
}
195232

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-
201233
pub(crate) fn run(
202234
cmd: &mut Command,
203235
program: &str,
204-
print: Option<&PrintThread>,
236+
cargo_output: &CargoOutput,
205237
) -> Result<(), Error> {
206-
let pipe_writer = print.map(PrintThread::clone_pipe_writer).transpose()?;
207-
run_inner(cmd, program, pipe_writer)?;
208-
209-
Ok(())
238+
let mut child = spawn(cmd, program, cargo_output)?;
239+
wait_on_child(cmd, program, &mut child)
210240
}
211241

212242
pub(crate) fn run_output(
@@ -216,12 +246,7 @@ pub(crate) fn run_output(
216246
) -> Result<Vec<u8>, Error> {
217247
cmd.stdout(Stdio::piped());
218248

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-
)?;
249+
let mut child = spawn(cmd, program, cargo_output)?;
225250

226251
let mut stdout = vec![];
227252
child
@@ -239,7 +264,7 @@ pub(crate) fn run_output(
239264
pub(crate) fn spawn(
240265
cmd: &mut Command,
241266
program: &str,
242-
pipe_writer: Option<File>,
267+
cargo_output: &CargoOutput,
243268
) -> Result<Child, Error> {
244269
struct ResetStderr<'cmd>(&'cmd mut Command);
245270

@@ -254,10 +279,7 @@ pub(crate) fn spawn(
254279
println!("running: {:?}", cmd);
255280

256281
let cmd = ResetStderr(cmd);
257-
let child = cmd
258-
.0
259-
.stderr(pipe_writer.map_or_else(Stdio::null, Stdio::from))
260-
.spawn();
282+
let child = cmd.0.stderr(cargo_output.stdio_for_warnings()).spawn();
261283
match child {
262284
Ok(child) => Ok(child),
263285
Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
@@ -307,9 +329,14 @@ pub(crate) fn try_wait_on_child(
307329
program: &str,
308330
child: &mut Child,
309331
stdout: &mut dyn io::Write,
332+
stderr_forwarder: &mut StderrForwarder,
310333
) -> Result<Option<()>, Error> {
334+
stderr_forwarder.forward_available();
335+
311336
match child.try_wait() {
312337
Ok(Some(status)) => {
338+
stderr_forwarder.forward_all();
339+
313340
let _ = writeln!(stdout, "{}", status);
314341

315342
if status.success() {
@@ -325,12 +352,15 @@ pub(crate) fn try_wait_on_child(
325352
}
326353
}
327354
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-
)),
355+
Err(e) => {
356+
stderr_forwarder.forward_all();
357+
Err(Error::new(
358+
ErrorKind::ToolExecError,
359+
format!(
360+
"Failed to wait on spawned child process, command {:?} with args {:?}: {}.",
361+
cmd, program, e
362+
),
363+
))
364+
}
335365
}
336366
}

0 commit comments

Comments
 (0)