repo: Fix deadlock in git command

ec27a33ea04a37c06b0f182ce250885387e5d63c
Alexis Sellier committed ago 1 parent 273ad484
crates/repo/src/git.rs +26 -4
4 4
use std::ffi::OsString;
5 5
use std::fs;
6 6
use std::io::{self, Read as _, Write as _};
7 7
use std::path::{Path, PathBuf};
8 8
use std::process::{Command, Output, Stdio};
9 +
use std::thread;
9 10
use std::time::{SystemTime, UNIX_EPOCH};
10 11
11 12
use self::refs::Qualified;
12 13
use crate::{
13 14
    AheadBehind, Branch, CommitTime, DiffRepository, DiffStat, MergeStatus, Oid, PatchId,
358 359
            command
359 360
                .stdin(Stdio::piped())
360 361
                .stdout(Stdio::piped())
361 362
                .stderr(Stdio::piped());
362 363
            let mut child = command.spawn()?;
363 -
364 -
            if let Some(child_stdin) = child.stdin.as_mut() {
365 -
                child_stdin.write_all(stdin)?;
364 +
            // Feed the payload from a worker thread. Commands such as `patch-id`
365 +
            // write results while they read, so writing a large payload inline
366 +
            // deadlocks as soon as their output fills the pipe buffer.
367 +
            let payload = stdin.to_vec();
368 +
            let writer = child.stdin.take().map(|mut pipe| {
369 +
                thread::spawn(move || {
370 +
                    let result = pipe.write_all(&payload);
371 +
                    drop(pipe);
372 +
                    result
373 +
                })
374 +
            });
375 +
            let output = child.wait_with_output().map_err(RepoError::Io)?;
376 +
            if let Some(writer) = writer {
377 +
                match writer.join() {
378 +
                    // A command that fails early closes its input; report its own
379 +
                    // failure rather than the resulting broken pipe.
380 +
                    Ok(Err(error)) if output.status.success() => return Err(RepoError::Io(error)),
381 +
                    Ok(_) => {}
382 +
                    Err(_) => {
383 +
                        return Err(RepoError::Git(format!(
384 +
                            "git {subcommand} input writer panicked"
385 +
                        )));
386 +
                    }
387 +
                }
366 388
            }
367 -
            child.wait_with_output().map_err(RepoError::Io)
389 +
            Ok(output)
368 390
        } else {
369 391
            command.output().map_err(RepoError::Io)
370 392
        }
371 393
    }
372 394
}
root\nnew file mode")); +0 -0
file\n")); +0 -0
file\n"), +0 -0
file\n"), +0 -0
a\n--- a/a\n+++ b/a\n@@ -1 +1 @@\n-old\n+new\n".to_owned(), +0 -0
b\n--- a/b\n+++ b/b\n@@ -0,0 +1 @@\n+line\n".to_owned(), +0 -0
f{index}\n--- a/f{index}\n+++ b/f{index}\n\ +0 -0