use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use crate::env::{ExecutionEnv, FileContent, ShellExecOptions};
use crate::error::{ExecutionError, ExecutionErrorCode};
use crate::truncate::{
trim_to_last_utf8_bytes, truncate_tail, TruncationLimit, TruncationOptions, TruncationResult,
DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES,
};
const MAX_TAIL_BYTES: usize = DEFAULT_MAX_BYTES * 2;
const SPILL_BATCH_BYTES: usize = 64 * 1024;
const NATIVE_OUTPUT_QUEUE: usize = 16;
#[derive(Clone)]
pub struct ShellCaptureProgress {
pub output: String,
pub truncation: TruncationResult,
pub full_output_path: Option<PathBuf>,
pub last_line_bytes: usize,
}
#[derive(Clone)]
pub struct ShellCaptureResult {
pub output: String,
pub truncation: TruncationResult,
pub full_output_path: Option<PathBuf>,
pub last_line_bytes: usize,
pub exit_code: Option<i32>,
pub cancelled: bool,
pub truncated: bool,
pub execution_error: Option<ExecutionError>,
}
pub struct ShellCaptureOptions<'a> {
pub shell: Option<crate::env::ShellOverride>,
pub cwd: Option<PathBuf>,
pub env: Option<HashMap<String, String>>,
pub inherit_env: bool,
pub timeout: Option<f64>,
pub cancel: Option<&'a CancellationToken>,
pub on_chunk: Option<Box<dyn FnMut(&str, &dyn Fn() -> ShellCaptureProgress) + Send + 'a>>,
pub return_execution_errors: bool,
}
impl<'a> Default for ShellCaptureOptions<'a> {
fn default() -> Self {
Self {
shell: None,
cwd: None,
env: None,
inherit_env: true,
timeout: None,
cancel: None,
on_chunk: None,
return_execution_errors: false,
}
}
}
#[derive(Default)]
struct CaptureState {
tail_output: String,
total_bytes: usize,
completed_lines: usize,
current_line_bytes: usize,
last_completed_line_bytes: usize,
}
impl CaptureState {
fn ingest_chunk(&mut self, text: &str) {
self.total_bytes += text.len();
self.completed_lines += text.matches('\n').count();
if let Some((complete, tail)) = text.rsplit_once('\n') {
self.last_completed_line_bytes = complete
.rsplit_once('\n')
.map_or(self.current_line_bytes + complete.len(), |(_, line)| {
line.len()
});
self.current_line_bytes = tail.len();
} else {
self.current_line_bytes += text.len();
}
if text.len() >= MAX_TAIL_BYTES {
self.tail_output.clear();
self.tail_output
.push_str(trim_to_last_utf8_bytes(text, MAX_TAIL_BYTES));
} else {
self.tail_output.push_str(text);
if self.tail_output.len() > MAX_TAIL_BYTES {
let keep = trim_to_last_utf8_bytes(
&self.tail_output,
MAX_TAIL_BYTES - DEFAULT_MAX_BYTES / 2,
)
.len();
self.tail_output.drain(..self.tail_output.len() - keep);
}
}
}
fn total_lines(&self) -> usize {
self.completed_lines + usize::from(self.current_line_bytes > 0)
}
fn is_truncated(&self) -> bool {
self.total_lines() > DEFAULT_MAX_LINES || self.total_bytes > DEFAULT_MAX_BYTES
}
fn create_progress(&self, full_output_path: Option<PathBuf>) -> ShellCaptureProgress {
let tail = truncate_tail(&self.tail_output, TruncationOptions::default());
let truncated = self.is_truncated();
let truncated_by = if truncated {
tail.truncated_by
.or(if self.total_bytes > DEFAULT_MAX_BYTES {
Some(TruncationLimit::Bytes)
} else {
Some(TruncationLimit::Lines)
})
} else {
None
};
let truncation = TruncationResult {
truncated,
truncated_by,
total_lines: self.total_lines(),
total_bytes: self.total_bytes,
..tail
};
ShellCaptureProgress {
output: truncation.content.clone(),
truncation,
full_output_path,
last_line_bytes: if self.current_line_bytes > 0 {
self.current_line_bytes
} else {
self.last_completed_line_bytes
},
}
}
}
struct OutputSpill {
env: Arc<dyn ExecutionEnv>,
path: Option<PathBuf>,
pending: String,
failed: bool,
}
impl OutputSpill {
async fn record(&mut self, text: &str, truncated: bool) {
if self.failed {
return;
}
self.pending.push_str(text);
if truncated && (self.path.is_none() || self.pending.len() >= SPILL_BATCH_BYTES) {
self.flush().await;
}
}
async fn flush(&mut self) {
if self.pending.is_empty() {
return;
}
let result = async {
let path = match &self.path {
Some(path) => path,
None => self
.path
.insert(self.env.create_temp_file("bash-", ".log", None).await?),
};
self.env
.append_file(
&path.to_string_lossy(),
FileContent::Text(std::mem::take(&mut self.pending)),
None,
)
.await
}
.await;
if let Err(error) = result {
tracing::warn!("shell full-output file unavailable: {error}");
self.failed = true;
self.pending.clear();
if let Some(path) = self.path.take() {
let _ = self
.env
.remove(&path.to_string_lossy(), false, true, None)
.await;
}
}
}
async fn finish(mut self) -> Option<PathBuf> {
if self.path.is_some() {
self.flush().await;
}
self.path.take()
}
}
impl Drop for OutputSpill {
fn drop(&mut self) {
if let (Some(path), Ok(runtime)) = (self.path.take(), tokio::runtime::Handle::try_current())
{
let env = self.env.clone();
runtime.spawn(async move {
let _ = env.remove(&path.to_string_lossy(), false, true, None).await;
});
}
}
}
fn sanitize_and_strip_cr(chunk: &str) -> String {
let mut out = String::with_capacity(chunk.len());
let mut chars = chunk.chars().peekable();
while let Some(c) = chars.next() {
let u = c as u32;
if c == '\x1b' {
skip_escape_sequence(&mut chars);
} else if u == 0x09 || u == 0x0a || u == 0x0d {
out.push(c);
} else if u <= 0x1f {
} else if (0xfff9..=0xfffb).contains(&u) {
} else {
out.push(c);
}
}
out.replace('\r', "")
}
fn skip_escape_sequence(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) {
match chars.peek() {
Some('[') => {
chars.next();
while let Some(c) = chars.next() {
if (0x40..=0x7e).contains(&(c as u32)) {
break;
}
}
}
Some(']') => {
chars.next();
while let Some(c) = chars.next() {
if c == '\x07' {
break;
}
if c == '\x1b' {
if let Some('\\') = chars.peek() {
chars.next();
}
break;
}
}
}
Some('(') | Some(')') => {
chars.next();
chars.next();
}
Some(_) => {
chars.next();
}
None => {}
}
}
pub async fn execute_shell_with_capture(
env: &Arc<dyn ExecutionEnv>,
command: &str,
options: ShellCaptureOptions<'_>,
) -> Result<ShellCaptureResult, ExecutionError> {
let (sender, mut receiver) = mpsc::channel::<String>(NATIVE_OUTPUT_QUEUE);
let exec = env.exec_streamed(
command,
ShellExecOptions {
shell: options.shell,
cwd: options.cwd,
env: options.env,
inherit_env: options.inherit_env,
timeout: options.timeout,
cancel: options.cancel,
..Default::default()
},
sender,
);
let collect = async {
let mut state = CaptureState::default();
let mut spill = OutputSpill {
env: env.clone(),
path: None,
pending: String::new(),
failed: false,
};
let mut on_chunk = options.on_chunk;
while let Some(chunk) = receiver.recv().await {
let text = sanitize_and_strip_cr(&chunk);
state.ingest_chunk(&text);
spill.record(&text, state.is_truncated()).await;
if let Some(callback) = on_chunk.as_mut() {
callback(&chunk, &|| state.create_progress(None));
}
}
state.create_progress(spill.finish().await)
};
let (exec_result, progress) = tokio::join!(exec, collect);
let cancelled = options.cancel.is_some_and(CancellationToken::is_cancelled)
|| exec_result
.as_ref()
.is_err_and(|error| error.code == ExecutionErrorCode::Aborted);
let (exit_code, execution_error) = match exec_result {
_ if cancelled => (None, None),
Ok(code) => (Some(code), None),
Err(error) if options.return_execution_errors => (None, Some(error)),
Err(error) => {
if let Some(path) = progress.full_output_path {
let _ = env.remove(&path.to_string_lossy(), false, true, None).await;
}
return Err(error);
}
};
Ok(ShellCaptureResult {
output: progress.output,
truncated: progress.truncation.truncated,
truncation: progress.truncation,
full_output_path: progress.full_output_path,
last_line_bytes: progress.last_line_bytes,
exit_code,
cancelled,
execution_error,
})
}
pub use crate::truncate::format_size;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sanitize_strips_controls_keeps_tab_lf() {
let s = "a\x01b\tc\nd\x0be";
let out = sanitize_and_strip_cr(&s);
assert_eq!(out, "ab\tc\nde");
}
#[test]
fn sanitize_strips_cr() {
let s = "a\r\nb\rc";
let out = sanitize_and_strip_cr(&s);
assert_eq!(out, "a\nbc");
}
#[test]
fn sanitize_strips_interlinear_annotation() {
let s = "a\u{fff9}b\u{fffb}c";
let out = sanitize_and_strip_cr(&s);
assert_eq!(out, "abc");
}
#[test]
fn sanitize_strips_full_ansi_sequences() {
let s = "\x1b[36mvite v6.4.3\x1b[39m \x1b[32m\u{2713}\x1b[39m built\n";
assert_eq!(sanitize_and_strip_cr(s), "vite v6.4.3 \u{2713} built\n");
let s = "a\x1b[1m\x1b[2mX\x1b[22m\x1b[22mb";
assert_eq!(sanitize_and_strip_cr(s), "aXb");
}
#[test]
fn sanitize_strips_osc_sequences() {
assert_eq!(sanitize_and_strip_cr("a\x1b]0;title\x07b"), "ab");
assert_eq!(sanitize_and_strip_cr("a\x1b]8;;http://x\x1b\\b"), "ab");
}
#[test]
fn capture_state_ingest_and_progress() {
let mut s = CaptureState::default();
s.ingest_chunk("line1\nline2\n");
s.ingest_chunk("line3");
let p = s.create_progress(None);
assert_eq!(p.truncation.total_lines, 3);
assert!(!p.truncation.truncated);
assert_eq!(p.output, "line1\nline2\nline3");
}
}