use std::io::Write;
use std::path::Path;
use std::process::Stdio;
use gitpoulpi_core::Result;
use crate::process::{failed_with, git, spawn_failed};
const EXIT_POLL: std::time::Duration = std::time::Duration::from_millis(50);
const EXIT_GRACE: std::time::Duration = std::time::Duration::from_millis(300);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Streamed {
Done,
Stopped,
TimedOut,
}
pub(crate) fn stream_lines(
repo_root: &Path,
args: &[&str],
stdin: Option<Vec<u8>>,
deadline: Option<std::time::Instant>,
mut on_line: impl FnMut(&str) -> bool,
) -> Result<Streamed> {
use std::io::{BufRead, Read};
use std::sync::{Arc, Mutex};
let mut cmd = git(repo_root, args);
cmd.stdin(if stdin.is_some() {
Stdio::piped()
} else {
Stdio::null()
})
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = cmd.spawn().map_err(spawn_failed)?;
let writer = stdin.map(|input| {
let mut pipe = child.stdin.take().expect("stdin was piped");
std::thread::spawn(move || pipe.write_all(&input))
});
let stdout = child.stdout.take().expect("stdout was piped");
let mut stderr = child.stderr.take().expect("stderr was piped");
let (stderr_tx, stderr_rx) = std::sync::mpsc::channel::<String>();
std::thread::spawn(move || {
let mut text = String::new();
let _ = stderr.read_to_string(&mut text);
let _ = stderr_tx.send(text);
});
let child = Arc::new(Mutex::new(child));
let timed_out = Arc::new(std::sync::atomic::AtomicBool::new(false));
let (done_tx, done_rx) = std::sync::mpsc::channel::<()>();
let watchdog = deadline.map(|deadline| {
let child = Arc::clone(&child);
let timed_out = Arc::clone(&timed_out);
std::thread::spawn(move || {
let wait = deadline.saturating_duration_since(std::time::Instant::now());
if done_rx.recv_timeout(wait).is_err() {
timed_out.store(true, std::sync::atomic::Ordering::SeqCst);
let _ = child.lock().unwrap_or_else(|e| e.into_inner()).kill();
}
})
});
let (line_tx, line_rx) = std::sync::mpsc::channel::<Vec<u8>>();
std::thread::spawn(move || {
let mut reader = std::io::BufReader::new(stdout);
loop {
let mut buf = Vec::new();
match reader.read_until(b'\n', &mut buf) {
Ok(0) | Err(_) => break,
Ok(_) => {
if line_tx.send(buf).is_err() {
break;
}
}
}
}
});
let mut stopped = false;
let mut handle = |mut buf: Vec<u8>| -> bool {
while matches!(buf.last(), Some(b'\n' | b'\r')) {
buf.pop();
}
if on_line(&String::from_utf8_lossy(&buf)) {
return true;
}
stopped = true;
let _ = child.lock().unwrap_or_else(|e| e.into_inner()).kill();
false
};
'read: loop {
match line_rx.recv_timeout(EXIT_POLL) {
Ok(buf) => {
if !handle(buf) {
break;
}
}
Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
let exited = matches!(
child.lock().unwrap_or_else(|e| e.into_inner()).try_wait(),
Ok(Some(_)) | Err(_)
);
if exited {
while let Ok(buf) = line_rx.recv_timeout(EXIT_GRACE) {
if !handle(buf) {
break 'read;
}
}
break;
}
}
}
}
drop(line_rx);
let status = child.lock().unwrap_or_else(|e| e.into_inner()).wait();
let _ = done_tx.send(());
if let Some(w) = watchdog {
let _ = w.join();
}
if let Some(w) = writer {
let _ = w.join();
}
let stderr = stderr_rx.recv_timeout(EXIT_GRACE).unwrap_or_default();
let timed_out = timed_out.load(std::sync::atomic::Ordering::SeqCst);
if stopped {
return Ok(Streamed::Stopped);
}
if timed_out {
return Ok(Streamed::TimedOut);
}
let status = status
.map_err(|e| gitpoulpi_core::Error::Backend(format!("failed to wait for git: {e}")))?;
if !status.success() {
return Err(failed_with(args, status.code(), &stderr));
}
Ok(Streamed::Done)
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
#[test]
fn a_process_holding_the_pipe_open_does_not_hold_the_scan() {
let dir = tempfile::tempdir().unwrap();
let started = std::time::Instant::now();
let mut lines = Vec::new();
let ended = stream_lines(
dir.path(),
&["-c", "alias.bg=!sleep 8 & echo hi", "bg"],
None,
None,
|l| {
lines.push(l.to_string());
true
},
)
.unwrap();
assert_eq!(ended, Streamed::Done);
assert_eq!(lines, vec!["hi".to_string()]);
assert!(started.elapsed() < std::time::Duration::from_secs(5));
}
#[test]
fn crlf_lines_lose_their_terminators() {
let dir = tempfile::tempdir().unwrap();
let mut lines = Vec::new();
stream_lines(
dir.path(),
&["-c", "alias.crlf=!printf 'a\\r\\nb\\r\\n'", "crlf"],
None,
None,
|l| {
lines.push(l.to_string());
true
},
)
.unwrap();
assert_eq!(lines, vec!["a".to_string(), "b".to_string()]);
}
}