use serde_json::{json, Value};
use crate::jobs::CancelToken;
use crate::lines::LineReader;
use crate::text::TextBuf;
const READ_LINES: usize = 200;
pub const SAMPLE_LINES: usize = 12;
pub const LINE_CHARS: usize = 200;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Profile {
pub name: String,
pub size: u64,
pub encoding: String,
pub line_ending: &'static str,
pub lines: (u64, bool),
pub kind: &'static str,
pub log_format: Option<(String, Vec<String>)>,
pub levels: bool,
pub first_time: Option<String>,
pub last_time: Option<String>,
pub csv: Option<(String, Vec<String>)>,
pub fields: Vec<String>,
pub samples: Vec<(u64, String)>,
pub edited: bool,
}
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
}
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
}
}
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;
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");
}
}