use std::io::{self, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::csv;
use crate::encoding::{self, Detected};
use crate::file::{display_path, OpenMode, Source};
use crate::filter::{self, FilterSpec};
use crate::index::LineIndex;
use crate::jobs::{human_bytes, CancelToken, Progress};
use crate::lines::LineReader;
use crate::loglevel::{self, Level, Levels};
use crate::merge::{self, Input};
use crate::search::{Matcher, Query};
use crate::split::{self, SplitBy};
use crate::table_export::{self, Format};
use crate::text::TextBuf;
use crate::timestamp;
pub const USAGE: &str = "\
bigtext-cli: BigText's tools for scripts (bigtext --COMMAND works too)
COMMAND --help (or -h) prints only that command's part of this help;
--version (or -V) prints the version.
filter [-v] [-i] [-w] [-E] [CONTEXT] PATTERN FILE [-o OUT]
Lines with a match (-v: without one; -i: ignore case; -w: whole words;
-E: regular expression). To OUT in the file's encoding, or to the
console. Exit code 1 when no line matched.
More patterns: -e PAT (each must match; with --any, one of them does),
--not PAT (must not match); all can be repeated.
levels ERROR,WARN,INFO,DEBUG [CONTEXT] FILE [-o OUT]
Lines of these log levels.
CONTEXT of filter and levels: -A N / -B N / -C N lines after / before /
around each line, --entries the whole log entry (a stack trace under the
line), -n line numbers (\"12:\" a match, \"13-\" context); \"--\" between
groups; --from TIME / --to TIME only the lines between those times
(\"14:30\", \"2024-05-01 14:30:00\"; --to includes its second).
extract [-i] [-w] [-E] [-g N] [--count] PATTERN FILE [-o OUT]
Only the matched texts (or capture group N), one per line; with
--count, each different one with how often it matched, most first.
count [-v] [-i] [-w] [-E] PATTERN FILE
The number of lines with a match.
split (--size 100MB | --lines 1000000) FILE [--out-dir DIR]
[--gz|--zst|--xz|--bz2]
Parts name.part001.ext, … cut at line breaks (compressed: .ext.gz,
…); prints their paths. Sizes are binary: 100MB (or 100M, 100MiB) is
100 × 1,048,576 bytes; KB, GB and TB likewise.
stats [--fields] FILE...
Size, lines, encoding, line breaks by kind, the longest line, NUL and
non-UTF-8 bytes, and the first and last times;
with --fields, the key paths of JSON records (JSON Lines or an array's
items) with their types, counts, nulls, numbers and examples, as CSV.
merge FILE FILE... [-o OUT]
Log lines of all files in time order, each labelled with its file.
gaps FILE [--min 30s]
Places where the next timestamp is at least that much later (or
earlier: the clock went back), with line numbers; --min in ms, s, m
or min, h or d (not M, which could be a month). Exit code 1 when
there are none.
patterns FILE [--top N] [--rare] [-o OUT]
The log's message templates (numbers, ids, IPs and paths replaced by
<n>, <hex>, <ip>, <path>) with how many lines each has, as CSV, most
lines first (--rare: fewest first).
join LEFT RIGHT (--on COL | --left-on COL --right-on COL) [--inner] [-o OUT]
Each row of the LEFT table with the other columns of the RIGHT table's
rows with the same key (COL: a header name or a 1-based number), as
CSV; rows without a match get empty fields, or are left out (--inner).
jsonl FILE [-q QUERY] [-v] [--fields a,b.c] [--to jsonl|csv] [--count]
[-o OUT]
query FILE -q QUERY ... (the same)
Lines that meet a field query: JSON Lines, logfmt (key=value), or a web
server or syslog log by its columns (.status >= 500 and .method = POST).
==, !=, <, >, <=, >=, in (a, b), contains, ~ regex, exists, missing,
joined with and, or, not and parentheses; a time value without a date
compares with the time of day (.time >= 10:00). As they are, only some
fields (--fields), or as CSV; --count prints how many.
jsondiff A B
Two JSON files compared by structure, whatever the key order and the
formatting: path: old -> new, path: added, path: removed. Exit code 0
when they are the same, 1 when they differ.
diff A B [-w] [-i] [-t] [--mask RE] [-U N] [-q] [-o OUT]
A unified diff (diff -u) with N lines of context (3), of files of any
size; -w ignores white space, -i case, -t the timestamp at the start
of each line, --mask what RE matches (ids, durations); -q only says
whether they differ. Exit code 0 when they are the same, 1 when they
differ.
only-in A B [-w] [-i] [-t] [--mask RE] [--count] [-o OUT]
The lines of A that occur nowhere in B, whatever their order, in A's
order (files of any size); -w, -i, -t and --mask as for diff; --count
prints how many. Exit code 0 when there are none, 1 when there are.
diff-table A B (--on COL | --left-on COL --right-on COL) [--all] [-o OUT]
Two tables compared by a key column (COL: a header name or a 1-based
number; --right-on when B's differs) whatever their row order, as CSV:
status (changed, removed, added; same with --all), the key, the
changed columns, and A's columns with \"old → new\" where a value
changed. Columns pair up by header name. Exit code 0 when they are the
same, 1 when they differ.
csv FILE cut COLS | drop COLS | sort --by COL [--desc] | where COND... |
stats COL | group COL [--sum COL]
[-o OUT] [--delimiter X] [--no-header]
The table view's column tools, streamed: keep or delete columns, sort
rows (files up to 1 GB), keep the rows where every condition holds
(col=v, col!=v, col~v contains, col>n, col<n; or col eq|ne|has|gt|lt v,
col empty, col nonempty — quote > and < for cmd.exe), a column's
statistics, or rows per value. Columns are header names or 1-based
numbers; --delimiter , ; | or tab.
replace [-i] [-w] [-E] PATTERN REPLACEMENT FILE [-o OUT | --in-place [--bak]]
Every match replaced by REPLACEMENT as written (with -E: $1, ${name},
\\n and \\t in it), streamed, keeping the encoding and line breaks;
--in-place swaps the file atomically (--bak keeps the old one).
Exit code 1 when nothing matched.
saved [--settings FILE]
The searches saved in BigText (the search bar's star menu);
filter, count and grep --saved NAME run one. Exit code 1 when there
are none, 2 when FILE is not a BigText settings file.
--json on filter, levels, grep, count, stats, replace (with -o or
--in-place), saved and csv stats gives one JSON record per line ({file,
line, offset, text, context}; errors as {\"error\": …}).
-- ends the options: a pattern after it may start with a dash.
grep [-i] [-w] [-E] PATTERN FILES... | -r DIR [--names '*.log;*.gz']
Find in files without a window: file:line:text for every line with a
match, over files, *.log patterns or a folder (compressed files are
unpacked on the way).
filter, count and levels take several FILES, *.log names and -r DIR
[--names] too (file: before each output line; count gives each file's
count and a total), and --out-dir DIR for one name.filtered.ext per input.
head [-n N] FILE [-o OUT]
tail [-n N] FILE [-o OUT]
The first or last N lines (10), read from that end only.
slice FILE (--lines A-B | --bytes A-B | --from TIME [--to TIME])
[--with-header] [-o OUT]
Lines A to B (1-based, inclusive), the lines around bytes A to B, or
the lines from one time to another (inclusive to the second; a --to
without a date is on --from's day), found by binary search in a time-
ordered log; --with-header puts line 1 first. Exit code 1 when nothing
is in the range.
sort [-r] [-n] [-i] [-u] FILE [-o OUT]
The lines sorted (-r reversed, -n by the number at their start, -i
ignoring case, -u each once), of a file of any size (temporary runs
and a merge).
uniq [-c] FILE [-o OUT]
Each line once, sorted; with -c, count<TAB>line, most frequent first.
transform --op upper|lower|trim|tabs|untabs FILE [-o OUT]
The file in UPPERCASE or lowercase, with trailing white space trimmed,
tabs as spaces or leading spaces as tabs (width 4), streamed.
format FILE [--style pretty|minify] [-o OUT]
JSON (or JSON Lines, a value per line) indented by two spaces (pretty,
the default) or with all insignificant white space removed (minify);
key order, numbers and escapes stay as written.
derive FILE --name NAME --expr EXPR [-o OUT]
The table with a new last column computed per row, like {price} * {qty},
substr({ts}, 0, 10) or if({status} = \"ok\", 1, 0).
pivot FILE --rows COL --cols COL [--value COL --agg sum|mean|min|max]
[--by hour|day|month] [-o OUT]
A pivot table as CSV: a row per value of --rows (or per hour, day or
month of a time column), a column per value of --cols, row counts or
the aggregated --value in the cells, and a total column.
validate FILE [--as csv|json|jsonl] [--no-header] [--numeric 3,5]
Checks a CSV / TSV table: rows with another field count, stray or
unclosed quotes, control characters, and (--numeric) text in number
columns (1-based). A JSON file is checked strictly as one value, a
JSON Lines file line by line; --as gives the kind when the file does
not look like it. Prints line: problem; exit code 1 when any.
report FILE [--urls | --minutes | --slow] [--top N] [-o OUT]
Reports of a web server log (nginx / Apache, AWS ALB or Classic ELB,
IIS): requests by status, the top URLs, the minutes with the most 5xx
errors and the slowest requests, as text (the first 10 of each, or
N); or one of them in full as CSV: --urls (requests, 4xx, 5xx, bytes
and times per URL), --minutes (requests, 4xx and 5xx per minute),
--slow (the 1,000 slowest requests with their line numbers).
redact FILE [-o OUT] [--ips] [--pattern RE]... [--no-tokens] [--no-urls]
[--no-keys] [--no-emails]
The file with secrets and personal data hidden, to share it: tokens
(also GitHub, AWS, Slack, Stripe and Google keys on their own),
Authorization and Cookie headers, secrets in URLs, password= and
\"secret\": values, e-mail addresses, with --ips IP addresses, with
--pattern more (its first group, or the match). Each becomes a label
like <email-3f9a2c>, the same for the same value in one run. What was
hidden is counted on stderr. The rules find common secrets, not every
one: look at the result before you share it.
sqldump FILE [tables | extract TABLE[,TABLE...] | split] [-o OUT]
[--out-dir DIR] [--no-settings]
A SQL dump (mysqldump, pg_dump's plain format, SQLite's .dump), read in
one pass: tables lists its tables with their rows and bytes as CSV;
extract writes those tables (CREATE, rows, keys, indexes, triggers and
for PostgreSQL their sequences) with the dump's opening and closing
settings, so the file restores on its own (--no-settings: without
them); split writes into --out-dir (the dump's folder) the files that
restore the dump in the order of their names: NAME.0-before-tables.sql
(functions, types), NAME.1-TABLE.sql per table, NAME.2-after-tables.sql
(views, routines, foreign keys added after the data).
values FIELD FILE [-o OUT]
The values of a JSON Lines or logfmt (key=value) field with how many
lines have each and their first and last time, as CSV, most frequent
first. Nested JSON keys: user.id.
convert FILE --to json|jsonl|md|xlsx|csv [--kind KIND] [--path $.a] [-o OUT]
A CSV / TSV table as JSON, JSON Lines, Markdown or Excel (.xlsx needs
-o); JSON Lines as CSV or one JSON array; a JSON array (or the one at
--path, or the first under the top object) as JSON Lines; logfmt
(key=value) lines, and nginx / Apache, AWS load balancer (ALB, Classic),
IIS and syslog logs, as CSV with a column per field. --kind
json|jsonl|logfmt|log|csv when the kind is not what it looks like.
The header and lines before the table (sep=;, comments) are detected;
--header / --no-header, --skip N and --quote ' override that (also
for validate).
ask FILE QUESTION... [--plan] [--json] [--provider ID] [--model M]
[--url URL] [--workspace ID] [--steps N] [--settings FILE]
Asks the AI provider set up in the app (AI -> AI settings) about the
file, as Ask BigText does: the model plans BigText's steps, which run
here, and gets only the file's profile and the steps' short results
(secrets hidden as the settings say). Prints each step on stderr and
the answer; --plan only prints the first step planned, without running
it; --json the answer, the steps and the tokens as JSON. It never
changes the file. --provider anthropic|openai|ollama|… and --model,
--url override the settings; the key comes from the provider's
environment variable (ANTHROPIC_API_KEY, …, BIGTEXT_AI_KEY) or the
system keychain. --workspace names the workspace for an Anthropic
organization key that is not scoped to one (or ANTHROPIC_WORKSPACE_ID).
Exit code 2 when the provider fails.
-o OUT ending in .gz, .zst, .xz or .bz2 is written compressed.
Exit codes: 0 done, 1 nothing found (for diff, only-in, jsondiff, diff-table
and validate: the files differ, or there are problems), 2 error.
";
const COMMANDS: [&str; 36] = [
"filter",
"levels",
"count",
"split",
"stats",
"merge",
"convert",
"report",
"sqldump",
"redact",
"values",
"gaps",
"patterns",
"extract",
"validate",
"join",
"pivot",
"derive",
"jsonl",
"query",
"jsondiff",
"diff",
"only-in",
"diff-table",
"transform",
"format",
"sort",
"uniq",
"head",
"tail",
"slice",
"grep",
"replace",
"saved",
"csv",
"ask",
];
pub fn is_command(arg: &str) -> bool {
arg.strip_prefix("--")
.is_some_and(|name| COMMANDS.contains(&name))
}
const HELP: &str = "\0help";
pub fn command_help(cmd: &str) -> Option<String> {
let depth = |l: &str| l.len() - l.trim_start_matches(' ').len();
let heads = |l: &str| depth(l) == 2 && l.split_whitespace().next() == Some(cmd);
let entry_start = |l: &str| {
depth(l) == 2
&& l.split_whitespace()
.next()
.is_some_and(|w| COMMANDS.contains(&w))
};
let names = |b: &[&str], c: &str| {
b.iter().any(|l| {
l.split(|ch: char| !(ch.is_ascii_lowercase() || ch == '-'))
.any(|w| w == c)
})
};
let mut blocks: Vec<Vec<&str>> = Vec::new();
let mut after_blank = true;
for line in USAGE.lines() {
if line.trim().is_empty() {
after_blank = true;
continue;
}
let d = depth(line);
let joins = blocks.last().is_some_and(|b| match (depth(b[0]), d) {
(2, 3..) => true,
(0, 0) => !after_blank,
(2, 2) => entry_start(b[0]) && entry_start(line) && !b.iter().any(|l| depth(l) == 8),
_ => false,
});
match blocks.last_mut() {
Some(b) if joins => b.push(line),
_ => blocks.push(vec![line]),
}
after_blank = false;
}
let entry = blocks
.iter()
.find(|b| entry_start(b[0]) && b.iter().any(|l| heads(l)))?;
let mut out: Vec<&str> = entry.clone();
for b in &blocks {
let note = depth(b[0]) == 2 && !entry_start(b[0]);
if note && (names(b, cmd) || !COMMANDS.iter().any(|c| names(b, c))) {
out.extend(b);
}
}
for b in blocks.iter().filter(|b| depth(b[0]) == 0).skip(1) {
out.push("");
out.extend(b);
}
Some(out.join("\n") + "\n")
}
struct Fail(String);
impl From<io::Error> for Fail {
fn from(e: io::Error) -> Fail {
Fail(e.to_string())
}
}
type Res<T> = Result<T, Fail>;
fn fail<T>(msg: impl Into<String>) -> Res<T> {
Err(Fail(msg.into()))
}
struct Args {
flags: Vec<String>,
opts: Vec<(String, String)>,
rest: Vec<String>,
}
impl Args {
fn parse(args: &[String], flags: &[&str], opts: &[&str]) -> Res<Args> {
let mut a = Args {
flags: Vec::new(),
opts: Vec::new(),
rest: Vec::new(),
};
let mut it = args.iter();
while let Some(x) = it.next() {
if x == "--" {
a.rest.extend(it.cloned());
break;
} else if flags.contains(&x.as_str()) {
a.flags.push(x.clone());
} else if opts.contains(&x.as_str()) {
let v = it
.next()
.ok_or_else(|| Fail(format!("{x} needs a value")))?;
a.opts.push((x.clone(), v.clone()));
} else if x == "-h" || x == "--help" {
return fail(HELP);
} else if x.starts_with('-') && x.len() > 1 && x.parse::<f64>().is_err() {
return fail(format!("unknown option {x}"));
} else {
a.rest.push(x.clone());
}
}
Ok(a)
}
fn flag(&self, names: &[&str]) -> bool {
self.flags.iter().any(|f| names.contains(&f.as_str()))
}
fn opt(&self, names: &[&str]) -> Option<&str> {
self.opts
.iter()
.rev()
.find(|(k, _)| names.contains(&k.as_str()))
.map(|(_, v)| v.as_str())
}
fn all(&self, names: &[&str]) -> Vec<&str> {
self.opts
.iter()
.filter(|(k, _)| names.contains(&k.as_str()))
.map(|(_, v)| v.as_str())
.collect()
}
}
thread_local! {
static JSON: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
fn json() -> bool {
JSON.with(|j| j.get())
}
thread_local! {
static TEMPS: std::cell::RefCell<Vec<PathBuf>> = const { std::cell::RefCell::new(Vec::new()) };
}
fn open(path: &Path) -> Res<(TextBuf, Detected)> {
let unpacked;
let path = match crate::decompress::detect(path) {
Some(kind) => {
let t =
crate::decompress::unpack(path, kind, &CancelToken::new(), &Progress::default())
.map_err(|e| Fail(format!("{}: {e}", display_path(path))))?
.ok_or_else(|| Fail("cancelled".into()))?;
TEMPS.with(|v| v.borrow_mut().push(t.clone()));
unpacked = t;
unpacked.as_path()
}
None => path,
};
let src = Source::open(path, OpenMode::Auto)
.map_err(|e| Fail(format!("{}: {e}", display_path(path))))?;
let n = src.len().min(1 << 20);
let det = encoding::detect(&src.read(0..n)?, n == src.len());
let len = src.len();
let mut buf = TextBuf::new(Arc::new(src), LineIndex::new(len), det.codec);
buf.blocking = true;
Ok((buf, det))
}
struct NoSeek<W>(W);
impl<W: Write> Write for NoSeek<W> {
fn write(&mut self, b: &[u8]) -> io::Result<usize> {
self.0.write(b)
}
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
impl<W> Seek for NoSeek<W> {
fn seek(&mut self, _: SeekFrom) -> io::Result<u64> {
Err(io::Error::other("cannot seek"))
}
}
fn with_output(
target: Option<&str>,
out: &mut dyn Write,
f: impl FnOnce(&mut dyn WriteSeek) -> Res<()>,
) -> Res<()> {
match target {
Some(t) => {
let path = PathBuf::from(t);
let temp = crate::save::temp_path_for(&path);
let file = crate::save::create_temp(&temp, &path)
.map_err(|e| Fail(format!("{}: {e}", display_path(&temp))))?;
let r = (|| {
let mut w = crate::decompress::Packer::new(
io::BufWriter::with_capacity(8 << 20, &file),
crate::decompress::target_kind(&path),
)?;
f(&mut w)?;
let mut w = w.finish()?;
w.flush()?;
drop(w);
file.sync_all()?;
Ok(())
})();
drop(file);
match r {
Ok(()) => crate::save::finalize(&temp, &path, false).map_err(Fail),
Err(e) => {
let _ = std::fs::remove_file(&temp);
Err(e)
}
}
}
None => {
let mut w = NoSeek(io::BufWriter::new(out));
f(&mut w)?;
w.flush()?;
Ok(())
}
}
}
trait WriteSeek: Write + Seek {}
impl<T: Write + Seek> WriteSeek for T {}
fn query(a: &Args, pattern: &str) -> Query {
Query {
pattern: pattern.to_string(),
regex: a.flag(&["-E", "--regex"]),
case_sensitive: !a.flag(&["-i", "--ignore-case"]),
whole_word: a.flag(&["-w", "--word"]),
dot_all: false,
}
}
#[allow(clippy::too_many_arguments)]
fn write_kept(
buf: &TextBuf,
file: &str,
m: &Matcher,
spec: FilterSpec,
terms: &[filter::Term],
numbers: bool,
target: Option<&str>,
out: &mut dyn Write,
) -> Res<u64> {
let cancel = CancelToken::new();
let mut kept = 0;
let json = json();
let numbers = numbers || json;
with_output(target, out, |w| {
let to_file = target.is_some() && !json;
if to_file && !numbers {
kept = filter::write_lines_to(buf, m, spec, terms, &mut &mut *w, &cancel, None)?
.map(|n| n.lines)
.unwrap_or(0);
return Ok(());
}
let codec = buf.codec;
let bom = codec.bom_len as u64;
if to_file && bom > 0 {
w.write_all(
&buf.read(0..bom)
.ok_or_else(|| Fail("could not read the file".into()))?,
)?;
}
let mut err: Option<io::Error> = None;
let mut prev: Option<u64> = None;
let mut counted = (0u64, 0u64);
let end = filter::filter_lines_with(buf, m, spec, terms, &cancel, None, |ls, le, kind| {
let r = (|| -> io::Result<()> {
if let Some(pe) = prev.filter(|&pe| spec.has_context() && ls > pe && !json) {
if to_file {
w.write_all(&codec.encode("--"))?;
w.write_all(&filter::line_break_before(buf, pe))?;
} else {
writeln!(w, "--")?;
}
}
prev = Some(le);
let mut prefix = String::new();
if numbers {
let mut n = counted.1;
buf.for_each_chunk(counted.0..ls, |base, c| {
n += codec.count_nl(c, base);
true
})
.ok_or_else(|| io::Error::other("could not read the file"))?;
counted = (ls, n);
prefix = format!(
"{}{}",
n + 1,
if kind == filter::LineKind::Hit {
':'
} else {
'-'
}
);
}
let bytes = buf
.read(ls.max(bom)..le)
.ok_or_else(|| io::Error::other("could not read the file"))?;
if json {
let text = codec.decode_lossy(&bytes);
let line: u64 = prefix.trim_end_matches([':', '-']).parse().unwrap_or(0);
let rec = serde_json::json!({"file": file, "line": line, "offset": ls, "text": text.trim_end_matches(['\n', '\r']), "context": kind != filter::LineKind::Hit});
return writeln!(w, "{rec}");
}
if to_file {
w.write_all(&codec.encode(&prefix))?;
w.write_all(&bytes)
} else {
let text = codec.decode_lossy(&bytes);
writeln!(w, "{prefix}{}", text.trim_end_matches(['\n', '\r']))
}
})();
if let Err(e) = r {
err = Some(e);
return false;
}
kept += 1;
true
});
match err {
Some(e) => Err(e.into()),
None if end == crate::search::SearchEnd::Unavailable => fail("could not read the file"),
None => Ok(()),
}
})?;
Ok(kept)
}
const CONTEXT_FLAGS: [&str; 3] = ["--entries", "-n", "--line-numbers"];
const CONTEXT_OPTS: [&str; 8] = [
"-A",
"--after",
"-B",
"--before",
"-C",
"--context",
"--from",
"--to",
];
fn spec_from(a: &Args, invert: bool) -> Res<FilterSpec> {
let num = |names: &[&str]| -> Res<Option<u32>> {
a.opt(names)
.map(|v| {
v.parse::<u32>()
.ok()
.filter(|&n| n <= filter::CONTEXT_MAX)
.ok_or_else(|| {
Fail(format!("not a line count (0-{}): {v}", filter::CONTEXT_MAX))
})
})
.transpose()
};
let around = num(&["-C", "--context"])?;
let before = num(&["-B", "--before"])?.or(around).unwrap_or(0);
let after = num(&["-A", "--after"])?.or(around).unwrap_or(0);
Ok(FilterSpec {
invert,
column: None,
before,
after,
entries: a.flag(&["--entries"]),
range: None,
})
}
fn time_range(a: &Args, buf: &TextBuf) -> Res<Option<(u64, u64)>> {
let (from, to) = (a.opt(&["--from"]), a.opt(&["--to"]));
if from.is_none() && to.is_none() {
return Ok(None);
}
let parse = |t: Option<&str>| {
t.map(|t| timestamp::parse(t).ok_or_else(|| Fail(format!("not a time: {t}"))))
.transpose()
};
match timestamp::time_range(buf, parse(from)?, parse(to)?, &CancelToken::new()) {
Ok(r) => Ok(Some(r)),
Err(_) => fail("the file has no timestamps"),
}
}
fn cmd_filter(args: &[String], out: &mut dyn Write, count_only: bool) -> Res<i32> {
let flags = [
&[
"-v",
"--invert",
"-i",
"--ignore-case",
"-w",
"--word",
"-E",
"--regex",
"--any",
][..],
&CONTEXT_FLAGS,
]
.concat();
let a = Args::parse(
args,
&flags,
&[
&["-o", "--output", "-e", "--pattern", "--not"][..],
&CONTEXT_OPTS,
]
.concat(),
)?;
if count_only && a.opt(&["-o", "--output"]).is_some() {
return fail("count prints a number and writes no file; redirect it instead (> FILE)");
}
let mut pats: Vec<String> = a
.all(&["-e", "--pattern"])
.into_iter()
.map(String::from)
.collect();
let file = match &a.rest[..] {
[pattern, file] => {
pats.insert(0, pattern.clone());
file
}
[file] if !pats.is_empty() => file,
_ => return fail("needs PATTERN (or -e PATTERN) and FILE"),
};
let (buf, _) = open(Path::new(file))?;
let any = a.flag(&["--any"]) && pats.len() > 1;
let driver = if any {
let regex = a.flag(&["-E", "--regex"]);
let alt: Vec<String> = pats
.iter()
.map(|p| {
format!(
"(?:{})",
if regex {
p.clone()
} else {
regex_syntax::escape(p)
}
)
})
.collect();
Query {
pattern: alt.join("|"),
regex: true,
..query(&a, "")
}
} else {
query(&a, &pats[0])
};
let m = Matcher::new(&driver, buf.codec).map_err(Fail)?;
let mut owned: Vec<(Matcher, bool)> = Vec::new();
for p in if any { &[][..] } else { &pats[1..] } {
owned.push((Matcher::new(&query(&a, p), buf.codec).map_err(Fail)?, false));
}
for p in a.all(&["--not"]) {
owned.push((Matcher::new(&query(&a, p), buf.codec).map_err(Fail)?, true));
}
let terms: Vec<filter::Term> = owned
.iter()
.map(|(m, negated)| filter::Term {
m,
negated: *negated,
})
.collect();
let mut spec = spec_from(&a, a.flag(&["-v", "--invert"]))?;
spec.range = time_range(&a, &buf)?;
let n = if count_only {
let mut n = 0u64;
filter::filter_lines_with(
&buf,
&m,
FilterSpec {
invert: spec.invert,
range: spec.range,
..Default::default()
},
&terms,
&CancelToken::new(),
None,
|_, _, _| {
n += 1;
true
},
);
if json() {
writeln!(out, "{}", serde_json::json!({"file": file, "count": n}))?;
} else {
writeln!(out, "{n}")?;
}
n
} else {
write_kept(
&buf,
file,
&m,
spec,
&terms,
a.flag(&["-n", "--line-numbers"]),
a.opt(&["-o", "--output"]),
out,
)?
};
Ok(if n > 0 { 0 } else { 1 })
}
fn cmd_levels(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(
args,
&CONTEXT_FLAGS,
&[&["-o", "--output"][..], &CONTEXT_OPTS].concat(),
)?;
let [names, file] = &a.rest[..] else {
return fail("needs LEVELS and FILE");
};
let mut levels = Levels::default();
for n in names.split(',').map(str::trim).filter(|n| !n.is_empty()) {
let l = Level::ALL.into_iter().find(|l| {
l.name().eq_ignore_ascii_case(n)
|| (n.eq_ignore_ascii_case("warning") && *l == Level::Warn)
});
match l {
Some(l) if !levels.contains(l) => levels = levels.toggled(l),
Some(_) => {}
None => return fail(format!("unknown level {n} (ERROR, WARN, INFO, DEBUG)")),
}
}
let q = loglevel::query(levels).ok_or_else(|| Fail("no levels".into()))?;
let (buf, _) = open(Path::new(file))?;
let m = Matcher::new(&q, buf.codec).map_err(Fail)?;
let spec = FilterSpec {
range: time_range(&a, &buf)?,
..spec_from(&a, false)?
};
let n = write_kept(
&buf,
file,
&m,
spec,
&[],
a.flag(&["-n", "--line-numbers"]),
a.opt(&["-o", "--output"]),
out,
)?;
Ok(if n > 0 { 0 } else { 1 })
}
fn parse_size(s: &str) -> Option<u64> {
let t = s.trim().to_ascii_lowercase();
let t = t.trim_end_matches('b');
let t = t.strip_suffix('i').unwrap_or(t);
let (num, mul) = match t.chars().last()? {
'k' => (&t[..t.len() - 1], 1u64 << 10),
'm' => (&t[..t.len() - 1], 1 << 20),
'g' => (&t[..t.len() - 1], 1 << 30),
't' => (&t[..t.len() - 1], 1 << 40),
_ => (t, 1),
};
let v: f64 = num.trim().parse().ok()?;
(v > 0.0).then_some((v * mul as f64) as u64)
}
fn cmd_split(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(
args,
&["--gz", "--zst", "--xz", "--bz2"],
&["--size", "--lines", "--out-dir"],
)?;
let [file] = &a.rest[..] else {
return fail("needs FILE");
};
let by = match (a.opt(&["--size"]), a.opt(&["--lines"])) {
(Some(s), None) => {
SplitBy::Bytes(parse_size(s).ok_or_else(|| Fail(format!("not a size: {s}")))?)
}
(None, Some(n)) => SplitBy::Lines(
n.parse()
.ok()
.filter(|&n| n > 0)
.ok_or_else(|| Fail(format!("not a line count: {n}")))?,
),
_ => return fail("give --size or --lines"),
};
let path = Path::new(file);
let dir = a
.opt(&["--out-dir"])
.map(PathBuf::from)
.or_else(|| path.parent().map(Path::to_path_buf))
.unwrap_or_default();
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "part".into());
let (buf, _) = open(path)?;
let pack = crate::decompress::Kind::ALL
.into_iter()
.find(|k| a.flag(&[&format!("--{}", k.extension())]));
let lower = file.to_ascii_lowercase();
let csv = if a.flag(&["--csv"]) || lower.ends_with(".csv") || lower.ends_with(".tsv") {
Some(split::CsvSplit {
dialect: table_of(&buf, file, &a)?.dialect,
repeat_header: a.flag(&["--repeat-header"]),
})
} else {
None
};
let parts = split::split_to_files(
&buf,
by,
&dir,
&name,
pack,
csv,
&CancelToken::new(),
&Progress::default(),
)?
.unwrap_or_default();
for p in &parts {
writeln!(out, "{}", display_path(p))?;
}
Ok(if parts.is_empty() { 1 } else { 0 })
}
fn cmd_stats(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(args, &["--fields"], &[])?;
if a.rest.is_empty() {
return fail("needs FILE");
}
if a.flag(&["--fields"]) {
for file in &a.rest {
let (buf, _) = open(Path::new(file))?;
let f = crate::json_fields::field_stats(&buf, &CancelToken::new(), None)
.map_err(Fail)?
.unwrap_or_default();
crate::json_fields::fields_to_csv(&f, &mut &mut *out)?;
}
return Ok(0);
}
for file in &a.rest {
let path = Path::new(file);
let (buf, det) = open(path)?;
let codec = buf.codec;
let Some(st) = crate::stats::scan(&buf.snapshot(), &CancelToken::new(), None, |_| {})
else {
return fail(format!("{}: could not read the file", display_path(path)));
};
if json() {
let span = crate::stats::time_span(&buf).map(|(f, l)| {
let key = |s: timestamp::Stamp| timestamp::format_key(s.ms, s.has_date, true);
(key(f), key(l))
});
let rec = serde_json::json!({
"file": display_path(path), "bytes": buf.len(), "lines": st.lines, "encoding": codec.enc.name(),
"lf": st.lf, "crlf": st.crlf, "cr": st.cr, "final_line_break": st.final_break,
"longest_line": {"bytes": st.longest.0, "line": st.longest.1 + 1}, "nul": st.nul, "not_utf8": st.invalid_utf8,
"first_time": span.as_ref().map(|s| s.0.clone()), "last_time": span.map(|s| s.1),
});
writeln!(out, "{rec}")?;
continue;
}
writeln!(out, "file: {}", display_path(path))?;
writeln!(
out,
"size: {} ({} bytes)",
human_bytes(buf.len()),
buf.len()
)?;
writeln!(out, "lines: {}", st.lines)?;
writeln!(out, "encoding: {}", codec.enc.name())?;
writeln!(
out,
"line endings: {} (LF {}, CRLF {}, CR {})",
det.line_ending.name(),
st.lf,
st.crlf,
st.cr
)?;
writeln!(
out,
"final line break: {}",
if st.final_break { "yes" } else { "no" }
)?;
writeln!(
out,
"longest line: {} bytes (line {})",
st.longest.0,
st.longest.1 + 1
)?;
if st.nul > 0 {
writeln!(
out,
"NUL bytes: {} (first at byte {})",
st.nul,
st.first_nul.unwrap_or(0)
)?;
}
if st.invalid_utf8 > 0 {
writeln!(
out,
"bytes that are not UTF-8: {} (first at byte {})",
st.invalid_utf8,
st.first_invalid.unwrap_or(0)
)?;
}
if let Some((f, l)) = crate::stats::time_span(&buf) {
let key = |s: timestamp::Stamp| timestamp::format_key(s.ms, s.has_date, true);
writeln!(out, "first time: {}", key(f))?;
writeln!(out, "last time: {}", key(l))?;
if f.has_date && l.has_date {
writeln!(
out,
"span: {}",
timestamp::format_delta(l.ms - f.ms).trim_start_matches('+')
)?;
}
}
if a.rest.len() > 1 {
writeln!(out)?;
}
}
Ok(0)
}
fn cmd_merge(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(args, &[], &["-o", "--output"])?;
if a.rest.len() < 2 {
return fail("needs two or more files");
}
let mut inputs = Vec::new();
let mut names: Vec<String> = Vec::new();
for f in &a.rest {
let p = Path::new(f);
let mut label = p
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| f.clone());
let base = label.clone();
let mut k = 1;
while names.contains(&label) {
k += 1;
label = format!("{base} ({k})");
}
names.push(label.clone());
inputs.push(Input {
buf: open(p)?.0,
label,
});
}
with_output(a.opt(&["-o", "--output"]), out, |w| {
merge::merge_to(&inputs, &mut &mut *w, &CancelToken::new(), None)?;
Ok(())
})?;
Ok(0)
}
fn sniff_kind(buf: &TextBuf) -> &'static str {
if crate::json::top_array(buf, &CancelToken::new()).is_some() {
return "json";
}
let mut r = LineReader::new(buf);
let mut lines = Vec::new();
while lines.len() < 10 {
let Ok(Some((_, l))) = r.next() else { break };
let t = l.trim_ascii();
if !t.is_empty() {
lines.push(t.to_vec());
}
}
match lines.first().and_then(|l| l.first()) {
Some(b'[') => "json",
Some(b'{')
if lines.len() > 1
&& lines
.iter()
.all(|l| l.first() == Some(&b'{') && l.last() == Some(&b'}')) =>
{
"jsonl"
}
Some(b'{') => "json",
_ if crate::logformat::Format::guess(&lines).is_some() => "log",
_ if lines
.iter()
.filter(|l| {
crate::fields::line_fields(&String::from_utf8_lossy(l))
.is_some_and(|f| f.0 == crate::fields::Syntax::Logfmt)
})
.count()
* 2
> lines.len() =>
{
"logfmt"
}
_ => "csv",
}
}
fn cmd_convert(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(
args,
&["--no-header", "--header"],
&[
"--to", "--kind", "--from", "--path", "-o", "--output", "--skip", "--quote",
],
)?;
let [file] = &a.rest[..] else {
return fail("needs FILE");
};
let to = a
.opt(&["--to"])
.ok_or_else(|| Fail("give --to json, jsonl, md, xlsx or csv".into()))?
.to_ascii_lowercase();
let target = a.opt(&["-o", "--output"]);
let (buf, _) = open(Path::new(file))?;
let cancel = CancelToken::new();
let from = match a.opt(&["--kind", "--from"]) {
Some(f) => f.to_ascii_lowercase(),
None => sniff_kind(&buf).to_string(),
};
match (from.as_str(), to.as_str()) {
("json", "jsonl") => {
let at = match a.opt(&["--path"]) {
Some(p) => crate::json::resolve(&buf, &crate::json::parse_path(p).map_err(Fail)?, &cancel).map_err(Fail)?.0,
None => crate::json::find_array(&buf, &cancel).map_err(Fail)?.0,
};
with_output(target, out, |w| {
crate::json::array_to_lines(&buf, at, &mut &mut *w, &cancel, None).map_err(Fail)?;
Ok(())
})?;
return Ok(0);
}
("jsonl", "json") => {
with_output(target, out, |w| {
crate::json::lines_to_array(&buf, &mut &mut *w, &cancel, None)?;
Ok(())
})?;
return Ok(0);
}
("jsonl", "csv") | ("json", "csv") => {
let array = match a.opt(&["--path"]) {
_ if from != "json" => None,
Some(p) => Some(
crate::json::resolve(&buf, &crate::json::parse_path(p).map_err(Fail)?, &cancel)
.map_err(Fail)?
.0,
),
None => crate::json::top_array(&buf, &cancel),
};
with_output(target, out, |w| {
match array {
Some(at) => crate::json::array_to_csv(&buf, at, &mut &mut *w, &cancel, None)?,
None => crate::json::jsonl_to_csv(&buf, &mut &mut *w, &cancel, None)?,
};
Ok(())
})?;
return Ok(0);
}
("log", "csv") => {
let f = crate::logformat::detect(&buf)?.ok_or_else(|| Fail(format!("{file}: not an nginx / Apache, AWS load balancer, IIS or syslog log")))?;
with_output(target, out, |w| {
crate::logformat::to_csv(&buf, &f, &mut &mut *w, &cancel, None)?;
Ok(())
})?;
return Ok(0);
}
("logfmt", "csv") => {
with_output(target, out, |w| {
crate::fields::logfmt_to_csv(&buf, &mut &mut *w, &cancel, None)?;
Ok(())
})?;
return Ok(0);
}
("csv", _) => {}
(f, t) => return fail(format!("cannot convert {f} to {t} (json → jsonl, jsonl → json or csv, logfmt or log → csv, csv → json, jsonl, md, xlsx)")),
}
let format = Format::ALL
.into_iter()
.find(|f| f.ext() == to || (to == "markdown" && *f == Format::Markdown))
.ok_or_else(|| Fail(format!("unknown format {to}")))?;
if format == Format::Xlsx && target.is_none() {
return fail("an .xlsx workbook needs -o FILE");
}
let g = table_of(&buf, file, &a)?;
let spec = table_export::Spec {
dialect: g.dialect,
cols: None,
header: g.header,
format,
};
with_output(target, out, |w| {
table_export::export(&buf, spec, w, &CancelToken::new(), None)?;
Ok(())
})?;
Ok(0)
}
fn cmd_report(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(
args,
&["--urls", "--minutes", "--slow"],
&["--top", "-o", "--output"],
)?;
let [file] = &a.rest[..] else {
return fail("needs FILE");
};
let top = a
.opt(&["--top"])
.map(|n| {
n.parse::<usize>()
.map_err(|_| Fail(format!("not a number: {n}")))
})
.transpose()?;
let (buf, _) = open(Path::new(file))?;
let f = crate::logformat::detect(&buf)?
.filter(|f| f.has_requests())
.ok_or_else(|| {
Fail(format!(
"{file}: not a web server log (nginx / Apache, AWS ALB or Classic ELB, IIS)"
))
})?;
let r =
crate::logformat::report(&buf, &f, &CancelToken::new(), None, |_| {})?.unwrap_or_default();
with_output(a.opt(&["-o", "--output"]), out, |w| {
let w = &mut &mut *w;
if a.flag(&["--urls"]) {
crate::logformat::urls_csv(&r, w, top)?;
} else if a.flag(&["--minutes"]) {
crate::logformat::minutes_csv(&r, w)?;
} else if a.flag(&["--slow"]) {
crate::logformat::slow_csv(&r, w, top)?;
} else {
crate::logformat::write_summary(&r, &f, w, top.unwrap_or(10))?;
}
Ok(())
})?;
Ok(if r.requests > 0 { 0 } else { 1 })
}
fn cmd_redact(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(
args,
&[
"--ips",
"--no-tokens",
"--no-urls",
"--no-keys",
"--no-emails",
],
&["-o", "--output", "--pattern"],
)?;
let [file] = &a.rest[..] else {
return fail("needs FILE");
};
let opts = crate::redact::Options {
tokens: !a.flag(&["--no-tokens"]),
urls: !a.flag(&["--no-urls"]),
keys: !a.flag(&["--no-keys"]),
emails: !a.flag(&["--no-emails"]),
ips: a.flag(&["--ips"]),
custom: a
.all(&["--pattern"])
.into_iter()
.map(String::from)
.collect(),
};
let mut r = crate::redact::Redactor::new(&opts, crate::redact::random_salt()).map_err(Fail)?;
let (buf, _) = open(Path::new(file))?;
with_output(a.opt(&["-o", "--output"]), out, |w| {
crate::redact::redact_to(&buf, 0..buf.len(), &mut r, w, &CancelToken::new(), None)?;
Ok(())
})?;
let hidden: Vec<String> = crate::redact::KINDS
.iter()
.zip(r.counts())
.filter(|(_, n)| *n > 0)
.map(|(k, n)| format!("{k} {n}"))
.collect();
eprintln!(
"hidden: {}",
if hidden.is_empty() {
"nothing".to_string()
} else {
hidden.join(", ")
}
);
Ok(0)
}
fn cmd_sqldump(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(args, &["--no-settings"], &["-o", "--output", "--out-dir"])?;
let (file, action, names) = match &a.rest[..] {
[f] => (f, "tables", None),
[f, act] => (f, act.as_str(), None),
[f, act, n] => (f, act.as_str(), Some(n.as_str())),
_ => return fail("needs FILE [tables | extract TABLE | split]"),
};
let (buf, _) = open(Path::new(file))?;
let cancel = CancelToken::new();
let dump = crate::sqldump::scan(&buf, &cancel, None, |_| {})?.unwrap_or_default();
let settings = !a.flag(&["--no-settings"]);
match (action, names) {
("tables", None) => {
with_output(a.opt(&["-o", "--output"]), out, |w| {
Ok(crate::sqldump::tables_csv(&dump, &mut &mut *w)?)
})?;
Ok(if dump.tables.is_empty() { 1 } else { 0 })
}
("extract", Some(names)) => {
let mut which = Vec::new();
for n in names.split(',').map(str::trim).filter(|n| !n.is_empty()) {
match dump.find(n) {
Some(i) => which.push(i),
None => {
return fail(format!(
"no table {n} in {file} (bigtext-cli sqldump {file} tables lists them)"
))
}
}
}
with_output(a.opt(&["-o", "--output"]), out, |w| {
crate::sqldump::write_tables(
&buf,
&dump,
&which,
if settings {
crate::sqldump::Extract::WHOLE
} else {
crate::sqldump::Extract::BARE
},
&mut &mut *w,
&cancel,
None,
)?;
Ok(())
})?;
Ok(0)
}
("split", None) => {
let path = Path::new(file);
let dir = a
.opt(&["--out-dir"])
.map(PathBuf::from)
.or_else(|| path.parent().map(Path::to_path_buf))
.unwrap_or_default();
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let stem = name
.trim_end_matches(".gz")
.trim_end_matches(".zst")
.trim_end_matches(".xz")
.trim_end_matches(".bz2")
.trim_end_matches(".sql")
.to_string();
std::fs::create_dir_all(&dir)?;
let files = crate::sqldump::split(&buf, &dump, &dir, &stem, settings, &cancel, None)?
.unwrap_or_default();
for (p, n) in &files {
writeln!(out, "{}\t{}", p.display(), human_bytes(*n))?;
}
Ok(if files.is_empty() { 1 } else { 0 })
}
_ => fail("needs tables, extract TABLE[,TABLE...] or split"),
}
}
fn cmd_values(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(args, &[], &["-o", "--output"])?;
let [key, file] = &a.rest[..] else {
return fail("needs FIELD and FILE");
};
let (buf, _) = open(Path::new(file))?;
let mut r = LineReader::new(&buf);
let mut syntax = crate::fields::Syntax::Logfmt;
while let Some((_, l)) = r.next()? {
match l.trim_ascii().first() {
None => continue,
Some(b'{') => syntax = crate::fields::Syntax::Json,
Some(_) => {}
}
break;
}
let c = crate::fields::value_counts(&buf, key, syntax, &CancelToken::new(), None)?
.unwrap_or_default();
with_output(a.opt(&["-o", "--output"]), out, |w| {
Ok(crate::fields::counts_to_csv(&c, key, &mut &mut *w)?)
})?;
Ok(if c.lines > 0 { 0 } else { 1 })
}
fn table_of(buf: &TextBuf, file: &str, a: &Args) -> Res<csv::TableGuess> {
let bom = buf.codec.bom_len as u64;
let sample = buf
.read(bom..buf.len().min(bom + 64 * 1024))
.ok_or_else(|| Fail("could not read the file".into()))?;
let preferred = if file.to_ascii_lowercase().ends_with(".tsv") {
b'\t'
} else {
b','
};
let mut g = csv::detect_table(
&buf.codec,
&sample,
bom + sample.len() as u64 == buf.len(),
preferred,
bom,
);
if let Some(n) = a.opt(&["--skip"]) {
let n: usize = n
.parse()
.map_err(|_| Fail(format!("not a line count: {n}")))?;
let mut at = bom;
for _ in 0..n {
at = crate::filter::line_end_at(buf, at).unwrap_or(buf.len());
}
g.skip = n;
g.dialect.start = if n == 0 { 0 } else { at };
}
match a.opt(&["--quote"]) {
Some(q) if q.len() == 1 => g.dialect.quote = q.as_bytes()[0],
Some(q) => return fail(format!("the quote is one character, not {q}")),
None => {}
}
if a.flag(&["--no-header"]) {
g.header = false;
} else if a.flag(&["--header"]) {
g.header = true;
}
Ok(g)
}
fn column_index(buf: &TextBuf, g: &csv::TableGuess, col: &str) -> Res<usize> {
if let Ok(n) = col.parse::<usize>() {
return if n > 0 {
Ok(n - 1)
} else {
fail("columns count from 1")
};
}
let mut names = Vec::new();
csv::for_each_record(buf, g.dialect, &CancelToken::new(), None, |r| {
names = r
.fields
.iter()
.filter_map(|f| {
buf.read(f.clone())
.map(|b| csv::field_value(&buf.codec, g.dialect, &b))
})
.collect();
false
});
names
.iter()
.position(|n| n.trim() == col.trim())
.ok_or_else(|| Fail(format!("no column named {col}")))
}
fn cmd_join(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(
args,
&["--inner", "--no-header", "--header"],
&[
"--on",
"--left-on",
"--right-on",
"-o",
"--output",
"--skip",
"--quote",
],
)?;
let [lf, rf] = &a.rest[..] else {
return fail("needs LEFT and RIGHT");
};
let (left, _) = open(Path::new(lf))?;
let (right, _) = open(Path::new(rf))?;
let (lg, rg) = (table_of(&left, lf, &a)?, table_of(&right, rf, &a)?);
let (lc, rc) = match (
a.opt(&["--on"]),
a.opt(&["--left-on"]),
a.opt(&["--right-on"]),
) {
(Some(c), None, None) => (c, c),
(None, Some(l), Some(r)) => (l, r),
_ => return fail("give --on COL, or --left-on COL and --right-on COL"),
};
let spec = crate::csv_join::JoinSpec {
left_key: column_index(&left, &lg, lc)?,
right_key: column_index(&right, &rg, rc)?,
inner: a.flag(&["--inner"]),
header: lg.header && rg.header,
};
with_output(a.opt(&["-o", "--output"]), out, |w| {
crate::csv_join::join_to(
(&left, lg.dialect),
(&right, rg.dialect),
spec,
&mut &mut *w,
&CancelToken::new(),
None,
)?;
Ok(())
})?;
Ok(0)
}
fn parse_conds(tokens: &[String], col: &dyn Fn(&str) -> Res<usize>) -> Res<Vec<csv::Cond>> {
use csv::CondOp;
let mut out = Vec::new();
let mut i = 0;
while i < tokens.len() {
let t = &tokens[i];
let sym = [
("!=", CondOp::NotEquals),
("!~", CondOp::NotContains),
("=", CondOp::Equals),
("~", CondOp::Contains),
(">", CondOp::Greater),
("<", CondOp::Less),
];
if let Some((at, len, op)) = sym
.iter()
.filter_map(|(s, op)| t.find(s).map(|at| (at, s.len(), *op)))
.min_by_key(|x| x.0)
{
out.push(csv::Cond {
col: col(&t[..at])?,
op,
value: t[at + len..].to_string(),
});
i += 1;
continue;
}
let word = tokens
.get(i + 1)
.map(|w| w.to_ascii_lowercase())
.unwrap_or_default();
let (op, takes) = match word.as_str() {
"eq" => (CondOp::Equals, true),
"ne" => (CondOp::NotEquals, true),
"has" => (CondOp::Contains, true),
"gt" => (CondOp::Greater, true),
"lt" => (CondOp::Less, true),
"empty" => (CondOp::Empty, false),
"nonempty" => (CondOp::NotEmpty, false),
_ => {
return fail(format!(
"not a condition: {t} (col=v, col>n, col~v, or col eq v)"
))
}
};
let value = if takes {
tokens
.get(i + 2)
.cloned()
.ok_or_else(|| Fail(format!("{t} {word} needs a value")))?
} else {
String::new()
};
out.push(csv::Cond {
col: col(t)?,
op,
value,
});
i += if takes { 3 } else { 2 };
}
if out.is_empty() {
return fail("where needs a condition");
}
Ok(out)
}
fn cmd_csv(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(
args,
&["--no-header", "--header", "--desc"],
&[
"-o",
"--output",
"--skip",
"--quote",
"--delimiter",
"--by",
"--sum",
],
)?;
let (file, op, rest) = match &a.rest[..] {
[file, op, rest @ ..] => (file, op.as_str(), rest),
_ => return fail("needs FILE and an operation (cut, drop, sort, where, stats, group)"),
};
let (buf, _) = open(Path::new(file))?;
let mut g = table_of(&buf, file, &a)?;
if let Some(d) = a.opt(&["--delimiter"]) {
g.dialect.delim = match d {
"tab" | "\\t" | "\t" => b'\t',
d if d.len() == 1 => d.as_bytes()[0],
d => return fail(format!("the delimiter is one character or tab, not {d}")),
};
}
let d = g.dialect;
let col = |t: &str| -> Res<usize> {
column_index(&buf, &g, t).map_err(|Fail(e)| {
let mut names = Vec::new();
csv::for_each_record(&buf, d, &CancelToken::new(), None, |r| {
names = r
.fields
.iter()
.filter_map(|f| {
buf.read(f.clone())
.map(|b| csv::field_value(&buf.codec, d, &b))
})
.collect();
false
});
Fail(format!("{e}; the columns are {}", names.join(", ")))
})
};
let cols = |list: &str| {
list.split(',')
.map(|c| col(c.trim()))
.collect::<Res<Vec<usize>>>()
};
let to = a.opt(&["-o", "--output"]);
let cancel = CancelToken::new();
let one = |what: &str| {
rest.first()
.cloned()
.ok_or_else(|| Fail(format!("{op} needs {what}")))
};
match op {
"cut" | "drop" => {
let mut c = cols(&one("COLUMNS")?)?;
with_output(to, out, |w| {
if op == "cut" {
csv::rewrite_to(
&buf,
d,
&csv::Rewrite::Select(c.clone()),
&mut &mut *w,
&cancel,
None,
)?;
} else {
c.sort_unstable();
c.dedup();
csv::delete_columns_to(&buf, d, &c, &mut &mut *w, &cancel, None)?;
}
Ok(())
})?;
Ok(0)
}
"sort" => {
let by = match a.opt(&["--by"]) {
Some(b) => b.to_string(),
None => one("--by COLUMN")?,
};
if buf.len() > csv::SORT_MAX {
return fail(format!(
"sorting works on files up to {}; this one is {}",
human_bytes(csv::SORT_MAX),
human_bytes(buf.len())
));
}
let rw = csv::Rewrite::Sort {
col: col(&by)?,
desc: a.flag(&["--desc"]),
header: g.header,
};
with_output(to, out, |w| {
csv::rewrite_to(&buf, d, &rw, &mut &mut *w, &cancel, None)?;
Ok(())
})?;
Ok(0)
}
"where" => {
let conds = parse_conds(rest, &col)?;
let mut kept = 0;
with_output(to, out, |w| {
kept = csv::filter_rows_to(&buf, d, &conds, g.header, &mut &mut *w, &cancel, None)?
.map(|x| x.0)
.unwrap_or(0);
Ok(())
})?;
Ok(if kept > 0 { 0 } else { 1 })
}
"stats" => {
let c = col(&one("a COLUMN")?)?;
let st = csv::column_stats(&buf, d, c, g.header, &cancel, None)
.map_err(|_| Fail("could not read the file".into()))?;
if json() {
let top: Vec<serde_json::Value> = st
.top
.iter()
.map(|(v, n)| serde_json::json!({"value": v, "count": n}))
.collect();
writeln!(
out,
"{}",
serde_json::json!({"column": st.name, "rows": st.rows, "empty": st.empty, "numbers": st.numeric, "sum": st.sum, "min": st.min, "max": st.max, "mean": st.mean(), "distinct": st.distinct, "top": top})
)?;
return Ok(0);
}
writeln!(out, "column: {}", st.name)?;
writeln!(out, "rows: {}", st.rows)?;
writeln!(out, "empty: {}", st.empty)?;
if st.numeric > 0 {
writeln!(out, "numbers: {}", st.numeric)?;
writeln!(out, "sum: {}", st.sum)?;
if let (Some(lo), Some(hi)) = (st.min, st.max) {
writeln!(out, "min: {lo}\nmax: {hi}")?;
}
if let Some(m) = st.mean() {
writeln!(out, "mean: {m}")?;
}
}
writeln!(
out,
"distinct: {}{}",
st.distinct,
if st.distinct_capped { "+" } else { "" }
)?;
for (v, n) in st.top.iter().take(10) {
writeln!(out, " {n}\t{v}")?;
}
Ok(0)
}
"group" => {
let key = col(&one("a COLUMN")?)?;
let sum = a.opt(&["--sum"]).map(col).transpose()?;
let gr = csv::group_by(&buf, d, key, sum, g.header, &cancel, None)
.map_err(|_| Fail("could not read the file".into()))?;
with_output(to, out, |w| {
csv::groups_to_csv(&gr, &mut &mut *w)?;
Ok(())
})?;
Ok(0)
}
_ => fail(format!(
"unknown csv operation {op} (cut, drop, sort, where, stats, group)"
)),
}
}
fn settings_path(a: &Args) -> Res<PathBuf> {
match a.opt(&["--settings"]) {
Some(p) => Ok(PathBuf::from(p)),
None => crate::settings_file::state_file()
.ok_or_else(|| Fail("no settings file (give --settings FILE)".into())),
}
}
fn cmd_ask(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> Res<i32> {
use crate::ai::agent::{drive, Config, Next, Session};
use crate::ai::config::{resolve_key, AiConfig};
use crate::ai::privacy::Redact;
use crate::ai::profile::Profile;
use crate::ai::tools;
let a = Args::parse(
args,
&["--json", "--plan"],
&[
"--provider",
"--model",
"--url",
"--workspace",
"--steps",
"--settings",
],
)?;
let Some((file, words)) = a.rest.split_first() else {
return fail("ask needs a FILE and a question");
};
let question = words.join(" ");
if question.trim().is_empty() {
return fail("ask needs a question after the FILE");
}
let lines: Vec<String> = match settings_path(&a).ok().map(std::fs::read) {
Some(Ok(b)) => String::from_utf8_lossy(&b)
.lines()
.filter(|l| l.starts_with("ai_"))
.map(str::to_string)
.collect(),
_ => Vec::new(),
};
let mut cfg = AiConfig::from_lines(&lines);
if let Some(id) = a.opt(&["--provider"]) {
if crate::ai::preset(id).is_none() {
let ids: Vec<&str> = crate::ai::PRESETS.iter().map(|p| p.id).collect();
return fail(format!(
"unknown provider {id}; the providers are: {}",
ids.join(", ")
));
}
cfg.provider = id.to_string();
}
let Some(mut p) = cfg.provider() else {
return fail("no AI provider is set up: choose one in the app (AI -> AI settings) or give --provider");
};
if let Some(m) = a.opt(&["--model"]) {
p.model = m.to_string();
}
if let Some(u) = a.opt(&["--url"]) {
p.url = u.to_string();
}
if let Some(w) = a.opt(&["--workspace"]) {
p.workspace = w.to_string();
}
let preset = crate::ai::preset(&p.id).ok_or_else(|| Fail("unknown provider".into()))?;
let store = crate::ai::keys::KeyStore::for_this_copy();
p.key = resolve_key(&store, preset).0;
p.check().map_err(|e| Fail(e.user_text()))?;
let steps = match a.opt(&["--steps"]) {
Some(n) => n
.parse::<usize>()
.ok()
.filter(|n| (1..=8).contains(n))
.ok_or_else(|| Fail(format!("--steps takes 1 to 8, not {n}")))?,
None => cfg.steps as usize,
};
let (buf, _) = open(Path::new(file))?;
let local = p.is_local();
let mut privacy = cfg.privacy.clone();
if local {
privacy.redact = cfg.redact_local;
}
let cancel = CancelToken::new();
let name = Path::new(file)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
let mut red = Redact::new(&privacy);
let profile = Profile::build(&buf, &name, &cancel).to_json(&mut |s| red.text(s));
let conf = cfg.conf(&p.id);
let mut session = Session::new(Config {
tools: conf.map(|c| c.tools).unwrap_or(true),
max_steps: steps,
explain: true,
writes: false,
effort: (p.protocol == crate::ai::Protocol::Anthropic).then_some(cfg.effort),
max_tokens: 8192,
language: "English".into(),
limit: privacy.limit,
});
let json = a.flag(&["--json"]);
let say = |err: &mut dyn Write, s: String| {
if !json {
let _ = writeln!(err, "{s}");
}
};
say(
err,
format!(
"Asking {} ({}, {}): the file's profile and the steps' short results are sent, never the file.",
preset.name,
p.model.trim(),
if local { "on this computer" } else { "cloud" }
),
);
if a.flag(&["--plan"]) {
session.ask(&question, Some(&profile));
let reply = p
.send(&session.request(), &cancel, &mut |_| {})
.map_err(|e| Fail(e.user_text()))?;
return match session.on_reply(&reply) {
Next::Calls(steps) => {
for st in &steps {
let checked = match &st.call {
Ok(_) => String::new(),
Err(e) => format!(" (invalid: {e})"),
};
if json {
writeln!(
out,
"{}",
serde_json::json!({"tool": st.name, "input": st.input, "note": st.note, "error": st.call.as_ref().err()})
)?;
} else {
writeln!(out, "{} {}{checked}", st.name, st.input)?;
}
}
Ok(0)
}
Next::Answer(t) => {
writeln!(out, "{t}")?;
Ok(0)
}
Next::Again => fail("the model did not reply with a step"),
};
}
let mut red = Redact::new(&privacy);
let mut redact = |s: &str| red.text(s);
let mut run = |c: &tools::Call| {
tools::run(
&mut tools::Run {
buf: &buf,
cancel: &cancel,
name: &name,
selection: None,
bookmarks: &[],
redact: &mut redact,
},
c,
)
};
let (answer, done) = drive(
&mut session,
&p,
&question,
Some(&profile),
&mut run,
&cancel,
&mut |_| {},
)
.map_err(|e| Fail(e.user_text()))?;
if json {
let steps: Vec<serde_json::Value> = done
.iter()
.map(|d| {
serde_json::json!({
"tool": d.step.name,
"input": d.step.input,
"error": d.step.call.as_ref().err(),
"n": d.output.as_ref().and_then(|o| o.n),
"lines": d.output.as_ref().map(|o| o.lines.clone()).unwrap_or_default(),
})
})
.collect();
let u = session.usage;
writeln!(
out,
"{}",
serde_json::json!({"answer": answer, "steps": steps, "model": p.model.trim(),
"tokens": {"input": u.total_input(), "output": u.output}})
)?;
} else {
for d in &done {
let what = match (&d.step.call, &d.output) {
(Err(e), _) => format!("not run: {e}"),
(Ok(_), Some(o)) => o
.summary
.replace("{n}", &o.n.map(|n| n.to_string()).unwrap_or_default()),
(Ok(_), None) => "failed".into(),
};
say(err, format!(" {} {} -> {what}", d.step.name, d.step.input));
}
writeln!(out, "{}", answer.trim())?;
}
Ok(0)
}
fn with_saved(rest: &[String]) -> Res<Vec<String>> {
let Some(i) = rest.iter().position(|a| a == "--saved") else {
return Ok(rest.to_vec());
};
let name = rest
.get(i + 1)
.ok_or_else(|| Fail("--saved needs a NAME".into()))?
.clone();
let mut others: Vec<String> = Vec::new();
let mut settings = None;
let mut it = rest.iter().enumerate();
while let Some((k, x)) = it.next() {
if k == i || k == i + 1 {
continue;
}
if x == "--settings" {
settings = it.next().map(|(_, v)| v.clone());
continue;
}
others.push(x.clone());
}
let path = match settings {
Some(p) => PathBuf::from(p),
None => crate::settings_file::state_file()
.ok_or_else(|| Fail("no settings file (give --settings FILE)".into()))?,
};
let all = crate::settings_file::saved_searches(&path)
.map_err(|e| Fail(format!("{}: {e}", display_path(&path))))?;
let s = all
.iter()
.find(|s| s.name == name)
.ok_or_else(|| Fail(format!("no saved search named “{name}”")))?;
let mut out = Vec::new();
if s.query.regex {
out.push("-E".into());
}
if !s.query.case_sensitive {
out.push("-i".into());
}
if s.query.whole_word {
out.push("-w".into());
}
if s.invert {
out.push("-v".into());
}
out.push("-e".into());
out.push(s.query.pattern.clone());
out.extend(others);
Ok(out)
}
fn cmd_saved(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(args, &[], &["--settings"])?;
let path = settings_path(&a)?;
let all = crate::settings_file::saved_searches(&path)
.map_err(|e| Fail(format!("{}: {e}", display_path(&path))))?;
for s in &all {
let flags = crate::settings_file::query_flags(&s.query);
if json() {
writeln!(
out,
"{}",
serde_json::json!({"name": s.name, "pattern": s.query.pattern, "regex": s.query.regex, "case_sensitive": s.query.case_sensitive, "whole_word": s.query.whole_word, "invert": s.invert})
)?;
} else {
writeln!(
out,
"{}\t{}{}{}",
s.name,
s.query.pattern,
if flags.is_empty() {
String::new()
} else {
format!(" ({flags})")
},
if s.invert { " (lines without)" } else { "" }
)?;
}
}
Ok(if all.is_empty() { 1 } else { 0 })
}
fn cmd_replace(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(
args,
&[
"-i",
"--ignore-case",
"-w",
"--word",
"-E",
"--regex",
"--in-place",
"--bak",
],
&["-o", "--output"],
)?;
let [pattern, replacement, file] = &a.rest[..] else {
return fail("needs PATTERN, REPLACEMENT and FILE");
};
let path = Path::new(file);
if a.flag(&["--in-place"]) && crate::decompress::detect(path).is_some() {
return fail("--in-place does not work on a compressed file; give -o OUT");
}
if json() && !a.flag(&["--in-place"]) && a.opt(&["-o", "--output"]).is_none() {
return fail(
"--json needs -o OUT or --in-place: the replaced text would mix with the record",
);
}
let (buf, _) = open(path)?;
let q = query(&a, pattern);
let m = Matcher::new(&q, buf.codec).map_err(Fail)?;
let tpl = if q.regex {
crate::replace::Template::new(replacement, true)
} else {
crate::replace::Template::verbatim(replacement)
};
let cancel = CancelToken::new();
let count = if a.flag(&["--in-place"]) {
let t = crate::save::Transform::Replace {
matcher: &m,
template: &tpl,
range: 0..buf.len(),
};
let (temp, stats) =
match crate::save::write_temp(&buf, path, t, &cancel, &Progress::default()) {
Ok(x) => x,
Err(crate::save::SaveError::Io(e)) => return fail(e),
Err(crate::save::SaveError::Cancelled) => return fail("cancelled"),
};
drop(buf);
if stats.count == 0 {
let _ = std::fs::remove_file(&temp);
} else {
crate::save::finalize(&temp, path, a.flag(&["--bak"])).map_err(Fail)?;
}
stats.count
} else {
let mut n = 0;
with_output(a.opt(&["-o", "--output"]), out, |w| {
n = crate::replace::replace_all_to(
&buf,
&m,
&tpl,
0..buf.len(),
&mut &mut *w,
&cancel,
None,
)?
.map(|s| s.count)
.unwrap_or(0);
Ok(())
})?;
n
};
if json() {
writeln!(
out,
"{}",
serde_json::json!({"file": file, "replaced": count})
)?;
} else if a.flag(&["--in-place"]) {
writeln!(out, "{count} replaced")?;
}
Ok(if count > 0 { 0 } else { 1 })
}
fn write_slice(
buf: &TextBuf,
range: std::ops::Range<u64>,
header: bool,
to: Option<&str>,
out: &mut dyn Write,
) -> Res<i32> {
let codec = buf.codec;
let bom = codec.bom_len as u64;
let header = if header && range.start > bom {
crate::filter::line_end_at(buf, bom).map(|e| bom..e)
} else {
None
};
let raw = to.is_some() || codec.enc == crate::encoding::Encoding::Utf8;
with_output(to, out, |w| {
if to.is_some() && bom > 0 {
w.write_all(
&buf.read(0..bom)
.ok_or_else(|| Fail("could not read the file".into()))?,
)?;
}
let mut copy = |r: std::ops::Range<u64>| -> Res<()> {
let r = r.start.max(bom)..r.end;
let mut err = None;
buf.for_each_chunk(r, |_, b| {
let res = if raw {
w.write_all(b)
} else {
w.write_all(codec.decode_lossy(b).as_bytes())
};
match res {
Ok(()) => true,
Err(e) => {
err = Some(e);
false
}
}
})
.ok_or_else(|| Fail("could not read the file".into()))?;
match err {
Some(e) => Err(e.into()),
None => Ok(()),
}
};
if let Some(h) = header {
copy(h)?;
}
copy(range.clone())
})?;
Ok((range.start >= range.end) as i32)
}
fn cmd_head_tail(args: &[String], out: &mut dyn Write, head: bool) -> Res<i32> {
let a = Args::parse(args, &[], &["-n", "--lines", "-o", "--output"])?;
let [file] = &a.rest[..] else {
return fail("needs FILE");
};
let n: u64 = match a.opt(&["-n", "--lines"]) {
Some(v) => v
.parse()
.map_err(|_| Fail(format!("-n needs a number of lines, not {v}")))?,
None => 10,
};
let (buf, _) = open(Path::new(file))?;
let buf = buf.snapshot();
let range = if head {
match split::line_range(&buf, 1, n.max(1), &CancelToken::new(), None) {
Some(r) if n > 0 => r,
_ => 0..0,
}
} else {
crate::lines::last_lines_start(&buf, n)
.ok_or_else(|| Fail("could not read the file".into()))?..buf.len()
};
write_slice(&buf, range, false, a.opt(&["-o", "--output"]), out)
}
fn cmd_slice(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(
args,
&["--with-header", "--header"],
&["--lines", "--bytes", "--from", "--to", "-o", "--output"],
)?;
let [file] = &a.rest[..] else {
return fail("needs FILE");
};
let (buf, _) = open(Path::new(file))?;
let buf = buf.snapshot();
let pair = |v: &str, what: &str| -> Res<(u64, u64)> {
let (x, y) = v
.split_once('-')
.ok_or_else(|| Fail(format!("{what} needs A-B")))?;
let num = |s: &str| {
s.trim()
.replace('_', "")
.parse::<u64>()
.map_err(|_| Fail(format!("{what}: “{s}” is not a number")))
};
let (x, y) = (num(x)?, num(y)?);
if x > y {
return fail(format!("{what}: {x} is after {y}"));
}
Ok((x, y))
};
let cancel = CancelToken::new();
let range = match (
a.opt(&["--lines"]),
a.opt(&["--bytes"]),
a.opt(&["--from"]),
a.opt(&["--to"]),
) {
(Some(v), None, None, None) => {
let (x, y) = pair(v, "--lines")?;
split::line_range(&buf, x.max(1), y.max(1), &cancel, None).unwrap_or(0..0)
}
(None, Some(v), None, None) => {
let (x, y) = pair(v, "--bytes")?;
let (x, y) = (x.min(buf.len()), y.min(buf.len()));
let s = crate::filter::line_start_at(&buf, x).unwrap_or(x);
let e = crate::filter::line_end_at(&buf, y.saturating_sub(1).max(x)).unwrap_or(y);
s..e.max(s)
}
(None, None, from, to) if from.is_some() || to.is_some() => {
let parse =
|t: &str| timestamp::parse(t).ok_or_else(|| Fail(format!("not a time: {t}")));
let from = from.map(parse).transpose()?;
let to = to
.map(parse)
.transpose()?
.map(|t| from.map(|f| timestamp::rebase(t, f)).unwrap_or(t));
match timestamp::time_range(&buf, from, to, &cancel) {
Ok((s, e)) => s..e,
Err(timestamp::TimeError::NoTimestamps) => {
return fail("the file has no timestamps")
}
Err(e) => return fail(format!("{e:?}")),
}
}
_ => return fail("give one of --lines A-B, --bytes A-B, or --from (and --to)"),
};
write_slice(
&buf,
range,
a.flag(&["--with-header", "--header"]),
a.opt(&["-o", "--output"]),
out,
)
}
fn cmd_sort(args: &[String], out: &mut dyn Write, uniq: bool) -> Res<i32> {
use crate::extsort::{SortMode, SortSpec};
let a = Args::parse(args, &["-r", "-n", "-i", "-u", "-c"], &["-o", "--output"])?;
let [file] = &a.rest[..] else {
return fail("needs FILE");
};
let mode = match (uniq, a.flag(&["-c"]), a.flag(&["-u"])) {
(true, true, _) => SortMode::Count,
(true, false, _) | (false, _, true) => SortMode::Unique,
_ => SortMode::Sort,
};
let spec = SortSpec {
reverse: a.flag(&["-r"]),
numeric: a.flag(&["-n"]),
ignore_case: a.flag(&["-i"]),
mode,
counts_csv: false,
};
let (buf, det) = open(Path::new(file))?;
let snap = buf.snapshot();
let eol = snap
.codec
.encode(if det.line_ending == crate::encoding::LineEnding::CrLf {
"\r\n"
} else {
"\n"
});
with_output(a.opt(&["-o", "--output"]), out, |w| {
crate::extsort::sort_to(&snap, spec, &eol, w, &CancelToken::new(), None)?;
Ok(())
})?;
Ok(0)
}
fn text_op(file: &str, op: crate::textops::Op, to: Option<&str>, out: &mut dyn Write) -> Res<i32> {
let (buf, _) = open(Path::new(file))?;
let snap = buf.snapshot();
with_output(to, out, |w| {
crate::textops::text_op_to(
&snap,
0..snap.len(),
op,
crate::text::rows::TAB_WIDTH,
w,
&CancelToken::new(),
None,
)
.map_err(|e| Fail(e.to_string()))?;
Ok(())
})?;
Ok(0)
}
fn cmd_transform(args: &[String], out: &mut dyn Write) -> Res<i32> {
use crate::textops::Op;
let a = Args::parse(args, &[], &["--op", "-o", "--output"])?;
let [file] = &a.rest[..] else {
return fail("needs FILE");
};
let op = match a.opt(&["--op"]) {
Some("upper") => Op::Upper,
Some("lower") => Op::Lower,
Some("trim") => Op::TrimTrailing,
Some("tabs") => Op::TabsToSpaces,
Some("untabs") => Op::SpacesToTabs,
Some(o) => {
return fail(format!(
"unknown --op {o} (upper, lower, trim, tabs, untabs)"
))
}
None => return fail("give --op upper|lower|trim|tabs|untabs"),
};
text_op(file, op, a.opt(&["-o", "--output"]), out)
}
fn cmd_format(args: &[String], out: &mut dyn Write) -> Res<i32> {
use crate::textops::Op;
let a = Args::parse(args, &[], &["--style", "--json", "-o", "--output"])?;
let [file] = &a.rest[..] else {
return fail("needs FILE");
};
let op = match a.opt(&["--style", "--json"]) {
Some("pretty") | None => Op::JsonPretty,
Some("minify") => Op::JsonMinify,
Some(o) => return fail(format!("unknown --style {o} (pretty, minify)")),
};
text_op(file, op, a.opt(&["-o", "--output"]), out)
}
fn cmd_diff_table(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(
args,
&["--all", "--no-header", "--header"],
&[
"--on",
"--left-on",
"--right-on",
"--key",
"--key-b",
"-o",
"--output",
"--skip",
"--quote",
],
)?;
let [fa, fb] = &a.rest[..] else {
return fail("needs A and B");
};
let Some(ka) = a.opt(&["--on", "--left-on", "--key"]) else {
return fail("give --on COL (a header name or a 1-based number)");
};
let kb = a.opt(&["--right-on", "--key-b"]).unwrap_or(ka);
let (ta, _) = open(Path::new(fa))?;
let (tb, _) = open(Path::new(fb))?;
let (ga, gb) = (table_of(&ta, fa, &a)?, table_of(&tb, fb, &a)?);
let spec = crate::csv_diff::KeyedSpec {
key_a: column_index(&ta, &ga, ka)?,
key_b: column_index(&tb, &gb, kb)?,
header: ga.header && gb.header,
all: a.flag(&["--all"]),
};
let mut stats = None;
with_output(a.opt(&["-o", "--output"]), out, |w| {
stats = crate::csv_diff::keyed_diff_to(
(&ta, ga.dialect),
(&tb, gb.dialect),
spec,
w,
&CancelToken::new(),
None,
)?;
Ok(())
})?;
Ok(stats.is_some_and(|s| s.changed + s.added + s.removed > 0) as i32)
}
fn cmd_jsonl(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(
args,
&["-v", "--invert", "--count"],
&["-q", "--query", "--fields", "--to", "-o", "--output"],
)?;
let [file] = &a.rest[..] else {
return fail("needs FILE");
};
let q = a
.opt(&["-q", "--query"])
.map(crate::jsonq::FieldQuery::parse)
.transpose()
.map_err(Fail)?;
let invert = a.flag(&["-v", "--invert"]);
let fields: Vec<String> = a
.opt(&["--fields"])
.map(|f| {
f.split(',')
.map(|s| s.trim().trim_start_matches('.').to_string())
.filter(|s| !s.is_empty())
.collect()
})
.unwrap_or_default();
let csv_out = match a.opt(&["--to"]).map(str::to_ascii_lowercase).as_deref() {
None | Some("jsonl") => false,
Some("csv") if !fields.is_empty() => true,
Some("csv") => return fail("--to csv needs --fields"),
Some(t) => return fail(format!("unknown --to {t} (jsonl, csv)")),
};
let (buf, _) = open(Path::new(file))?;
if buf.codec.unit() != 1 {
return fail("JSON Lines must be UTF-8");
}
let head = buf
.read(0..buf.len().min(4096))
.map(|b| b.to_vec())
.unwrap_or_default();
let format = if head.trim_ascii_start().starts_with(b"{") {
None
} else {
crate::logformat::detect(&buf)?
};
let value_of = |line: &[u8], f: &str| -> Option<String> {
if let Some(fmt) = &format {
let mut s = crate::logformat::Splitter::new(fmt);
if s.split(line) != crate::logformat::Split::Row {
return None;
}
let i = fmt.columns.iter().position(|c| c.eq_ignore_ascii_case(f))?;
let values = s.values(line);
let v = values.get(i).filter(|v| !v.is_empty())?;
Some(String::from_utf8_lossy(v).into_owned())
} else if line.trim_ascii_start().starts_with(b"{") {
crate::fields::find_value(line, f, crate::fields::Syntax::Json)
} else {
crate::fields::find_value(line, f, crate::fields::Syntax::Logfmt)
}
};
let q = q.map(|q| q.for_document(format.clone(), false));
let quote = |s: &str| {
if s.contains([',', '"', '\n', '\r']) {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s.to_string()
}
};
let mut n = 0u64;
with_output(a.opt(&["-o", "--output"]), out, |w| {
if csv_out {
writeln!(
w,
"{}",
fields
.iter()
.map(|f| quote(f))
.collect::<Vec<_>>()
.join(",")
)?;
}
let mut r = LineReader::new(&buf);
while let Some((_, line)) = r.next()? {
let keep = q.as_ref().is_none_or(|q| q.matches(line)) != invert;
if !keep || (line.trim_ascii().is_empty() && q.is_none()) {
continue;
}
n += 1;
if a.flag(&["--count"]) {
continue;
}
if fields.is_empty() {
w.write_all(line.strip_suffix(b"\r").unwrap_or(line))?;
w.write_all(b"\n")?;
} else if csv_out {
let row: Vec<String> = fields
.iter()
.map(|f| quote(&value_of(line, f).unwrap_or_default()))
.collect();
writeln!(w, "{}", row.join(","))?;
} else {
let parts: Vec<String> = fields
.iter()
.map(|f| {
format!(
"{}:{}",
serde_json::Value::from(f.as_str()),
if line.trim_ascii_start().starts_with(b"{") {
crate::fields::find_raw_json(line, f)
.map(|v| String::from_utf8_lossy(v).into_owned())
} else {
value_of(line, f).map(|v| serde_json::Value::from(v).to_string())
}
.unwrap_or_else(|| "null".into())
)
})
.collect();
writeln!(w, "{{{}}}", parts.join(","))?;
}
}
if a.flag(&["--count"]) {
writeln!(w, "{n}")?;
}
Ok(())
})?;
Ok(if n > 0 { 0 } else { 1 })
}
fn cmd_jsondiff(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(args, &[], &[])?;
let [fa, fb] = &a.rest[..] else {
return fail("needs A and B");
};
let (ba, _) = open(Path::new(fa))?;
let (bb, _) = open(Path::new(fb))?;
let cancel = CancelToken::new();
let pa = crate::json_diff::flatten_to_temp(&ba, "a.flat", &cancel, None)
.map_err(Fail)?
.ok_or_else(|| Fail("cancelled".into()))?;
let pb = match crate::json_diff::flatten_to_temp(&bb, "b.flat", &cancel, None) {
Ok(Some(p)) => p,
r => {
crate::decompress::remove_temp(&pa);
return Err(Fail(r.err().unwrap_or_else(|| "cancelled".into())));
}
};
let mut err = None;
let r = crate::json_diff::changes(&pa, &pb, &cancel, None, |ch| {
let line = match (&ch.old, &ch.new) {
(Some(o), Some(n)) => format!("{}: {o} -> {n}", ch.path),
(None, Some(n)) => format!("{}: added {n}", ch.path),
(Some(o), None) => format!("{}: removed {o}", ch.path),
(None, None) => return true,
};
if let Err(e) = writeln!(out, "{line}") {
err = Some(e);
return false;
}
true
});
crate::decompress::remove_temp(&pa);
crate::decompress::remove_temp(&pb);
if let Some(e) = err {
return Err(e.into());
}
Ok(if r.map_err(Fail)?.unwrap_or(false) {
1
} else {
0
})
}
fn diff_options(a: &Args) -> Res<crate::diff::DiffOptions> {
let mask = match a.opt(&["--mask"]) {
Some(m) => {
Some(regex_automata::meta::Regex::new(m).map_err(|e| Fail(format!("--mask: {e}")))?)
}
None => None,
};
Ok(crate::diff::DiffOptions {
whitespace: a.flag(&["-w", "-b"]),
case: a.flag(&["-i"]),
timestamps: a.flag(&["-t"]),
mask,
})
}
fn cmd_only_in(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(
args,
&["-w", "-b", "-i", "-t", "--count"],
&["--mask", "-o", "--output"],
)?;
let [fa, fb] = &a.rest[..] else {
return fail("needs A and B");
};
let opts = diff_options(&a)?;
let (ba, _) = open(Path::new(fa))?;
let (bb, _) = open(Path::new(fb))?;
let (ba, bb) = (ba.snapshot(), bb.snapshot());
let cancel = CancelToken::new();
let budget = crate::setdiff::BUDGET;
if a.flag(&["--count"]) {
let c = crate::setdiff::only_in(&ba, &bb, &opts, budget, &cancel, None, |_| true)?
.ok_or_else(|| Fail("cancelled".into()))?;
writeln!(out, "{}", c.only)?;
return Ok((c.only > 0) as i32);
}
let mut only = 0u64;
with_output(a.opt(&["-o", "--output"]), out, |w| {
let mut err = None;
let c = crate::setdiff::only_in(&ba, &bb, &opts, budget, &cancel, None, |off| {
match crate::setdiff::write_line_at(&ba, off, w) {
Ok(()) => true,
Err(e) => {
err = Some(e);
false
}
}
})?;
if let Some(e) = err {
return Err(e.into());
}
only = c.map(|c| c.only).unwrap_or(0);
Ok(())
})?;
Ok((only > 0) as i32)
}
fn cmd_diff(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(
args,
&["-w", "-b", "-i", "-t", "-q", "-u"],
&["--mask", "-U", "--context", "-o", "--output"],
)?;
let [fa, fb] = &a.rest[..] else {
return fail("needs A and B");
};
let opts = diff_options(&a)?;
let context = match a.opt(&["-U", "--context"]) {
Some(n) => n
.parse::<u64>()
.map_err(|_| Fail(format!("-U needs a number of lines, not {n}")))?,
None => 3,
};
let (ba, _) = open(Path::new(fa))?;
let (bb, _) = open(Path::new(fb))?;
if a.flag(&["-q"]) {
let mut differ = false;
let end = crate::diff::diff_with(
&*ba.source,
&*bb.source,
&opts,
&CancelToken::new(),
None,
|_| {
differ = true;
false
},
);
if matches!(
end,
crate::diff::DiffEnd::Failed | crate::diff::DiffEnd::Cancelled
) {
return fail("could not read the files");
}
if differ {
writeln!(out, "Files {fa} and {fb} differ")?;
}
return Ok(differ as i32);
}
let u = crate::unified::Unified {
a: &*ba.source,
b: &*bb.source,
a_name: fa,
b_name: fb,
opts: &opts,
context,
};
let mut differ = false;
with_output(a.opt(&["-o", "--output"]), out, |w| {
differ = crate::unified::write_unified(&u, w, &CancelToken::new(), None)?.unwrap_or(false);
Ok(())
})?;
Ok(differ as i32)
}
fn cmd_derive(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(
args,
&["--no-header", "--header"],
&["--name", "--expr", "-o", "--output", "--skip", "--quote"],
)?;
let [file] = &a.rest[..] else {
return fail("needs FILE");
};
let (name, expr) = match (a.opt(&["--name"]), a.opt(&["--expr"])) {
(Some(n), Some(e)) => (n.to_string(), e.to_string()),
_ => return fail("give --name NAME and --expr EXPR"),
};
let (buf, _) = open(Path::new(file))?;
let g = table_of(&buf, file, &a)?;
let mut names = Vec::new();
if g.header {
csv::for_each_record(&buf, g.dialect, &CancelToken::new(), None, |r| {
names = r
.fields
.iter()
.filter_map(|f| {
buf.read(f.clone())
.map(|b| csv::field_value(&buf.codec, g.dialect, &b))
})
.collect();
false
});
}
crate::csv_expr::Expr::compile(&expr, &names).map_err(Fail)?;
let rw = csv::Rewrite::Derive {
name,
expr,
names,
header: g.header,
};
with_output(a.opt(&["-o", "--output"]), out, |w| {
csv::rewrite_to(
&buf,
g.dialect,
&rw,
&mut &mut *w,
&CancelToken::new(),
None,
)?;
Ok(())
})?;
Ok(0)
}
fn cmd_pivot(args: &[String], out: &mut dyn Write) -> Res<i32> {
use crate::csv_pivot::{Agg, Bucket, PivotSpec};
let a = Args::parse(
args,
&["--no-header", "--header"],
&[
"--rows", "--cols", "--value", "--agg", "--by", "-o", "--output", "--skip", "--quote",
],
)?;
let [file] = &a.rest[..] else {
return fail("needs FILE");
};
let (buf, _) = open(Path::new(file))?;
let g = table_of(&buf, file, &a)?;
let col = |name: &str| -> Res<usize> {
let c = a
.opt(&[name])
.ok_or_else(|| Fail(format!("give {name} COL")))?;
column_index(&buf, &g, c)
};
let value = a
.opt(&["--value"])
.map(|c| column_index(&buf, &g, c))
.transpose()?;
let agg = match a.opt(&["--agg"]) {
None if value.is_some() => Agg::Sum,
None => Agg::Count,
Some(n) => Agg::ALL
.into_iter()
.find(|x| x.name() == n.to_ascii_lowercase())
.ok_or_else(|| Fail(format!("unknown --agg {n} (count, sum, mean, min, max)")))?,
};
if agg != Agg::Count && value.is_none() {
return fail("--agg needs --value COL");
}
let bucket = match a.opt(&["--by"]).map(str::to_ascii_lowercase).as_deref() {
None => Bucket::AsIs,
Some("hour") => Bucket::Hour,
Some("day") => Bucket::Day,
Some("month") => Bucket::Month,
Some(b) => return fail(format!("unknown --by {b} (hour, day, month)")),
};
let spec = PivotSpec {
rows: col("--rows")?,
cols: col("--cols")?,
value,
agg,
bucket,
header: g.header,
};
let p = crate::csv_pivot::pivot(&buf, g.dialect, spec, &CancelToken::new(), None)
.map_err(|_| Fail("could not read the file".into()))?;
with_output(a.opt(&["-o", "--output"]), out, |w| {
Ok(crate::csv_pivot::pivot_to_csv(&p, agg, &mut &mut *w)?)
})?;
Ok(0)
}
fn cmd_validate(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(
args,
&["--no-header", "--header", "--json", "--lines"],
&["--as", "--numeric", "--skip", "--quote"],
)?;
let [file] = &a.rest[..] else {
return fail("needs FILE");
};
let (jbuf, _) = open(Path::new(file))?;
let kind = match a.opt(&["--as"]).map(str::to_ascii_lowercase).as_deref() {
Some("json") => "json",
Some("jsonl") => "jsonl",
Some("csv") => "csv",
Some(o) => return fail(format!("unknown --as {o} (json, jsonl, csv)")),
None if a.flag(&["--lines"]) => "jsonl",
None if a.flag(&["--json"]) => "json",
None => sniff_kind(&jbuf),
};
if kind == "json" || kind == "jsonl" {
let cancel = CancelToken::new();
let c = if kind == "jsonl" {
crate::json_check::check_lines(&jbuf, &cancel, None, |_| {})?
} else {
crate::json_check::check_document(&jbuf, &cancel, None)
}
.unwrap_or_default();
let (mut at, mut line) = (0u64, 0u64);
for p in &c.problems {
jbuf.for_each_chunk(at..p.at, |base, ch| {
line += jbuf.codec.count_nl(ch, base);
true
})
.ok_or_else(|| Fail("could not read the file".into()))?;
at = p.at;
writeln!(out, "{}: byte {}: {}", line + 1, p.at, p.message)?;
}
return Ok(if c.problems.is_empty() { 0 } else { 1 });
}
let mut numeric = Vec::new();
for n in a
.opt(&["--numeric"])
.unwrap_or("")
.split(',')
.map(str::trim)
.filter(|n| !n.is_empty())
{
match n.parse::<usize>() {
Ok(n) if n > 0 => numeric.push(n - 1),
_ => return fail(format!("not a column number: {n}")),
}
}
let (buf, _) = open(Path::new(file))?;
let g = table_of(&buf, file, &a)?;
let c = crate::csv_check::check(
&buf,
g.dialect,
g.header,
&numeric,
&CancelToken::new(),
None,
|_| {},
)?
.unwrap_or_default();
let (mut at, mut line) = (0u64, 0u64);
for p in &c.problems {
buf.for_each_chunk(at..p.start, |base, ch| {
line += buf.codec.count_nl(ch, base);
true
})
.ok_or_else(|| Fail("could not read the file".into()))?;
at = p.start;
let what = match p.kind {
crate::csv_check::Kind::Fields { got, want } => {
format!("{got} fields instead of {want}")
}
crate::csv_check::Kind::StrayQuote { col } => {
format!("column {}: a stray quote", col + 1)
}
crate::csv_check::Kind::Unclosed { col } => {
format!("column {}: a quote that is never closed", col + 1)
}
crate::csv_check::Kind::Control { col } => {
format!("column {}: a control character", col + 1)
}
crate::csv_check::Kind::NotNumber { col } => {
format!("column {}: not a number", col + 1)
}
crate::csv_check::Kind::Huge => "longer than 64 KB, not checked".to_string(),
};
writeln!(out, "{}: {what}", line + 1)?;
}
Ok(if c.problems.is_empty() { 0 } else { 1 })
}
fn cmd_extract(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(
args,
&[
"-i",
"--ignore-case",
"-w",
"--word",
"-E",
"--regex",
"--count",
],
&["-g", "--group", "-o", "--output"],
)?;
let [pattern, file] = &a.rest[..] else {
return fail("needs PATTERN and FILE");
};
let group = a
.opt(&["-g", "--group"])
.map(|g| {
g.parse::<usize>()
.map_err(|_| Fail(format!("not a group number: {g}")))
})
.transpose()?
.unwrap_or(0);
let (buf, _) = open(Path::new(file))?;
let m = Matcher::new(&query(&a, pattern), buf.codec).map_err(Fail)?;
if group > crate::search::group_names(&m).len() {
return fail(format!("the pattern has no group {group}"));
}
let cancel = CancelToken::new();
let mut n = 0;
with_output(a.opt(&["-o", "--output"]), out, |w| {
if a.flag(&["--count"]) {
let t = crate::extract::count(&buf, &m, group, 0..buf.len(), &cancel, None)?
.unwrap_or_default();
for (v, c) in &t.values {
writeln!(w, "{c}\t{v}")?;
}
n = t.matches;
} else {
n = crate::extract::write_values_to(
&buf,
&m,
group,
0..buf.len(),
&mut &mut *w,
&cancel,
None,
)?
.unwrap_or(0);
}
Ok(())
})?;
Ok(if n > 0 { 0 } else { 1 })
}
fn cmd_patterns(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(args, &["--rare"], &["--top", "-o", "--output"])?;
let [file] = &a.rest[..] else {
return fail("needs FILE");
};
let top = a
.opt(&["--top"])
.map(|n| {
n.parse::<usize>()
.map_err(|_| Fail(format!("not a number: {n}")))
})
.transpose()?;
let (buf, _) = open(Path::new(file))?;
let mut p =
crate::patterns::build(&buf, None, &CancelToken::new(), None, |_| {})?.unwrap_or_default();
crate::patterns::sort(&mut p.templates, a.flag(&["--rare"]));
if let Some(n) = top {
p.templates.truncate(n);
}
with_output(a.opt(&["-o", "--output"]), out, |w| {
Ok(crate::patterns::to_csv(&p.templates, &mut &mut *w)?)
})?;
Ok(0)
}
fn cmd_gaps(args: &[String], out: &mut dyn Write) -> Res<i32> {
let a = Args::parse(args, &[], &["--min"])?;
let [file] = &a.rest[..] else {
return fail("needs FILE");
};
let min = a.opt(&["--min"]).unwrap_or("30s");
let min_ms = crate::gaps::parse_duration(min)
.ok_or_else(|| Fail(format!("not a duration: {min} (30s, 5m or 5min, 1h)")))?;
let (buf, _) = open(Path::new(file))?;
let g = crate::gaps::scan(&buf, min_ms, &CancelToken::new(), None, |_| {})?.unwrap_or_default();
let (mut at, mut line) = (0u64, 0u64);
let mut line_of = |off: u64| -> Res<u64> {
buf.for_each_chunk(at..off, |base, c| {
line += buf.codec.count_nl(c, base);
true
})
.ok_or_else(|| Fail("could not read the file".into()))?;
at = off;
Ok(line + 1)
};
for x in &g.gaps {
let (a1, a2) = (line_of(x.before)?, line_of(x.after)?);
let time = |at, k| {
timestamp::stamp_text_at(&buf, at)
.unwrap_or_else(|| timestamp::format_key(k, g.dated, true))
};
writeln!(
out,
"{a1}-{a2}: {} ({} -> {})",
timestamp::format_delta(x.ms()),
time(x.before, x.from),
time(x.after, x.to)
)?;
}
Ok(if g.gaps.is_empty() { 1 } else { 0 })
}
pub fn run(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> i32 {
let code = run_command(args, out, err);
for t in TEMPS.with(|v| std::mem::take(&mut *v.borrow_mut())) {
crate::decompress::remove_temp(&t);
}
code
}
fn expand_inputs(
positionals: &[String],
dir: Option<&str>,
names: Option<&str>,
) -> Res<Vec<String>> {
let cancel = CancelToken::new();
let mut out = Vec::new();
for p in positionals {
let path = Path::new(p);
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
if name.contains(['*', '?']) && !path.exists() {
let parent = path
.parent()
.filter(|d| !d.as_os_str().is_empty())
.unwrap_or(Path::new("."));
let mut found =
crate::find_files::list_files(parent, std::slice::from_ref(&name), false, &cancel)
.map_err(|e| Fail(format!("{p}: {e}")))?;
if found.is_empty() {
return fail(format!("no files match {p}"));
}
found.sort();
out.extend(found.into_iter().map(|f| f.to_string_lossy().into_owned()));
} else {
out.push(p.clone());
}
}
if let Some(d) = dir {
let pats = names.map(crate::find_files::patterns).unwrap_or_default();
let mut found = crate::find_files::list_files(Path::new(d), &pats, true, &cancel)
.map_err(|e| Fail(format!("{d}: {e}")))?;
found.sort();
out.extend(found.into_iter().map(|f| f.to_string_lossy().into_owned()));
}
Ok(out)
}
fn run_batch(cmd: &str, rest: &[String], out: &mut dyn Write, err: &mut dyn Write) -> Option<i32> {
let filter_flags = [
&[
"-v",
"--invert",
"-i",
"--ignore-case",
"-w",
"--word",
"-E",
"--regex",
"--any",
][..],
&CONTEXT_FLAGS,
]
.concat();
let (flags, opts): (Vec<&str>, Vec<&str>) = match cmd {
"filter" | "count" | "grep" => (
filter_flags,
[
&["-o", "--output", "-e", "--pattern", "--not"][..],
&CONTEXT_OPTS,
]
.concat(),
),
"levels" => (
CONTEXT_FLAGS.to_vec(),
[&["-o", "--output"][..], &CONTEXT_OPTS].concat(),
),
_ => return None,
};
const BATCH: [&str; 4] = ["-r", "--recursive", "--names", "--out-dir"];
let (mut own, mut positionals) = (Vec::new(), Vec::new());
let (mut dir, mut names, mut out_dir) = (None, None, None);
let mut it = rest.iter();
while let Some(x) = it.next() {
if x == "--" {
positionals.extend(it.cloned());
break;
}
if BATCH.contains(&x.as_str()) {
let v = it.next().cloned();
match x.as_str() {
"--names" => names = v,
"--out-dir" => out_dir = v,
_ => dir = v,
}
} else if flags.contains(&x.as_str()) {
own.push(x.clone());
} else if opts.contains(&x.as_str()) {
own.push(x.clone());
own.extend(it.next().cloned());
} else if x.starts_with('-') && x.len() > 1 && x.parse::<f64>().is_err() {
return None;
} else {
positionals.push(x.clone());
}
}
let with_e = own.iter().any(|o| o == "-e" || o == "--pattern");
let lead = if cmd != "levels"
&& with_e
&& positionals.first().is_some_and(|p| Path::new(p).exists())
{
0
} else {
1
};
if positionals.len() < lead {
return None;
}
let files = match expand_inputs(&positionals[lead..], dir.as_deref(), names.as_deref()) {
Ok(f) => f,
Err(Fail(e)) => {
let _ = writeln!(err, "bigtext {cmd}: {e}");
return Some(2);
}
};
if cmd != "grep"
&& files.len() <= 1
&& dir.is_none()
&& out_dir.is_none()
&& files.len() + lead == positionals.len()
{
return None;
}
let single = if cmd == "grep" { "filter" } else { cmd };
let json = JSON.with(|j| j.get());
if files.len() > 1 && own.iter().any(|o| o == "-o" || o == "--output") {
let _ = writeln!(err, "bigtext {cmd}: -o writes one file; with several input files use --out-dir DIR (a NAME.filtered.EXT per file)");
return Some(2);
}
if let Some(d) = &out_dir {
if let Err(e) = std::fs::create_dir_all(d) {
let _ = writeln!(err, "bigtext {cmd}: {d}: {e}");
return Some(2);
}
}
let mut used_names = std::collections::HashSet::new();
let (mut matched, mut failed, mut total) = (false, false, 0u64);
for f in &files {
let mut a: Vec<String> = vec![single.to_string()];
a.extend(own.iter().cloned());
if json {
a.push("--json".into());
}
if cmd == "grep" && !own.iter().any(|o| o == "-n" || o == "--line-numbers") {
a.push("-n".into());
}
a.extend(positionals[..lead].iter().cloned());
a.push(f.clone());
if let Some(d) = &out_dir {
let p = Path::new(f);
let inner = match crate::decompress::detect(p) {
Some(_) => crate::decompress::inner_name(p),
None => p
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default(),
};
let q = Path::new(&inner);
let stem = q
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let ext = q.extension().map(|e| format!(".{}", e.to_string_lossy()));
let ext = ext.unwrap_or_default();
let mut name = format!("{stem}.filtered{ext}");
let mut k = 2;
while !used_names.insert(name.to_lowercase()) {
name = format!("{stem}.filtered-{k}{ext}");
k += 1;
}
a.push("-o".into());
a.push(Path::new(d).join(name).to_string_lossy().into_owned());
}
let mut buf = Vec::new();
let mut ebuf = Vec::new();
let code = run_command(&a, &mut buf, &mut ebuf);
let _ = err.write_all(&ebuf);
match code {
0 => matched = true,
1 => {}
_ => failed = true,
}
let name = display_path(Path::new(f));
if json {
if cmd == "count" {
let n = serde_json::from_slice::<serde_json::Value>(&buf)
.ok()
.and_then(|v| v["count"].as_u64())
.unwrap_or(0);
total += n;
}
let _ = out.write_all(&buf);
} else if cmd == "count" {
let n: u64 = String::from_utf8_lossy(&buf).trim().parse().unwrap_or(0);
total += n;
let _ = writeln!(out, "{name}: {n}");
} else {
for line in buf.split_inclusive(|&b| b == b'\n') {
let _ = out.write_all(format!("{name}:").as_bytes());
let _ = out.write_all(line);
}
}
}
if cmd == "count" && json {
let _ = writeln!(out, "{}", serde_json::json!({ "total": total }));
} else if cmd == "count" {
let _ = writeln!(out, "total: {total}");
}
Some(if failed {
2
} else if matched {
0
} else {
1
})
}
fn run_command(args: &[String], out: &mut dyn Write, err: &mut dyn Write) -> i32 {
let Some(cmd) = args.first().map(|c| c.trim_start_matches('-').to_string()) else {
let _ = write!(err, "{USAGE}");
return 2;
};
let json = matches!(
cmd.as_str(),
"filter" | "grep" | "count" | "levels" | "stats" | "replace" | "saved" | "csv"
) && args.iter().any(|a| a == "--json");
JSON.with(|j| j.set(json));
let mut rest: Vec<String> = args[1..]
.iter()
.filter(|a| !json || *a != "--json")
.cloned()
.collect();
if matches!(cmd.as_str(), "filter" | "count" | "grep") {
match with_saved(&rest) {
Ok(r) => rest = r,
Err(Fail(e)) => {
if json {
let _ = writeln!(out, "{}", serde_json::json!({"error": e}));
} else {
let _ = writeln!(err, "bigtext {cmd}: {e}");
}
return 2;
}
}
}
let rest = &rest[..];
if let Some(code) = run_batch(&cmd, rest, out, err) {
return code;
}
let r = match cmd.as_str() {
"filter" | "grep" => cmd_filter(rest, out, false),
"count" => cmd_filter(rest, out, true),
"levels" => cmd_levels(rest, out),
"split" => cmd_split(rest, out),
"redact" => cmd_redact(rest, out),
"stats" => cmd_stats(rest, out),
"merge" => cmd_merge(rest, out),
"convert" => cmd_convert(rest, out),
"report" => cmd_report(rest, out),
"sqldump" => cmd_sqldump(rest, out),
"values" => cmd_values(rest, out),
"gaps" => cmd_gaps(rest, out),
"patterns" => cmd_patterns(rest, out),
"extract" => cmd_extract(rest, out),
"validate" => cmd_validate(rest, out),
"join" => cmd_join(rest, out),
"pivot" => cmd_pivot(rest, out),
"derive" => cmd_derive(rest, out),
"jsonl" | "query" => cmd_jsonl(rest, out),
"jsondiff" => cmd_jsondiff(rest, out),
"diff" => cmd_diff(rest, out),
"only-in" => cmd_only_in(rest, out),
"diff-table" => cmd_diff_table(rest, out),
"transform" => cmd_transform(rest, out),
"replace" => cmd_replace(rest, out),
"csv" => cmd_csv(rest, out),
"saved" => cmd_saved(rest, out),
"ask" => cmd_ask(rest, out, err),
"head" => cmd_head_tail(rest, out, true),
"tail" => cmd_head_tail(rest, out, false),
"slice" => cmd_slice(rest, out),
"sort" => cmd_sort(rest, out, false),
"uniq" => cmd_sort(rest, out, true),
"format" => cmd_format(rest, out),
"help" | "h" => {
let _ = write!(out, "{USAGE}");
return 0;
}
_ => fail(format!("unknown command {cmd}")),
};
let _ = out.flush();
match r {
Ok(code) => code,
Err(Fail(m)) if m == HELP => {
let _ = write!(out, "{}", command_help(&cmd).unwrap_or_default());
0
}
Err(Fail(m)) if json => {
let _ = writeln!(out, "{}", serde_json::json!({"error": m}));
2
}
Err(Fail(m)) => {
let _ = writeln!(err, "bigtext {cmd}: {m}");
2
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn run_args(args: &[&str]) -> (i32, String, String) {
let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();
let (mut out, mut err) = (Vec::new(), Vec::new());
let code = run(&args, &mut out, &mut err);
(
code,
String::from_utf8_lossy(&out).into_owned(),
String::from_utf8_lossy(&err).into_owned(),
)
}
fn file(dir: &tempfile::TempDir, name: &str, text: &[u8]) -> String {
let p = dir.path().join(name);
std::fs::write(&p, text).unwrap();
p.to_string_lossy().into_owned()
}
#[test]
fn ask_runs_the_steps_and_prints_the_answer() {
use crate::ai::fake::{FakeReply, FakeServer};
let dir = tempfile::tempdir().unwrap();
let log = file(
&dir,
"app.log",
b"2024-05-01 10:00:00 INFO start\n2024-05-01 10:00:01 ERROR db timeout\n",
);
let none = file(&dir, "none.txt", b"# none\n");
let server = FakeServer::start(vec![
FakeReply::openai_tool("levels", r#"{"levels":["error"]}"#),
FakeReply::openai_text("1 error line: L2."),
FakeReply::openai_tool("count", r#"{"pattern":"INFO"}"#),
])
.unwrap();
let settings = file(
&dir,
"state.txt",
format!("ai_provider=custom\nai_conf=custom|1|fake|{}\n", server.url).as_bytes(),
);
let (code, out, err) = run_args(&[
"ask",
&log,
"find",
"all",
"errors",
"--settings",
&settings,
]);
assert_eq!(code, 0, "{err}");
assert_eq!(out.trim(), "1 error line: L2.", "{err}");
assert!(err.contains("levels"), "{err}");
assert!(err.contains("on this computer"), "{err}");
let body = server.requests()[0].json();
assert!(body["tools"]
.as_array()
.unwrap()
.iter()
.all(|t| t["function"]["name"] != "replace_all"));
let (code, out, _) = run_args(&[
"ask",
&log,
"how many INFO lines?",
"--plan",
"--provider",
"custom",
"--url",
&server.url,
"--model",
"fake",
"--settings",
&settings,
]);
assert_eq!(code, 0);
assert_eq!(out.trim(), r#"count {"pattern":"INFO"}"#);
let (code, _, err) = run_args(&["ask", &log, "x", "--settings", &none]);
assert_eq!(code, 2);
assert!(err.contains("no AI provider is set up"), "{err}");
let (code, _, err) =
run_args(&["ask", &log, "x", "--provider", "nope", "--settings", &none]);
assert_eq!(code, 2);
assert!(err.contains("the providers are: anthropic"), "{err}");
}
#[test]
fn sizes_are_binary_with_or_without_i() {
assert_eq!(parse_size("100MB"), Some(100 << 20));
assert_eq!(parse_size("100M"), Some(100 << 20));
assert_eq!(parse_size("100MiB"), Some(100 << 20));
assert_eq!(parse_size("1.5GiB"), Some(3 << 29));
assert_eq!(parse_size("64kib"), Some(64 << 10));
assert_eq!(parse_size("512"), Some(512));
assert_eq!(parse_size("MiB"), None);
assert_eq!(parse_size("0MB"), None);
}
#[test]
fn the_windowed_program_takes_commands_with_two_dashes() {
assert!(is_command("--filter"));
assert!(is_command("--diff-table"));
assert!(!is_command("sort"));
assert!(!is_command("-sort"));
assert!(!is_command("--nope"));
let d = tempfile::tempdir().unwrap();
let f = file(&d, "a.log", b"b\na\n");
assert_eq!(run_args(&["sort", &f]).1, "a\nb\n");
assert_eq!(run_args(&["--sort", &f]).1, "a\nb\n");
}
#[test]
fn filter_count_and_exit_codes() {
let d = tempfile::tempdir().unwrap();
let log = file(
&d,
"app.log",
b"10:00:00 INFO a\r\n10:00:01 ERROR b\r\n10:00:02 error c\r\n",
);
assert_eq!(
run_args(&["filter", "ERROR", &log]),
(0, "10:00:01 ERROR b\n".into(), String::new())
);
assert_eq!(
run_args(&["--filter", "-i", "error", &log]).1,
"10:00:01 ERROR b\n10:00:02 error c\n"
);
assert_eq!(
run_args(&["filter", "-v", "-E", "ERROR|INFO", &log]).1,
"10:00:02 error c\n"
);
assert_eq!(run_args(&["filter", "NOPE", &log]).0, 1);
assert_eq!(
run_args(&["count", "-i", "error", &log]),
(0, "2\n".into(), String::new())
);
assert_eq!(run_args(&["levels", "error", &log]).1, "10:00:01 ERROR b\n");
let out = d.path().join("errors.log");
assert_eq!(
run_args(&["filter", "ERROR", &log, "-o", &out.to_string_lossy()]).0,
0
);
assert_eq!(std::fs::read(&out).unwrap(), b"10:00:01 ERROR b\r\n");
let (code, _, err) =
run_args(&["filter", "x", &d.path().join("missing").to_string_lossy()]);
assert_eq!(code, 2);
assert!(err.starts_with("bigtext filter: "), "{err}");
assert_eq!(run_args(&["filter", "--bogus", "x", &log]).0, 2);
assert_eq!(run_args(&["frobnicate"]).0, 2);
assert_eq!(run_args(&["filter", "-E", "(", &log]).0, 2);
assert!(is_command("--stats") && !is_command("merge") && !is_command("--follow"));
}
#[test]
fn context_options() {
let d = tempfile::tempdir().unwrap();
let log = file(&d, "app.log", b"2024-05-01 10:00:00 INFO a\n2024-05-01 10:00:01 ERROR b\n\tat x.Y(Y.java:1)\n2024-05-01 10:00:02 INFO c\n2024-05-01 10:00:03 INFO d\n2024-05-01 10:00:04 ERROR e\n");
let (code, out, _) = run_args(&["filter", "-n", "-B", "1", "ERROR", &log]);
assert_eq!(code, 0);
assert_eq!(out, "1-2024-05-01 10:00:00 INFO a\n2:2024-05-01 10:00:01 ERROR b\n--\n5-2024-05-01 10:00:03 INFO d\n6:2024-05-01 10:00:04 ERROR e\n");
assert_eq!(
run_args(&["levels", "--entries", "error", &log]).1,
"2024-05-01 10:00:01 ERROR b\n\tat x.Y(Y.java:1)\n--\n2024-05-01 10:00:04 ERROR e\n"
);
assert_eq!(
run_args(&["filter", "-C", "1", "c$", &log, "-E"])
.1
.lines()
.count(),
3
);
assert_eq!(run_args(&["count", "-C", "3", "ERROR", &log]).1, "2\n");
let o = d.path().join("o.log");
run_args(&[
"filter",
"-n",
"-A",
"1",
"ERROR",
&log,
"-o",
&o.to_string_lossy(),
]);
assert_eq!(std::fs::read_to_string(&o).unwrap(), "2:2024-05-01 10:00:01 ERROR b\n3-\tat x.Y(Y.java:1)\n--\n6:2024-05-01 10:00:04 ERROR e\n");
assert_eq!(run_args(&["filter", "-A", "x", "ERROR", &log]).0, 2);
}
#[test]
fn convert_json_and_logfmt() {
let d = tempfile::tempdir().unwrap();
let j = file(
&d,
"a.json",
b"{\"n\": 2, \"events\": [ {\"id\": 1}, {\"id\": 2} ]}",
);
assert_eq!(
run_args(&["convert", &j, "--to", "jsonl"]).1,
"{\"id\":1}\n{\"id\":2}\n"
);
assert_eq!(
run_args(&["convert", &j, "--to", "jsonl", "--path", "$.events[1]"]).0,
2
);
let l = file(&d, "a.jsonl", b"{\"id\":1}\n{\"id\":2}\n");
assert_eq!(
run_args(&["convert", &l, "--to", "json"]).1,
"[\n{\"id\":1},\n{\"id\":2}\n]\n"
);
let f = file(
&d,
"a.log",
b"level=info msg=ok\nlevel=error msg=\"bad x\"\n",
);
assert_eq!(
run_args(&["convert", &f, "--to", "csv"]).1,
"level,msg\ninfo,ok\nerror,bad x\n"
);
assert_eq!(run_args(&["convert", &f, "--to", "json"]).0, 2);
let as_csv = run_args(&["convert", &f, "--to", "jsonl", "--kind", "csv"]);
assert_eq!(as_csv.0, 0);
assert_eq!(
as_csv,
run_args(&["convert", &f, "--to", "jsonl", "--from", "csv"])
);
}
#[test]
fn convert_json_array_to_csv_however_it_is_laid_out() {
let d = tempfile::tempdir().unwrap();
let rows = "a,b\n1,\"x, y\"\n2,\n";
for (name, text) in [
("one.json", &b"[{\"a\":1,\"b\":\"x, y\"},{\"a\":2}]"[..]),
("space.json", b" \n [{\"a\":1,\"b\":\"x, y\"},{\"a\":2}]\n"),
(
"bom.json",
b"\xEF\xBB\xBF[{\"a\":1,\"b\":\"x, y\"},{\"a\":2}]",
),
(
"pretty.json",
b"[\n {\"a\": 1, \"b\": \"x, y\"},\n {\"a\": 2}\n]\n",
),
(
"deep.json",
b"[\n {\n \"a\": 1,\n \"b\": \"x, y\"\n },\n {\n \"a\": 2\n }\n]\n",
),
] {
let f = file(&d, name, text);
assert_eq!(
run_args(&["convert", &f, "--to", "csv"]),
(0, rows.into(), String::new()),
"{name}"
);
}
let o = file(
&d,
"o.json",
b"{\"n\": 2, \"events\": [{\"a\":1,\"b\":\"x, y\"},{\"a\":2}]}",
);
assert_eq!(
run_args(&["convert", &o, "--to", "csv", "--path", "$.events"]).1,
rows
);
let bad = file(&d, "bad.json", b"[{\"a\":1} {\"a\":2}]");
let (code, _, err) = run_args(&["convert", &bad, "--to", "csv"]);
assert_eq!(code, 2);
assert!(err.starts_with("bigtext convert: expected ','"), "{err}");
}
#[test]
fn convert_detects_the_table() {
let d = tempfile::tempdir().unwrap();
let t = file(&d, "t.csv", b"sep=;\n# note\nk;v\nx;1\n");
assert_eq!(
run_args(&["convert", &t, "--to", "jsonl"]).1,
"{\"k\":\"x\",\"v\":\"1\"}\n"
);
let n = file(&d, "n.csv", b"1,2\n3,4\n5,6\n");
assert_eq!(
run_args(&["convert", &n, "--to", "jsonl"]).1.lines().next(),
Some("{\"column1\":\"1\",\"column2\":\"2\"}")
);
assert_eq!(
run_args(&["convert", &n, "--to", "jsonl", "--header"])
.1
.lines()
.next(),
Some("{\"1\":\"3\",\"2\":\"4\"}")
);
let q = file(&d, "q.csv", b"a,b\n'x,y',2\n");
assert_eq!(
run_args(&["convert", &q, "--to", "jsonl", "--quote", "'"]).1,
"{\"a\":\"x,y\",\"b\":\"2\"}\n"
);
}
#[test]
fn json_lines_queries() {
let d = tempfile::tempdir().unwrap();
let f = file(&d, "e.jsonl", b"{\"level\":\"error\",\"ms\":700,\"u\":{\"id\":1}}\n{\"level\":\"info\",\"ms\":20}\n{\"level\":\"error\",\"ms\":5,\"msg\":\"a, b\"}\n");
assert_eq!(
run_args(&["jsonl", &f, "-q", ".level == error and .ms > 500"]).1,
"{\"level\":\"error\",\"ms\":700,\"u\":{\"id\":1}}\n"
);
assert_eq!(
run_args(&["jsonl", &f, "-q", ".level = error", "--count"]).1,
"2\n"
);
assert_eq!(
run_args(&[
"jsonl",
&f,
"-q",
".level = error",
"-v",
"--fields",
"level,ms"
])
.1,
"{\"level\":\"info\",\"ms\":20}\n"
);
assert_eq!(
run_args(&["jsonl", &f, "--fields", "ms,u.id,msg", "--to", "csv"]).1,
"ms,u.id,msg\n700,1,\n20,,\n5,,\"a, b\"\n"
);
assert_eq!(run_args(&["jsonl", &f, "-q", ".nope exists"]).0, 1);
assert_eq!(run_args(&["jsonl", &f, "-q", "level"]).0, 2);
}
#[test]
fn derived_column() {
let d = tempfile::tempdir().unwrap();
let t = file(&d, "s.csv", b"price,qty\r\n2.5,4\r\n1,\"x\"\r\n");
assert_eq!(
run_args(&["derive", &t, "--name", "total", "--expr", "{price} * {qty}"]).1,
"price,qty,total\r\n2.5,4,10\r\n1,\"x\",\r\n"
);
assert_eq!(
run_args(&["derive", &t, "--name", "x", "--expr", "{nope}"]).0,
2
);
}
#[test]
fn pivot_tables() {
let d = tempfile::tempdir().unwrap();
let t = file(
&d,
"s.csv",
b"city,product,qty\nT,tea,3\nB,tea,5\nT,rice,7\n",
);
assert_eq!(
run_args(&["pivot", &t, "--rows", "city", "--cols", "product"]).1,
"city,rice,tea,total\nT,1,1,2\nB,0,1,1\n"
);
assert_eq!(
run_args(&["pivot", &t, "--rows", "1", "--cols", "2", "--value", "qty"]).1,
"city,rice,tea,total\nT,7,3,10\nB,,5,5\n"
);
assert_eq!(
run_args(&["pivot", &t, "--rows", "city", "--cols", "product", "--agg", "mean"]).0,
2
);
}
#[test]
fn join_tables() {
let d = tempfile::tempdir().unwrap();
let o = file(&d, "o.csv", b"order,user\n1,u1\n2,u3\n");
let u = file(&d, "u.csv", b"id,name\nu1,Ann\nu2,Bob\n");
assert_eq!(
run_args(&["join", &o, &u, "--left-on", "user", "--right-on", "id"]).1,
"order,user,name\n1,u1,Ann\n2,u3,\n"
);
assert_eq!(
run_args(&[
"join",
&o,
&u,
"--left-on",
"2",
"--right-on",
"1",
"--inner"
])
.1,
"order,user,name\n1,u1,Ann\n"
);
assert_eq!(run_args(&["join", &o, &u, "--on", "nope"]).0, 2);
}
#[test]
fn line_diff() {
let d = tempfile::tempdir().unwrap();
let a = file(
&d,
"a.log",
b"10:00:01 start req=a1\n10:00:02 Working\n10:00:03 end\n",
);
let b = file(
&d,
"b.log",
b"11:20:01 start req=f9\n11:20:02 working\n11:20:03 end\nextra\n",
);
let (code, out, _) = run_args(&["diff", &a, &b]);
assert_eq!(code, 1);
assert!(
out.starts_with(&format!(
"--- {a}\n+++ {b}\n@@ -1,3 +1,4 @@\n-10:00:01 start req=a1\n"
)),
"{out}"
);
assert!(out.ends_with("+11:20:03 end\n+extra\n"), "{out}");
let masked = ["diff", &a, &b, "-t", "-i", "--mask", "req=[0-9a-f]+"];
let (code, out, _) = run_args(&masked);
let body = |out: &str| out.lines().skip(2).map(String::from).collect::<Vec<_>>();
assert_eq!(
(code, body(&out)),
(
1,
vec![
"@@ -1,3 +1,4 @@".into(),
" 10:00:01 start req=a1".into(),
" 10:00:02 Working".into(),
" 10:00:03 end".into(),
"+extra".into()
]
)
);
let (_, out, _) = run_args(&[&masked[..], &["-U", "0"]].concat());
assert_eq!(body(&out), vec!["@@ -3,0 +4,1 @@", "+extra"]);
assert_eq!(
run_args(&["diff", &a, &b, "-q"]),
(1, format!("Files {a} and {b} differ\n"), String::new())
);
let o = d.path().join("out.diff").to_string_lossy().into_owned();
assert_eq!(run_args(&["diff", &a, &b, "-o", &o]).1, "");
assert!(std::fs::read_to_string(&o).unwrap().contains("+extra\n"));
assert_eq!(
run_args(&["diff", &a, &a]),
(0, String::new(), String::new())
);
assert_eq!(run_args(&["diff", &a, &a, "-q"]).0, 0);
assert_eq!(run_args(&["diff", &a, &b, "--mask", "("]).0, 2);
}
#[test]
fn lines_only_in_one_file() {
let d = tempfile::tempdir().unwrap();
let a = file(
&d,
"a.log",
b"09:00:01 start job=1\n09:00:02 load\n09:00:03 crash\n09:00:04 load\n",
);
let b = file(&d, "b.log", b"10:15:00 load\n10:15:01 start job=7\n");
assert_eq!(
run_args(&["only-in", &a, &b]),
(
1,
"09:00:01 start job=1\n09:00:02 load\n09:00:03 crash\n09:00:04 load\n".into(),
String::new()
)
);
let masked = ["only-in", &a, &b, "-t", "--mask", "job=[0-9]+"];
assert_eq!(
run_args(&masked),
(1, "09:00:03 crash\n".into(), String::new())
);
assert_eq!(
run_args(&[&masked[..], &["--count"]].concat()),
(1, "1\n".into(), String::new())
);
assert_eq!(
run_args(&["only-in", &b, &a, "-t", "--mask", "job=[0-9]+"]),
(0, String::new(), String::new())
);
}
#[test]
fn table_diff_by_key() {
let d = tempfile::tempdir().unwrap();
let a = file(&d, "a.csv", b"id,name,qty\n1,apple,5\n2,banana,7\n");
let b = file(
&d,
"b.csv",
b"qty,name,id\n6,apple,1\n7,banana,2\n1,fig,9\n",
);
assert_eq!(
run_args(&["diff-table", &a, &b, "--on", "id"]),
(
1,
"status,id,changed,name,qty\nchanged,1,qty,apple,5 → 6\nadded,9,,fig,1\n".into(),
String::new()
)
);
assert_eq!(
run_args(&[
"diff-table",
&a,
&b,
"--left-on",
"1",
"--right-on",
"3",
"--all"
])
.1
.lines()
.nth(2),
Some("same,2,,banana,7")
);
assert_eq!(
run_args(&["diff-table", &a, &b, "--key", "1", "--key-b", "3", "--all"]).1,
run_args(&[
"diff-table",
&a,
&b,
"--on",
"1",
"--right-on",
"3",
"--all"
])
.1
);
assert_eq!(run_args(&["diff-table", &a, &a, "--key", "id"]).0, 0);
assert_eq!(run_args(&["diff-table", &a, &b]).0, 2);
}
#[test]
fn csv_column_tools() {
let d = tempfile::tempdir().unwrap();
let t = file(
&d,
"s.csv",
b"id,city,amount\n1,Tashkent,120\n2,Bukhara,80\n3,Tashkent,40\n",
);
assert_eq!(
run_args(&["csv", &t, "cut", "amount,id"]).1,
"amount,id\n120,1\n80,2\n40,3\n"
);
assert_eq!(
run_args(&["csv", &t, "drop", "2"]).1,
"id,amount\n1,120\n2,80\n3,40\n"
);
assert_eq!(
run_args(&["csv", &t, "sort", "--by", "amount", "--desc"]).1,
"id,city,amount\n1,Tashkent,120\n2,Bukhara,80\n3,Tashkent,40\n"
);
assert_eq!(
run_args(&["csv", &t, "sort", "amount"]).1.lines().nth(1),
Some("3,Tashkent,40")
);
assert_eq!(
run_args(&["csv", &t, "where", "city=Tashkent", "amount>50"]).1,
"id,city,amount\n1,Tashkent,120\n"
);
assert_eq!(
run_args(&["csv", &t, "where", "amount", "lt", "100"]).1,
"id,city,amount\n2,Bukhara,80\n3,Tashkent,40\n"
);
assert_eq!(run_args(&["csv", &t, "where", "city~zzz"]).0, 1);
let st = run_args(&["csv", &t, "stats", "amount"]).1;
assert!(
st.contains("rows: 3\n") && st.contains("sum: 240\n") && st.contains("mean: 80\n"),
"{st}"
);
let gr = run_args(&["csv", &t, "group", "city", "--sum", "amount"]).1;
assert!(
gr.starts_with("city,rows,sum") || gr.contains("Tashkent"),
"{gr}"
);
let (code, _, err) = run_args(&["csv", &t, "cut", "nope"]);
assert!(
code == 2 && err.contains("the columns are id, city, amount"),
"{err}"
);
let semi = file(&d, "p.txt", b"a|b\n1|2\n");
assert_eq!(
run_args(&["csv", &semi, "cut", "b", "--delimiter", "|"]).1,
"b\n2\n"
);
}
#[test]
fn json_replace_and_saved_searches() {
let d = tempfile::tempdir().unwrap();
let log = file(&d, "a.log", b"ok\r\nERROR one\r\nERROR two\r\n");
let (code, out, _) = run_args(&["filter", "ERROR", &log, "--json"]);
assert_eq!(code, 0);
let recs: Vec<serde_json::Value> = out
.lines()
.map(|l| serde_json::from_str(l).unwrap())
.collect();
assert_eq!(
(
recs.len(),
recs[0]["line"].as_u64(),
recs[0]["offset"].as_u64(),
recs[1]["text"].as_str()
),
(2, Some(2), Some(4), Some("ERROR two"))
);
let c: serde_json::Value =
serde_json::from_str(run_args(&["count", "ERROR", &log, "--json"]).1.trim()).unwrap();
assert_eq!(c["count"], 2);
let st: serde_json::Value =
serde_json::from_str(run_args(&["stats", &log, "--json"]).1.trim()).unwrap();
assert_eq!(
(st["lines"].as_u64(), st["crlf"].as_u64()),
(Some(3), Some(3))
);
let no_saved = file(&d, "state.txt", b"# BigText session state\nfont_size=14\n");
let e: serde_json::Value = serde_json::from_str(
run_args(&[
"count",
"x",
"--saved",
"nope",
"--settings",
&no_saved,
"--json",
])
.1
.trim(),
)
.unwrap();
assert!(e["error"].as_str().unwrap().contains("nope"));
assert_eq!(
run_args(&["replace", "-E", "ERROR (\\w+)", "E[$1]", &log]).1,
"ok\r\nE[one]\r\nE[two]\r\n"
);
assert_eq!(
run_args(&["replace", "ERROR", "Error", &log, "--in-place", "--bak"]),
(0, "2 replaced\n".into(), String::new())
);
assert_eq!(
std::fs::read(&log).unwrap(),
b"ok\r\nError one\r\nError two\r\n"
);
assert!(std::path::Path::new(&format!("{log}.bak")).exists());
assert_eq!(
run_args(&["replace", "nothing", "x", &log, "--in-place"]).0,
1
);
let settings = file(
&d,
"settings.txt",
b"saved=Errors|i|0||error\nsaved=Not ok|c|1||ok\n",
);
assert_eq!(
run_args(&["saved", "--settings", &settings]).1,
"Errors\terror\nNot ok\tok (c) (lines without)\n"
);
assert_eq!(
run_args(&["count", "--saved", "Errors", "--settings", &settings, &log]).1,
"2\n"
);
assert_eq!(
run_args(&["filter", "--saved", "Not ok", "--settings", &settings, &log]).1,
"Error one\nError two\n"
);
}
#[test]
fn saved_tells_a_wrong_file_from_settings_without_searches() {
let d = tempfile::tempdir().unwrap();
let state = file(
&d,
"state.txt",
b"# BigText session state\r\nfont_size=14\r\n",
);
assert_eq!(
run_args(&["saved", "--settings", &state]),
(1, String::new(), String::new())
);
let not =
"not a BigText settings file (the app's state.txt, or one from Help → Export settings)";
for (name, text) in [
(
"app.log",
&b"2024-05-01 10:00:00 INFO start\n2024-05-01 10:00:01 ERROR x\n"[..],
),
("t.csv", b"name,count\nsaved,3\n"),
("a.json", b"[{\"saved\":1},{\"saved\":2}]"),
("b.bin", b"\x00\x01\x02\xFF\xFE\x00garbage"),
("logfmt.log", b"level=info msg=ok\nlevel=error msg=bad\n"),
(
"work.session",
b"# BigText session\ntab=0|0|0||a.log\npinned=0\n",
),
("empty.txt", b""),
] {
let f = file(&d, name, text);
let shown = display_path(Path::new(&f));
assert_eq!(
run_args(&["saved", "--settings", &f]),
(2, String::new(), format!("bigtext saved: {shown}: {not}\n")),
"{name}"
);
if name == "app.log" {
assert_eq!(
run_args(&["saved", "--json", "--settings", &f]),
(
2,
format!(
"{}\n",
serde_json::json!({"error": format!("{shown}: {not}")})
),
String::new()
)
);
assert_eq!(
run_args(&["count", "--saved", "Errors", "--settings", &f, &f]),
(2, String::new(), format!("bigtext count: {shown}: {not}\n"))
);
}
}
let missing = d.path().join("missing.txt");
let shown = display_path(&missing);
let (code, out, err) = run_args(&["saved", "--settings", &missing.to_string_lossy()]);
assert_eq!((code, out.as_str()), (2, ""));
assert!(
err.starts_with(&format!("bigtext saved: {shown}: ")) && !err.contains(not),
"{err}"
);
let exported = file(
&d,
"my.settings",
b"\xEF\xBB\xBF# BigText settings\nfont=Caf\xE9\nsaved=Errors|i|0||error\n",
);
assert_eq!(
run_args(&["saved", "--settings", &exported]),
(0, "Errors\terror\n".into(), String::new())
);
}
#[test]
fn many_files_folders_and_compressed_inputs() {
use std::io::Write as _;
let d = tempfile::tempdir().unwrap();
let sub = d.path().join("old");
std::fs::create_dir(&sub).unwrap();
let a = file(&d, "a.log", b"ok\nERROR one\n");
let _b = file(&d, "b.log", b"fine\n");
let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
gz.write_all(b"ERROR packed\nok\n").unwrap();
std::fs::write(sub.join("c.log.gz"), gz.finish().unwrap()).unwrap();
let star = d.path().join("*.log").to_string_lossy().into_owned();
let (code, out, _) = run_args(&["count", "ERROR", &star]);
assert_eq!(code, 0);
assert!(
out.contains("a.log: 1\n") && out.contains("b.log: 0\n") && out.ends_with("total: 1\n"),
"{out}"
);
let dir = d.path().to_string_lossy().into_owned();
let (code, out, _) = run_args(&["grep", "ERROR", "-r", &dir, "--names", "*.log;*.gz"]);
assert_eq!(code, 0);
assert!(
out.contains("a.log:2:ERROR one\n") && out.contains("c.log.gz:1:ERROR packed\n"),
"{out}"
);
assert_eq!(run_args(&["grep", "nothing", &a]).0, 1);
let outdir = d.path().join("out");
std::fs::create_dir(&outdir).unwrap();
let (code, _, _) = run_args(&[
"filter",
"ERROR",
&star,
"--out-dir",
&outdir.to_string_lossy(),
]);
assert_eq!(code, 0);
assert_eq!(
std::fs::read_to_string(outdir.join("a.filtered.log")).unwrap(),
"ERROR one\n"
);
assert_eq!(
run_args(&["filter", "packed", &sub.join("c.log.gz").to_string_lossy()]).1,
"ERROR packed\n"
);
assert_eq!(
run_args(&["count", "ERROR", &d.path().join("*.txt").to_string_lossy()]).0,
2
);
}
#[test]
fn head_tail_slice() {
let d = tempfile::tempdir().unwrap();
let log: String = (0..100)
.map(|i| format!("2024-05-01 10:{:02}:{:02} line {i}\n", i / 60, i % 60))
.collect();
let f = file(&d, "t.log", log.as_bytes());
let lines = |s: &str| s.lines().map(String::from).collect::<Vec<_>>();
assert_eq!(
lines(&run_args(&["head", "-n", "2", &f]).1),
["2024-05-01 10:00:00 line 0", "2024-05-01 10:00:01 line 1"]
);
assert_eq!(
lines(&run_args(&["tail", "-n", "1", &f]).1),
["2024-05-01 10:01:39 line 99"]
);
assert_eq!(run_args(&["tail", &f]).1.lines().count(), 10);
assert_eq!(
lines(&run_args(&["slice", &f, "--lines", "3-4"]).1),
["2024-05-01 10:00:02 line 2", "2024-05-01 10:00:03 line 3"]
);
assert_eq!(
run_args(&["slice", &f, "--bytes", "5-40"])
.1
.lines()
.count(),
2
);
let (code, out, _) = run_args(&[
"slice",
&f,
"--from",
"2024-05-01 10:01:00",
"--to",
"10:01:02",
]);
assert_eq!(
(code, lines(&out)),
(
0,
vec![
"2024-05-01 10:01:00 line 60".to_string(),
"2024-05-01 10:01:01 line 61".into(),
"2024-05-01 10:01:02 line 62".into()
]
)
);
assert_eq!(
run_args(&["slice", &f, "--from", "2024-05-02 00:00:00"]).0,
1
);
let csv = file(&d, "t.csv", b"id,v\n1,a\n2,b\n3,c\n");
assert_eq!(
run_args(&["slice", &csv, "--lines", "3-3", "--with-header"]).1,
"id,v\n2,b\n"
);
assert_eq!(
run_args(&["slice", &csv, "--lines", "3-3", "--header"]).1,
"id,v\n2,b\n"
);
assert_eq!(run_args(&["slice", &f]).0, 2);
}
#[test]
fn sort_and_uniq() {
let d = tempfile::tempdir().unwrap();
let f = file(&d, "s.txt", b"pear\napple\n10\n9\napple\n");
assert_eq!(run_args(&["sort", &f]).1, "10\n9\napple\napple\npear\n");
assert_eq!(
run_args(&["sort", "-n", "-r", &f]).1.lines().next(),
Some("10")
);
assert_eq!(run_args(&["sort", "-u", &f]).1, "10\n9\napple\npear\n");
assert_eq!(
run_args(&["uniq", "-c", &f]).1,
"2\tapple\n1\t10\n1\t9\n1\tpear\n"
);
}
#[test]
fn transform_and_format() {
let d = tempfile::tempdir().unwrap();
let t = file(&d, "t.log", b"Hello\tworld \nSecond\n");
assert_eq!(
run_args(&["transform", "--op", "upper", &t]).1,
"HELLO\tWORLD \nSECOND\n"
);
assert_eq!(
run_args(&["transform", "--op", "trim", &t]).1,
"Hello\tworld\nSecond\n"
);
assert_eq!(
run_args(&["transform", "--op", "tabs", &t]).1,
"Hello world \nSecond\n"
);
assert_eq!(run_args(&["transform", "--op", "sort", &t]).0, 2);
let j = file(&d, "j.json", b"{\"a\": [1, {\"b\": null}]}\n");
assert_eq!(
run_args(&["format", &j, "--style", "minify"]).1,
"{\"a\":[1,{\"b\":null}]}\n"
);
assert_eq!(
run_args(&["format", &j, "--json", "minify"]).1,
"{\"a\":[1,{\"b\":null}]}\n"
);
assert_eq!(run_args(&["format", &j, "--style", "tight"]).0, 2);
assert_eq!(
run_args(&["format", &j]).1,
"{\n \"a\": [\n 1,\n {\n \"b\": null\n }\n ]\n}\n"
);
let bad = file(&d, "bad.json", b"[1, 2");
assert_eq!(run_args(&["format", &bad]).0, 2);
}
#[test]
fn json_diff() {
let d = tempfile::tempdir().unwrap();
let a = file(&d, "a.json", b"{\"x\": 1, \"y\": [1, 2]}");
let b = file(&d, "b.json", b"{\n \"y\": [1, 3],\n \"x\": 1\n}");
assert_eq!(
run_args(&["jsondiff", &a, &b]),
(1, "$.y[1]: 2 -> 3\n".into(), String::new())
);
let c = file(&d, "c.json", b"{\"y\":[1,2],\"x\":1}");
assert_eq!(run_args(&["jsondiff", &a, &c]).0, 0);
}
#[test]
fn validate_json() {
let d = tempfile::tempdir().unwrap();
let j = file(&d, "a.json", b"{\n \"a\": [1, 2,]\n}\n");
assert_eq!(
run_args(&["validate", &j]),
(
1,
"2: byte 15: a comma before a closing bracket (a trailing comma)\n".into(),
String::new()
)
);
let l = file(&d, "a.jsonl", b"{\"a\":1}\n{\"a\":}\n{\"b\":2}\n");
assert_eq!(
run_args(&["validate", &l]).1,
"2: byte 13: a value is missing after the key\n"
);
let ok = file(&d, "ok.json", b"[1, {\"x\": null}]");
assert_eq!(run_args(&["validate", &ok]).0, 0);
let t = file(&d, "lines.txt", b"{\"a\":1}\n{\"a\":}\n");
let jsonl_problem = "2: byte 13: a value is missing after the key\n";
assert_eq!(
run_args(&["validate", &t, "--as", "jsonl"]).1,
jsonl_problem
);
assert_eq!(run_args(&["validate", &t, "--lines"]).1, jsonl_problem);
assert_eq!(run_args(&["validate", &t, "--as", "json"]).0, 1);
let braces = file(&d, "braces.csv", b"{a},b\n1,2\n");
assert_eq!(run_args(&["validate", &braces]).0, 1);
assert_eq!(run_args(&["validate", &braces, "--as", "csv"]).0, 0);
assert_eq!(run_args(&["validate", &ok, "--as", "xml"]).0, 2);
}
#[test]
fn validate_a_table() {
let d = tempfile::tempdir().unwrap();
let t = file(&d, "t.csv", b"id,qty\n1,2\n2\n3,x\n");
assert_eq!(
run_args(&["validate", "--numeric", "2", &t]),
(
1,
"3: 1 fields instead of 2\n4: column 2: not a number\n".into(),
String::new()
)
);
let ok = file(&d, "ok.csv", b"a,b\n1,2\n");
assert_eq!(run_args(&["validate", &ok]).0, 0);
}
#[test]
fn extract_matches() {
let d = tempfile::tempdir().unwrap();
let log = file(&d, "a.log", b"GET /a 200\nGET /b 404\nPOST /a 200\n");
assert_eq!(
run_args(&["extract", "-E", "[0-9]{3}", &log]).1,
"200\n404\n200\n"
);
assert_eq!(
run_args(&["extract", "-E", "--count", "-g", "1", r"(GET|POST) /", &log]).1,
"2\tGET\n1\tPOST\n"
);
assert_eq!(run_args(&["extract", "-E", "-g", "2", "(x)", &log]).0, 2);
assert_eq!(run_args(&["extract", "nope", &log]).0, 1);
}
#[test]
fn message_patterns() {
let d = tempfile::tempdir().unwrap();
let log = file(
&d,
"a.log",
b"10:00:00 INFO req 1 ok\n10:00:01 INFO req 2 ok\n10:00:02 ERROR disk full\n",
);
let (code, out, _) = run_args(&["patterns", &log]);
assert_eq!(code, 0);
assert_eq!(out.lines().nth(1), Some("2,INFO,INFO req <n> ok,0,23"));
assert_eq!(
run_args(&["patterns", "--rare", "--top", "1", &log])
.1
.lines()
.nth(1),
Some("1,ERROR,ERROR disk full,46,46")
);
}
#[test]
fn between_times() {
let d = tempfile::tempdir().unwrap();
let log = file(&d, "a.log", b"2024-05-01 10:00:00 ERROR a\n2024-05-01 10:00:30 ERROR b\n2024-05-01 10:01:00 INFO c\n2024-05-01 10:01:30 ERROR d\n");
assert_eq!(
run_args(&["filter", "ERROR", "--from", "10:00:30", "--to", "10:01:00", &log]).1,
"2024-05-01 10:00:30 ERROR b\n"
);
assert_eq!(
run_args(&["levels", "error", "--from", "2024-05-01 10:00:15", &log]).1,
"2024-05-01 10:00:30 ERROR b\n2024-05-01 10:01:30 ERROR d\n"
);
assert_eq!(
run_args(&["count", "ERROR", "--to", "10:00:30", &log]).1,
"2\n"
);
assert_eq!(run_args(&["filter", "ERROR", "--from", "noon", &log]).0, 2);
}
#[test]
fn combined_patterns() {
let d = tempfile::tempdir().unwrap();
let log = file(
&d,
"a.log",
b"ERROR timeout user=1\nERROR timeout healthcheck\nWARN timeout user=1\nERROR disk\n",
);
assert_eq!(
run_args(&[
"filter",
"ERROR",
"-e",
"timeout",
"--not",
"healthcheck",
&log
])
.1,
"ERROR timeout user=1\n"
);
assert_eq!(
run_args(&["count", "-e", "disk", "-e", "WARN", "--any", &log]).1,
"2\n"
);
assert_eq!(
run_args(&["count", "-e", "ERROR", "-e", "user=1", &log]).1,
"1\n"
);
assert_eq!(
run_args(&["filter", "-E", "--any", "-e", "^WARN", "-e", "disk$", &log]).1,
"WARN timeout user=1\nERROR disk\n"
);
assert_eq!(run_args(&["filter", &log]).0, 2);
}
#[test]
fn values_of_a_field() {
let d = tempfile::tempdir().unwrap();
let jl = file(
&d,
"e.jsonl",
b"\n{\"level\":\"info\"}\n{\"level\":\"error\"}\n{\"level\":\"info\"}\n",
);
assert_eq!(
run_args(&["values", "level", &jl]),
(
0,
"level,lines,percent,first,last\ninfo,2,66.67,,\nerror,1,33.33,,\n".into(),
String::new()
)
);
let lf = file(
&d,
"a.log",
b"ts=2024-05-01T10:00:00Z status=200\nts=2024-05-01T10:00:09Z status=200\n",
);
assert_eq!(
run_args(&["values", "status", &lf]).1.lines().nth(1),
Some("200,2,100.00,2024-05-01T10:00:00Z,2024-05-01T10:00:09Z")
);
let comma = file(
&d,
"c.log",
b"2024-05-01 10:00:00,250 status=500\n2024-05-01 10:00:01,500 status=500\n",
);
assert_eq!(
run_args(&["values", "status", &comma]).1.lines().nth(1),
Some("500,2,100.00,\"2024-05-01 10:00:00,250\",\"2024-05-01 10:00:01,500\"")
);
assert_eq!(run_args(&["values", "nope", &lf]).0, 1);
}
#[test]
fn gaps_with_line_numbers() {
let d = tempfile::tempdir().unwrap();
let log = file(
&d,
"a.log",
b"2024-05-01 10:00:00 a\n2024-05-01 10:00:05 b\n trace\n2024-05-01 10:02:05 c\n",
);
assert_eq!(
run_args(&["gaps", &log]),
(
0,
"2-4: +2 m 00.000 s (2024-05-01 10:00:05 -> 2024-05-01 10:02:05)\n".into(),
String::new()
)
);
assert_eq!(run_args(&["gaps", "--min", "5m", &log]).0, 1);
assert_eq!(run_args(&["gaps", "--min", "soon", &log]).0, 2);
assert_eq!(run_args(&["gaps", "--min", "1M", &log]).0, 2);
assert_eq!(run_args(&["gaps", "--min", "1min", &log]).0, 0);
let iso = file(
&d,
"iso.log",
b"2024-05-01T10:00:00.120Z a\n2024-05-01T10:01:00.120Z b\n",
);
assert_eq!(
run_args(&["gaps", &iso]).1,
"1-2: +1 m 00.000 s (2024-05-01T10:00:00.120Z -> 2024-05-01T10:01:00.120Z)\n"
);
}
#[test]
fn split_stats_merge_convert() {
let d = tempfile::tempdir().unwrap();
let log = file(
&d,
"a.log",
b"2024-05-01 10:00:00 one\n2024-05-01 10:00:02 two\n2024-05-01 11:00:00 three\n",
);
let (code, out, _) = run_args(&["split", "--lines", "2", &log]);
assert_eq!(code, 0);
assert_eq!(out.lines().count(), 2);
assert_eq!(
std::fs::read_to_string(d.path().join("a.part002.log")).unwrap(),
"2024-05-01 11:00:00 three\n"
);
let packed = d.path().join("packed");
std::fs::create_dir(&packed).unwrap();
let (_, out, _) = run_args(&[
"split",
"--lines",
"2",
"--gz",
"--out-dir",
&packed.to_string_lossy(),
&log,
]);
assert!(out.lines().all(|l| l.ends_with(".log.gz")), "{out}");
let empty = file(&d, "empty.log", b"");
assert_eq!(
run_args(&["split", "--lines", "2", &empty]),
(1, String::new(), String::new())
);
let gz = d.path().join("two.log.gz").to_string_lossy().into_owned();
assert_eq!(run_args(&["filter", "two", &log, "-o", &gz]).0, 0);
let mut text = Vec::new();
crate::decompress::unpack_to(
Path::new(&gz),
crate::decompress::Kind::Gzip,
&mut text,
&CancelToken::new(),
&Progress::default(),
)
.unwrap();
assert_eq!(text, b"2024-05-01 10:00:02 two\n");
let (_, s, _) = run_args(&["stats", &log]);
assert!(
s.contains("line endings: LF (LF 3, CRLF 0, CR 0)\n")
&& s.contains("final line break: yes\n")
&& s.contains("longest line: 25 bytes (line 3)\n"),
"{s}"
);
assert!(
s.contains("lines: 3\n")
&& s.contains("encoding: UTF-8")
&& s.contains("first time: 2024-05-01 10:00:00")
&& s.contains("last time: 2024-05-01 11:00:00")
&& s.contains("span: 1 h 00 m 00 s"),
"{s}"
);
let b = file(&d, "b.log", b"2024-05-01 10:00:01 b1\n");
assert_eq!(
run_args(&["merge", &log, &b]).1.lines().nth(1),
Some("b.log │ 2024-05-01 10:00:01 b1")
);
let csv_path = file(&d, "t.csv", b"k,v\nx,1\n");
assert_eq!(
run_args(&["convert", &csv_path, "--to", "jsonl"]).1,
"{\"k\":\"x\",\"v\":\"1\"}\n"
);
assert_eq!(run_args(&["convert", &csv_path, "--to", "xlsx"]).0, 2);
let jl = file(&d, "e.jsonl", b"{\"a\": 1}\n");
assert_eq!(run_args(&["convert", &jl, "--to", "csv"]).1, "a\n1\n");
assert_eq!(parse_size("100MB"), Some(100 << 20));
assert_eq!(parse_size("1.5g"), Some(3 << 29));
assert_eq!(parse_size("x"), None);
}
#[test]
fn options_json_and_several_files() {
let d = tempfile::tempdir().unwrap();
let a = file(
&d,
"a.log",
b"ERROR one
-foo two
INFO three
",
);
let sub = d.path().join("sub");
std::fs::create_dir(&sub).unwrap();
let b = sub.join("a.log");
std::fs::write(
&b,
b"ERROR four
",
)
.unwrap();
let b = b.to_string_lossy().into_owned();
let (code, out, err) = run_args(&["filter", "--", "-foo", &a]);
assert_eq!(
(code, out.as_str()),
(
0,
"-foo two
"
),
"{err}"
);
let (code, _, err) = run_args(&["filter", "-iv", "error", &a]);
assert_eq!(
(code, err.matches("unknown option").count()),
(2, 1),
"{err}"
);
let t = file(
&d,
"t.csv",
b"k,qty
x,-9
y,3
",
);
let (code, out, err) = run_args(&["csv", &t, "where", "qty", "lt", "-5"]);
assert_eq!(
(code, out.as_str()),
(
0,
"k,qty
x,-9
"
),
"{err}"
);
let nj = file(
&d,
"n.txt",
b"not json
",
);
assert_eq!(run_args(&["validate", &nj, "--json"]).0, 1);
let (code, out, _) = run_args(&["filter", "ERROR", &a, &b, "--json"]);
assert_eq!(code, 0);
let recs: Vec<serde_json::Value> = out
.lines()
.map(|l| serde_json::from_str(l).unwrap())
.collect();
assert_eq!(recs.len(), 2, "{out}");
let (_, out, _) = run_args(&["count", "ERROR", &a, &b, "--json"]);
assert!(
out.ends_with(
"{\"total\":2}
"
),
"{out}"
);
let o = d.path().join("o.txt").to_string_lossy().into_owned();
let (code, _, err) = run_args(&["filter", "ERROR", &a, &b, "-o", &o]);
assert_eq!(code, 2, "{err}");
assert!(err.contains("--out-dir"), "{err}");
let od = d.path().join("new").join("out");
let ods = od.to_string_lossy().into_owned();
assert_eq!(
run_args(&["filter", "ERROR", &a, &b, "--out-dir", &ods]).0,
0
);
let mut names: Vec<String> = std::fs::read_dir(&od)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
names.sort();
assert_eq!(names, ["a.filtered-2.log", "a.filtered.log"]);
assert_eq!(run_args(&["count", "ERROR", &a, "-o", &o]).0, 2);
assert_eq!(run_args(&["replace", "ERROR", "E", &a, "--json"]).0, 2);
let lf = file(
&d,
"lf.log",
b"level=error user=ann ms=5\nlevel=info user=bob ms=1\n",
);
let (code, out, err) =
run_args(&["jsonl", &lf, "-q", ".level = error", "--fields", "user,ms"]);
assert_eq!(
(code, out.as_str()),
(0, "{\"user\":\"ann\",\"ms\":\"5\"}\n"),
"{err}"
);
let (_, out, _) = run_args(&[
"jsonl",
&lf,
"-q",
".level = error",
"--fields",
"user,ms",
"--to",
"csv",
]);
assert_eq!(out, "user,ms\nann,5\n");
}
#[test]
fn command_help_prints_that_commands_part() {
let (code, out, err) = run_args(&["filter", "--help"]);
assert_eq!((code, err.as_str()), (0, ""));
assert!(out.starts_with(" filter [-v]"), "{out}");
assert!(out.contains("More patterns: -e PAT"), "{out}");
for part in [
"CONTEXT of filter",
"--json on",
"-- ends the options",
"several FILES",
] {
assert!(out.contains(part), "{part}: {out}");
}
assert!(out.contains("-o OUT ending in .gz") && out.contains("Exit codes:"));
for other in [
" split",
" levels",
" grep",
"bigtext-cli:",
"COMMAND --help",
] {
assert!(!out.contains(other), "{other}: {out}");
}
let (code, out, _) = run_args(&["split", "-h"]);
assert_eq!(code, 0);
assert!(out.starts_with(" split (--size"), "{out}");
assert!(out.contains("[--gz|--zst|--xz|--bz2]") && out.contains("Parts name"));
assert!(!out.contains("CONTEXT of") && !out.contains("--json on"));
assert!(out.contains("-- ends the options"));
for cmd in ["head", "tail"] {
let out = run_args(&[cmd, "--help"]).1;
assert!(out.contains(" head [-n N]") && out.contains(" tail [-n N]"));
assert!(out.contains("The first or last N lines"), "{out}");
assert!(!out.contains(" slice"), "{out}");
}
let out = run_args(&["query", "--help"]).1;
assert!(out.starts_with(" jsonl FILE") && out.contains("Lines that meet"));
for cmd in COMMANDS {
let (code, out, err) = run_args(&[cmd, "--help"]);
assert_eq!((code, err.as_str()), (0, ""), "{cmd}");
assert!(out.lines().any(|l| l.starts_with(&format!(" {cmd} "))));
assert_eq!(run_args(&[&format!("--{cmd}"), "-h"]).1, out, "{cmd}");
}
assert!(run_args(&["count", "--json", "--help"])
.1
.starts_with(" count "));
}
#[test]
fn help_as_a_pattern_is_still_searched() {
let d = tempfile::tempdir().unwrap();
let a = file(&d, "a.txt", b"run with --help\nother\n");
for args in [
vec!["filter", "--", "--help", &a],
vec!["filter", "-e", "--help", &a],
] {
let (code, out, err) = run_args(&args);
assert_eq!((code, out.as_str()), (0, "run with --help\n"), "{err}");
}
assert_eq!(run_args(&["help"]).1, USAGE);
assert_eq!(run_args(&["nosuch", "--help"]).0, 2);
}
}