use std::ops::Range;
use serde_json::{json, Map, Value};
use super::chat::ToolSpec;
use super::profile::{clip, Profile};
use crate::encoding::Codec;
use crate::filter::{self, FilterSpec, LineKind};
use crate::jobs::CancelToken;
use crate::loglevel::{Level, Levels};
use crate::search::{self, Matcher, Query, SearchEnd};
use crate::text::TextBuf;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Read,
App,
Write,
}
pub struct Tool {
pub name: &'static str,
pub kind: Kind,
pub description: &'static str,
schema: fn() -> Value,
}
impl Tool {
pub fn spec(&self) -> ToolSpec {
ToolSpec {
name: self.name.into(),
description: self.description.into(),
schema: (self.schema)(),
}
}
}
const REGEX_NOTE: &str = "Regular expressions use Rust syntax: no look-around and no \
backreferences; \\b, \\d, (?i) and character classes work.";
fn object(props: Vec<(&str, Value)>, required: &[&str]) -> Value {
let mut m = Map::new();
for (k, v) in props {
m.insert(k.into(), v);
}
json!({"type": "object", "properties": m, "required": required, "additionalProperties": false})
}
fn pattern_props() -> Vec<(&'static str, Value)> {
vec![
(
"pattern",
json!({"type": "string", "description": "The text to find; a regular expression when regex is true."}),
),
(
"regex",
json!({"type": "boolean", "description": "pattern is a regular expression (default false)."}),
),
(
"ignore_case",
json!({"type": "boolean", "description": "Ignore upper and lower case (default false)."}),
),
(
"whole_word",
json!({"type": "boolean", "description": "Match whole words only (default false)."}),
),
]
}
fn time_props() -> Vec<(&'static str, Value)> {
vec![
(
"from",
json!({"type": "string", "description": "Only lines at or after this time, as the log writes times or like \"14:30\" or \"2024-05-01 14:30:00\"."}),
),
(
"to",
json!({"type": "string", "description": "Only lines up to and including this time (its whole second or minute)."}),
),
]
}
fn with(
mut a: Vec<(&'static str, Value)>,
b: Vec<(&'static str, Value)>,
) -> Vec<(&'static str, Value)> {
a.extend(b);
a
}
fn int(desc: &str) -> Value {
json!({"type": "integer", "description": desc})
}
fn string(desc: &str) -> Value {
json!({"type": "string", "description": desc})
}
pub const TOOLS: &[Tool] = &[
Tool {
name: "file_profile",
kind: Kind::Read,
description: "The open file's kind, size, encoding, line breaks, log format and fields, \
whether it has log levels and timestamps, and its first lines. Given at the start already; call \
it again only after the file changed.",
schema: || object(vec![], &[]),
},
Tool {
name: "find_all",
kind: Kind::Read,
description: "Finds every match of a text or regular expression in the open file and \
lists them in BigText's Find All results. Returns the number of matches and the first lines with \
a match, with line numbers. For log levels prefer `levels`; for fields of JSON Lines, logfmt, \
web server or syslog logs prefer `field_query`.",
schema: || object(with(pattern_props(), time_props()), &["pattern"]),
},
Tool {
name: "count",
kind: Kind::Read,
description: "Counts the lines with a match (or, with invert, without one). Shows \
nothing; use it to answer \"how many\" questions.",
schema: || {
object(
with(
with(
pattern_props(),
vec![(
"invert",
json!({"type": "boolean", "description": "Count the lines without a match."}),
)],
),
time_props(),
),
&["pattern"],
)
},
},
Tool {
name: "filter_lines",
kind: Kind::Read,
description: "Shows only the lines with a match (or, with invert, without one) in \
BigText's filter view, with optional lines of context around each. Returns the number of lines \
and the first ones.",
schema: || {
object(
with(
with(
pattern_props(),
vec![
("invert", json!({"type": "boolean", "description": "Keep the lines without a match."})),
("context", int("Lines kept before and after each line with a match, 0 to 20 (default 0).")),
],
),
time_props(),
),
&["pattern"],
)
},
},
Tool {
name: "field_query",
kind: Kind::Read,
description: "Shows the lines that meet a field query, in the filter view: JSON Lines \
and logfmt fields by name (nested as .user.id), web server and syslog logs by their columns \
(see the profile's log_format). Syntax: `.status >= 500 and .method == \"POST\"`, `.level in \
(\"error\", \"fatal\")`, `.msg contains \"timeout\"`, `.path ~ \"^/api/\"`, `.user exists`, `not \
(…)`, `or`. Strings in double quotes; numbers compare as numbers.",
schema: || {
object(
with(vec![("query", string("The field query."))], time_props()),
&["query"],
)
},
},
Tool {
name: "levels",
kind: Kind::Read,
description: "Counts the lines of each log level (ERROR also counts FATAL, CRITICAL, \
PANIC; WARN also WARNING; DEBUG also TRACE) and shows the lines of the chosen levels in the \
filter view, as BigText's level bar does. Use it when the profile says log_levels is true.",
schema: || {
object(
with(
vec![(
"levels",
json!({"type": "array", "items": {"type": "string", "enum": ["error", "warn", "info", "debug"]},
"description": "The levels to show (default: error)."}),
)],
time_props(),
),
&[],
)
},
},
Tool {
name: "time_range",
kind: Kind::Read,
description: "Limits BigText's searches and filters to the lines between two times and \
returns that range's first and last line numbers. Search tools also take from and to directly.",
schema: || object(time_props(), &[]),
},
Tool {
name: "histogram",
kind: Kind::Read,
description: "Lines per time interval over the whole log (at most 60 bars), optionally \
counting only the lines with a match as hits. Opens BigText's time histogram. Use it to see when \
something started or peaked.",
schema: || {
object(
vec![
("pattern", string("Optional: count the lines with a match of this text or regular expression as hits.")),
("regex", json!({"type": "boolean"})),
("ignore_case", json!({"type": "boolean"})),
],
&[],
)
},
},
Tool {
name: "message_patterns",
kind: Kind::Read,
description: "Groups the log lines by message template (numbers, ids, IPs and paths \
replaced by <n>, <hex>, <ip>, <path>) and returns the most frequent ones with their line counts. \
Optionally only over the lines with a match. Opens BigText's Message patterns window.",
schema: || {
object(
vec![
("pattern", string("Optional: only the lines with a match of this text or regular expression.")),
("regex", json!({"type": "boolean"})),
("ignore_case", json!({"type": "boolean"})),
("rare", json!({"type": "boolean", "description": "The rarest templates first (default: the most frequent)."})),
("top", int("How many templates to return, 1 to 30 (default 20).")),
],
&[],
)
},
},
Tool {
name: "top_values",
kind: Kind::Read,
description: "The most frequent values of one field (JSON Lines and logfmt keys, web \
server and syslog columns) with their line counts.",
schema: || {
object(
vec![
(
"field",
string("The field's key (user.id) or column name (status)."),
),
("top", int("How many values, 1 to 30 (default 20).")),
],
&["field"],
)
},
},
Tool {
name: "read_lines",
kind: Kind::Read,
description: "Reads up to 80 lines starting at a line number, to look at a place in the \
file (each line at most 200 characters).",
schema: || {
object(
vec![
("start_line", int("The first line, from 1.")),
("count", int("Lines to read, 1 to 80.")),
],
&["start_line"],
)
},
},
Tool {
name: "context",
kind: Kind::Read,
description: "The lines around one line (up to 20 before and 20 after), to understand \
what happened there: the request before an error, the stack trace after it.",
schema: || {
object(
vec![
("line", int("The line, from 1.")),
("before", int("Lines before it, 0 to 20 (default 5).")),
("after", int("Lines after it, 0 to 20 (default 10).")),
],
&["line"],
)
},
},
Tool {
name: "time_gaps",
kind: Kind::Read,
description: "The longest pauses between consecutive timestamps (and places where the \
clock went back), at least `min` long: when a service stopped logging.",
schema: || {
object(
vec![(
"min",
string("The shortest gap: \"30s\", \"5m\", \"1h\" (default 1m)."),
)],
&[],
)
},
},
Tool {
name: "selection",
kind: Kind::Read,
description: "The text the user selected in the file (at most 8,000 characters) and its \
line numbers.",
schema: || object(vec![], &[]),
},
Tool {
name: "bookmarks",
kind: Kind::Read,
description: "The lines the user bookmarked (at most 30), each with two lines of context \
before and after: the evidence the user collected, for a report or an explanation.",
schema: || object(vec![], &[]),
},
Tool {
name: "extract_values",
kind: Kind::Read,
description: "Counts the different texts a regular expression matches, or its first \
capture group (…), most frequent first, like grep -o | sort | uniq -c: the IP addresses, URLs, \
user ids or error codes of a log. Returns the top values with their counts, the number of \
matches and of different values, and lists the matches in Find All.",
schema: || {
object(
vec![
("pattern", string("A regular expression; with a capture group, the group's text is counted.")),
("ignore_case", json!({"type": "boolean"})),
("top", int("How many values, 1 to 30 (default 20).")),
],
&["pattern"],
)
},
},
Tool {
name: "table_rows",
kind: Kind::Read,
description: "CSV and TSV tables: counts the rows that meet every condition and returns \
the first ones. A column is its header name or its number from 1. Operators: contains, \
not_contains, is, is_not, greater, less (numbers), empty, not_empty; text comparisons ignore \
case.",
schema: || {
object(
vec![(
"conditions",
json!({"type": "array", "description": "All must hold.", "items": {
"type": "object",
"properties": {
"column": {"type": "string"},
"op": {"type": "string", "enum": ["contains", "not_contains", "is", "is_not", "greater", "less", "empty", "not_empty"]},
"value": {"type": "string"}
},
"required": ["column", "op"],
"additionalProperties": false
}}),
)],
&["conditions"],
)
},
},
Tool {
name: "column_stats",
kind: Kind::Read,
description: "CSV and TSV tables: one column's rows, empty cells, numbers with their \
sum, minimum, maximum and mean, the number of different values and the most frequent ones.",
schema: || {
object(
vec![("column", string("The header name or the number from 1."))],
&["column"],
)
},
},
Tool {
name: "group_by",
kind: Kind::Read,
description: "CSV and TSV tables: rows per value of one column, largest groups first \
(GROUP BY), optionally with the sum, minimum, maximum and mean of a number column per group.",
schema: || {
object(
vec![
(
"column",
string("The column to group by: header name or number from 1."),
),
(
"sum_column",
string("Optional: a number column summed per group."),
),
("top", int("How many groups, 1 to 30 (default 20).")),
],
&["column"],
)
},
},
Tool {
name: "go_to_line",
kind: Kind::App,
description: "Scrolls BigText to a line and puts the caret there.",
schema: || object(vec![("line", int("The line, from 1."))], &["line"]),
},
Tool {
name: "highlight",
kind: Kind::App,
description: "Highlights every match of a pattern in colour while the user reads (View → \
Highlights). Does not change the file.",
schema: || object(pattern_props(), &["pattern"]),
},
Tool {
name: "bookmark",
kind: Kind::App,
description: "Bookmarks lines (F2 jumps between bookmarks), for example the evidence \
for an answer. Does not change the file.",
schema: || {
object(
vec![(
"lines",
json!({"type": "array", "items": {"type": "integer"}, "description": "Line numbers, from 1 (at most 50)."}),
)],
&["lines"],
)
},
},
Tool {
name: "save_search",
kind: Kind::App,
description: "Saves a search under a name in BigText's saved searches (the ★ menu of the \
search bar), to run it again later.",
schema: || {
object(
with(
vec![
("name", string("A short name.")),
(
"invert",
json!({"type": "boolean", "description": "The search filters the lines without a match."}),
),
],
pattern_props(),
),
&["name", "pattern"],
)
},
},
Tool {
name: "replace_all",
kind: Kind::Write,
description: "Replaces every match in the file. Only prepares the change: the user sees \
the number of matches and a preview, and confirms it (it can be undone). In regex mode the \
replacement may use $1, ${name} for groups.",
schema: || {
object(
with(
pattern_props(),
vec![("replacement", string("The new text."))],
),
&["pattern", "replacement"],
)
},
},
Tool {
name: "delete_lines",
kind: Kind::Write,
description: "Deletes every line with a match. Only prepares the change: the user sees \
how many lines and a preview, and confirms it (it can be undone).",
schema: || object(pattern_props(), &["pattern"]),
},
Tool {
name: "replace_lines",
kind: Kind::Write,
description: "Replaces the lines start_line to end_line (both included) with new text, \
for a small edit at one place (at most 200 lines). Only prepares the change: the user sees the \
old and new text and confirms it (it can be undone).",
schema: || {
object(
vec![
("start_line", int("The first line to replace, from 1.")),
("end_line", int("The last line to replace.")),
(
"text",
string("The new lines, separated by \\n (empty: delete the lines)."),
),
],
&["start_line", "end_line", "text"],
)
},
},
];
pub fn tool(name: &str) -> Option<&'static Tool> {
TOOLS.iter().find(|t| t.name == name)
}
pub fn specs(writes: bool) -> Vec<ToolSpec> {
TOOLS
.iter()
.filter(|t| writes || t.kind != Kind::Write)
.map(Tool::spec)
.collect()
}
#[derive(Clone, Debug, PartialEq)]
pub struct Pattern {
pub text: String,
pub regex: bool,
pub ignore_case: bool,
pub whole_word: bool,
}
impl Pattern {
pub fn query(&self) -> Query {
Query {
pattern: self.text.clone(),
regex: self.regex,
case_sensitive: !self.ignore_case,
whole_word: self.whole_word,
dot_all: false,
}
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Times {
pub from: Option<String>,
pub to: Option<String>,
}
impl Times {
pub fn any(&self) -> bool {
self.from.is_some() || self.to.is_some()
}
pub fn pair(&self) -> Option<(String, String)> {
self.any().then(|| {
(
self.from.clone().unwrap_or_default(),
self.to.clone().unwrap_or_default(),
)
})
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Call {
FileProfile,
FindAll {
pat: Pattern,
times: Times,
},
Count {
pat: Pattern,
invert: bool,
times: Times,
},
FilterLines {
pat: Pattern,
invert: bool,
context: u32,
times: Times,
},
FieldQuery {
query: String,
times: Times,
},
Levels {
levels: Levels,
times: Times,
},
TimeRange {
times: Times,
},
Histogram {
pat: Option<Pattern>,
},
MessagePatterns {
pat: Option<Pattern>,
rare: bool,
top: usize,
},
TopValues {
field: String,
top: usize,
},
ReadLines {
start: u64,
count: u64,
},
Context {
line: u64,
before: u64,
after: u64,
},
TimeGaps {
min_ms: i64,
},
Selection,
Bookmarks,
ExtractValues {
pat: Pattern,
top: usize,
},
TableRows {
conds: Vec<(String, crate::csv::CondOp, String)>,
},
ColumnStats {
column: String,
},
GroupBy {
column: String,
sum: Option<String>,
top: usize,
},
GoToLine {
line: u64,
},
Highlight {
pat: Pattern,
},
Bookmark {
lines: Vec<u64>,
},
SaveSearch {
name: String,
pat: Pattern,
invert: bool,
},
ReplaceAll {
pat: Pattern,
with: String,
},
DeleteLines {
pat: Pattern,
},
ReplaceLines {
start: u64,
end: u64,
text: String,
},
}
impl Call {
pub fn name(&self) -> &'static str {
match self {
Call::FileProfile => "file_profile",
Call::FindAll { .. } => "find_all",
Call::Count { .. } => "count",
Call::FilterLines { .. } => "filter_lines",
Call::FieldQuery { .. } => "field_query",
Call::Levels { .. } => "levels",
Call::TimeRange { .. } => "time_range",
Call::Histogram { .. } => "histogram",
Call::MessagePatterns { .. } => "message_patterns",
Call::TopValues { .. } => "top_values",
Call::ReadLines { .. } => "read_lines",
Call::Context { .. } => "context",
Call::TimeGaps { .. } => "time_gaps",
Call::Selection => "selection",
Call::ExtractValues { .. } => "extract_values",
Call::Bookmarks => "bookmarks",
Call::TableRows { .. } => "table_rows",
Call::ColumnStats { .. } => "column_stats",
Call::GroupBy { .. } => "group_by",
Call::GoToLine { .. } => "go_to_line",
Call::Highlight { .. } => "highlight",
Call::Bookmark { .. } => "bookmark",
Call::SaveSearch { .. } => "save_search",
Call::ReplaceAll { .. } => "replace_all",
Call::DeleteLines { .. } => "delete_lines",
Call::ReplaceLines { .. } => "replace_lines",
}
}
pub fn kind(&self) -> Kind {
tool(self.name()).map(|t| t.kind).unwrap_or(Kind::Read)
}
pub fn pattern(&self) -> Option<&Pattern> {
match self {
Call::FindAll { pat, .. }
| Call::Count { pat, .. }
| Call::FilterLines { pat, .. }
| Call::Highlight { pat }
| Call::SaveSearch { pat, .. }
| Call::ReplaceAll { pat, .. }
| Call::DeleteLines { pat }
| Call::ExtractValues { pat, .. } => Some(pat),
Call::Histogram { pat } | Call::MessagePatterns { pat, .. } => pat.as_ref(),
_ => None,
}
}
pub fn with_pattern(&self, text: &str) -> Option<Call> {
let mut c = self.clone();
let p = match &mut c {
Call::FindAll { pat, .. }
| Call::Count { pat, .. }
| Call::FilterLines { pat, .. }
| Call::Highlight { pat }
| Call::SaveSearch { pat, .. }
| Call::ReplaceAll { pat, .. }
| Call::DeleteLines { pat }
| Call::ExtractValues { pat, .. } => pat,
Call::Histogram { pat: Some(pat) } | Call::MessagePatterns { pat: Some(pat), .. } => {
pat
}
Call::FieldQuery { query, .. } => {
*query = text.to_string();
return Some(c);
}
_ => return None,
};
p.text = text.to_string();
Some(c)
}
pub fn editable_text(&self) -> Option<String> {
match self {
Call::FieldQuery { query, .. } => Some(query.clone()),
c => c.pattern().map(|p| p.text.clone()),
}
}
pub fn input(&self) -> Value {
fn pat(p: &Pattern) -> Map<String, Value> {
let mut m = Map::new();
m.insert("pattern".into(), json!(p.text));
if p.regex {
m.insert("regex".into(), json!(true));
}
if p.ignore_case {
m.insert("ignore_case".into(), json!(true));
}
if p.whole_word {
m.insert("whole_word".into(), json!(true));
}
m
}
fn times(m: &mut Map<String, Value>, t: &Times) {
if let Some(f) = &t.from {
m.insert("from".into(), json!(f));
}
if let Some(x) = &t.to {
m.insert("to".into(), json!(x));
}
}
let mut m = Map::new();
match self {
Call::FindAll { pat: p, times: t } => {
m = pat(p);
times(&mut m, t);
}
Call::Count {
pat: p,
invert,
times: t,
} => {
m = pat(p);
if *invert {
m.insert("invert".into(), json!(true));
}
times(&mut m, t);
}
Call::FilterLines {
pat: p,
invert,
context,
times: t,
} => {
m = pat(p);
if *invert {
m.insert("invert".into(), json!(true));
}
if *context > 0 {
m.insert("context".into(), json!(context));
}
times(&mut m, t);
}
Call::FieldQuery { query, times: t } => {
m.insert("query".into(), json!(query));
times(&mut m, t);
}
Call::Levels { levels, times: t } => {
m.insert(
"levels".into(),
json!(levels
.iter()
.map(|l| l.name().to_ascii_lowercase())
.collect::<Vec<_>>()),
);
times(&mut m, t);
}
Call::TimeRange { times: t } => times(&mut m, t),
Call::Histogram { pat: Some(p) } => m = pat(p),
Call::MessagePatterns { pat: p, rare, top } => {
if let Some(p) = p {
m = pat(p);
}
if *rare {
m.insert("rare".into(), json!(true));
}
m.insert("top".into(), json!(top));
}
Call::TopValues { field, top } => {
m.insert("field".into(), json!(field));
m.insert("top".into(), json!(top));
}
Call::ReadLines { start, count } => {
m.insert("start_line".into(), json!(start));
m.insert("count".into(), json!(count));
}
Call::Context {
line,
before,
after,
} => {
m.insert("line".into(), json!(line));
m.insert("before".into(), json!(before));
m.insert("after".into(), json!(after));
}
Call::TimeGaps { min_ms } => {
m.insert("min".into(), json!(format!("{}s", min_ms / 1000)));
}
Call::GoToLine { line } => {
m.insert("line".into(), json!(line));
}
Call::Highlight { pat: p } | Call::DeleteLines { pat: p } => m = pat(p),
Call::Bookmark { lines } => {
m.insert("lines".into(), json!(lines));
}
Call::ExtractValues { pat: p, top } => {
m.insert("pattern".into(), json!(p.text));
if p.ignore_case {
m.insert("ignore_case".into(), json!(true));
}
m.insert("top".into(), json!(top));
}
Call::TableRows { conds } => {
let list: Vec<Value> = conds
.iter()
.map(|(c, op, v)| {
let mut x = json!({"column": c, "op": op_id(*op)});
if op.takes_value() {
x["value"] = json!(v);
}
x
})
.collect();
m.insert("conditions".into(), json!(list));
}
Call::ColumnStats { column } => {
m.insert("column".into(), json!(column));
}
Call::GroupBy { column, sum, top } => {
m.insert("column".into(), json!(column));
if let Some(x) = sum {
m.insert("sum_column".into(), json!(x));
}
m.insert("top".into(), json!(top));
}
Call::SaveSearch {
name,
pat: p,
invert,
} => {
m = pat(p);
m.insert("name".into(), json!(name));
if *invert {
m.insert("invert".into(), json!(true));
}
}
Call::ReplaceAll { pat: p, with } => {
m = pat(p);
m.insert("replacement".into(), json!(with));
}
Call::ReplaceLines { start, end, text } => {
m.insert("start_line".into(), json!(start));
m.insert("end_line".into(), json!(end));
m.insert("text".into(), json!(text));
}
Call::FileProfile
| Call::Selection
| Call::Bookmarks
| Call::Histogram { pat: None } => {}
}
Value::Object(m)
}
}
struct Args<'a>(&'a Map<String, Value>);
impl Args<'_> {
fn known(&self, keys: &[&str]) -> Result<(), String> {
match self.0.keys().find(|k| !keys.contains(&k.as_str())) {
Some(k) => Err(format!(
"unknown argument \"{k}\"; the arguments are: {}",
keys.join(", ")
)),
None => Ok(()),
}
}
fn str(&self, k: &str) -> Result<Option<String>, String> {
match self.0.get(k) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(s)) => Ok(Some(s.clone())),
Some(v) => Err(format!("\"{k}\" must be a string, not {v}")),
}
}
fn need_str(&self, k: &str) -> Result<String, String> {
self.str(k)?.ok_or_else(|| format!("\"{k}\" is missing"))
}
fn bool(&self, k: &str) -> Result<bool, String> {
match self.0.get(k) {
None | Some(Value::Null) => Ok(false),
Some(Value::Bool(b)) => Ok(*b),
Some(Value::String(s)) if s == "true" || s == "false" => Ok(s == "true"),
Some(v) => Err(format!("\"{k}\" must be true or false, not {v}")),
}
}
fn int(&self, k: &str, default: Option<u64>, min: u64, max: u64) -> Result<u64, String> {
let v = match self.0.get(k) {
None | Some(Value::Null) => default.ok_or_else(|| format!("\"{k}\" is missing"))?,
Some(Value::Number(n)) => n
.as_u64()
.or_else(|| {
n.as_f64()
.filter(|f| *f >= 0.0 && f.fract() == 0.0)
.map(|f| f as u64)
})
.ok_or_else(|| format!("\"{k}\" must be a whole number of at least {min}"))?,
Some(Value::String(s)) => s
.trim()
.parse()
.map_err(|_| format!("\"{k}\" must be a whole number, not \"{s}\""))?,
Some(v) => return Err(format!("\"{k}\" must be a whole number, not {v}")),
};
if v < min || v > max {
return Err(format!("\"{k}\" must be from {min} to {max}, not {v}"));
}
Ok(v)
}
fn pattern(&self) -> Result<Pattern, String> {
let p = Pattern {
text: self.need_str("pattern")?,
regex: self.bool("regex")?,
ignore_case: self.bool("ignore_case")?,
whole_word: self.bool("whole_word")?,
};
check_pattern(&p)?;
Ok(p)
}
fn opt_pattern(&self) -> Result<Option<Pattern>, String> {
match self.str("pattern")?.filter(|s| !s.is_empty()) {
Some(_) => self.pattern().map(Some),
None => Ok(None),
}
}
fn times(&self) -> Result<Times, String> {
for k in ["from", "to"] {
if let Some(Value::Number(n)) = self.0.get(k) {
return Err(format!(
"\"{k}\": {n} is a number; from and to are times (not line numbers), written like \"14:30\""
));
}
}
let t = Times {
from: self.str("from")?.filter(|s| !s.trim().is_empty()),
to: self.str("to")?.filter(|s| !s.trim().is_empty()),
};
for (k, v) in [("from", &t.from), ("to", &t.to)] {
if let Some(v) = v {
if crate::timestamp::parse_input(v).is_none() {
return Err(format!("\"{k}\": \"{v}\" is not a time BigText reads; from and to are times (not line numbers), written like \"14:30\" or \"2024-05-01 14:30:00\""));
}
}
}
Ok(t)
}
}
const FIELD_QUERY_HELP: &str = "fields start with a dot and text is in double quotes: \
.status >= 500 and .method == \"POST\", .user.id == 7, .level in (\"error\", \"fatal\")";
pub fn field_query_text(q: &str) -> Result<String, String> {
let q = q.trim();
let first = match crate::jsonq::FieldQuery::parse(q) {
Ok(_) => return Ok(q.to_string()),
Err(e) => e,
};
let fixed = add_field_dots(&single_to_double_quotes(q));
if crate::jsonq::FieldQuery::parse(&fixed).is_ok() {
return Ok(fixed);
}
Err(format!(
"the field query does not parse: {first}; {FIELD_QUERY_HELP}"
))
}
fn single_to_double_quotes(q: &str) -> String {
let mut out = String::with_capacity(q.len());
let mut in_double = false;
for c in q.chars() {
match c {
'"' => {
in_double = !in_double;
out.push(c);
}
'\'' if !in_double => out.push('"'),
c => out.push(c),
}
}
out
}
fn add_field_dots(q: &str) -> String {
let ops = ["==", "!=", ">=", "<=", "=", ">", "<", "~"];
let words = ["contains", "in", "exists", "missing"];
let b: Vec<char> = q.chars().collect();
let mut out = String::with_capacity(q.len() + 8);
let mut i = 0;
let mut in_quote = false;
while i < b.len() {
let c = b[i];
if c == '"' {
in_quote = !in_quote;
out.push(c);
i += 1;
continue;
}
let starts_word = !in_quote
&& (c.is_alphabetic() || c == '_' || c == '@')
&& (i == 0 || b[i - 1].is_whitespace() || b[i - 1] == '(' || b[i - 1] == '!');
if !starts_word {
out.push(c);
i += 1;
continue;
}
let end = (i..b.len())
.find(|&j| !(b[j].is_alphanumeric() || "_.@-".contains(b[j])))
.unwrap_or(b.len());
let word: String = b[i..end].iter().collect();
let rest: String = b[end..].iter().collect();
let rest_t = rest.trim_start();
let lower = word.to_ascii_lowercase();
let is_keyword = ["and", "or", "not"].contains(&lower.as_str());
let compared = ops.iter().any(|o| rest_t.starts_with(o))
|| words.iter().any(|w| {
rest_t.len() > w.len()
&& rest_t[..w.len()].eq_ignore_ascii_case(w)
&& !rest_t[w.len()..].starts_with(|ch: char| ch.is_alphanumeric() || ch == '_')
&& rest.len() > rest_t.len()
});
if compared && !is_keyword {
out.push('.');
}
out.push_str(&word);
i = end;
}
out
}
pub fn check_pattern(p: &Pattern) -> Result<(), String> {
if p.text.is_empty() {
return Err("\"pattern\" is empty".into());
}
Matcher::new(&p.query(), Codec::utf8())
.map(|_| ())
.map_err(|e| format!("the regular expression does not compile: {e}. {REGEX_NOTE}"))
}
const PATTERN_KEYS: [&str; 4] = ["pattern", "regex", "ignore_case", "whole_word"];
fn keys(extra: &[&'static str], pattern: bool, times: bool) -> Vec<&'static str> {
let mut k: Vec<&str> = extra.to_vec();
if pattern {
k.extend(PATTERN_KEYS);
}
if times {
k.extend(["from", "to"]);
}
k
}
pub fn parse(name: &str, input: &Value) -> Result<Call, String> {
let empty = Map::new();
let map = match input {
Value::Object(m) => m,
Value::Null => &empty,
Value::String(s) => return Err(format!("the arguments are not valid JSON: {s}")),
v => return Err(format!("the arguments must be a JSON object, not {v}")),
};
let a = Args(map);
let call = match name {
"file_profile" => {
a.known(&[])?;
Call::FileProfile
}
"find_all" => {
a.known(&keys(&[], true, true))?;
Call::FindAll {
pat: a.pattern()?,
times: a.times()?,
}
}
"count" => {
a.known(&keys(&["invert"], true, true))?;
Call::Count {
pat: a.pattern()?,
invert: a.bool("invert")?,
times: a.times()?,
}
}
"filter_lines" => {
a.known(&keys(&["invert", "context"], true, true))?;
Call::FilterLines {
pat: a.pattern()?,
invert: a.bool("invert")?,
context: a.int("context", Some(0), 0, 20)? as u32,
times: a.times()?,
}
}
"field_query" => {
a.known(&keys(&["query"], false, true))?;
let query = field_query_text(&a.need_str("query")?)?;
Call::FieldQuery {
query,
times: a.times()?,
}
}
"levels" => {
a.known(&keys(&["levels"], false, true))?;
let mut levels = Levels::default();
match map.get("levels") {
None | Some(Value::Null) => levels = Levels::only(Level::Error),
Some(Value::Array(v)) => {
for x in v {
let s = x.as_str().unwrap_or_default().to_ascii_uppercase();
let l = match s.as_str() {
"ERROR" | "ERR" | "FATAL" | "CRITICAL" => Level::Error,
"WARN" | "WARNING" => Level::Warn,
"INFO" => Level::Info,
"DEBUG" | "TRACE" => Level::Debug,
_ => {
return Err(format!(
"unknown level {x}; the levels are error, warn, info, debug"
))
}
};
if !levels.contains(l) {
levels = levels.toggled(l);
}
}
if levels.is_empty() {
levels = Levels::only(Level::Error);
}
}
Some(Value::String(s)) => {
return parse(
name,
&json!({"levels": [s], "from": map.get("from"), "to": map.get("to")}),
)
}
Some(v) => {
return Err(format!(
"\"levels\" must be a list like [\"error\"], not {v}"
))
}
}
Call::Levels {
levels,
times: a.times()?,
}
}
"time_range" => {
a.known(&["from", "to"])?;
let times = a.times()?;
if !times.any() {
return Err("give \"from\", \"to\" or both".into());
}
Call::TimeRange { times }
}
"histogram" => {
a.known(&["pattern", "regex", "ignore_case"])?;
Call::Histogram {
pat: a.opt_pattern()?,
}
}
"message_patterns" => {
a.known(&["pattern", "regex", "ignore_case", "rare", "top"])?;
Call::MessagePatterns {
pat: a.opt_pattern()?,
rare: a.bool("rare")?,
top: a.int("top", Some(20), 1, 30)? as usize,
}
}
"top_values" => {
a.known(&["field", "top"])?;
Call::TopValues {
field: a
.need_str("field")?
.trim()
.trim_start_matches('.')
.to_string(),
top: a.int("top", Some(20), 1, 30)? as usize,
}
}
"read_lines" => {
a.known(&["start_line", "count"])?;
Call::ReadLines {
start: a.int("start_line", None, 1, u64::MAX / 2)?,
count: a.int("count", Some(40), 1, 80)?,
}
}
"context" => {
a.known(&["line", "before", "after"])?;
Call::Context {
line: a.int("line", None, 1, u64::MAX / 2)?,
before: a.int("before", Some(5), 0, 20)?,
after: a.int("after", Some(10), 0, 20)?,
}
}
"time_gaps" => {
a.known(&["min"])?;
let min = match map.get("min") {
Some(Value::Number(n)) => n.to_string(),
_ => a.str("min")?.unwrap_or_else(|| "1m".into()),
};
let min_ms = crate::gaps::parse_duration(&min).ok_or_else(|| {
format!("\"min\": \"{min}\" is not a duration like \"30s\", \"5m\" or \"1h\"")
})?;
Call::TimeGaps { min_ms }
}
"selection" => {
a.known(&[])?;
Call::Selection
}
"bookmarks" => {
a.known(&[])?;
Call::Bookmarks
}
"extract_values" => {
a.known(&["pattern", "ignore_case", "top"])?;
let pat = Pattern {
text: a.need_str("pattern")?,
regex: true,
ignore_case: a.bool("ignore_case")?,
whole_word: false,
};
check_pattern(&pat)?;
Call::ExtractValues {
pat,
top: a.int("top", Some(20), 1, 30)? as usize,
}
}
"table_rows" => {
a.known(&["conditions"])?;
let Some(Value::Array(list)) = map.get("conditions") else {
return Err("\"conditions\" must be a list of {column, op, value}".into());
};
let mut conds = Vec::new();
for c in list {
let o = c
.as_object()
.ok_or("each condition is an object {column, op, value}")?;
let a = Args(o);
let short = (!o.contains_key("op")
&& !o.contains_key("operator")
&& !o.contains_key("value")
&& o.len() == 2)
.then(|| o.iter().find(|(k, _)| k.as_str() != "column"))
.flatten()
.map(|(k, v)| (k.clone(), v.clone()));
if short.is_none() {
a.known(&["column", "op", "operator", "value"])?;
}
let column = match o.get("column") {
Some(Value::Number(n)) => n.to_string(),
_ => a.need_str("column")?,
};
let op = match (&short, a.str("op")?) {
(Some((k, _)), _) => k.clone(),
(None, Some(op)) => op,
(None, None) => a.str("operator")?.ok_or("\"op\" is missing")?,
};
let op = match op.trim().to_ascii_lowercase().as_str() {
"contains" | "like" => crate::csv::CondOp::Contains,
"not_contains" | "does_not_contain" | "not_like" => crate::csv::CondOp::NotContains,
"is" | "equals" | "eq" | "==" | "=" => crate::csv::CondOp::Equals,
"is_not" | "not_equals" | "ne" | "neq" | "!=" | "<>" => crate::csv::CondOp::NotEquals,
"greater" | "greater_than" | "gt" | ">" => crate::csv::CondOp::Greater,
"less" | "less_than" | "lt" | "<" => crate::csv::CondOp::Less,
"empty" | "is_empty" | "blank" => crate::csv::CondOp::Empty,
"not_empty" | "is_not_empty" | "not_blank" => crate::csv::CondOp::NotEmpty,
o => return Err(format!("unknown op \"{o}\"; the ops are contains, not_contains, is, is_not, greater, less, empty, not_empty")),
};
let value = match short.as_ref().map(|x| &x.1).or(o.get("value")) {
Some(Value::Number(n)) => n.to_string(),
Some(Value::String(v)) => v.clone(),
Some(Value::Null) | None => String::new(),
Some(v) => return Err(format!("the value of the condition on \"{column}\" must be text or a number, not {v}")),
};
if op.takes_value() && value.is_empty() {
return Err(format!("the condition on \"{column}\" needs a value"));
}
conds.push((column, op, value));
}
if conds.is_empty() {
return Err("\"conditions\" is empty".into());
}
Call::TableRows { conds }
}
"column_stats" => {
a.known(&["column"])?;
Call::ColumnStats {
column: column_arg(&a, "column")?,
}
}
"group_by" => {
a.known(&["column", "sum_column", "top"])?;
Call::GroupBy {
column: column_arg(&a, "column")?,
sum: match map.get("sum_column") {
None | Some(Value::Null) => None,
_ => Some(column_arg(&a, "sum_column")?).filter(|s| !s.is_empty()),
},
top: a.int("top", Some(20), 1, 30)? as usize,
}
}
"go_to_line" => {
a.known(&["line"])?;
Call::GoToLine {
line: a.int("line", None, 1, u64::MAX / 2)?,
}
}
"highlight" => {
a.known(&PATTERN_KEYS)?;
Call::Highlight { pat: a.pattern()? }
}
"bookmark" => {
a.known(&["lines"])?;
let lines: Vec<u64> = match map.get("lines") {
Some(Value::Array(v)) => v
.iter()
.filter_map(|x| x.as_u64().filter(|&n| n > 0))
.take(50)
.collect(),
_ => return Err("\"lines\" must be a list of line numbers".into()),
};
if lines.is_empty() {
return Err("\"lines\" is empty".into());
}
Call::Bookmark { lines }
}
"save_search" => {
a.known(&keys(&["name", "invert"], true, false))?;
let name = a.need_str("name")?.trim().replace('|', "/");
if name.is_empty() {
return Err("\"name\" is empty".into());
}
Call::SaveSearch {
name,
pat: a.pattern()?,
invert: a.bool("invert")?,
}
}
"replace_all" => {
a.known(&keys(&["replacement"], true, false))?;
Call::ReplaceAll {
pat: a.pattern()?,
with: a.need_str("replacement")?,
}
}
"delete_lines" => {
a.known(&PATTERN_KEYS)?;
Call::DeleteLines { pat: a.pattern()? }
}
"replace_lines" => {
a.known(&["start_line", "end_line", "text"])?;
let start = a.int("start_line", None, 1, u64::MAX / 2)?;
let end = a.int("end_line", None, start, start + 199)?;
Call::ReplaceLines {
start,
end,
text: a.need_str("text")?,
}
}
other => {
let names: Vec<&str> = TOOLS.iter().map(|t| t.name).collect();
return Err(format!(
"there is no tool \"{other}\"; the tools are: {}",
names.join(", ")
));
}
};
Ok(call)
}
#[derive(Clone, Debug, PartialEq)]
pub enum Show {
FindAll {
query: Query,
times: Times,
},
Filter {
query: Query,
invert: bool,
context: u32,
times: Times,
},
FieldFilter {
query: String,
times: Times,
},
Levels {
levels: Levels,
times: Times,
},
TimeRange(Times),
Histogram(Option<Query>),
Patterns(Option<Query>),
TopValues(String),
Gaps(i64),
Line(u64),
Highlight(Query),
Bookmarks(Vec<u64>),
SaveSearch {
name: String,
query: Query,
invert: bool,
},
}
#[derive(Clone, Debug, PartialEq)]
pub enum Change {
ReplaceAll {
query: Query,
with: String,
count: u64,
},
ReplaceRange { range: Range<u64>, text: String },
}
#[derive(Clone, Debug, PartialEq)]
pub struct Output {
pub for_model: Value,
pub summary: &'static str,
pub n: Option<u64>,
pub lines: Vec<u64>,
pub show: Option<Show>,
pub change: Option<Change>,
pub preview: Vec<(u64, String, String)>,
}
impl Output {
fn new(for_model: Value, summary: &'static str, n: Option<u64>) -> Output {
Output {
for_model,
summary,
n,
lines: Vec::new(),
show: None,
change: None,
preview: Vec::new(),
}
}
}
pub const RESULT_TEXT_MAX: usize = 3500;
pub const RESULT_LINES: usize = 20;
pub struct Run<'a> {
pub buf: &'a TextBuf,
pub cancel: &'a CancelToken,
pub name: &'a str,
pub selection: Option<(u64, u64)>,
pub bookmarks: &'a [u64],
pub redact: &'a mut dyn FnMut(&str) -> String,
}
struct Sampler {
out: Vec<Value>,
lines: Vec<u64>,
bytes: usize,
max: usize,
}
impl Sampler {
fn new(max: usize) -> Sampler {
Sampler {
out: Vec::new(),
lines: Vec::new(),
bytes: 0,
max,
}
}
fn full(&self) -> bool {
self.out.len() >= self.max || self.bytes >= RESULT_TEXT_MAX
}
fn push(&mut self, r: &mut Run, ls: u64, le: u64) {
if self.full() || self.lines.last() == Some(&line_no(r.buf, ls)) {
return;
}
let n = line_no(r.buf, ls);
let t = (r.redact)(&line_text(r.buf, ls, le));
self.bytes += t.len() + 20;
self.lines.push(n);
self.out.push(json!({"line": n, "text": t}));
}
}
pub fn line_no(buf: &TextBuf, off: u64) -> u64 {
buf.line_of(off).0 + 1
}
fn line_text(buf: &TextBuf, ls: u64, le: u64) -> String {
let le = le.min(ls + 4096).max(ls);
let b = buf.read(ls..le).map(|b| b.to_vec()).unwrap_or_default();
clip(&buf.codec.decode_lossy(&b))
}
fn time_bytes(r: &Run, t: &Times) -> Result<Option<(u64, u64)>, String> {
if !t.any() {
return Ok(None);
}
let parse = |s: &Option<String>| s.as_deref().and_then(crate::timestamp::parse_input);
let (from, mut to) = (parse(&t.from), parse(&t.to));
if let (Some(f), Some(x)) = (from, to) {
to = Some(crate::timestamp::rebase(x, f));
}
match crate::timestamp::time_range(r.buf, from, to, r.cancel) {
Ok(range) => Ok(Some(range)),
Err(crate::timestamp::TimeError::NoTimestamps) => {
Err("the file has no timestamps BigText reads, so from and to cannot be used".into())
}
Err(crate::timestamp::TimeError::Cancelled) => Err(CANCELLED.into()),
}
}
const CANCELLED: &str = "stopped by the user";
fn matcher(r: &Run, q: &Query) -> Result<Matcher, String> {
Matcher::new(q, r.buf.codec).map_err(|e| format!("the pattern does not compile: {e}"))
}
fn ended(end: SearchEnd) -> Result<(), String> {
match end {
SearchEnd::Cancelled => Err(CANCELLED.into()),
SearchEnd::Unavailable => Err("the file could not be read".into()),
_ => Ok(()),
}
}
fn range_json(v: &mut Value, r: &Run, range: Option<(u64, u64)>) {
if let Some((a, b)) = range {
v["time_range_lines"] = json!([line_no(r.buf, a), line_no(r.buf, b.max(a + 1) - 1)]);
}
}
fn filter_count(
r: &mut Run,
m: &Matcher,
spec: FilterSpec,
sample: usize,
) -> Result<(u64, Sampler), String> {
let mut s = Sampler::new(sample);
let mut n = 0u64;
let buf = r.buf;
let cancel = r.cancel;
let mut hits: Vec<(u64, u64)> = Vec::new();
let end = filter::filter_lines(buf, m, spec, cancel, None, |ls, le, kind| {
if kind == LineKind::Hit {
n += 1;
if hits.len() < sample {
hits.push((ls, le));
}
}
true
});
ended(end)?;
for (ls, le) in hits {
s.push(r, ls, le);
}
Ok((n, s))
}
fn level_of(text: &str) -> Option<Level> {
let word: String = text
.trim_end_matches(|c: char| !c.is_ascii_alphabetic())
.chars()
.rev()
.take_while(|c| c.is_ascii_alphabetic())
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect::<String>()
.to_ascii_uppercase();
Level::ALL
.into_iter()
.find(|l| l.words().contains(&word.as_str()))
}
fn count_levels(
buf: &TextBuf,
range: Range<u64>,
cancel: &CancelToken,
) -> Result<[u64; 4], String> {
let q = crate::loglevel::query(Levels::from_bits(0x0F)).unwrap();
let m = Matcher::new(&q, buf.codec).map_err(|e| e.to_string())?;
let nl = buf.codec.nl_unit();
let mut counts = [0u64; 4];
let mut line_end = 0u64;
let end = search::search_forward_par_ctx(buf, &m, range, cancel, None, |s, e, hay, base| {
if s < line_end {
return true;
}
let in_hay = s >= base && (e - base) as usize <= hay.len();
let text = if in_hay {
buf.codec
.decode_lossy(&hay[(s - base) as usize..(e - base) as usize])
} else {
buf.read(s..e.min(s + 256))
.map(|b| buf.codec.decode_lossy(&b))
.unwrap_or_default()
};
if let Some(l) = level_of(&text) {
counts[l as usize] += 1;
}
line_end = if in_hay {
memchr::memmem::find(&hay[(e - base) as usize..], nl)
.map(|i| e + i as u64 + nl.len() as u64)
.unwrap_or(e)
} else {
e
};
true
});
ended(end)?;
Ok(counts)
}
fn lines_from(buf: &TextBuf, off: u64, n: u64) -> Vec<(u64, u64, String)> {
let mut out = Vec::new();
let (codec, len) = (buf.codec, buf.len());
let mut at = off;
while (out.len() as u64) < n && at < len {
let to = (at + 64 * 1024).min(len);
let Some(b) = buf.read(at..to) else { break };
let (le, next) = match codec.find_nl(&b, at) {
Some(i) => (at + i as u64, at + i as u64 + codec.unit() as u64),
None => (to, to),
};
out.push((at, next, line_text(buf, at, le)));
at = if next == to && to < len {
filter::line_end_at(buf, to).unwrap_or(len)
} else {
next
};
}
out
}
fn start_of_line(buf: &TextBuf, line: u64) -> Result<u64, String> {
let (lines, exact) = buf.line_count();
if exact && line > lines {
return Err(format!("the file has {lines} lines"));
}
let (off, exact) = buf
.line_start(line - 1)
.ok_or_else(|| format!("the file has no line {line}"))?;
Ok(if exact {
off
} else {
filter::line_start_at(buf, off).unwrap_or(off)
})
}
fn log_format(buf: &TextBuf) -> Option<crate::logformat::Format> {
let head = buf
.read(0..buf.len().min(4096))
.map(|b| b.to_vec())
.unwrap_or_default();
if head.trim_ascii_start().starts_with(b"{") {
return None;
}
crate::logformat::detect(buf).ok().flatten()
}
pub fn run(r: &mut Run, call: &Call) -> Result<Output, String> {
let buf = r.buf;
if r.cancel.is_cancelled() {
return Err(CANCELLED.into());
}
Ok(match call {
Call::FileProfile => {
let p = Profile::build(buf, r.name, r.cancel);
Output::new(p.to_json(r.redact), "File profile", None)
}
Call::FindAll { pat, times } => {
let q = pat.query();
let m = matcher(r, &q)?;
let range = time_bytes(r, times)?;
let (a, b) = range.unwrap_or((0, buf.len()));
let mut count = 0u64;
let mut first: Vec<u64> = Vec::new();
let end = search::search_forward_par(buf, &m, a..b, r.cancel, None, |s, _| {
count += 1;
if first.len() < RESULT_LINES * 2 {
first.push(s);
}
true
});
ended(end)?;
let mut s = Sampler::new(RESULT_LINES);
for off in first {
let ls = filter::line_start_at(buf, off).unwrap_or(off);
let le = filter::line_end_at(buf, off).unwrap_or(buf.len());
s.push(r, ls, le);
}
let mut v = json!({"matches": count, "first_lines": s.out});
range_json(&mut v, r, range);
regex_hint(&mut v, pat, count);
let mut o = Output::new(v, "{n} matches", Some(count));
o.lines = s.lines;
o.show = Some(Show::FindAll {
query: q,
times: times.clone(),
});
o
}
Call::Count { pat, invert, times } => {
let m = matcher(r, &pat.query())?;
let range = time_bytes(r, times)?;
let spec = FilterSpec {
invert: *invert,
range,
..Default::default()
};
let (n, _) = filter_count(r, &m, spec, 0)?;
let mut v = json!({"lines": n});
range_json(&mut v, r, range);
if !*invert {
regex_hint(&mut v, pat, n);
}
Output::new(v, "{n} lines", Some(n))
}
Call::FilterLines {
pat,
invert,
context,
times,
} => {
let q = pat.query();
let m = matcher(r, &q)?;
let range = time_bytes(r, times)?;
let spec = FilterSpec {
invert: *invert,
range,
..Default::default()
};
let (n, s) = filter_count(r, &m, spec, RESULT_LINES)?;
let mut v = json!({"lines": n, "first_lines": s.out});
range_json(&mut v, r, range);
if !*invert {
regex_hint(&mut v, pat, n);
}
let mut o = Output::new(v, "{n} lines", Some(n));
o.lines = s.lines;
o.show = Some(Show::Filter {
query: q,
invert: *invert,
context: *context,
times: times.clone(),
});
o
}
Call::FieldQuery { query, times } => {
if buf.codec.unit() != 1 {
return Err("field queries need a UTF-8 file".into());
}
let head = buf
.read(0..buf.len().min(4096))
.map(|b| b.to_vec())
.unwrap_or_default();
let json_doc = head.trim_ascii_start().starts_with(b"{");
let format = if json_doc { None } else { log_format(buf) };
let logfmt = !json_doc && format.is_none();
let q = crate::jsonq::FieldQuery::parse(query)?.for_document(format, logfmt);
let range = time_bytes(r, times)?;
let spec = FilterSpec {
range,
..Default::default()
};
let mut n = 0u64;
let mut hits = Vec::new();
let end = filter::filter_predicate(
buf,
spec,
&|l| q.matches(l),
r.cancel,
None,
|ls, le, kind| {
if kind == LineKind::Hit {
n += 1;
if hits.len() < RESULT_LINES {
hits.push((ls, le));
}
}
true
},
);
ended(end)?;
let mut s = Sampler::new(RESULT_LINES);
for (ls, le) in hits {
s.push(r, ls, le);
}
let mut v = json!({"lines": n, "first_lines": s.out});
range_json(&mut v, r, range);
let mut o = Output::new(v, "{n} lines", Some(n));
o.lines = s.lines;
o.show = Some(Show::FieldFilter {
query: query.clone(),
times: times.clone(),
});
o
}
Call::Levels { levels, times } => {
let range = time_bytes(r, times)?;
let (a, b) = range.unwrap_or((0, buf.len()));
let counts = count_levels(buf, a..b, r.cancel)?;
let q = crate::loglevel::query(*levels).ok_or("no level chosen")?;
let m = matcher(r, &q)?;
let spec = FilterSpec {
range,
..Default::default()
};
let mut s = Sampler::new(RESULT_LINES);
let mut hits = Vec::new();
let end = filter::filter_lines(buf, &m, spec, r.cancel, None, |ls, le, _| {
hits.push((ls, le));
hits.len() < RESULT_LINES
});
ended(end)?;
for (ls, le) in hits {
s.push(r, ls, le);
}
let shown: u64 = levels.iter().map(|l| counts[l as usize]).sum();
let mut v = json!({
"lines_per_level": {"error": counts[0], "warn": counts[1], "info": counts[2], "debug": counts[3]},
"shown_levels": levels.names(),
"first_lines": s.out,
});
range_json(&mut v, r, range);
let mut o = Output::new(v, "{n} lines", Some(shown));
o.lines = s.lines;
o.show = Some(Show::Levels {
levels: *levels,
times: times.clone(),
});
o
}
Call::TimeRange { times } => {
let (a, b) = time_bytes(r, times)?.unwrap_or((0, buf.len()));
let (first, last) = (line_no(buf, a), line_no(buf, b.max(a + 1) - 1));
let n = if b > a { last - first + 1 } else { 0 };
let v = json!({"first_line": first, "last_line": last, "lines": n});
let mut o = Output::new(v, "{n} lines in the range", Some(n));
o.lines = vec![first];
o.show = Some(Show::TimeRange(times.clone()));
o
}
Call::Histogram { pat } => {
let q = pat.as_ref().map(Pattern::query);
let m = match &q {
Some(q) => Some(matcher(r, q)?),
None => None,
};
let h = crate::histogram::build(buf, m.as_ref(), r.cancel, None, |_| {})
.map_err(|e| e.to_string())?
.ok_or(CANCELLED)?;
if h.buckets.is_empty() {
return Err("the file has no timestamps BigText reads".into());
}
let step = h.step_for(60);
let bars: Vec<Value> = h
.bars(step)
.into_iter()
.map(|(k, b)| {
let mut x = json!({"from": crate::timestamp::format_key(k, h.dated, step < 60_000), "lines": b.lines});
if q.is_some() {
x["hits"] = json!(b.hits);
}
x
})
.collect();
let n = bars.len() as u64;
let mut v = json!({"bar_seconds": step / 1000, "lines": h.lines, "bars": bars});
if q.is_some() {
v["hits"] = json!(h.hits);
}
let mut o = Output::new(v, "{n} bars", Some(n));
o.show = Some(Show::Histogram(q));
o
}
Call::MessagePatterns { pat, rare, top } => {
let q = pat.as_ref().map(Pattern::query);
let mut starts = None;
if let Some(q) = &q {
let m = matcher(r, q)?;
let mut v: Vec<u64> = Vec::new();
let end = filter::filter_lines(
buf,
&m,
FilterSpec::default(),
r.cancel,
None,
|ls, _, _| {
v.push(ls);
v.len() < 4_000_000
},
);
ended(end)?;
starts = Some(v);
}
let mut p = crate::patterns::build(buf, starts.as_deref(), r.cancel, None, |_| {})
.map_err(|e| e.to_string())?
.ok_or(CANCELLED)?;
crate::patterns::sort(&mut p.templates, *rare);
let list: Vec<Value> = p
.templates
.iter()
.take(*top)
.map(|t| {
let mut x = json!({"template": (r.redact)(&clip(&t.text)), "lines": t.count, "first_line": line_no(buf, t.first)});
if let Some(l) = t.level {
x["level"] = json!(l.name());
}
x
})
.collect();
let n = p.templates.len() as u64;
let v = json!({"lines": p.lines, "templates": n, "top": list});
let mut o = Output::new(v, "{n} message patterns", Some(n));
o.show = Some(Show::Patterns(q));
o
}
Call::TopValues { field, top } => top_values(r, field, *top)?,
Call::ReadLines { start, count } => {
let off = start_of_line(buf, *start)?;
let lines = lines_from(buf, off, *count);
let mut out = Vec::new();
let mut bytes = 0;
for (i, (_, _, t)) in lines.iter().enumerate() {
let t = (r.redact)(t);
bytes += t.len();
if bytes > RESULT_TEXT_MAX * 3 {
break;
}
out.push(json!({"line": start + i as u64, "text": t}));
}
let n = out.len() as u64;
let mut o = Output::new(json!({"lines": out}), "{n} lines", Some(n));
o.lines = vec![*start];
o
}
Call::Context {
line,
before,
after,
} => {
let first = line.saturating_sub(*before).max(1);
let off = start_of_line(buf, first)?;
let lines = lines_from(buf, off, line - first + after + 1);
let out: Vec<Value> = lines
.iter()
.enumerate()
.map(|(i, (_, _, t))| {
let n = first + i as u64;
let mut x = json!({"line": n, "text": (r.redact)(t)});
if n == *line {
x["this"] = json!(true);
}
x
})
.collect();
let n = out.len() as u64;
let mut o = Output::new(json!({"lines": out}), "{n} lines", Some(n));
o.lines = vec![*line];
o
}
Call::TimeGaps { min_ms } => {
let g = crate::gaps::scan(buf, *min_ms, r.cancel, None, |_| {})
.map_err(|e| e.to_string())?
.ok_or(CANCELLED)?;
if g.stamped == 0 {
return Err("the file has no timestamps BigText reads".into());
}
let mut gaps = g.gaps.clone();
gaps.sort_by_key(|x| std::cmp::Reverse(x.ms().unsigned_abs()));
let list: Vec<Value> = gaps
.iter()
.take(10)
.map(|x| {
json!({
"gap": crate::timestamp::format_delta(x.ms()),
"from": crate::timestamp::format_key(x.from, g.dated, true),
"to": crate::timestamp::format_key(x.to, g.dated, true),
"line_before": line_no(buf, x.before),
"line_after": line_no(buf, x.after),
})
})
.collect();
let n = g.gaps.len() as u64;
let mut o = Output::new(
json!({"gaps": n, "longest": list}),
"{n} time gaps",
Some(n),
);
o.lines = gaps
.iter()
.take(10)
.map(|x| line_no(buf, x.after))
.collect();
o.show = Some(Show::Gaps(*min_ms));
o
}
Call::ExtractValues { pat, top } => extract_values(r, pat, *top)?,
Call::Bookmarks => {
if r.bookmarks.is_empty() {
return Err("there are no bookmarks (Ctrl+F2 bookmarks a line)".into());
}
let mut out = Vec::new();
let mut lines = Vec::new();
let mut bytes = 0;
for &off in r.bookmarks.iter().take(30) {
let n = line_no(buf, off);
let first = n.saturating_sub(2).max(1);
let Ok(start) = start_of_line(buf, first) else {
continue;
};
let around: Vec<Value> = lines_from(buf, start, n - first + 3)
.iter()
.enumerate()
.map(|(i, (_, _, t))| json!({"line": first + i as u64, "text": (r.redact)(t)}))
.collect();
bytes += around.iter().map(|x| x.to_string().len()).sum::<usize>();
lines.push(n);
out.push(json!({"bookmark": n, "lines": around}));
if bytes > RESULT_TEXT_MAX * 3 {
break;
}
}
let n = out.len() as u64;
let mut o = Output::new(
json!({"bookmarks": r.bookmarks.len(), "shown": out}),
"{n} bookmarks",
Some(n),
);
o.lines = lines;
o
}
Call::TableRows { conds } => table_rows(r, conds)?,
Call::ColumnStats { column } => column_stats(r, column)?,
Call::GroupBy { column, sum, top } => group_by(r, column, sum.as_deref(), *top)?,
Call::Selection => {
let (s, e) = r
.selection
.filter(|(s, e)| e > s)
.ok_or("nothing is selected")?;
let b = buf
.read(s..e.min(s + 32 * 1024))
.map(|b| b.to_vec())
.unwrap_or_default();
let text = buf.codec.decode_lossy(&b);
let mut t: String = text.chars().take(8000).collect();
if t.len() < text.len() || e - s > 32 * 1024 {
t.push('…');
}
let (first, last) = (line_no(buf, s), line_no(buf, e.max(s + 1) - 1));
let mut o = Output::new(
json!({"first_line": first, "last_line": last, "text": (r.redact)(&t)}),
"{n} lines",
Some(last - first + 1),
);
o.lines = vec![first];
o
}
Call::GoToLine { line } => {
start_of_line(buf, *line)?;
let mut o = Output::new(json!({"done": true}), "Line {n}", Some(*line));
o.lines = vec![*line];
o.show = Some(Show::Line(*line));
o
}
Call::Highlight { pat } => {
let mut o = Output::new(json!({"done": true}), "Highlighted", None);
o.show = Some(Show::Highlight(pat.query()));
o
}
Call::Bookmark { lines } => {
let mut o = Output::new(
json!({"done": true, "bookmarked": lines.len()}),
"{n} bookmarks",
Some(lines.len() as u64),
);
o.lines = lines.clone();
o.show = Some(Show::Bookmarks(lines.clone()));
o
}
Call::SaveSearch { name, pat, invert } => {
let mut o = Output::new(json!({"done": true}), "Saved", None);
o.show = Some(Show::SaveSearch {
name: name.clone(),
query: pat.query(),
invert: *invert,
});
o
}
Call::ReplaceAll { pat, with } => replace_preview(r, pat.query(), with.clone(), false)?,
Call::DeleteLines { pat } => replace_preview(r, delete_query(pat), String::new(), true)?,
Call::ReplaceLines { start, end, text } => {
let a = start_of_line(buf, *start)?;
let lines = lines_from(buf, a, end - start + 1);
let Some(&(_, b, _)) = lines.last() else {
return Err(format!("the file has no line {start}"));
};
if b - a > 1 << 20 {
return Err("those lines are too long to replace this way; use replace_all".into());
}
let old = buf
.read(a..b)
.map(|x| buf.codec.decode_lossy(&x))
.unwrap_or_default();
let nl = if old.ends_with("\r\n") {
"\r\n"
} else if old.ends_with('\n') {
"\n"
} else {
""
};
let mut new = text.replace("\r\n", "\n");
if nl == "\r\n" {
new = new.replace('\n', "\r\n");
}
if !new.is_empty() && !nl.is_empty() && !new.ends_with(nl) {
new.push_str(nl);
}
let preview: Vec<(u64, String, String)> =
vec![(*start, clip_block(&old), clip_block(&new))];
let n = lines.len() as u64;
let v = json!({"lines_to_replace": n, "status": "waiting for the user to confirm"});
let mut o = Output::new(v, "{n} lines to change", Some(n));
o.lines = vec![*start];
o.preview = preview;
o.change = Some(Change::ReplaceRange {
range: a..b,
text: new,
});
o
}
})
}
fn clip_block(text: &str) -> String {
let lines: Vec<String> = text.lines().take(40).map(clip).collect();
let mut out = lines.join("\n");
if text.lines().count() > 40 {
out.push_str("\n…");
}
out
}
fn regex_hint(v: &mut Value, pat: &Pattern, found: u64) {
if found > 0 || pat.regex {
return;
}
let t = &pat.text;
let looks = [
"\\b", "\\d", "\\w", "\\s", "\\.", ".*", ".+", "\\(", "[0-9]", "(?i)",
]
.iter()
.any(|x| t.contains(x))
|| (t.contains('|') && t.contains('('));
if looks {
v["hint"] = json!("nothing matched the pattern as plain text; it looks like a regular expression: set \"regex\": true if it is one");
}
}
pub fn delete_query(pat: &Pattern) -> Query {
let inner = if pat.regex {
pat.text.clone()
} else {
regex_syntax::escape(&pat.text)
};
let inner = if pat.whole_word {
format!(r"\b(?:{inner})\b")
} else {
inner
};
let inner = if pat.ignore_case {
format!("(?i:{inner})")
} else {
format!("(?:{inner})")
};
Query {
pattern: format!(r"(?m)^[^\n]*{inner}[^\n]*(?:\n|\z)"),
regex: true,
case_sensitive: true,
whole_word: false,
dot_all: false,
}
}
fn replace_preview(r: &mut Run, q: Query, with: String, lines: bool) -> Result<Output, String> {
let buf = r.buf;
let m = matcher(r, &q)?;
let mut count = 0u64;
let end = search::search_forward_par(buf, &m, 0..buf.len(), r.cancel, None, |_, _| {
count += 1;
true
});
ended(end)?;
if count == 0 {
return Err("nothing matches, so nothing would change".into());
}
let tpl = crate::replace::Template::new(&with, q.regex);
let samples = crate::replace::preview(buf, &m, &tpl, 0..buf.len(), 5, r.cancel);
let preview: Vec<(u64, String, String)> = samples
.iter()
.map(|(off, before, after)| (line_no(buf, *off), clip_block(before), clip_block(after)))
.collect();
let for_model: Vec<Value> = preview
.iter()
.map(|(n, b, a)| json!({"line": n, "before": (r.redact)(b), "after": (r.redact)(a)}))
.collect();
let v = json!({
if lines { "lines_to_delete" } else { "matches" }: count,
"preview": for_model,
"status": "waiting for the user to confirm",
});
let mut o = Output::new(
v,
if lines {
"{n} lines to delete"
} else {
"{n} matches to replace"
},
Some(count),
);
o.lines = preview.iter().map(|p| p.0).collect();
o.preview = preview;
o.change = Some(Change::ReplaceAll {
query: q,
with,
count,
});
Ok(o)
}
fn op_id(op: crate::csv::CondOp) -> &'static str {
use crate::csv::CondOp::*;
match op {
Contains => "contains",
NotContains => "not_contains",
Equals => "is",
NotEquals => "is_not",
Greater => "greater",
Less => "less",
Empty => "empty",
NotEmpty => "not_empty",
}
}
fn column_arg(a: &Args, k: &str) -> Result<String, String> {
match a.0.get(k) {
Some(Value::Number(n)) => Ok(n.to_string()),
_ => Ok(a.need_str(k)?.trim().to_string()),
}
}
const EXTRACT_MAX: u64 = 2_000_000;
fn extract_values(r: &mut Run, pat: &Pattern, top: usize) -> Result<Output, String> {
let buf = r.buf;
let q = pat.query();
let m = matcher(r, &q)?;
let groups = m.regex().map(|re| re.captures_len()).unwrap_or(1);
let mut map: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
let (mut matches, mut capped, mut other) = (0u64, false, 0u64);
let end = search::search_forward(buf, &m, 0..buf.len(), r.cancel, None, |s, e| {
matches += 1;
if matches > EXTRACT_MAX {
capped = true;
return false;
}
let v = if groups > 1 {
search::group_text(buf, &m, s, e, 1).unwrap_or_default()
} else {
buf.read(s..e.min(s + 400))
.map(|b| buf.codec.decode_lossy(&b))
.unwrap_or_default()
};
let v: String = v.chars().take(200).collect();
if map.len() < 100_000 || map.contains_key(&v) {
*map.entry(v).or_default() += 1;
} else {
other += 1;
}
true
});
ended(end)?;
let mut values: Vec<(String, u64)> = map.into_iter().collect();
values.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
let list: Vec<Value> = values
.iter()
.take(top)
.map(|(v, n)| json!({"value": (r.redact)(v), "matches": n}))
.collect();
let n = values.len() as u64;
let mut v = json!({"matches": matches.min(EXTRACT_MAX), "distinct_values": n, "top": list});
if capped {
v["stopped_after"] = json!(EXTRACT_MAX);
}
if other > 0 {
v["matches_of_other_values"] = json!(other);
}
let mut o = Output::new(v, "{n} values", Some(n));
o.show = Some(Show::FindAll {
query: q,
times: Times::default(),
});
Ok(o)
}
fn table(buf: &TextBuf, name: &str) -> Result<(crate::csv::TableGuess, Vec<String>), String> {
let bom = buf.codec.bom_len as u64;
let sample = buf
.read(bom..buf.len().min(bom + 64 * 1024))
.ok_or("the file could not be read")?;
let preferred = if name.to_ascii_lowercase().ends_with(".tsv") {
b'\t'
} else {
b','
};
let g = crate::csv::detect_table(
&buf.codec,
&sample,
bom + sample.len() as u64 == buf.len(),
preferred,
bom,
);
let mut names = Vec::new();
crate::csv::for_each_record(buf, g.dialect, &CancelToken::new(), None, |rec| {
names = rec
.fields
.iter()
.filter_map(|f| {
buf.read(f.clone())
.map(|b| crate::csv::field_value(&buf.codec, g.dialect, &b))
})
.collect();
false
});
if names.len() < 2 {
return Err("this does not look like a CSV or TSV table".into());
}
Ok((g, names))
}
fn column_of(g: &crate::csv::TableGuess, names: &[String], col: &str) -> Result<usize, String> {
if let Ok(n) = col.parse::<usize>() {
if n >= 1 && n <= names.len() {
return Ok(n - 1);
}
return Err(format!("the table has columns 1 to {}", names.len()));
}
let found = names.iter().position(|n| n.trim() == col).or_else(|| {
names
.iter()
.position(|n| n.trim().eq_ignore_ascii_case(col))
});
match found {
Some(i) if g.header => Ok(i),
_ => Err(format!(
"no column named \"{col}\"; the columns are: {}",
names.iter().map(|n| clip(n)).collect::<Vec<_>>().join(", ")
)),
}
}
fn scan_end(e: crate::csv::ScanEnd) -> Result<(), String> {
match e {
crate::csv::ScanEnd::Cancelled => Err(CANCELLED.into()),
crate::csv::ScanEnd::Failed => Err("the file could not be read".into()),
_ => Ok(()),
}
}
fn table_rows(
r: &mut Run,
conds: &[(String, crate::csv::CondOp, String)],
) -> Result<Output, String> {
let buf = r.buf;
let (g, names) = table(buf, r.name)?;
let mut cs = Vec::new();
for (col, op, value) in conds {
cs.push(crate::csv::Cond {
col: column_of(&g, &names, col)?,
op: *op,
value: value.clone(),
});
}
let d = g.dialect;
let codec = buf.codec;
let (mut kept, mut rows) = (0u64, 0u64);
let mut first: Vec<(u64, u64)> = Vec::new();
let mut header = g.header;
let end = crate::csv::for_each_record(buf, d, r.cancel, None, |rec| {
if header {
header = false;
return true;
}
rows += 1;
let ok = cs.iter().all(|c| {
let v = rec
.fields
.get(c.col)
.and_then(|f| rec.bytes(buf, f))
.map(|b| crate::csv::field_str(&codec, d, &b).into_owned())
.unwrap_or_default();
c.test(&v)
});
if ok {
kept += 1;
if first.len() < RESULT_LINES {
first.push((rec.content.start, rec.content.end));
}
}
true
});
scan_end(end)?;
let mut s = Sampler::new(RESULT_LINES);
for (a, b) in first {
s.push(r, a, b);
}
let v = json!({"rows": kept, "of_rows": rows, "header": names.iter().map(|n| clip(n)).collect::<Vec<_>>(), "first_rows": s.out});
let mut o = Output::new(v, "{n} rows", Some(kept));
o.lines = s.lines;
Ok(o)
}
fn column_stats(r: &mut Run, column: &str) -> Result<Output, String> {
let buf = r.buf;
let (g, names) = table(buf, r.name)?;
let col = column_of(&g, &names, column)?;
let st = crate::csv::column_stats(buf, g.dialect, col, g.header, r.cancel, None).map_err(
|e| match e {
crate::csv::ScanEnd::Cancelled => CANCELLED.to_string(),
_ => "the file could not be read".to_string(),
},
)?;
let top: Vec<Value> = st
.top
.iter()
.take(15)
.map(|(v, n)| json!({"value": (r.redact)(&clip(v)), "rows": n}))
.collect();
let mut v = json!({
"column": clip(&names[col]),
"rows": st.rows,
"empty": st.empty,
"numbers": st.numeric,
"distinct_values": st.distinct,
"top": top,
});
if st.numeric > 0 {
v["sum"] = json!(st.sum);
v["min"] = json!(st.min);
v["max"] = json!(st.max);
v["mean"] = json!(st.mean());
}
if st.distinct_capped {
v["distinct_at_least"] = json!(true);
}
Ok(Output::new(v, "{n} rows", Some(st.rows)))
}
fn group_by(r: &mut Run, column: &str, sum: Option<&str>, top: usize) -> Result<Output, String> {
let buf = r.buf;
let (g, names) = table(buf, r.name)?;
let key = column_of(&g, &names, column)?;
let value = match sum {
Some(s) => Some(column_of(&g, &names, s)?),
None => None,
};
let gr = crate::csv::group_by(buf, g.dialect, key, value, g.header, r.cancel, None).map_err(
|e| match e {
crate::csv::ScanEnd::Cancelled => CANCELLED.to_string(),
_ => "the file could not be read".to_string(),
},
)?;
let list: Vec<Value> = gr
.groups
.iter()
.take(top)
.map(|x| {
let mut j = json!({"value": (r.redact)(&clip(&x.key)), "rows": x.rows});
if value.is_some() && x.numeric > 0 {
j["sum"] = json!(x.sum);
j["min"] = json!(x.min);
j["max"] = json!(x.max);
j["mean"] = json!(x.mean());
}
j
})
.collect();
let n = gr.groups.len() as u64;
let mut v = json!({"column": clip(&names[key]), "rows": gr.rows, "groups": n, "top": list});
if let Some(c) = value {
v["sum_column"] = json!(clip(&names[c]));
}
if gr.capped {
v["too_many_groups"] = json!(true);
}
Ok(Output::new(v, "{n} groups", Some(n)))
}
fn top_values(r: &mut Run, field: &str, top: usize) -> Result<Output, String> {
let buf = r.buf;
if buf.codec.unit() != 1 {
return Err("counting values needs a UTF-8 file".into());
}
let (values, lines, without): (Vec<(String, u64)>, u64, u64) = if let Some(f) = log_format(buf)
{
let col = f
.columns
.iter()
.position(|c| c.eq_ignore_ascii_case(field))
.ok_or_else(|| {
format!(
"the log has no column \"{field}\"; its columns are: {}",
f.columns.join(", ")
)
})?;
let mut sp = crate::logformat::Splitter::new(&f);
let mut map: std::collections::HashMap<Vec<u8>, u64> = std::collections::HashMap::new();
let (mut with, mut without) = (0u64, 0u64);
let mut lr = crate::lines::LineReader::new(buf);
let mut n = 0u32;
while let Some((_, l)) = lr.next().map_err(|e| e.to_string())? {
n = n.wrapping_add(1);
if n.is_multiple_of(4096) && r.cancel.is_cancelled() {
return Err(CANCELLED.into());
}
if sp.split(l) != crate::logformat::Split::Row {
without += 1;
continue;
}
let v = sp.values(l);
match v.get(col) {
Some(x) if map.len() < 100_000 || map.contains_key(x.as_ref()) => {
*map.entry(x.to_vec()).or_default() += 1;
with += 1;
}
_ => without += 1,
}
}
let mut v: Vec<(String, u64)> = map
.into_iter()
.map(|(k, n)| (String::from_utf8_lossy(&k).into_owned(), n))
.collect();
v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
(v, with, without)
} else {
let head = buf
.read(0..buf.len().min(4096))
.map(|b| b.to_vec())
.unwrap_or_default();
let first = String::from_utf8_lossy(&head);
let syntax = first
.lines()
.find_map(|l| crate::fields::line_fields(l).map(|f| f.0))
.ok_or("top_values needs JSON Lines, logfmt or a web server or syslog log")?;
let c = crate::fields::value_counts(buf, field, syntax, r.cancel, None)
.map_err(|e| e.to_string())?
.ok_or(CANCELLED)?;
(
c.values
.iter()
.map(|v| (v.value.clone(), v.lines))
.collect(),
c.lines,
c.without,
)
};
let list: Vec<Value> = values
.iter()
.take(top)
.map(|(v, n)| json!({"value": (r.redact)(&clip(v)), "lines": n}))
.collect();
let n = values.len() as u64;
let v = json!({"field": field, "lines_with_field": lines, "lines_without": without, "distinct_values": n, "top": list});
let mut o = Output::new(v, "{n} values", Some(n));
o.show = Some(Show::TopValues(field.to_string()));
Ok(o)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ai::profile::tests::buf;
const LOG: &str = "2024-05-01 10:00:00 INFO start user=alice\n\
2024-05-01 10:00:01 ERROR db timeout after 5000 ms\n\
2024-05-01 10:00:02 WARN slow query 1200 ms\n\
2024-05-01 10:00:03 ERROR db timeout after 5001 ms\n\
2024-05-01 10:20:00 INFO request done status=200\n\
2024-05-01 10:20:01 [error] payment failed\n";
fn go(text: &str, name: &str, input: Value) -> Result<Output, String> {
let (_f, b) = buf(text);
let call = parse(name, &input)?;
let cancel = CancelToken::new();
let mut id = |s: &str| s.to_string();
let mut r = Run {
buf: &b,
cancel: &cancel,
name: "app.log",
selection: Some((0, 10)),
bookmarks: &[0, 137],
redact: &mut id,
};
run(&mut r, &call)
}
#[test]
fn every_tool_has_a_valid_schema() {
for t in TOOLS {
let s = t.spec();
assert_eq!(s.schema["type"], "object", "{}", t.name);
assert_eq!(s.schema["additionalProperties"], false, "{}", t.name);
for r in s.schema["required"].as_array().unwrap() {
assert!(
s.schema["properties"].get(r.as_str().unwrap()).is_some(),
"{}: {r}",
t.name
);
}
assert!(t.description.len() > 40, "{}", t.name);
}
assert!(specs(false)
.iter()
.all(|s| tool(&s.name).unwrap().kind != Kind::Write));
assert_eq!(specs(true).len(), TOOLS.len());
}
#[test]
fn arguments_are_checked_with_fixable_errors() {
let e = parse("find_all", &json!({"pattern": "(error", "regex": true})).unwrap_err();
assert!(e.contains("does not compile"), "{e}");
let e = parse("find_all", &json!({"pattern": "x", "colour": 1})).unwrap_err();
assert!(e.contains("unknown argument \"colour\""), "{e}");
let e = parse("filter_lines", &json!({"pattern": "x", "context": 50})).unwrap_err();
assert!(e.contains("from 0 to 20"), "{e}");
let e = parse("find_all", &json!({"pattern": "x", "from": "yesterday"})).unwrap_err();
assert!(e.contains("not a time"), "{e}");
let e = parse("grep", &json!({})).unwrap_err();
assert!(e.contains("there is no tool"), "{e}");
let e = parse("find_all", &Value::String("{bad".into())).unwrap_err();
assert!(e.contains("not valid JSON"), "{e}");
let e = parse("field_query", &json!({"query": ".status >>> 5"})).unwrap_err();
assert!(e.contains("does not parse"), "{e}");
let c = parse("context", &json!({"line": "12", "before": 2})).unwrap();
assert_eq!(
c,
Call::Context {
line: 12,
before: 2,
after: 10
}
);
let c = parse("levels", &json!({"levels": "warn"})).unwrap();
assert_eq!(
c,
Call::Levels {
levels: Levels::only(Level::Warn),
times: Times::default()
}
);
}
#[test]
fn find_all_counts_and_lists_lines() {
let o = go(LOG, "find_all", json!({"pattern": "timeout"})).unwrap();
assert_eq!(o.n, Some(2));
assert_eq!(o.lines, vec![2, 4]);
assert_eq!(
o.for_model["first_lines"][0]["text"],
"2024-05-01 10:00:01 ERROR db timeout after 5000 ms"
);
assert!(matches!(o.show, Some(Show::FindAll { .. })));
let o = go(
LOG,
"find_all",
json!({"pattern": "\\d{4} ms", "regex": true, "to": "2024-05-01 10:00:01"}),
)
.unwrap();
assert_eq!(o.n, Some(1));
assert_eq!(o.for_model["time_range_lines"], json!([1, 2]));
}
#[test]
fn count_and_filter() {
let o = go(
LOG,
"count",
json!({"pattern": "error", "ignore_case": true}),
)
.unwrap();
assert_eq!(o.n, Some(3));
let o = go(
LOG,
"count",
json!({"pattern": "error", "ignore_case": true, "invert": true}),
)
.unwrap();
assert_eq!(o.n, Some(3));
let o = go(
LOG,
"filter_lines",
json!({"pattern": "INFO", "context": 1}),
)
.unwrap();
assert_eq!(o.n, Some(2));
assert!(matches!(o.show, Some(Show::Filter { context: 1, .. })));
}
#[test]
fn levels_are_counted_per_line() {
let o = go(LOG, "levels", json!({"levels": ["error"]})).unwrap();
assert_eq!(
o.for_model["lines_per_level"],
json!({"error": 3, "warn": 1, "info": 2, "debug": 0})
);
assert_eq!(o.n, Some(3));
assert_eq!(o.lines, vec![2, 4, 6]);
assert_eq!(level_of("level=error"), Some(Level::Error));
assert_eq!(level_of("[Warning]"), Some(Level::Warn));
assert_eq!(level_of("\"level\":\"debug"), Some(Level::Debug));
}
#[test]
fn field_queries_and_top_values() {
let jl = "{\"level\":\"error\",\"status\":500,\"user\":\"a\"}\n{\"level\":\"info\",\"status\":200,\"user\":\"b\"}\n{\"level\":\"error\",\"status\":503,\"user\":\"a\"}\n";
let o = go(jl, "field_query", json!({"query": ".status >= 500"})).unwrap();
assert_eq!(o.n, Some(2));
let o = go(jl, "top_values", json!({"field": "user"})).unwrap();
assert_eq!(o.for_model["top"][0], json!({"value": "a", "lines": 2}));
let web =
"1.2.3.4 - - [01/May/2024:10:00:00 +0000] \"GET /a HTTP/1.1\" 200 12 \"-\" \"x\"\n\
5.6.7.8 - - [01/May/2024:10:00:01 +0000] \"GET /b HTTP/1.1\" 500 12 \"-\" \"x\"\n\
1.2.3.4 - - [01/May/2024:10:00:02 +0000] \"POST /a HTTP/1.1\" 200 12 \"-\" \"x\"\n";
let o = go(web, "top_values", json!({"field": "status"})).unwrap();
assert_eq!(o.for_model["top"][0], json!({"value": "200", "lines": 2}));
let e = go(web, "top_values", json!({"field": "nope"})).unwrap_err();
assert!(e.contains("its columns are"), "{e}");
}
#[test]
fn reading_lines_and_context() {
let o = go(LOG, "read_lines", json!({"start_line": 5, "count": 3})).unwrap();
assert_eq!(o.for_model["lines"].as_array().unwrap().len(), 2);
assert_eq!(o.for_model["lines"][0]["line"], 5);
let o = go(LOG, "context", json!({"line": 2, "before": 1, "after": 1})).unwrap();
let l = o.for_model["lines"].as_array().unwrap();
assert_eq!(l.len(), 3);
assert_eq!(l[1]["this"], true);
assert!(go(LOG, "read_lines", json!({"start_line": 99}))
.unwrap_err()
.contains("has 7 lines"));
let o = go(LOG, "bookmarks", json!({})).unwrap();
assert_eq!(o.lines, vec![1, 4]);
assert_eq!(
o.for_model["shown"][1]["lines"].as_array().unwrap().len(),
5
);
let o = go(LOG, "selection", json!({})).unwrap();
assert_eq!(o.for_model["text"], "2024-05-01");
}
#[test]
fn time_tools() {
let o = go(LOG, "time_gaps", json!({"min": "5m"})).unwrap();
assert_eq!(o.n, Some(1));
assert_eq!(o.for_model["longest"][0]["line_after"], 5);
let o = go(LOG, "histogram", json!({"pattern": "ERROR"})).unwrap();
assert_eq!(o.for_model["hits"], 2);
let o = go(LOG, "time_range", json!({"from": "2024-05-01 10:20:00"})).unwrap();
assert_eq!(o.for_model["first_line"], 5);
assert!(go("no times here\n", "histogram", json!({})).is_err());
}
#[test]
fn message_patterns() {
let o = go(LOG, "message_patterns", json!({"pattern": "timeout"})).unwrap();
assert_eq!(o.for_model["templates"], 1);
assert_eq!(o.for_model["top"][0]["lines"], 2);
}
#[test]
fn write_tools_only_prepare_a_change() {
let o = go(
LOG,
"replace_all",
json!({"pattern": "(\\d+) ms", "regex": true, "replacement": "${1}ms"}),
)
.unwrap();
assert_eq!(o.n, Some(3));
assert_eq!(o.preview[0].2, "5000ms");
assert!(matches!(
&o.change,
Some(Change::ReplaceAll { count: 3, .. })
));
let o = go(LOG, "delete_lines", json!({"pattern": "timeout"})).unwrap();
assert_eq!(o.n, Some(2));
let Some(Change::ReplaceAll { query, .. }) = &o.change else {
panic!()
};
let (_f, b) = buf(LOG);
let m = Matcher::new(query, Codec::utf8()).unwrap();
let mut hits = Vec::new();
search::search_forward(&b, &m, 0..b.len(), &CancelToken::new(), None, |s, e| {
hits.push((s, e));
true
});
let first = b.read(hits[0].0..hits[0].1).unwrap().to_vec();
assert_eq!(
String::from_utf8(first).unwrap(),
"2024-05-01 10:00:01 ERROR db timeout after 5000 ms\n"
);
let o = go(
LOG,
"replace_lines",
json!({"start_line": 2, "end_line": 3, "text": "one\ntwo"}),
)
.unwrap();
let Some(Change::ReplaceRange { range, text }) = &o.change else {
panic!()
};
assert_eq!(text, "one\ntwo\n");
assert_eq!(
range.end - range.start,
(LOG.lines().nth(1).unwrap().len() + LOG.lines().nth(2).unwrap().len() + 2) as u64
);
assert!(go(
LOG,
"replace_all",
json!({"pattern": "zzz", "replacement": ""})
)
.unwrap_err()
.contains("nothing matches"));
}
#[test]
fn values_of_a_capture_group() {
let web = "GET /a 200\nGET /b 500\nPOST /a 200\nGET /a 404\n";
let o = go(web, "extract_values", json!({"pattern": "^\\w+ (/\\w+)"})).unwrap();
assert_eq!(o.for_model["matches"], 4);
assert_eq!(o.for_model["top"][0], json!({"value": "/a", "matches": 3}));
let o = go(web, "extract_values", json!({"pattern": "\\d{3}$"})).unwrap();
assert_eq!(o.for_model["top"][0], json!({"value": "200", "matches": 2}));
assert!(parse("extract_values", &json!({"pattern": "(x"})).is_err());
}
#[test]
fn table_questions() {
let csv =
"city,age,amount\nTashkent,31,10.5\nSamarkand,25,3\nTashkent,45,1.5\nBukhara,31,\n";
let o = go(
csv,
"table_rows",
json!({"conditions": [
{"column": "city", "op": "is", "value": "tashkent"},
{"column": "age", "op": "greater", "value": 30}
]}),
)
.unwrap();
assert_eq!(o.for_model["rows"], 2);
assert_eq!(o.for_model["of_rows"], 4);
assert_eq!(o.lines, vec![2, 4]);
let o = go(csv, "column_stats", json!({"column": "amount"})).unwrap();
assert_eq!(o.for_model["sum"], 15.0);
assert_eq!(o.for_model["empty"], 1);
let o = go(
csv,
"group_by",
json!({"column": 1, "sum_column": "amount"}),
)
.unwrap();
assert_eq!(o.for_model["top"][0]["value"], "Tashkent");
assert_eq!(o.for_model["top"][0]["sum"], 12.0);
let e = go(csv, "column_stats", json!({"column": "price"})).unwrap_err();
assert!(e.contains("the columns are: city, age, amount"), "{e}");
assert!(go("just text\n", "column_stats", json!({"column": "a"})).is_err());
let c = parse(
"table_rows",
&json!({"conditions": [{"column": "a", "op": "empty"}]}),
)
.unwrap();
assert_eq!(parse(c.name(), &c.input()).unwrap(), c);
}
#[test]
fn hints_and_short_forms() {
let o = go(LOG, "count", json!({"pattern": "timeout\\b"})).unwrap();
assert_eq!(o.n, Some(0));
assert!(o.for_model["hint"].as_str().unwrap().contains("regex"));
let o = go(LOG, "find_all", json!({"pattern": "C:\\data"})).unwrap();
assert!(o.for_model.get("hint").is_some());
let o = go(LOG, "count", json!({"pattern": "timeout"})).unwrap();
assert!(o.for_model.get("hint").is_none());
assert_eq!(
parse("time_gaps", &json!({"min": 90})).unwrap(),
Call::TimeGaps { min_ms: 90_000 }
);
let c = parse("table_rows", &json!({"conditions": [{"column": "city", "is": "Tashkent"}, {"column": "age", "greater": 30}]})).unwrap();
assert_eq!(
c,
Call::TableRows {
conds: vec![
("city".into(), crate::csv::CondOp::Equals, "Tashkent".into()),
("age".into(), crate::csv::CondOp::Greater, "30".into())
]
}
);
assert!(parse(
"table_rows",
&json!({"conditions": [{"column": "city", "near": "x"}]})
)
.is_err());
}
#[test]
fn plain_mistakes_in_arguments_are_forgiven() {
let q = |s: &str| field_query_text(s);
assert_eq!(q(".status >= 500").unwrap(), ".status >= 500");
assert_eq!(q("user.id == 7").unwrap(), ".user.id == 7");
assert_eq!(q("status=404").unwrap(), ".status=404");
assert_eq!(
q("client == '10.0.0.5'").unwrap(),
".client == \"10.0.0.5\""
);
assert_eq!(
q("level == error && status == 503").unwrap(),
".level == error && .status == 503"
);
assert_eq!(
q("(method in (\"GET\", \"POST\")) and not url contains \"/a b\"").unwrap(),
"(.method in (\"GET\", \"POST\")) and not .url contains \"/a b\""
);
let e = q("status:5*").unwrap_err();
assert!(e.contains("fields start with a dot"), "{e}");
let c = parse(
"table_rows",
&json!({"conditions": [{"column": "age", "operator": "gt", "value": 30}]}),
)
.unwrap();
assert_eq!(
c,
Call::TableRows {
conds: vec![("age".into(), crate::csv::CondOp::Greater, "30".into())]
}
);
let e = parse("filter_lines", &json!({"pattern": "x", "from": 2})).unwrap_err();
assert!(e.contains("not line numbers"), "{e}");
}
#[test]
fn edited_call_keeps_its_other_arguments() {
let c = parse("filter_lines", &json!({"pattern": "a", "invert": true})).unwrap();
let d = c.with_pattern("b").unwrap();
assert_eq!(d.pattern().unwrap().text, "b");
assert_eq!(parse(d.name(), &d.input()).unwrap(), d);
for name in [
"find_all",
"levels",
"message_patterns",
"time_gaps",
"bookmark",
] {
let input = match name {
"find_all" => json!({"pattern": "x", "from": "10:00"}),
"bookmark" => json!({"lines": [3, 1]}),
_ => json!({}),
};
let c = parse(name, &input).unwrap();
assert_eq!(parse(c.name(), &c.input()).unwrap(), c, "{name}");
}
}
}