diff --git a/crates/ide-android/src/process.rs b/crates/ide-android/src/process.rs index b5b858389..2f74a34f0 100644 --- a/crates/ide-android/src/process.rs +++ b/crates/ide-android/src/process.rs @@ -1,101 +1,18 @@ -//! Child processes of the `adb` CLI: bounded runs, and cancellable line streams +//! The `adb` CLI as a child process: bounded runs, and cancellable line streams //! that are handed over in batches (logcat is far too chatty for one message a line). -use ide_core::process::terminate_tree; -use ide_core::{CancellationToken, IdeError, IdeResult}; -use std::io::Read; -use std::process::{Child, Command, Stdio}; -use std::sync::mpsc; +pub(crate) use ide_core::cli_process::Output; +use ide_core::cli_process::{CarriageReturn, CliTool, Decoding, Poll, Stream, keep_stderr_line}; +use ide_core::{CancellationToken, IdeResult}; +use std::process::Command; use std::time::{Duration, Instant}; -/// How long a cancelled child gets to exit on `SIGTERM` (and flush) before `SIGKILL`. -const KILL_GRACE: Duration = Duration::from_millis(20); - -pub(crate) struct Output { - pub stdout: String, - pub stderr: String, - pub success: bool, -} - -fn prepare(cmd: &mut Command) { - cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); - ide_core::process::prepare(ide_core::process::own_group(cmd)); -} - -fn spawn(cmd: &mut Command) -> IdeResult { - cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run adb: {e}"))) -} - -fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle { - std::thread::spawn(move || { - let mut buf = Vec::new(); - let _ = pipe.read_to_end(&mut buf); - ide_core::output_encoding::decode_tool_output(&buf) - }) -} +const ADB: CliTool = CliTool::new("adb", Decoding::ToolOutput); /// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires; /// a non-zero exit is reported in [`Output::success`], not as an error. -pub(crate) fn run(mut cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult { - prepare(&mut cmd); - let mut child = spawn(&mut cmd)?; - let out = child.stdout.take().map(read_all); - let err = child.stderr.take().map(read_all); - let deadline = Instant::now() + timeout; - let status = loop { - if let Some(status) = child.try_wait()? { - break status; - } - if cancel.is_some_and(CancellationToken::is_cancelled) { - terminate_tree(&mut child, KILL_GRACE); - return Err(IdeError::cancelled()); - } - if Instant::now() >= deadline { - terminate_tree(&mut child, KILL_GRACE); - return Err(IdeError::unavailable("adb did not respond in time")); - } - std::thread::sleep(Duration::from_millis(10)); - }; - Ok(Output { - stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(), - stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(), - success: status.success(), - }) -} - -enum Event { - Line(bool, String), - Closed, -} - -fn spawn_reader(mut pipe: impl Read + Send + 'static, tx: mpsc::Sender, stdout: bool) { - std::thread::spawn(move || { - let mut buf = [0u8; 8192]; - let mut pending: Vec = Vec::new(); - let flush = |pending: &mut Vec| { - if !pending.is_empty() { - let line = ide_core::output_encoding::decode_tool_output(pending); - pending.clear(); - let _ = tx.send(Event::Line(stdout, line.trim_end().to_string())); - } - }; - loop { - match pipe.read(&mut buf) { - Ok(0) | Err(_) => break, - Ok(n) => { - for &b in &buf[..n] { - if b == b'\n' { - flush(&mut pending); - } else if b != b'\r' { - pending.push(b); - } - } - } - } - } - flush(&mut pending); - let _ = tx.send(Event::Closed); - }); +pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult { + ADB.run(cmd, timeout, cancel) } fn flush(batch: &mut Vec, on_batch: &mut dyn FnMut(Vec)) { @@ -109,41 +26,22 @@ fn flush(batch: &mut Vec, on_batch: &mut dyn FnMut(Vec)) { /// old, so neither a quiet nor a steady stream holds lines back. Stderr is kept as a /// tail for the error message. Returns whether the child exited successfully. pub(crate) fn stream_batched( - mut cmd: Command, + cmd: Command, cancel: &CancellationToken, idle: Duration, max: usize, mut parse: impl FnMut(&str) -> Option, on_batch: &mut dyn FnMut(Vec), ) -> IdeResult<(bool, Vec)> { - if cancel.is_cancelled() { - return Err(IdeError::cancelled()); - } - prepare(&mut cmd); - let mut child = spawn(&mut cmd)?; - let (tx, rx) = mpsc::channel::(); - let mut open = 0; - if let Some(out) = child.stdout.take() { - spawn_reader(out, tx.clone(), true); - open += 1; - } - if let Some(err) = child.stderr.take() { - spawn_reader(err, tx.clone(), false); - open += 1; - } - drop(tx); + let mut lines = ADB.lines(cmd, cancel, CarriageReturn::Dropped)?; let mut stderr_tail: Vec = Vec::new(); let mut batch: Vec = Vec::with_capacity(max); // When the first line of the waiting batch arrived. let mut since = Instant::now(); - while open > 0 { - if cancel.is_cancelled() { - terminate_tree(&mut child, KILL_GRACE); - return Err(IdeError::cancelled()); - } + loop { let wait = if batch.is_empty() { idle } else { idle.saturating_sub(since.elapsed()) }; - match rx.recv_timeout(wait) { - Ok(Event::Line(true, line)) => { + match lines.poll(cancel, wait)? { + Poll::Line(Stream::Stdout, line) => { if let Some(item) = parse(&line) { if batch.is_empty() { since = Instant::now(); @@ -154,36 +52,25 @@ pub(crate) fn stream_batched( } } } - Ok(Event::Line(false, line)) => { + Poll::Line(Stream::Stderr, line) => { if !line.trim().is_empty() { - stderr_tail.push(line); - if stderr_tail.len() > 20 { - stderr_tail.remove(0); - } + keep_stderr_line(&mut stderr_tail, line); } } - Ok(Event::Closed) => open -= 1, - Err(mpsc::RecvTimeoutError::Timeout) => flush(&mut batch, on_batch), - Err(mpsc::RecvTimeoutError::Disconnected) => break, + Poll::Closed => {} + Poll::Timeout => flush(&mut batch, on_batch), + Poll::Finished => break, } } flush(&mut batch, on_batch); - let status = loop { - if let Some(status) = child.try_wait()? { - break status; - } - if cancel.is_cancelled() { - terminate_tree(&mut child, KILL_GRACE); - return Err(IdeError::cancelled()); - } - std::thread::sleep(Duration::from_millis(10)); - }; - Ok((status.success(), stderr_tail)) + Ok((lines.finish(cancel)?, stderr_tail)) } #[cfg(all(test, unix))] mod tests { use super::*; + use ide_core::error::ErrorKind; + use ide_core::process::process_alive; #[test] fn a_steady_stream_is_handed_over_while_it_runs() { @@ -203,4 +90,199 @@ mod tests { assert_eq!(sizes.iter().sum::(), 20); assert!(sizes.len() >= 3, "lines arriving every 20 ms waited for the end: {sizes:?}"); } + + const LONG: Duration = Duration::from_secs(30); + + fn sh(script: &str) -> Command { + let mut cmd = Command::new("sh"); + cmd.args(["-c", script]); + cmd + } + + /// A script that records its pid in `name`'s file, then runs `rest`. + fn recording_pid(name: &str, rest: &str) -> (Command, std::path::PathBuf) { + let file = std::env::temp_dir().join(format!("openidea-process-{}-{name}", std::process::id())); + let _ = std::fs::remove_file(&file); + (sh(&format!("echo $$ > '{0}.tmp' && mv '{0}.tmp' '{0}'; {rest}", file.display())), file) + } + + fn recorded_pid(file: &std::path::Path) -> u32 { + let pid = std::fs::read_to_string(file).unwrap().trim().parse().unwrap(); + let _ = std::fs::remove_file(file); + pid + } + + /// Cancels `cancel` once the script has recorded its pid. + fn cancel_when_recorded(file: &std::path::Path, cancel: &CancellationToken) { + let (file, cancel) = (file.to_owned(), cancel.clone()); + std::thread::spawn(move || { + while !file.exists() { + std::thread::sleep(Duration::from_millis(5)); + } + cancel.cancel(); + }); + } + + fn assert_gone(pid: u32) { + let deadline = Instant::now() + Duration::from_secs(5); + while process_alive(pid) { + assert!(Instant::now() < deadline, "process {pid} survived"); + std::thread::sleep(Duration::from_millis(20)); + } + } + + #[test] + fn the_exit_status_is_reported_not_raised() { + assert!(run(sh("exit 0"), LONG, None).unwrap().success); + assert!(!run(sh("exit 3"), LONG, None).unwrap().success); + } + + #[test] + fn both_streams_are_captured_separately_and_in_order() { + let out = run(sh("printf 'a\\nb\\nc\\n'; printf 'x\\ny\\n' >&2"), LONG, None).unwrap(); + assert_eq!(out.stdout, "a\nb\nc\n"); + assert_eq!(out.stderr, "x\ny\n"); + assert!(out.success); + } + + #[test] + fn invalid_utf8_is_replaced_in_collected_output() { + let out = run(sh("printf 'ok\\n\\377\\n'; printf 'a\\377b' >&2"), LONG, None).unwrap(); + assert_eq!(out.stdout, "ok\n\u{FFFD}\n"); + assert_eq!(out.stderr, "a\u{FFFD}b"); + } + + #[test] + fn stdin_is_closed() { + assert_eq!(run(sh("cat; echo done"), LONG, None).unwrap().stdout, "done\n"); + } + + #[test] + fn a_missing_program_is_unavailable() { + let err = run(Command::new("/nonexistent/openidea-adb"), LONG, None).err().unwrap(); + assert_eq!(err.kind, ErrorKind::Unavailable); + assert_eq!(err.message, "could not run adb: No such file or directory (os error 2)"); + } + + #[test] + fn a_run_past_its_timeout_fails_and_the_child_is_killed() { + let (cmd, file) = recording_pid("adb-timeout", "exec sleep 30"); + let err = run(cmd, Duration::from_secs(1), None).err().unwrap(); + assert_eq!(err.kind, ErrorKind::Unavailable); + assert_eq!(err.message, "adb did not respond in time"); + assert_gone(recorded_pid(&file)); + } + + #[test] + fn a_cancelled_run_fails_and_the_child_is_killed() { + let (cmd, file) = recording_pid("adb-cancel", "exec sleep 30"); + let cancel = CancellationToken::new(); + cancel_when_recorded(&file, &cancel); + let err = run(cmd, LONG, Some(&cancel)).err().unwrap(); + assert_eq!(err.kind, ErrorKind::Cancelled); + assert_eq!(err.message, "cancelled"); + assert_gone(recorded_pid(&file)); + } + + /// Runs `script` batched by `max` lines (a long `idle`, so only `max` and the end flush), + /// parsing stdout lines unless they are `skip`. + fn batches(script: &str, max: usize) -> (bool, Vec>, Vec) { + let mut batches = Vec::new(); + let (ok, tail) = stream_batched( + sh(script), + &CancellationToken::new(), + LONG, + max, + |line| (line != "skip").then(|| line.to_owned()), + &mut |batch| batches.push(batch), + ) + .unwrap(); + (ok, batches, tail) + } + + #[test] + fn a_batch_is_handed_over_as_soon_as_max_lines_are_ready() { + let (ok, batches, _) = batches("printf '1\\n2\\n3\\n4\\n5\\n'", 2); + assert!(ok); + assert_eq!(batches, [vec!["1", "2"], vec!["3", "4"], vec!["5"]]); + } + + #[test] + fn lines_the_parser_rejects_are_dropped() { + let (_, batches, _) = batches("printf '1\\nskip\\n2\\n'", 10); + assert_eq!(batches, [vec!["1", "2"]]); + } + + #[test] + fn carriage_returns_are_dropped_not_split_on_and_line_ends_are_trimmed() { + let (_, batches, _) = batches("printf 'a\\r\\nb\\rc \\n\\n\\nd'", 10); + assert_eq!(batches, [vec!["a", "bc", "d"]]); + } + + #[test] + fn a_stream_replaces_invalid_utf8() { + let (_, batches, _) = batches("printf 'a\\377b\\n'", 10); + assert_eq!(batches, [vec!["a\u{FFFD}b"]]); + } + + #[test] + fn a_stream_reports_the_exit_status() { + assert!(batches("exit 0", 10).0); + assert!(!batches("exit 2", 10).0); + } + + #[test] + fn stderr_is_not_parsed_and_its_last_twenty_non_blank_lines_are_kept() { + let (_, batches, tail) = + batches("echo ' ' >&2; i=1; while [ $i -le 25 ]; do echo e$i >&2; i=$((i+1)); done; echo out", 10); + assert_eq!(batches, [vec!["out"]]); + let expected: Vec = (6..=25).map(|i| format!("e{i}")).collect(); + assert_eq!(tail, expected); + } + + #[test] + fn a_stream_cancelled_before_it_starts_does_not_spawn() { + let cancel = CancellationToken::new(); + cancel.cancel(); + let err = stream_batched( + Command::new("/nonexistent/openidea-adb"), + &cancel, + LONG, + 10, + |line| Some(line.to_owned()), + &mut |_| {}, + ) + .err() + .unwrap(); + assert_eq!(err.kind, ErrorKind::Cancelled); + assert_eq!(err.message, "cancelled"); + } + + #[test] + fn a_stream_cancelled_while_running_fails_and_the_child_is_killed() { + let (cmd, file) = recording_pid("adb-stream-cancel", "echo started; exec sleep 30"); + let cancel = CancellationToken::new(); + let err = stream_batched(cmd, &cancel, LONG, 1, |line| Some(line.to_owned()), &mut |_| cancel.cancel()) + .err() + .unwrap(); + assert_eq!(err.kind, ErrorKind::Cancelled); + assert_eq!(err.message, "cancelled"); + assert_gone(recorded_pid(&file)); + } + + #[test] + fn a_missing_program_cannot_be_streamed() { + let err = stream_batched( + Command::new("/nonexistent/openidea-adb"), + &CancellationToken::new(), + LONG, + 10, + |line| Some(line.to_owned()), + &mut |_| {}, + ) + .err() + .unwrap(); + assert_eq!(err.kind, ErrorKind::Unavailable); + assert_eq!(err.message, "could not run adb: No such file or directory (os error 2)"); + } } diff --git a/crates/ide-core/src/cli_process.rs b/crates/ide-core/src/cli_process.rs new file mode 100644 index 000000000..3eb133335 --- /dev/null +++ b/crates/ide-core/src/cli_process.rs @@ -0,0 +1,319 @@ +//! Runs a tool's CLI (`docker`, `gh`, `adb`) as a child process: bounded runs that collect +//! its output, and cancellable streams that hand over its output line by line. +//! +//! Every child leads its own process group ([`own_group`]), so cancelling or timing out +//! reaches what it started in turn (`gh` → `git`, `docker` → CLI plugins such as compose). +//! They get [`KILL_GRACE`] to exit on `SIGTERM` and clean up (git removes its lock files) +//! before `SIGKILL`. + +use crate::process::{own_group, prepare, terminate_tree}; +use crate::{CancellationToken, IdeError, IdeResult}; +use std::borrow::Cow; +use std::io::{Read, Write}; +use std::process::{Child, Command, Stdio}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +/// How long a cancelled or timed-out child's process group gets to exit on `SIGTERM` +/// before `SIGKILL`. +const KILL_GRACE: Duration = Duration::from_millis(20); + +/// How many of a streamed child's last non-blank stderr lines are kept for its error message. +const STDERR_TAIL: usize = 20; + +/// How a tool's output bytes become text. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Decoding { + /// [`decode_tool_output`](crate::output_encoding::decode_tool_output): UTF-8, and on + /// Windows the system code page for what is not. + ToolOutput, + /// UTF-8, invalid bytes replaced by U+FFFD. + Utf8Lossy, +} + +impl Decoding { + fn decode(self, bytes: &[u8]) -> Cow<'_, str> { + match self { + Decoding::ToolOutput => Cow::Owned(crate::output_encoding::decode_tool_output(bytes)), + Decoding::Utf8Lossy => String::from_utf8_lossy(bytes), + } + } +} + +/// What a child's stdin is fed with, and how. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Input<'a> { + /// Written before the output is read, then closed: only for input small enough + /// (a password) to fit the pipe, as a full pipe blocks the caller. + Inline(&'a str), + /// Written by a thread of its own, then closed: a large body must not block on a full + /// pipe while the child is not reading yet. + Threaded(&'a str), +} + +/// How a streamed child's `\r` is read. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CarriageReturn { + /// Ends a line like `\n`: progress output rewrites its line in place. + EndsLine, + /// Is dropped; only `\n` ends a line. + Dropped, +} + +/// What a bounded run collected. +pub struct Output { + pub stdout: String, + pub stderr: String, + pub success: bool, +} + +/// Which pipe a streamed line came from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Stream { + Stdout, + Stderr, +} + +/// One tool's CLI: its name for error messages and how its output is decoded. +#[derive(Clone, Copy, Debug)] +pub struct CliTool { + name: &'static str, + decoding: Decoding, +} + +impl CliTool { + pub const fn new(name: &'static str, decoding: Decoding) -> Self { + Self { name, decoding } + } + + fn spawn(self, cmd: &mut Command) -> IdeResult { + cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run {}: {e}", self.name))) + } + + /// Pipes stdout and stderr, closes stdin and starts the child in its own process group. + fn configure(cmd: &mut Command) { + cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); + prepare(own_group(cmd)); + } + + /// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires; + /// a non-zero exit is reported in [`Output::success`], not as an error. + pub fn run(self, cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult { + self.run_with_input(cmd, None, timeout, cancel) + } + + /// [`run`](Self::run) with `input` written to the child's stdin and then closed. + pub fn run_with_input( + self, + mut cmd: Command, + input: Option, + timeout: Duration, + cancel: Option<&CancellationToken>, + ) -> IdeResult { + Self::configure(&mut cmd); + if input.is_some() { + cmd.stdin(Stdio::piped()); + } + let mut child = self.spawn(&mut cmd)?; + match (input, child.stdin.take()) { + (Some(Input::Inline(text)), Some(mut stdin)) => { + // Dropping `stdin` afterwards closes it, so the CLI sees EOF. + let _ = stdin.write_all(text.as_bytes()); + } + (Some(Input::Threaded(text)), Some(mut stdin)) => { + let text = text.to_owned(); + std::thread::spawn(move || { + let _ = stdin.write_all(text.as_bytes()); + }); + } + _ => {} + } + let decoding = self.decoding; + let out = child.stdout.take().map(|pipe| read_all(pipe, decoding)); + let err = child.stderr.take().map(|pipe| read_all(pipe, decoding)); + let deadline = Instant::now() + timeout; + let status = loop { + if let Some(status) = child.try_wait()? { + break status; + } + if cancel.is_some_and(CancellationToken::is_cancelled) { + terminate_tree(&mut child, KILL_GRACE); + return Err(IdeError::cancelled()); + } + if Instant::now() >= deadline { + terminate_tree(&mut child, KILL_GRACE); + return Err(IdeError::unavailable(format!("{} did not respond in time", self.name))); + } + std::thread::sleep(Duration::from_millis(10)); + }; + Ok(Output { + stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(), + stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(), + success: status.success(), + }) + } + + /// Runs `cmd`, handing every output line to `on_line` until it exits or `cancel` + /// fires. Returns whether it exited successfully plus the last stderr lines. + pub fn stream( + self, + cmd: Command, + cancel: &CancellationToken, + on_line: &mut dyn FnMut(Stream, String), + ) -> IdeResult<(bool, Vec)> { + let mut lines = self.lines(cmd, cancel, CarriageReturn::EndsLine)?; + let mut stderr_tail: Vec = Vec::new(); + loop { + match lines.poll(cancel, Duration::from_millis(50))? { + Poll::Line(stream, line) => { + if stream == Stream::Stderr && !line.trim().is_empty() { + keep_stderr_line(&mut stderr_tail, line.clone()); + } + on_line(stream, line); + } + Poll::Closed | Poll::Timeout => {} + Poll::Finished => break, + } + } + Ok((lines.finish(cancel)?, stderr_tail)) + } + + /// Starts `cmd` with a reader thread per pipe, for a caller that drives the loop itself + /// (see [`Lines::poll`]). Fails when `cancel` has already fired, without starting it. + pub fn lines(self, mut cmd: Command, cancel: &CancellationToken, cr: CarriageReturn) -> IdeResult { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + Self::configure(&mut cmd); + let mut child = self.spawn(&mut cmd)?; + let (tx, rx) = mpsc::channel::(); + let mut open = 0; + if let Some(out) = child.stdout.take() { + spawn_reader(out, tx.clone(), Stream::Stdout, self.decoding, cr); + open += 1; + } + if let Some(err) = child.stderr.take() { + spawn_reader(err, tx.clone(), Stream::Stderr, self.decoding, cr); + open += 1; + } + drop(tx); + Ok(Lines { child, rx, open }) + } +} + +/// Appends a stderr line to `tail`, which keeps only the last [`STDERR_TAIL`]. +pub fn keep_stderr_line(tail: &mut Vec, line: String) { + tail.push(line); + if tail.len() > STDERR_TAIL { + tail.remove(0); + } +} + +fn read_all(mut pipe: impl Read + Send + 'static, decoding: Decoding) -> std::thread::JoinHandle { + std::thread::spawn(move || { + let mut buf = Vec::new(); + let _ = pipe.read_to_end(&mut buf); + decoding.decode(&buf).into_owned() + }) +} + +enum Event { + Line(Stream, String), + Closed, +} + +fn spawn_reader( + mut pipe: impl Read + Send + 'static, + tx: mpsc::Sender, + stream: Stream, + decoding: Decoding, + cr: CarriageReturn, +) { + std::thread::spawn(move || { + let mut buf = [0u8; 8192]; + let mut pending: Vec = Vec::new(); + let flush = |pending: &mut Vec| { + if !pending.is_empty() { + let line = decoding.decode(pending).trim_end().to_string(); + pending.clear(); + let _ = tx.send(Event::Line(stream, line)); + } + }; + loop { + match pipe.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => { + for &b in &buf[..n] { + if b == b'\n' || (b == b'\r' && cr == CarriageReturn::EndsLine) { + flush(&mut pending); + } else if b != b'\r' { + pending.push(b); + } + } + } + } + } + flush(&mut pending); + let _ = tx.send(Event::Closed); + }); +} + +/// A running child whose output lines are read by threads: see [`CliTool::lines`]. +pub struct Lines { + child: Child, + rx: mpsc::Receiver, + /// Pipes whose reader has not reported its end yet. + open: usize, +} + +/// What [`Lines::poll`] saw. +pub enum Poll { + Line(Stream, String), + /// A pipe reached its end. + Closed, + /// Nothing arrived within the wait. + Timeout, + /// Every pipe is at its end. + Finished, +} + +impl Lines { + /// Waits up to `wait` for the next line. Fails, after killing the child, when `cancel` has fired. + pub fn poll(&mut self, cancel: &CancellationToken, wait: Duration) -> IdeResult { + if self.open == 0 { + return Ok(Poll::Finished); + } + if cancel.is_cancelled() { + terminate_tree(&mut self.child, KILL_GRACE); + return Err(IdeError::cancelled()); + } + match self.rx.recv_timeout(wait) { + Ok(Event::Line(stream, line)) => Ok(Poll::Line(stream, line)), + Ok(Event::Closed) => { + self.open -= 1; + Ok(Poll::Closed) + } + Err(mpsc::RecvTimeoutError::Timeout) => Ok(Poll::Timeout), + Err(mpsc::RecvTimeoutError::Disconnected) => { + self.open = 0; + Ok(Poll::Finished) + } + } + } + + /// Waits for the child to exit and returns whether it did so successfully. Fails, after + /// killing it, when `cancel` fires first. + pub fn finish(mut self, cancel: &CancellationToken) -> IdeResult { + let status = loop { + if let Some(status) = self.child.try_wait()? { + break status; + } + if cancel.is_cancelled() { + terminate_tree(&mut self.child, KILL_GRACE); + return Err(IdeError::cancelled()); + } + std::thread::sleep(Duration::from_millis(10)); + }; + Ok(status.success()) + } +} diff --git a/crates/ide-core/src/lib.rs b/crates/ide-core/src/lib.rs index c1e52eee3..2932e667e 100644 --- a/crates/ide-core/src/lib.rs +++ b/crates/ide-core/src/lib.rs @@ -4,6 +4,7 @@ //! feature crates depend on `ide-core` and never on each other's internals. //! All IPC-facing types derive `specta::Type`, which generates `src/bindings.ts`. +pub mod cli_process; pub mod editor_settings; pub mod error; pub mod event; diff --git a/crates/ide-docker/src/process.rs b/crates/ide-docker/src/process.rs index 3941991dd..d091729ed 100644 --- a/crates/ide-docker/src/process.rs +++ b/crates/ide-docker/src/process.rs @@ -1,180 +1,216 @@ -//! Child processes of the docker CLI: bounded runs and cancellable line streams. +//! The docker CLI as a child process: bounded runs and cancellable line streams. -use ide_core::process::terminate_tree; -use ide_core::{CancellationToken, IdeError, IdeResult}; -use std::io::Read; -use std::process::{Child, Command, Stdio}; -use std::sync::mpsc; -use std::time::{Duration, Instant}; +use ide_core::cli_process::{CliTool, Decoding, Input}; +pub(crate) use ide_core::cli_process::{Output, Stream}; +use ide_core::{CancellationToken, IdeResult}; +use std::process::Command; +use std::time::Duration; -/// How long a cancelled or timed-out child's process group (CLI plugins such as compose) -/// gets to exit on `SIGTERM`, and clean up, before `SIGKILL`. -const KILL_GRACE: Duration = Duration::from_millis(20); - -pub(crate) struct Output { - pub stdout: String, - pub stderr: String, - pub success: bool, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Stream { - Stdout, - Stderr, -} - -fn prepare(cmd: &mut Command) { - cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); - ide_core::process::prepare(ide_core::process::own_group(cmd)); -} - -fn spawn(cmd: &mut Command) -> IdeResult { - cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run docker: {e}"))) -} - -fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle { - std::thread::spawn(move || { - let mut buf = Vec::new(); - let _ = pipe.read_to_end(&mut buf); - ide_core::output_encoding::decode_tool_output(&buf) - }) -} +const DOCKER: CliTool = CliTool::new("docker", Decoding::ToolOutput); /// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires; /// a non-zero exit is reported in [`Output::success`], not as an error. pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult { - run_with_input(cmd, timeout, cancel, None) + DOCKER.run(cmd, timeout, cancel) } /// [`run`] with `input` written to the child's stdin (e.g. `--password-stdin`). pub(crate) fn run_with_input( - mut cmd: Command, + cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>, input: Option<&str>, ) -> IdeResult { - prepare(&mut cmd); - if input.is_some() { - cmd.stdin(Stdio::piped()); - } - let mut child = spawn(&mut cmd)?; - if let (Some(text), Some(mut stdin)) = (input, child.stdin.take()) { - // Dropping `stdin` afterwards closes it, so the CLI sees EOF. - let _ = std::io::Write::write_all(&mut stdin, text.as_bytes()); - } - let out = child.stdout.take().map(read_all); - let err = child.stderr.take().map(read_all); - let deadline = Instant::now() + timeout; - let status = loop { - if let Some(status) = child.try_wait()? { - break status; - } - if cancel.is_some_and(CancellationToken::is_cancelled) { - terminate_tree(&mut child, KILL_GRACE); - return Err(IdeError::cancelled()); - } - if Instant::now() >= deadline { - terminate_tree(&mut child, KILL_GRACE); - return Err(IdeError::unavailable("docker did not respond in time")); - } - std::thread::sleep(Duration::from_millis(10)); - }; - Ok(Output { - stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(), - stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(), - success: status.success(), - }) -} - -enum Event { - Line(Stream, String), - Closed, -} - -fn spawn_reader(mut pipe: impl Read + Send + 'static, tx: mpsc::Sender, stream: Stream) { - std::thread::spawn(move || { - let mut buf = [0u8; 8192]; - let mut pending: Vec = Vec::new(); - let flush = |pending: &mut Vec| { - if !pending.is_empty() { - let line = ide_core::output_encoding::decode_tool_output(pending).trim_end().to_string(); - pending.clear(); - let _ = tx.send(Event::Line(stream, line)); - } - }; - loop { - match pipe.read(&mut buf) { - Ok(0) | Err(_) => break, - Ok(n) => { - for &b in &buf[..n] { - // `\r` too: pull / build progress rewrites its line in place. - if b == b'\n' || b == b'\r' { - flush(&mut pending); - } else { - pending.push(b); - } - } - } - } - } - flush(&mut pending); - let _ = tx.send(Event::Closed); - }); + DOCKER.run_with_input(cmd, input.map(Input::Inline), timeout, cancel) } /// Runs `cmd`, handing every output line to `on_line` until it exits or `cancel` /// fires. Returns whether it exited successfully plus the last stderr lines. pub(crate) fn stream( - mut cmd: Command, + cmd: Command, cancel: &CancellationToken, on_line: &mut dyn FnMut(Stream, String), ) -> IdeResult<(bool, Vec)> { - if cancel.is_cancelled() { - return Err(IdeError::cancelled()); - } - prepare(&mut cmd); - let mut child = spawn(&mut cmd)?; - let (tx, rx) = mpsc::channel::(); - let mut open = 0; - if let Some(out) = child.stdout.take() { - spawn_reader(out, tx.clone(), Stream::Stdout); - open += 1; - } - if let Some(err) = child.stderr.take() { - spawn_reader(err, tx.clone(), Stream::Stderr); - open += 1; - } - drop(tx); - let mut stderr_tail: Vec = Vec::new(); - while open > 0 { - if cancel.is_cancelled() { - terminate_tree(&mut child, KILL_GRACE); - return Err(IdeError::cancelled()); - } - match rx.recv_timeout(Duration::from_millis(50)) { - Ok(Event::Line(stream, line)) => { - if stream == Stream::Stderr && !line.trim().is_empty() { - stderr_tail.push(line.clone()); - if stderr_tail.len() > 20 { - stderr_tail.remove(0); - } - } - on_line(stream, line); + DOCKER.stream(cmd, cancel, on_line) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use ide_core::error::ErrorKind; + use ide_core::process::process_alive; + use std::time::Instant; + + const LONG: Duration = Duration::from_secs(30); + + fn sh(script: &str) -> Command { + let mut cmd = Command::new("sh"); + cmd.args(["-c", script]); + cmd + } + + /// A script that records its pid in `name`'s file, then runs `rest`. + fn recording_pid(name: &str, rest: &str) -> (Command, std::path::PathBuf) { + let file = std::env::temp_dir().join(format!("openidea-process-{}-{name}", std::process::id())); + let _ = std::fs::remove_file(&file); + (sh(&format!("echo $$ > '{0}.tmp' && mv '{0}.tmp' '{0}'; {rest}", file.display())), file) + } + + fn recorded_pid(file: &std::path::Path) -> u32 { + let pid = std::fs::read_to_string(file).unwrap().trim().parse().unwrap(); + let _ = std::fs::remove_file(file); + pid + } + + /// Cancels `cancel` once the script has recorded its pid. + fn cancel_when_recorded(file: &std::path::Path, cancel: &CancellationToken) { + let (file, cancel) = (file.to_owned(), cancel.clone()); + std::thread::spawn(move || { + while !file.exists() { + std::thread::sleep(Duration::from_millis(5)); } - Ok(Event::Closed) => open -= 1, - Err(mpsc::RecvTimeoutError::Timeout) => {} - Err(mpsc::RecvTimeoutError::Disconnected) => break, + cancel.cancel(); + }); + } + + fn assert_gone(pid: u32) { + let deadline = Instant::now() + Duration::from_secs(5); + while process_alive(pid) { + assert!(Instant::now() < deadline, "process {pid} survived"); + std::thread::sleep(Duration::from_millis(20)); } + } + + #[test] + fn the_exit_status_is_reported_not_raised() { + assert!(run(sh("exit 0"), LONG, None).unwrap().success); + assert!(!run(sh("exit 3"), LONG, None).unwrap().success); + } + + #[test] + fn both_streams_are_captured_separately_and_in_order() { + let out = run(sh("printf 'a\\nb\\nc\\n'; printf 'x\\ny\\n' >&2"), LONG, None).unwrap(); + assert_eq!(out.stdout, "a\nb\nc\n"); + assert_eq!(out.stderr, "x\ny\n"); + assert!(out.success); + } + + #[test] + fn invalid_utf8_is_replaced_in_collected_output() { + let out = run(sh("printf 'ok\\n\\377\\n'; printf 'a\\377b' >&2"), LONG, None).unwrap(); + assert_eq!(out.stdout, "ok\n\u{FFFD}\n"); + assert_eq!(out.stderr, "a\u{FFFD}b"); + } + + #[test] + fn without_input_stdin_is_closed() { + assert_eq!(run(sh("cat; echo done"), LONG, None).unwrap().stdout, "done\n"); + } + + #[test] + fn input_reaches_the_child_stdin_and_is_then_closed() { + let out = run_with_input(sh("cat"), LONG, None, Some("secret\nmore")).unwrap(); + assert_eq!(out.stdout, "secret\nmore"); + assert!(out.success); + } + + #[test] + fn a_missing_program_is_unavailable() { + let err = run(Command::new("/nonexistent/openidea-docker"), LONG, None).err().unwrap(); + assert_eq!(err.kind, ErrorKind::Unavailable); + assert_eq!(err.message, "could not run docker: No such file or directory (os error 2)"); + } + + #[test] + fn a_run_past_its_timeout_fails_and_the_child_is_killed() { + let (cmd, file) = recording_pid("docker-timeout", "exec sleep 30"); + let err = run(cmd, Duration::from_secs(1), None).err().unwrap(); + assert_eq!(err.kind, ErrorKind::Unavailable); + assert_eq!(err.message, "docker did not respond in time"); + assert_gone(recorded_pid(&file)); + } + + #[test] + fn a_cancelled_run_fails_and_the_child_is_killed() { + let (cmd, file) = recording_pid("docker-cancel", "exec sleep 30"); + let cancel = CancellationToken::new(); + cancel_when_recorded(&file, &cancel); + let err = run(cmd, LONG, Some(&cancel)).err().unwrap(); + assert_eq!(err.kind, ErrorKind::Cancelled); + assert_eq!(err.message, "cancelled"); + assert_gone(recorded_pid(&file)); } - let status = loop { - if let Some(status) = child.try_wait()? { - break status; - } - if cancel.is_cancelled() { - terminate_tree(&mut child, KILL_GRACE); - return Err(IdeError::cancelled()); - } - std::thread::sleep(Duration::from_millis(10)); - }; - Ok((status.success(), stderr_tail)) + + fn collect(script: &str) -> (bool, Vec<(Stream, String)>, Vec) { + let mut lines = Vec::new(); + let (ok, tail) = stream(sh(script), &CancellationToken::new(), &mut |s, l| lines.push((s, l))).unwrap(); + (ok, lines, tail) + } + + fn of(lines: &[(Stream, String)], which: Stream) -> Vec<&str> { + lines.iter().filter(|(s, _)| *s == which).map(|(_, l)| l.as_str()).collect() + } + + #[test] + fn a_stream_splits_lines_at_lf_cr_and_crlf_and_trims_their_ends() { + let (ok, lines, _) = collect("printf 'a\\nb\\r\\nc\\rd \\n\\n\\ne'"); + assert!(ok); + assert_eq!(of(&lines, Stream::Stdout), ["a", "b", "c", "d", "e"]); + assert!(of(&lines, Stream::Stderr).is_empty()); + } + + #[test] + fn a_stream_labels_each_line_with_its_pipe() { + let (_, lines, _) = collect("echo out1; echo err1 >&2; echo out2"); + assert_eq!(of(&lines, Stream::Stdout), ["out1", "out2"]); + assert_eq!(of(&lines, Stream::Stderr), ["err1"]); + } + + #[test] + fn a_stream_reports_the_exit_status() { + assert!(collect("exit 0").0); + assert!(!collect("exit 2").0); + } + + #[test] + fn a_stream_replaces_invalid_utf8() { + let (_, lines, _) = collect("printf 'a\\377b\\n'"); + assert_eq!(of(&lines, Stream::Stdout), ["a\u{FFFD}b"]); + } + + #[test] + fn a_stream_keeps_the_last_twenty_non_blank_stderr_lines() { + let (_, lines, tail) = collect("echo ' ' >&2; i=1; while [ $i -le 25 ]; do echo e$i >&2; i=$((i+1)); done"); + let expected: Vec = (6..=25).map(|i| format!("e{i}")).collect(); + assert_eq!(tail, expected); + assert_eq!(of(&lines, Stream::Stderr).len(), 26, "blank lines are still handed over"); + } + + #[test] + fn a_stream_cancelled_before_it_starts_does_not_spawn() { + let cancel = CancellationToken::new(); + cancel.cancel(); + let err = stream(Command::new("/nonexistent/openidea-docker"), &cancel, &mut |_, _| {}).err().unwrap(); + assert_eq!(err.kind, ErrorKind::Cancelled); + assert_eq!(err.message, "cancelled"); + } + + #[test] + fn a_stream_cancelled_while_running_fails_and_the_child_is_killed() { + let (cmd, file) = recording_pid("docker-stream-cancel", "echo started; exec sleep 30"); + let cancel = CancellationToken::new(); + let err = stream(cmd, &cancel, &mut |_, _| cancel.cancel()).err().unwrap(); + assert_eq!(err.kind, ErrorKind::Cancelled); + assert_eq!(err.message, "cancelled"); + assert_gone(recorded_pid(&file)); + } + + #[test] + fn a_missing_program_cannot_be_streamed() { + let err = stream(Command::new("/nonexistent/openidea-docker"), &CancellationToken::new(), &mut |_, _| {}) + .err() + .unwrap(); + assert_eq!(err.kind, ErrorKind::Unavailable); + assert_eq!(err.message, "could not run docker: No such file or directory (os error 2)"); + } } diff --git a/crates/ide-github/src/process.rs b/crates/ide-github/src/process.rs index e945645b8..26da5665d 100644 --- a/crates/ide-github/src/process.rs +++ b/crates/ide-github/src/process.rs @@ -1,184 +1,222 @@ -//! Child processes of the gh CLI: bounded runs and cancellable line streams. +//! The gh CLI as a child process: bounded runs and cancellable line streams. -use ide_core::process::terminate_tree; -use ide_core::{CancellationToken, IdeError, IdeResult}; -use std::io::Read; -use std::process::{Child, Command, Stdio}; -use std::sync::mpsc; -use std::time::{Duration, Instant}; +use ide_core::cli_process::{CliTool, Decoding, Input}; +pub(crate) use ide_core::cli_process::{Output, Stream}; +use ide_core::{CancellationToken, IdeResult}; +use std::process::Command; +use std::time::Duration; -/// How long a cancelled or timed-out child's process group (gh spawns git and helpers) -/// gets to exit on `SIGTERM` before `SIGKILL`: git removes its lock files on `SIGTERM`. -const KILL_GRACE: Duration = Duration::from_millis(20); - -pub(crate) struct Output { - pub stdout: String, - pub stderr: String, - pub success: bool, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum Stream { - Stdout, - Stderr, -} - -fn prepare(cmd: &mut Command) { - cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); - ide_core::process::prepare(ide_core::process::own_group(cmd)); -} - -fn spawn(cmd: &mut Command) -> IdeResult { - cmd.spawn().map_err(|e| IdeError::unavailable(format!("could not run gh: {e}"))) -} - -fn read_all(mut pipe: impl Read + Send + 'static) -> std::thread::JoinHandle { - std::thread::spawn(move || { - let mut buf = Vec::new(); - let _ = pipe.read_to_end(&mut buf); - String::from_utf8_lossy(&buf).into_owned() - }) -} +const GH: CliTool = CliTool::new("gh", Decoding::Utf8Lossy); /// Runs `cmd` to completion. Fails when it outlives `timeout` or `cancel` fires; /// a non-zero exit is reported in [`Output::success`], not as an error. pub(crate) fn run(cmd: Command, timeout: Duration, cancel: Option<&CancellationToken>) -> IdeResult { - run_with_input(cmd, None, timeout, cancel) + GH.run(cmd, timeout, cancel) } /// [`run`] with `input` written to the child's stdin (then closed). pub(crate) fn run_with_input( - mut cmd: Command, + cmd: Command, input: Option<&str>, timeout: Duration, cancel: Option<&CancellationToken>, ) -> IdeResult { - prepare(&mut cmd); - if input.is_some() { - cmd.stdin(Stdio::piped()); - } - let mut child = spawn(&mut cmd)?; - if let (Some(input), Some(mut stdin)) = (input, child.stdin.take()) { - let input = input.to_owned(); - // A writer thread: a large body must not block on a full pipe while gh is not reading yet. - std::thread::spawn(move || { - use std::io::Write; - let _ = stdin.write_all(input.as_bytes()); - }); - } - let out = child.stdout.take().map(read_all); - let err = child.stderr.take().map(read_all); - let deadline = Instant::now() + timeout; - let status = loop { - if let Some(status) = child.try_wait()? { - break status; - } - if cancel.is_some_and(CancellationToken::is_cancelled) { - terminate_tree(&mut child, KILL_GRACE); - return Err(IdeError::cancelled()); - } - if Instant::now() >= deadline { - terminate_tree(&mut child, KILL_GRACE); - return Err(IdeError::unavailable("gh did not respond in time")); - } - std::thread::sleep(Duration::from_millis(10)); - }; - Ok(Output { - stdout: out.map(|t| t.join().unwrap_or_default()).unwrap_or_default(), - stderr: err.map(|t| t.join().unwrap_or_default()).unwrap_or_default(), - success: status.success(), - }) -} - -enum Event { - Line(Stream, String), - Closed, -} - -fn spawn_reader(mut pipe: impl Read + Send + 'static, tx: mpsc::Sender, stream: Stream) { - std::thread::spawn(move || { - let mut buf = [0u8; 8192]; - let mut pending: Vec = Vec::new(); - let flush = |pending: &mut Vec| { - if !pending.is_empty() { - let line = String::from_utf8_lossy(pending).trim_end().to_string(); - pending.clear(); - let _ = tx.send(Event::Line(stream, line)); - } - }; - loop { - match pipe.read(&mut buf) { - Ok(0) | Err(_) => break, - Ok(n) => { - for &b in &buf[..n] { - // `\r` too: git progress rewrites its line in place. - if b == b'\n' || b == b'\r' { - flush(&mut pending); - } else { - pending.push(b); - } - } - } - } - } - flush(&mut pending); - let _ = tx.send(Event::Closed); - }); + GH.run_with_input(cmd, input.map(Input::Threaded), timeout, cancel) } /// Runs `cmd`, handing every output line to `on_line` until it exits or `cancel` /// fires. Returns whether it exited successfully plus the last stderr lines. pub(crate) fn stream( - mut cmd: Command, + cmd: Command, cancel: &CancellationToken, on_line: &mut dyn FnMut(Stream, String), ) -> IdeResult<(bool, Vec)> { - if cancel.is_cancelled() { - return Err(IdeError::cancelled()); - } - prepare(&mut cmd); - let mut child = spawn(&mut cmd)?; - let (tx, rx) = mpsc::channel::(); - let mut open = 0; - if let Some(out) = child.stdout.take() { - spawn_reader(out, tx.clone(), Stream::Stdout); - open += 1; - } - if let Some(err) = child.stderr.take() { - spawn_reader(err, tx.clone(), Stream::Stderr); - open += 1; - } - drop(tx); - let mut stderr_tail: Vec = Vec::new(); - while open > 0 { - if cancel.is_cancelled() { - terminate_tree(&mut child, KILL_GRACE); - return Err(IdeError::cancelled()); - } - match rx.recv_timeout(Duration::from_millis(50)) { - Ok(Event::Line(stream, line)) => { - if stream == Stream::Stderr && !line.trim().is_empty() { - stderr_tail.push(line.clone()); - if stderr_tail.len() > 20 { - stderr_tail.remove(0); - } - } - on_line(stream, line); + GH.stream(cmd, cancel, on_line) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use ide_core::error::ErrorKind; + use ide_core::process::process_alive; + use std::time::Instant; + + const LONG: Duration = Duration::from_secs(30); + + fn sh(script: &str) -> Command { + let mut cmd = Command::new("sh"); + cmd.args(["-c", script]); + cmd + } + + /// A script that records its pid in `name`'s file, then runs `rest`. + fn recording_pid(name: &str, rest: &str) -> (Command, std::path::PathBuf) { + let file = std::env::temp_dir().join(format!("openidea-process-{}-{name}", std::process::id())); + let _ = std::fs::remove_file(&file); + (sh(&format!("echo $$ > '{0}.tmp' && mv '{0}.tmp' '{0}'; {rest}", file.display())), file) + } + + fn recorded_pid(file: &std::path::Path) -> u32 { + let pid = std::fs::read_to_string(file).unwrap().trim().parse().unwrap(); + let _ = std::fs::remove_file(file); + pid + } + + /// Cancels `cancel` once the script has recorded its pid. + fn cancel_when_recorded(file: &std::path::Path, cancel: &CancellationToken) { + let (file, cancel) = (file.to_owned(), cancel.clone()); + std::thread::spawn(move || { + while !file.exists() { + std::thread::sleep(Duration::from_millis(5)); } - Ok(Event::Closed) => open -= 1, - Err(mpsc::RecvTimeoutError::Timeout) => {} - Err(mpsc::RecvTimeoutError::Disconnected) => break, + cancel.cancel(); + }); + } + + fn assert_gone(pid: u32) { + let deadline = Instant::now() + Duration::from_secs(5); + while process_alive(pid) { + assert!(Instant::now() < deadline, "process {pid} survived"); + std::thread::sleep(Duration::from_millis(20)); } + } + + #[test] + fn the_exit_status_is_reported_not_raised() { + assert!(run(sh("exit 0"), LONG, None).unwrap().success); + assert!(!run(sh("exit 3"), LONG, None).unwrap().success); + } + + #[test] + fn both_streams_are_captured_separately_and_in_order() { + let out = run(sh("printf 'a\\nb\\nc\\n'; printf 'x\\ny\\n' >&2"), LONG, None).unwrap(); + assert_eq!(out.stdout, "a\nb\nc\n"); + assert_eq!(out.stderr, "x\ny\n"); + assert!(out.success); + } + + #[test] + fn invalid_utf8_is_replaced_in_collected_output() { + let out = run(sh("printf 'ok\\n\\377\\n'; printf 'a\\377b' >&2"), LONG, None).unwrap(); + assert_eq!(out.stdout, "ok\n\u{FFFD}\n"); + assert_eq!(out.stderr, "a\u{FFFD}b"); + } + + #[test] + fn without_input_stdin_is_closed() { + assert_eq!(run(sh("cat; echo done"), LONG, None).unwrap().stdout, "done\n"); + } + + #[test] + fn input_reaches_the_child_stdin_and_is_then_closed() { + let out = run_with_input(sh("cat"), Some("secret\nmore"), LONG, None).unwrap(); + assert_eq!(out.stdout, "secret\nmore"); + assert!(out.success); + } + + #[test] + fn a_body_larger_than_the_pipe_does_not_block_the_child_output() { + let body = "0123456789abcdef".repeat(64 * 1024); + let out = run_with_input(sh("cat"), Some(&body), LONG, None).unwrap(); + assert_eq!(out.stdout.len(), body.len()); + } + + #[test] + fn a_missing_program_is_unavailable() { + let err = run(Command::new("/nonexistent/openidea-gh"), LONG, None).err().unwrap(); + assert_eq!(err.kind, ErrorKind::Unavailable); + assert_eq!(err.message, "could not run gh: No such file or directory (os error 2)"); + } + + #[test] + fn a_run_past_its_timeout_fails_and_the_child_is_killed() { + let (cmd, file) = recording_pid("gh-timeout", "exec sleep 30"); + let err = run(cmd, Duration::from_secs(1), None).err().unwrap(); + assert_eq!(err.kind, ErrorKind::Unavailable); + assert_eq!(err.message, "gh did not respond in time"); + assert_gone(recorded_pid(&file)); } - let status = loop { - if let Some(status) = child.try_wait()? { - break status; - } - if cancel.is_cancelled() { - terminate_tree(&mut child, KILL_GRACE); - return Err(IdeError::cancelled()); - } - std::thread::sleep(Duration::from_millis(10)); - }; - Ok((status.success(), stderr_tail)) + + #[test] + fn a_cancelled_run_fails_and_the_child_is_killed() { + let (cmd, file) = recording_pid("gh-cancel", "exec sleep 30"); + let cancel = CancellationToken::new(); + cancel_when_recorded(&file, &cancel); + let err = run(cmd, LONG, Some(&cancel)).err().unwrap(); + assert_eq!(err.kind, ErrorKind::Cancelled); + assert_eq!(err.message, "cancelled"); + assert_gone(recorded_pid(&file)); + } + + fn collect(script: &str) -> (bool, Vec<(Stream, String)>, Vec) { + let mut lines = Vec::new(); + let (ok, tail) = stream(sh(script), &CancellationToken::new(), &mut |s, l| lines.push((s, l))).unwrap(); + (ok, lines, tail) + } + + fn of(lines: &[(Stream, String)], which: Stream) -> Vec<&str> { + lines.iter().filter(|(s, _)| *s == which).map(|(_, l)| l.as_str()).collect() + } + + #[test] + fn a_stream_splits_lines_at_lf_cr_and_crlf_and_trims_their_ends() { + let (ok, lines, _) = collect("printf 'a\\nb\\r\\nc\\rd \\n\\n\\ne'"); + assert!(ok); + assert_eq!(of(&lines, Stream::Stdout), ["a", "b", "c", "d", "e"]); + assert!(of(&lines, Stream::Stderr).is_empty()); + } + + #[test] + fn a_stream_labels_each_line_with_its_pipe() { + let (_, lines, _) = collect("echo out1; echo err1 >&2; echo out2"); + assert_eq!(of(&lines, Stream::Stdout), ["out1", "out2"]); + assert_eq!(of(&lines, Stream::Stderr), ["err1"]); + } + + #[test] + fn a_stream_reports_the_exit_status() { + assert!(collect("exit 0").0); + assert!(!collect("exit 2").0); + } + + #[test] + fn a_stream_replaces_invalid_utf8() { + let (_, lines, _) = collect("printf 'a\\377b\\n'"); + assert_eq!(of(&lines, Stream::Stdout), ["a\u{FFFD}b"]); + } + + #[test] + fn a_stream_keeps_the_last_twenty_non_blank_stderr_lines() { + let (_, lines, tail) = collect("echo ' ' >&2; i=1; while [ $i -le 25 ]; do echo e$i >&2; i=$((i+1)); done"); + let expected: Vec = (6..=25).map(|i| format!("e{i}")).collect(); + assert_eq!(tail, expected); + assert_eq!(of(&lines, Stream::Stderr).len(), 26, "blank lines are still handed over"); + } + + #[test] + fn a_stream_cancelled_before_it_starts_does_not_spawn() { + let cancel = CancellationToken::new(); + cancel.cancel(); + let err = stream(Command::new("/nonexistent/openidea-gh"), &cancel, &mut |_, _| {}).err().unwrap(); + assert_eq!(err.kind, ErrorKind::Cancelled); + assert_eq!(err.message, "cancelled"); + } + + #[test] + fn a_stream_cancelled_while_running_fails_and_the_child_is_killed() { + let (cmd, file) = recording_pid("gh-stream-cancel", "echo started; exec sleep 30"); + let cancel = CancellationToken::new(); + let err = stream(cmd, &cancel, &mut |_, _| cancel.cancel()).err().unwrap(); + assert_eq!(err.kind, ErrorKind::Cancelled); + assert_eq!(err.message, "cancelled"); + assert_gone(recorded_pid(&file)); + } + + #[test] + fn a_missing_program_cannot_be_streamed() { + let err = + stream(Command::new("/nonexistent/openidea-gh"), &CancellationToken::new(), &mut |_, _| {}).err().unwrap(); + assert_eq!(err.kind, ErrorKind::Unavailable); + assert_eq!(err.message, "could not run gh: No such file or directory (os error 2)"); + } }