use once_cell::sync::Lazy;
use regex::Regex;
const MIN_CHARS: usize = 800;
const MINIFIED_LINE_CHARS: usize = 2000;
const BASE64_RUN_CHARS: usize = 1500;
static LOCK_HEADER: Lazy<Regex> = Lazy::new(|| {
Regex::new(concat!(
r#"(?m)^# This file is automatically @?generated"#, r#"|^# yarn lockfile v1"#, r#"|^"lockfileVersion":"#, r#"|^lockfileVersion:"#, ))
.unwrap()
});
static LOCK_RECORD: Lazy<Regex> = Lazy::new(|| {
Regex::new(concat!(
r#"(?m)^\s*"?(resolved|integrity)"?\s*[:=]"#, r#"|^\s*checksum = ""#, r#"|^\s*"resolved":"#,
))
.unwrap()
});
static CARGO_PACKAGE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?m)^\[\[package\]\]").unwrap());
static BASE64_RUN: Lazy<Regex> = Lazy::new(|| Regex::new(r"[A-Za-z0-9+/=]{40,}").unwrap());
pub fn compress(text: &str) -> Option<String> {
let chars = text.chars().count();
if chars < MIN_CHARS {
return None;
}
if is_lockfile(text) || is_minified(text) || is_base64_blob(text) {
let lines = text.lines().count();
return Some(format!(
"[generated file elided: {lines} lines, ~{chars} chars]"
));
}
None
}
fn is_lockfile(text: &str) -> bool {
if LOCK_HEADER.is_match(text) {
return true;
}
let lines = text.lines().count();
if lines < 12 {
return false; }
let records = LOCK_RECORD.find_iter(text).count();
records * 100 >= lines * 15 || (CARGO_PACKAGE.find_iter(text).count() >= 5 && records >= 5)
}
fn is_minified(text: &str) -> bool {
text.lines().any(|line| {
let len = line.chars().count();
if len < MINIFIED_LINE_CHARS {
return false;
}
let ws = line.chars().filter(|c| c.is_whitespace()).count();
let punct = line
.chars()
.filter(|c| matches!(c, ';' | '{' | '}' | '(' | ')' | ',' | '=' | ':' | '.'))
.count();
ws * 100 < len * 8 && punct * 100 >= len * 4
})
}
fn is_base64_blob(text: &str) -> bool {
BASE64_RUN
.find_iter(text)
.any(|m| m.as_str().chars().count() >= BASE64_RUN_CHARS)
}
#[cfg(test)]
mod tests {
use super::*;
fn count_tokens(s: &str) -> usize {
s.split_whitespace().count()
}
fn assert_big_savings(input: &str, out: &str) {
let before = count_tokens(input);
let after = count_tokens(out);
let savings = 100.0 - (after as f64 / before as f64 * 100.0);
assert!(
savings >= 60.0,
"expected ≥60% token savings, got {savings:.1}%"
);
}
#[test]
fn cargo_lock_body_elides() {
let mut body = String::from("# This file is automatically @generated by Cargo.\n");
body.push_str("# It is not intended for manual editing.\n");
for i in 0..40 {
body.push_str(&format!(
"[[package]]\nname = \"crate-{i}\"\nversion = \"1.{i}.0\"\nsource = \"registry+https://github.com/rust-lang/crates.io-index\"\nchecksum = \"a1b2c3d4e5f6{i:040}\"\n\n"
));
}
let out = compress(&body).expect("a Cargo.lock body elides");
assert!(
out.starts_with("[generated file elided:"),
"marker emitted: {out}"
);
assert!(out.lines().count() == 1, "collapsed to one line");
assert_big_savings(&body, &out);
}
#[test]
fn package_lock_excerpt_elides_without_header() {
let mut body = String::new();
for i in 0..30 {
body.push_str(&format!(
" \"node_modules/pkg-{i}\": {{\n \"version\": \"2.{i}.1\",\n \"resolved\": \"https://registry.npmjs.org/pkg-{i}/-/pkg-{i}-2.{i}.1.tgz\",\n \"integrity\": \"sha512-{i:080}==\"\n }},\n"
));
}
let out = compress(&body).expect("a package-lock excerpt elides by density");
assert!(out.starts_with("[generated file elided:"));
assert_big_savings(&body, &out);
}
#[test]
fn minified_bundle_elides() {
let chunk = "function f(a,b){return a+b;}var x={k:1,v:2};g(x,f);";
let line = chunk.repeat(80); let body = format!("//# sourceMappingURL=bundle.js.map\n{line}\n");
let out = compress(&body).expect("a minified bundle elides");
assert!(out.starts_with("[generated file elided:"));
assert_big_savings(&body, &out);
}
#[test]
fn base64_blob_elides() {
let blob = "A".repeat(BASE64_RUN_CHARS + 200);
let body = format!("data:font/woff2;base64,{blob}");
let out = compress(&body).expect("a long base64 blob elides");
assert!(out.starts_with("[generated file elided:"));
}
#[test]
fn ordinary_rust_code_is_not_elided() {
let code = (0..60)
.map(|i| {
format!(
" let value_{i} = compute(input_{i}, factor); // step {i} of the pipeline"
)
})
.collect::<Vec<_>>()
.join("\n");
assert_eq!(
compress(&code),
None,
"ordinary source is left for the normal arm"
);
}
#[test]
fn ordinary_json_is_not_elided() {
let json = (0..40)
.map(|i| format!(" \"setting_{i}\": {{ \"enabled\": true, \"weight\": {i} }},"))
.collect::<Vec<_>>()
.join("\n");
let json = format!("{{\n{json}\n \"version\": \"1.0.0\"\n}}");
assert_eq!(
compress(&json),
None,
"ordinary JSON config is not a lockfile"
);
}
#[test]
fn prose_is_not_elided() {
let prose = "the quick brown fox jumps over the lazy dog ".repeat(60);
assert_eq!(compress(&prose), None, "prose is never a generated file");
}
#[test]
fn small_body_is_declined() {
let small = "resolved \"x\"\nintegrity \"y\"\nresolved \"z\"";
assert_eq!(compress(small), None, "below MIN_CHARS, declined");
}
}