Skip to main content

lean_ctx_patterns/
wget.rs

1// SPDX-License-Identifier: Apache-2.0
2
3macro_rules! static_regex {
4    ($pattern:expr_2021) => {{
5        static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
6        RE.get_or_init(|| {
7            regex::Regex::new($pattern).expect(concat!("BUG: invalid static regex: ", $pattern))
8        })
9    }};
10}
11
12fn progress_re() -> &'static regex::Regex {
13    static_regex!(r"^\s*\d+K\s+.*\d+%")
14}
15
16pub fn compress(output: &str) -> Option<String> {
17    let trimmed = output.trim();
18    if trimmed.is_empty() {
19        return Some("ok".to_string());
20    }
21
22    let useful: Vec<&str> = trimmed
23        .lines()
24        .filter(|l| {
25            let t = l.trim();
26            !t.is_empty()
27                && !progress_re().is_match(t)
28                && !t.starts_with("Length:")
29                && !t.starts_with("Connecting to")
30                && !t.starts_with("Resolving")
31                && !t.starts_with("HTTP request sent")
32                && !t.starts_with("Reusing existing")
33        })
34        .collect();
35
36    let saved = trimmed.lines().find(|l| l.contains("saved"));
37
38    if let Some(saved_line) = saved {
39        let mut result = Vec::new();
40        for line in &useful {
41            if line.contains("Saving to") || line.contains("saved") || line.contains("--") {
42                result.push(line.to_string());
43            }
44        }
45        if result.is_empty() {
46            result.push(saved_line.trim().to_string());
47        }
48        return Some(result.join("\n"));
49    }
50
51    if useful.len() <= 5 {
52        return Some(useful.join("\n"));
53    }
54    Some(format!(
55        "{}\n{}",
56        useful[..3].join("\n"),
57        super::elision_marker(useful.len() - 3)
58    ))
59}