use std::io::{BufRead, BufReader};
use std::path::Path;
use std::process::{Child, Command, Stdio};
use crate::screen::{fit, Row, Span, Style};
#[cfg(test)]
mod tests;
const MAX_LINES: usize = 5000;
pub enum Event {
Line(String),
Exit,
}
pub fn start(
command: &str,
dir: &Path,
forward: impl Fn(Event) + Send + Clone + 'static,
) -> std::io::Result<Child> {
let (shell, flag) = if cfg!(windows) { ("cmd", "/C") } else { ("sh", "-c") };
let mut child = Command::new(shell)
.arg(flag)
.arg(command)
.current_dir(dir)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let errors = child.stderr.take();
let output = child.stdout.take();
let pass_on = |stream: Box<dyn std::io::Read + Send>, forward: &(dyn Fn(Event) + Send)| {
let mut reader = BufReader::new(stream);
let mut bytes = Vec::new();
while reader.read_until(b'\n', &mut bytes).is_ok_and(|read| read > 0) {
forward(Event::Line(String::from_utf8_lossy(&bytes).into_owned()));
bytes.clear();
}
};
let error_forward = forward.clone();
let error_thread = errors.map(|errors| {
std::thread::spawn(move || pass_on(Box::new(errors), &error_forward))
});
if let Some(output) = output {
std::thread::spawn(move || {
pass_on(Box::new(output), &forward);
if let Some(thread) = error_thread {
let _ = thread.join();
}
forward(Event::Exit);
});
}
Ok(child)
}
pub fn clean(line: &str) -> String {
let line = line.trim_end_matches(['\n', '\r']);
let line = line.rsplit('\r').next().unwrap_or(line);
let mut text = String::new();
let mut chars = line.chars().peekable();
while let Some(c) = chars.next() {
if c == '\x1b' {
if chars.next_if_eq(&'[').is_some() {
while chars.next_if(|c| !c.is_ascii_alphabetic()).is_some() {}
chars.next();
}
} else if c == '\t' {
text.push_str(" ");
} else if !c.is_control() {
text.push(c);
}
}
text
}
pub fn location(line: &str) -> Option<(String, usize, usize)> {
if let Some((_, rest)) = line.split_once("File \"")
&& let Some((file, rest)) = rest.split_once("\", line ")
{
let digits: String = rest.chars().take_while(char::is_ascii_digit).collect();
let row = digits.parse::<usize>().ok().filter(|row| *row > 0)?;
return Some((file.to_string(), row, 1));
}
let is_path = |c: char| c.is_alphanumeric() || "/\\._-+@~".contains(c);
fn number(text: &str) -> Option<(usize, &str)> {
let digits = text.chars().take_while(char::is_ascii_digit).count();
Some((text[..digits].parse::<usize>().ok().filter(|n| *n > 0)?, &text[digits..]))
}
for (at, _) in line.match_indices(':') {
let file: String = line[..at].chars().rev().take_while(|c| is_path(*c)).collect();
let file: String = file.chars().rev().collect();
if file.contains(['.', '/'])
&& file.chars().any(char::is_alphabetic)
&& let Some((row, rest)) = number(&line[at + 1..])
{
let column = rest.strip_prefix(':').and_then(number).map_or(1, |(column, _)| column);
return Some((file, row, column));
}
}
None
}
#[derive(Default)]
pub struct Output {
pub command: String,
pub lines: Vec<String>,
pub running: bool,
pub status: String,
pub selected: usize,
top: usize,
walked: Option<usize>,
}
impl Output {
pub fn begin(&mut self, command: &str) {
*self = Self {
command: command.to_string(),
running: true,
..Self::default()
};
}
pub fn push(&mut self, line: &str) {
let following = self.selected + 1 >= self.lines.len();
self.lines.push(clean(line));
if self.lines.len() > MAX_LINES {
self.lines.remove(0);
self.selected = self.selected.saturating_sub(1);
}
if following {
self.selected = self.lines.len() - 1;
}
}
pub fn finish(&mut self, code: Option<i32>) {
self.running = false;
self.status = match code {
Some(0) => "finished".into(),
Some(code) => format!("failed (exit code {code})"),
None => "stopped".into(),
};
}
pub fn move_by(&mut self, rows: isize) {
let last = self.lines.len().saturating_sub(1) as isize;
self.selected = (self.selected as isize).saturating_add(rows).clamp(0, last) as usize;
}
pub fn click(&mut self, row: usize) {
if self.top + row < self.lines.len() {
self.selected = self.top + row;
}
}
pub fn next_location(&mut self, forward: bool) -> Option<(String, usize, usize)> {
let lines: Vec<usize> = match (forward, self.walked) {
(true, None) => (0..self.lines.len()).collect(),
(true, Some(at)) => (at + 1..self.lines.len()).collect(),
(false, None) => (0..self.lines.len()).rev().collect(),
(false, Some(at)) => (0..at).rev().collect(),
};
let found = lines.into_iter().find(|line| location(&self.lines[*line]).is_some())?;
self.walked = Some(found);
self.selected = found;
location(&self.lines[found])
}
pub fn selected_location(&self) -> Option<(String, usize, usize)> {
location(self.lines.get(self.selected)?)
}
pub fn render(&mut self, width: usize, height: usize, focused: bool) -> Vec<Row> {
let state = if self.running { "running (Ctrl+C stops it)" } else { self.status.as_str() };
let title = format!(" Run · {} · {state}", self.command);
let title_style = if focused { Style::Reverse } else { Style::Menu };
let mut rows = vec![vec![Span::new(title_style, fit(&title, width))]];
let body = height.saturating_sub(1);
if self.selected < self.top {
self.top = self.selected;
}
if body > 0 && self.selected >= self.top + body {
self.top = self.selected + 1 - body;
}
for row in 0..body {
let index = self.top + row;
let text = self.lines.get(index).map_or("", String::as_str);
let lower = text.trim_start().to_lowercase();
let style = if focused && index == self.selected && index < self.lines.len() {
Style::Reverse
} else if lower.starts_with("error") || lower.contains("panicked at") || lower.contains("failed") {
Style::Error
} else if lower.starts_with("warning") {
Style::Warning
} else {
Style::Plain
};
rows.push(vec![Span::new(style, fit(text, width))]);
}
rows.truncate(height);
rows
}
}