bigtext 0.19.0

Free editor for huge text and log files (1-50+ GB): opens them without loading them into memory, 4 GB/s search, atomic save
Documentation
//! What the model learns about a file before it plans: its kind (log, JSON Lines, CSV, …),
//! encoding, size, line breaks, log format and fields, whether it has log levels and
//! timestamps, and a few of its first lines. A few hundred bytes, whatever the file's size.

use serde_json::{json, Value};

use crate::jobs::CancelToken;
use crate::lines::LineReader;
use crate::text::TextBuf;

/// Lines read for the profile, and lines of them shown to the model.
const READ_LINES: usize = 200;
pub const SAMPLE_LINES: usize = 12;
/// Characters of a sample line the model sees.
pub const LINE_CHARS: usize = 200;

#[derive(Clone, Debug, Default, PartialEq)]
pub struct Profile {
    /// The file's name (not its folder).
    pub name: String,
    pub size: u64,
    pub encoding: String,
    pub line_ending: &'static str,
    /// Lines, and whether that number is exact yet.
    pub lines: (u64, bool),
    /// "log", "jsonl", "json", "logfmt", "csv" or "text".
    pub kind: &'static str,
    /// A web server or syslog format, with its columns.
    pub log_format: Option<(String, Vec<String>)>,
    /// Level words (ERROR, WARN, …) are in the first lines.
    pub levels: bool,
    /// The first and the last timestamp, as the file writes them.
    pub first_time: Option<String>,
    pub last_time: Option<String>,
    /// A table's delimiter and header.
    pub csv: Option<(String, Vec<String>)>,
    /// JSON Lines or logfmt keys of the first records.
    pub fields: Vec<String>,
    /// (1-based line, text) of the first lines.
    pub samples: Vec<(u64, String)>,
    /// The file has unsaved edits.
    pub edited: bool,
}

/// A line's text for the model: decoded, without its line break, at most [`LINE_CHARS`].
pub fn clip(text: &str) -> String {
    let t = text.trim_end_matches(['\n', '\r']);
    let mut out: String = t.chars().take(LINE_CHARS).collect();
    if out.len() < t.len() {
        out.push('…');
    }
    out
}

fn line_ending(head: &[u8]) -> &'static str {
    let crlf = head.windows(2).filter(|w| w == b"\r\n").count();
    let lf = head.iter().filter(|&&b| b == b'\n').count() - crlf;
    let cr = head.iter().filter(|&&b| b == b'\r').count() - crlf;
    match (crlf > 0, lf > 0, cr > 0) {
        (true, false, false) => "CRLF",
        (false, true, false) => "LF",
        (false, false, true) => "CR",
        (false, false, false) => "none",
        _ => "mixed",
    }
}

impl Profile {
    pub fn build(buf: &TextBuf, name: &str, cancel: &CancelToken) -> Profile {
        let codec = buf.codec;
        let head = buf
            .read(0..buf.len().min(64 * 1024))
            .map(|b| b.to_vec())
            .unwrap_or_default();
        let mut p = Profile {
            name: name.to_string(),
            size: buf.len(),
            encoding: codec.enc.name().to_string(),
            line_ending: line_ending(&head),
            lines: buf.line_count(),
            edited: !buf.is_pristine(),
            ..Default::default()
        };
        let mut r = LineReader::new(buf);
        let mut lines: Vec<(u64, Vec<u8>)> = Vec::new();
        while lines.len() < READ_LINES && !cancel.is_cancelled() {
            let Ok(Some((off, l))) = r.next() else { break };
            lines.push((off, l.to_vec()));
        }
        let texts: Vec<String> = lines
            .iter()
            .map(|(_, l)| {
                codec
                    .decode_lossy(l)
                    .trim_end_matches(['\n', '\r'])
                    .to_string()
            })
            .collect();
        let nonblank: Vec<&str> = texts
            .iter()
            .map(String::as_str)
            .filter(|t| !t.trim().is_empty())
            .collect();
        p.samples = texts
            .iter()
            .enumerate()
            .filter(|(_, t)| !t.trim().is_empty())
            .take(SAMPLE_LINES)
            .map(|(i, t)| (i as u64 + 1, clip(t)))
            .collect();
        let format = crate::logformat::detect(buf).ok().flatten();
        let jsonl = nonblank.len() > 1
            && nonblank
                .iter()
                .take(10)
                .all(|l| l.trim_start().starts_with('{') && l.trim_end().ends_with('}'));
        let logfmt = !jsonl
            && nonblank
                .iter()
                .take(10)
                .filter(|l| {
                    crate::fields::line_fields(l)
                        .is_some_and(|f| f.0 == crate::fields::Syntax::Logfmt)
                })
                .count()
                * 2
                > nonblank.len().min(10);
        let lq = crate::loglevel::query(crate::loglevel::Levels::from_bits(0x0F))
            .and_then(|q| crate::search::Matcher::new(&q, crate::encoding::Codec::utf8()).ok());
        p.levels = lq.is_some_and(|m| {
            nonblank.iter().any(|l| {
                let mut found = false;
                m.find_in(
                    l.as_bytes(),
                    0,
                    0,
                    l.len(),
                    l.len(),
                    &mut None,
                    &mut |_, _| {
                        found = true;
                        false
                    },
                );
                found
            })
        });
        let stamps: Vec<String> = nonblank
            .iter()
            .filter_map(|l| crate::timestamp::parse_text(l).map(|(_, t)| t))
            .take(1)
            .collect();
        p.first_time = stamps.into_iter().next();
        p.last_time = last_time(buf, cancel);
        if jsonl || logfmt {
            let mut keys: Vec<String> = Vec::new();
            for l in nonblank.iter().take(20) {
                if let Some((_, fs)) = crate::fields::line_fields(l) {
                    for f in fs {
                        if !keys.contains(&f.key) && keys.len() < 40 {
                            keys.push(f.key);
                        }
                    }
                }
            }
            p.fields = keys;
        }
        p.kind = if head.trim_ascii_start().starts_with(b"[")
            || (head.trim_ascii_start().starts_with(b"{") && !jsonl)
        {
            "json"
        } else if jsonl {
            "jsonl"
        } else if let Some(f) = &format {
            p.log_format = Some((f.kind.name().to_string(), f.columns.clone()));
            "log"
        } else if logfmt {
            "logfmt"
        } else if p.levels || p.first_time.is_some() {
            "log"
        } else if let Some(d) =
            crate::csv::detect(&codec, &head, head.len() as u64 == buf.len(), b',')
                .filter(|_| nonblank.len() > 1)
        {
            let mut ranges = Vec::new();
            let first = lines.first().map(|(_, l)| l.as_slice()).unwrap_or_default();
            crate::csv::split_fields(&codec, d, first, &mut ranges);
            let header = ranges
                .iter()
                .take(60)
                .map(|r| clip(&crate::csv::field_value(&codec, d, &first[r.clone()])))
                .collect();
            p.csv = Some((d.name().to_string(), header));
            "csv"
        } else {
            "text"
        };
        p
    }

    /// The profile for the model, its sample lines passed through `redact`.
    pub fn to_json(&self, redact: &mut dyn FnMut(&str) -> String) -> Value {
        let mut v = json!({
            "name": self.name,
            "kind": self.kind,
            "size_bytes": self.size,
            "encoding": self.encoding,
            "line_breaks": self.line_ending,
            "lines": self.lines.0,
        });
        if !self.lines.1 {
            v["lines_estimated"] = json!(true);
        }
        if self.edited {
            v["unsaved_edits"] = json!(true);
        }
        if let Some((name, cols)) = &self.log_format {
            v["log_format"] = json!({"name": name, "columns": cols});
        }
        v["log_levels"] = json!(self.levels);
        if let Some(t) = &self.first_time {
            v["first_time"] = json!(redact(t));
        }
        if let Some(t) = &self.last_time {
            v["last_time"] = json!(redact(t));
        }
        if let Some((delim, header)) = &self.csv {
            v["csv"] = json!({"delimiter": delim, "header": header.iter().map(|h| redact(h)).collect::<Vec<_>>()});
        }
        if !self.fields.is_empty() {
            v["fields"] = json!(self.fields);
        }
        v["first_lines"] = self
            .samples
            .iter()
            .map(|(n, t)| json!({"line": n, "text": redact(t)}))
            .collect();
        v
    }
}

/// The last timestamp in the last lines of the file.
fn last_time(buf: &TextBuf, cancel: &CancelToken) -> Option<String> {
    let start = crate::lines::last_lines_start(buf, 50)?;
    let tail = buf.read(start..buf.len())?;
    let text = buf.codec.decode_lossy(&tail);
    if cancel.is_cancelled() {
        return None;
    }
    text.lines()
        .rev()
        .find_map(|l| crate::timestamp::parse_text(l).map(|(_, t)| t))
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::encoding::Codec;
    use crate::file::{OpenMode, Source};
    use std::io::Write;
    use std::sync::Arc;

    /// A UTF-8 document of `text` (the file lives as long as the first value).
    pub fn buf(text: &str) -> (tempfile::NamedTempFile, TextBuf) {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        f.write_all(text.as_bytes()).unwrap();
        f.flush().unwrap();
        let src = Arc::new(Source::open(f.path(), OpenMode::Auto).unwrap());
        let idx = crate::index::build_blocking(&src, Codec::utf8());
        let mut b = TextBuf::new(src, idx, Codec::utf8());
        b.blocking = true;
        (f, b)
    }

    #[test]
    fn a_log() {
        let (_f, b) = buf("2024-05-01 10:00:00 INFO start\n2024-05-01 10:00:01 ERROR db timeout\n2024-05-01 10:05:00 WARN slow\n");
        let p = Profile::build(&b, "app.log", &CancelToken::new());
        assert_eq!(p.kind, "log");
        assert!(p.levels);
        assert_eq!(p.first_time.as_deref(), Some("2024-05-01 10:00:00"));
        assert_eq!(p.last_time.as_deref(), Some("2024-05-01 10:05:00"));
        assert_eq!(p.samples.len(), 3);
        assert_eq!(p.line_ending, "LF");
        let v = p.to_json(&mut |s| s.replace("db", "XX"));
        assert_eq!(
            v["first_lines"][1]["text"],
            "2024-05-01 10:00:01 ERROR XX timeout"
        );
        assert_eq!(v["lines"], 4);
    }

    #[test]
    fn json_lines_and_csv() {
        let (_f, b) = buf("{\"level\":\"info\",\"msg\":\"a\",\"user\":{\"id\":1}}\n{\"level\":\"error\",\"msg\":\"b\"}\n");
        let p = Profile::build(&b, "x.jsonl", &CancelToken::new());
        assert_eq!(p.kind, "jsonl");
        assert!(p.fields.contains(&"user.id".to_string()));
        let (_g, b) = buf("city,age\r\nTashkent,31\r\nSamarkand,25\r\n");
        let p = Profile::build(&b, "t.csv", &CancelToken::new());
        assert_eq!(p.kind, "csv");
        assert_eq!(p.csv.as_ref().unwrap().1, vec!["city", "age"]);
        assert_eq!(p.line_ending, "CRLF");
        let (_h, b) = buf("just some words\nand more\n");
        assert_eq!(
            Profile::build(&b, "a.txt", &CancelToken::new()).kind,
            "text"
        );
    }

    #[test]
    fn long_lines_are_clipped() {
        let long = "x".repeat(1000);
        assert_eq!(clip(&long).chars().count(), LINE_CHARS + 1);
        assert_eq!(clip("short\r\n"), "short");
    }
}