Skip to main content

lean_ctx/core/patterns/
docker.rs

1macro_rules! static_regex {
2    ($pattern:expr_2021) => {{
3        static RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
4        RE.get_or_init(|| {
5            regex::Regex::new($pattern).expect(concat!("BUG: invalid static regex: ", $pattern))
6        })
7    }};
8}
9
10fn log_timestamp_re() -> &'static regex::Regex {
11    static_regex!(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}")
12}
13
14pub fn compress(command: &str, output: &str) -> Option<String> {
15    if command.contains("build") {
16        return Some(compress_build(output));
17    }
18    if command.contains("compose") && command.contains("ps") {
19        return Some(compress_compose_ps(output));
20    }
21    if command.contains("compose")
22        && (command.contains("up")
23            || command.contains("down")
24            || command.contains("start")
25            || command.contains("stop"))
26    {
27        return Some(compress_compose_action(output));
28    }
29    if command.contains("ps") {
30        return Some(compress_ps(output));
31    }
32    if command.contains("images") {
33        return Some(compress_images(output));
34    }
35    if command.contains("logs") {
36        return Some(compress_logs(output));
37    }
38    if command.contains("network") {
39        return Some(compress_network(output));
40    }
41    if command.contains("volume") {
42        return Some(compress_volume(output));
43    }
44    if command.contains("inspect") {
45        return Some(compress_inspect(output));
46    }
47    if command.contains("exec") || command.contains("run") {
48        return Some(compress_exec(output));
49    }
50    if command.contains("system") && command.contains("df") {
51        return Some(compress_system_df(output));
52    }
53    if command.contains("info") {
54        return Some(compress_info(output));
55    }
56    if command.contains("version") {
57        return Some(compress_version(output));
58    }
59    None
60}
61
62fn compress_build(output: &str) -> String {
63    let mut steps = 0u32;
64    let mut last_step = String::new();
65    let mut errors = Vec::new();
66
67    for line in output.lines() {
68        if line.starts_with("Step ") || (line.starts_with('#') && line.contains('[')) {
69            steps += 1;
70            last_step = line.trim().to_string();
71        }
72        if line.contains("ERROR") || line.contains("error:") {
73            errors.push(line.trim().to_string());
74        }
75    }
76
77    if !errors.is_empty() {
78        return format!(
79            "{steps} steps, {} errors:\n{}",
80            errors.len(),
81            errors.join("\n")
82        );
83    }
84
85    if steps > 0 {
86        format!("{steps} steps, last: {last_step}")
87    } else {
88        "built".to_string()
89    }
90}
91
92fn compress_ps(output: &str) -> String {
93    let lines: Vec<&str> = output.lines().collect();
94    if lines.len() <= 1 {
95        return "no containers".to_string();
96    }
97
98    let header = lines[0];
99    let col_positions = parse_docker_columns(header);
100
101    let mut containers = Vec::new();
102    for line in &lines[1..] {
103        if line.trim().is_empty() {
104            continue;
105        }
106
107        let name = extract_column(line, &col_positions, "NAMES")
108            .unwrap_or_else(|| extract_last_word(line));
109        let mut status =
110            extract_column(line, &col_positions, "STATUS").unwrap_or_else(|| "?".to_string());
111        let image = extract_column(line, &col_positions, "IMAGE");
112
113        // Fallback: if health/exit annotations are in the raw line but missing
114        // from the column-extracted status (column slicing can truncate them),
115        // recover them from the raw line.
116        for annotation in &["(unhealthy)", "(healthy)", "(health: starting)"] {
117            if line.contains(annotation) && !status.contains(annotation) {
118                status = format!("{status} {annotation}");
119            }
120        }
121        if line.contains("Exited")
122            && !status.contains("Exited")
123            && let Some(pos) = line.find("Exited")
124        {
125            let end = line[pos..].find(')').map_or(pos + 6, |p| pos + p + 1);
126            let exited_str = &line[pos..end.min(line.len())];
127            status = exited_str.to_string();
128        }
129
130        let mut entry = name.clone();
131        if let Some(img) = image {
132            entry = format!("{name} ({img})");
133        }
134        entry = format!("{entry}: {status}");
135        containers.push(entry);
136    }
137
138    if containers.is_empty() {
139        return "no containers".to_string();
140    }
141    containers.join("\n")
142}
143
144fn parse_docker_columns(header: &str) -> Vec<(String, usize)> {
145    let cols = [
146        "CONTAINER ID",
147        "IMAGE",
148        "COMMAND",
149        "CREATED",
150        "STATUS",
151        "PORTS",
152        "NAMES",
153    ];
154    let mut positions: Vec<(String, usize)> = Vec::new();
155    for col in &cols {
156        if let Some(pos) = header.find(col) {
157            positions.push((col.to_string(), pos));
158        }
159    }
160    positions.sort_by_key(|(_, pos)| *pos);
161    positions
162}
163
164fn extract_column(line: &str, cols: &[(String, usize)], name: &str) -> Option<String> {
165    let idx = cols.iter().position(|(n, _)| n == name)?;
166    let start = cols[idx].1;
167    let end = cols.get(idx + 1).map_or(line.len(), |(_, p)| *p);
168    if start >= line.len() {
169        return None;
170    }
171    let end = end.min(line.len());
172    let val = line[start..end].trim().to_string();
173    if val.is_empty() { None } else { Some(val) }
174}
175
176fn extract_last_word(line: &str) -> String {
177    line.split_whitespace().last().unwrap_or("?").to_string()
178}
179
180fn compress_images(output: &str) -> String {
181    let lines: Vec<&str> = output.lines().collect();
182    if lines.len() <= 1 {
183        return "no images".to_string();
184    }
185
186    let mut images = Vec::new();
187    for line in &lines[1..] {
188        let parts: Vec<&str> = line.split_whitespace().collect();
189        if parts.len() >= 5 {
190            let repo = parts[0];
191            let tag = parts[1];
192            let size = parts.last().unwrap_or(&"?");
193            if repo == "<none>" {
194                continue;
195            }
196            images.push(format!("{repo}:{tag} ({size})"));
197        }
198    }
199
200    if images.is_empty() {
201        return "no images".to_string();
202    }
203    format!("{} images:\n{}", images.len(), images.join("\n"))
204}
205
206fn compress_logs(output: &str) -> String {
207    let lines: Vec<&str> = output.lines().collect();
208    if lines.len() <= 10 {
209        return output.to_string();
210    }
211
212    let mut deduped: Vec<(String, u32)> = Vec::new();
213    for line in &lines {
214        let normalized = log_timestamp_re().replace(line, "[T]").to_string();
215        let stripped = normalized.trim().to_string();
216        if stripped.is_empty() {
217            continue;
218        }
219
220        if let Some(last) = deduped.last_mut()
221            && last.0 == stripped
222        {
223            last.1 += 1;
224            continue;
225        }
226        deduped.push((stripped, 1));
227    }
228
229    let result: Vec<String> = deduped
230        .iter()
231        .map(|(line, count)| {
232            if *count > 1 {
233                format!("{line} (x{count})")
234            } else {
235                line.clone()
236            }
237        })
238        .collect();
239
240    if result.len() > 30 {
241        let result_strs: Vec<&str> = result.iter().map(std::string::String::as_str).collect();
242        let middle = &result_strs[..result_strs.len() - 15];
243        let safety = crate::core::safety_needles::extract_safety_lines(middle, 20);
244        let last_lines = &result[result.len() - 15..];
245
246        let mut out = format!("... ({} lines total", lines.len());
247        if !safety.is_empty() {
248            out.push_str(&format!(", {} safety-relevant preserved", safety.len()));
249        }
250        out.push_str(")\n");
251        for s in &safety {
252            out.push_str(s);
253            out.push('\n');
254        }
255        out.push_str(&last_lines.join("\n"));
256        out
257    } else {
258        result.join("\n")
259    }
260}
261
262fn compress_compose_ps(output: &str) -> String {
263    let lines: Vec<&str> = output.lines().collect();
264    if lines.len() <= 1 {
265        return "no services".to_string();
266    }
267
268    let mut services = Vec::new();
269    for line in &lines[1..] {
270        let parts: Vec<&str> = line.split_whitespace().collect();
271        if parts.len() >= 3 {
272            let name = parts[0];
273            let status_parts: Vec<&str> = parts[1..].to_vec();
274            let status = status_parts.join(" ");
275            services.push(format!("{name}: {status}"));
276        }
277    }
278
279    if services.is_empty() {
280        return "no services".to_string();
281    }
282    format!("{} services:\n{}", services.len(), services.join("\n"))
283}
284
285fn compress_compose_action(output: &str) -> String {
286    let trimmed = output.trim();
287    if trimmed.is_empty() {
288        return "ok".to_string();
289    }
290
291    let mut created = 0u32;
292    let mut started = 0u32;
293    let mut stopped = 0u32;
294    let mut removed = 0u32;
295
296    for line in trimmed.lines() {
297        let l = line.to_lowercase();
298        if l.contains("created") || l.contains("creating") {
299            created += 1;
300        }
301        if l.contains("started") || l.contains("starting") {
302            started += 1;
303        }
304        if l.contains("stopped") || l.contains("stopping") {
305            stopped += 1;
306        }
307        if l.contains("removed") || l.contains("removing") {
308            removed += 1;
309        }
310    }
311
312    let mut parts = Vec::new();
313    if created > 0 {
314        parts.push(format!("{created} created"));
315    }
316    if started > 0 {
317        parts.push(format!("{started} started"));
318    }
319    if stopped > 0 {
320        parts.push(format!("{stopped} stopped"));
321    }
322    if removed > 0 {
323        parts.push(format!("{removed} removed"));
324    }
325
326    if parts.is_empty() {
327        return "ok".to_string();
328    }
329    format!("ok ({})", parts.join(", "))
330}
331
332fn compress_network(output: &str) -> String {
333    let lines: Vec<&str> = output.lines().collect();
334    if lines.len() <= 1 {
335        return output.trim().to_string();
336    }
337
338    let mut networks = Vec::new();
339    for line in &lines[1..] {
340        let parts: Vec<&str> = line.split_whitespace().collect();
341        if parts.len() >= 3 {
342            let name = parts[1];
343            let driver = parts[2];
344            networks.push(format!("{name} ({driver})"));
345        }
346    }
347
348    if networks.is_empty() {
349        return "no networks".to_string();
350    }
351    networks.join(", ")
352}
353
354fn compress_volume(output: &str) -> String {
355    let lines: Vec<&str> = output.lines().collect();
356    if lines.len() <= 1 {
357        return output.trim().to_string();
358    }
359
360    let volumes: Vec<&str> = lines[1..]
361        .iter()
362        .filter_map(|l| l.split_whitespace().nth(1))
363        .collect();
364
365    if volumes.is_empty() {
366        return "no volumes".to_string();
367    }
368    format!("{} volumes: {}", volumes.len(), volumes.join(", "))
369}
370
371fn compress_inspect(output: &str) -> String {
372    let trimmed = output.trim();
373    if (trimmed.starts_with('[') || trimmed.starts_with('{'))
374        && let Ok(val) = serde_json::from_str::<serde_json::Value>(trimmed)
375    {
376        return compress_json_value(&val, 0);
377    }
378    if trimmed.lines().count() > 20 {
379        let lines: Vec<&str> = trimmed.lines().collect();
380        return format!(
381            "{}\n... ({} more lines)",
382            lines[..10].join("\n"),
383            lines.len() - 10
384        );
385    }
386    trimmed.to_string()
387}
388
389fn compress_exec(output: &str) -> String {
390    let trimmed = output.trim();
391    if trimmed.is_empty() {
392        return "ok".to_string();
393    }
394    let lines: Vec<&str> = trimmed.lines().collect();
395    if lines.len() > 30 {
396        let last = &lines[lines.len() - 10..];
397        return format!("... ({} lines)\n{}", lines.len(), last.join("\n"));
398    }
399    trimmed.to_string()
400}
401
402fn compress_system_df(output: &str) -> String {
403    let mut parts = Vec::new();
404    let mut current_type = String::new();
405
406    for line in output.lines() {
407        let trimmed = line.trim();
408        if trimmed.starts_with("TYPE") {
409            continue;
410        }
411        if trimmed.starts_with("Images")
412            || trimmed.starts_with("Containers")
413            || trimmed.starts_with("Local Volumes")
414            || trimmed.starts_with("Build Cache")
415        {
416            current_type = trimmed.to_string();
417            continue;
418        }
419        if !current_type.is_empty() && trimmed.contains("RECLAIMABLE") {
420            current_type.clear();
421        }
422    }
423
424    let lines: Vec<&str> = output
425        .lines()
426        .filter(|l| {
427            let t = l.trim();
428            !t.is_empty()
429                && (t.contains("RECLAIMABLE")
430                    || t.contains("SIZE")
431                    || t.starts_with("Images")
432                    || t.starts_with("Containers")
433                    || t.starts_with("Local Volumes")
434                    || t.starts_with("Build Cache")
435                    || t.chars().next().is_some_and(|c| c.is_ascii_digit()))
436        })
437        .collect();
438
439    if lines.is_empty() {
440        return compact_output(output, 10);
441    }
442
443    for line in &lines {
444        let trimmed = line.trim();
445        if !trimmed.starts_with("TYPE") && !trimmed.is_empty() {
446            parts.push(trimmed.to_string());
447        }
448    }
449
450    if parts.is_empty() {
451        compact_output(output, 10)
452    } else {
453        parts.join("\n")
454    }
455}
456
457fn compress_info(output: &str) -> String {
458    let mut key_info = Vec::new();
459    let important_keys = [
460        "Server Version",
461        "Operating System",
462        "Architecture",
463        "CPUs",
464        "Total Memory",
465        "Docker Root Dir",
466        "Storage Driver",
467        "Containers:",
468        "Images:",
469    ];
470
471    for line in output.lines() {
472        let trimmed = line.trim();
473        for key in &important_keys {
474            if trimmed.starts_with(key) {
475                key_info.push(trimmed.to_string());
476                break;
477            }
478        }
479    }
480
481    if key_info.is_empty() {
482        return compact_output(output, 10);
483    }
484    key_info.join("\n")
485}
486
487fn compress_version(output: &str) -> String {
488    let mut parts = Vec::new();
489    let important = ["Version:", "API version:", "Go version:", "OS/Arch:"];
490
491    for line in output.lines() {
492        let trimmed = line.trim();
493        for key in &important {
494            if trimmed.starts_with(key) {
495                parts.push(trimmed.to_string());
496                break;
497            }
498        }
499    }
500
501    if parts.is_empty() {
502        return compact_output(output, 5);
503    }
504    parts.join("\n")
505}
506
507fn compact_output(text: &str, max: usize) -> String {
508    let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
509    if lines.len() <= max {
510        return lines.join("\n");
511    }
512    format!(
513        "{}\n... ({} more lines)",
514        lines[..max].join("\n"),
515        lines.len() - max
516    )
517}
518
519fn compress_json_value(val: &serde_json::Value, depth: usize) -> String {
520    if depth > 2 {
521        return "...".to_string();
522    }
523    match val {
524        serde_json::Value::Object(map) => {
525            let keys: Vec<String> = map.keys().take(15).cloned().collect();
526            let total = map.len();
527            if total > 15 {
528                format!("{{{} ... +{} keys}}", keys.join(", "), total - 15)
529            } else {
530                format!("{{{}}}", keys.join(", "))
531            }
532        }
533        serde_json::Value::Array(arr) => format!("[...{}]", arr.len()),
534        other => format!("{other}"),
535    }
536}