use serde::{Deserialize, Serialize};
mod outline;
mod search;
pub(crate) use outline::TITLE_SOURCE_MAX;
pub(crate) use outline::title;
pub use outline::{
FailureSummary, LineRange, LogEvidence, LogGroup, LogMark, LogOutline, MarkKind, OutlineChange,
OutlineParts, Outliner, SavedOutline, StepLines, StepLog, StoredLog,
};
pub use search::{LogNeedle, LogSearch, LogSearchQuery, SEARCH_QUERY_MAX, Search};
pub const LINES_DEFAULT: u32 = 1000;
pub const LINES_MAX: u32 = 10_000;
pub const LINE_BYTES_MAX: u64 = 64 << 10;
pub const RUNS_MAX: usize = 1000;
const COMMAND: &str = "##[";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LineRead {
pub from: u64,
pub limit: u64,
pub prefix: u64,
pub bytes: u64,
}
impl LineRead {
pub fn of(self, lines: &[String]) -> Vec<StoredLine> {
let mut read = Vec::new();
let mut bytes = 0;
let first = usize::try_from(self.from).unwrap_or(usize::MAX);
let numbered = (self.from..).zip(lines.iter().skip(first));
for (line, text) in numbered.take(usize::try_from(self.limit).unwrap_or(usize::MAX)) {
if bytes >= self.bytes {
break;
}
let prefix = usize::try_from(self.prefix).unwrap_or(usize::MAX);
let cut = &text.as_bytes()[..text.len().min(prefix)];
let stored = StoredLine::cut(line, cut, text.len() as u64);
bytes += stored.text.len() as u64;
read.push(stored);
}
read
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StoredLine {
pub line: u64,
pub text: String,
pub omitted: u64,
}
impl StoredLine {
pub fn cut(line: u64, read: &[u8], stored: u64) -> StoredLine {
let whole = if (read.len() as u64) < stored {
whole_chars(read)
} else {
read
};
StoredLine {
line,
text: String::from_utf8_lossy(whole).into_owned(),
omitted: stored.saturating_sub(whole.len() as u64),
}
}
pub fn styled(&self) -> StyledLine {
let mut styled = StyledLine::parse(self.line, &self.text);
styled.omitted += self.omitted;
styled
}
}
fn whole_chars(bytes: &[u8]) -> &[u8] {
let Some(start) = (bytes.len().saturating_sub(4)..bytes.len())
.rev()
.find(|&at| bytes[at] & 0xC0 != 0x80)
else {
return bytes;
};
let width = match bytes[start] {
lead if lead >= 0xF0 => 4,
lead if lead >= 0xE0 => 3,
lead if lead >= 0xC0 => 2,
_ => 1,
};
if start + width > bytes.len() {
&bytes[..start]
} else {
bytes
}
}
pub(crate) fn prefix(text: &str, max: usize) -> &str {
if text.len() <= max {
return text;
}
let mut end = max;
while !text.is_char_boundary(end) {
end -= 1;
}
&text[..end]
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct LogLinesQuery {
pub from: Option<u64>,
pub limit: Option<u32>,
#[serde(default)]
pub follow: bool,
}
impl LogLinesQuery {
pub fn page(&self) -> u64 {
u64::from(self.limit.unwrap_or(LINES_DEFAULT).clamp(1, LINES_MAX))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum LineKind {
Output,
Group,
EndGroup,
Error,
Warning,
Notice,
Debug,
Command,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Color {
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
Grey,
#[serde(other)]
Unknown,
}
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "serde's skip_serializing_if passes a reference"
)]
fn is_false(value: &bool) -> bool {
!value
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Run {
pub text: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub color: Option<Color>,
#[serde(default, skip_serializing_if = "is_false")]
pub bold: bool,
#[serde(default, skip_serializing_if = "is_false")]
pub mark: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StyledLine {
pub line: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub at: Option<u64>,
pub kind: LineKind,
pub runs: Vec<Run>,
#[serde(default, skip_serializing_if = "is_zero")]
pub omitted: u64,
}
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "serde's skip_serializing_if passes a reference"
)]
fn is_zero(value: &u64) -> bool {
*value == 0
}
impl StyledLine {
pub fn parse(line: u64, text: &str) -> StyledLine {
let shown = prefix(text, usize::try_from(LINE_BYTES_MAX).unwrap_or(usize::MAX));
let (at, rest) = split_time(shown);
let (kind, rest) = command(rest);
let (runs, read) = runs(rest, RUNS_MAX);
StyledLine {
line,
at: at.map(|ms| ms / 1000),
kind,
runs,
omitted: (text.len() - shown.len() + rest.len() - read) as u64,
}
}
pub fn text(&self) -> String {
self.runs.iter().map(|run| run.text.as_str()).collect()
}
pub fn omitted_words(&self) -> Option<String> {
(self.omitted > 0).then(|| format!("{} not shown", crate::config::ByteSize(self.omitted)))
}
}
fn split_time(text: &str) -> (Option<u64>, &str) {
match text.split_once(' ') {
Some((stamp, rest)) => match crate::time::parse_ms(stamp) {
Some(at) => (Some(at), rest),
None => (None, text),
},
None => match crate::time::parse_ms(text) {
Some(at) => (Some(at), ""),
None => (None, text),
},
}
}
fn command(text: &str) -> (LineKind, &str) {
let Some((name, rest)) = text
.strip_prefix(COMMAND)
.and_then(|after| after.split_once(']'))
else {
return (LineKind::Output, text);
};
let kind = match name {
"group" => LineKind::Group,
"endgroup" => LineKind::EndGroup,
"error" => LineKind::Error,
"warning" => LineKind::Warning,
"notice" => LineKind::Notice,
"debug" => LineKind::Debug,
"command" => LineKind::Command,
_ => return (LineKind::Output, text),
};
(kind, rest)
}
pub(crate) fn classify(text: &str) -> (LineKind, &str) {
command(split_time(text).1)
}
pub(crate) fn time_of(text: &str) -> Option<u64> {
split_time(text).0.map(|ms| ms / 1000)
}
pub(crate) fn plain(text: &str) -> String {
runs(text, usize::MAX)
.0
.into_iter()
.map(|run| run.text)
.collect()
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct Style {
color: Option<Color>,
bold: bool,
}
fn basic(index: u16) -> Option<Color> {
match index {
0 => Some(Color::Grey),
1 => Some(Color::Red),
2 => Some(Color::Green),
3 => Some(Color::Yellow),
4 => Some(Color::Blue),
5 => Some(Color::Magenta),
6 => Some(Color::Cyan),
_ => None,
}
}
impl Style {
fn apply(self, params: &str) -> Style {
let codes: Vec<u16> = params
.split([';', ':'])
.map(|code| code.parse().unwrap_or(0))
.collect();
let mut style = self;
let mut codes = codes.into_iter();
while let Some(code) = codes.next() {
match code {
0 => style = Style::default(),
1 => style.bold = true,
22 => style.bold = false,
30..=37 => style.color = basic(code - 30),
90..=97 => style.color = basic(code - 90),
39 => style.color = None,
38 | 48 => {
let color = match codes.next() {
Some(5) => codes.next().and_then(|index| {
basic(if index >= 8 { index - 8 } else { index }).filter(|_| index < 16)
}),
Some(2) => {
codes.by_ref().take(3).for_each(drop);
None
}
_ => None,
};
if code == 38 {
style.color = color;
}
}
_ => {}
}
}
style
}
}
fn runs(text: &str, max: usize) -> (Vec<Run>, usize) {
let mut runs: Vec<Run> = Vec::new();
let mut style = Style::default();
let mut current = String::new();
let mut began = 0;
let mut chars = text.char_indices().peekable();
let flush = |runs: &mut Vec<Run>, current: &mut String, style: Style| {
if current.is_empty() {
return true;
}
let full = runs.len() >= max;
match runs.last_mut() {
Some(last) if last.color == style.color && last.bold == style.bold => {
last.text.push_str(current);
current.clear();
}
_ if full => return false,
_ => runs.push(Run {
text: std::mem::take(current),
color: style.color,
bold: style.bold,
mark: false,
}),
}
true
};
while let Some((at, c)) = chars.next() {
match c {
'\u{1b}' => match chars.next().map(|(_, c)| c) {
Some('[') => {
let mut params = String::new();
let mut last = None;
for (_, c) in chars.by_ref() {
if ('@'..='~').contains(&c) {
last = Some(c);
break;
}
params.push(c);
}
if last == Some('m') {
let next = style.apply(¶ms);
if next != style {
if !flush(&mut runs, &mut current, style) {
return (runs, began);
}
style = next;
}
}
}
Some(']') => {
while let Some((_, c)) = chars.next() {
if c == '\u{7}' {
break;
}
if c == '\u{1b}' {
chars.next_if(|&(_, c)| c == '\\');
break;
}
}
}
_ => {}
},
c if c == '\t' || !c.is_control() => {
if current.is_empty() {
began = at;
}
current.push(c);
}
_ => {}
}
}
if flush(&mut runs, &mut current, style) {
(runs, text.len())
} else {
(runs, began)
}
}
#[cfg(test)]
#[cfg(any(feature = "host", feature = "client"))]
mod tests;