Skip to main content

lean_ctx/core/patterns/
terraform.rs

1use regex::Regex;
2use std::sync::OnceLock;
3
4static PLAN_SUMMARY_RE: OnceLock<Regex> = OnceLock::new();
5static APPLY_SUMMARY_RE: OnceLock<Regex> = OnceLock::new();
6static INSTALLED_PROVIDER_RE: OnceLock<Regex> = OnceLock::new();
7static PROVIDER_VERSION_RE: OnceLock<Regex> = OnceLock::new();
8
9fn plan_summary_re() -> &'static Regex {
10    PLAN_SUMMARY_RE.get_or_init(|| {
11        Regex::new(r"Plan:\s*(\d+)\s+to add,\s*(\d+)\s+to change,\s*(\d+)\s+to destroy").unwrap()
12    })
13}
14
15fn apply_summary_re() -> &'static Regex {
16    APPLY_SUMMARY_RE.get_or_init(|| {
17        Regex::new(
18            r"Apply complete!\s*Resources:\s*(\d+)\s+added,\s*(\d+)\s+changed,\s*(\d+)\s+destroyed",
19        )
20        .unwrap()
21    })
22}
23
24fn installed_provider_re() -> &'static Regex {
25    INSTALLED_PROVIDER_RE
26        .get_or_init(|| Regex::new(r"-\s*Installed\s+([^\s]+)\s+v([0-9][^\s]*)").unwrap())
27}
28
29fn provider_version_re() -> &'static Regex {
30    PROVIDER_VERSION_RE
31        .get_or_init(|| Regex::new(r"\*\s*provider\[([^\]]+)\]\s+([0-9][^\s]*)").unwrap())
32}
33
34fn is_provider_init_noise(line: &str) -> bool {
35    let t = line.trim_start();
36    let tl = t.to_ascii_lowercase();
37    tl.contains("initializing provider plugins")
38        || tl.contains("initializing the backend")
39        || tl.contains("finding ")
40            && (tl.contains("versions matching") || tl.contains("version of"))
41        || tl.starts_with("- finding ")
42        || tl.starts_with("- installing ")
43        || tl.contains("terraform init") && tl.contains("upgrade")
44        || tl.starts_with("╷")
45        || tl.starts_with("╵")
46        || tl.starts_with("│")
47}
48
49pub fn compress(command: &str, output: &str) -> Option<String> {
50    let c = command.trim();
51    if c != "terraform" && !c.starts_with("terraform ") {
52        return None;
53    }
54    let sub = c
55        .strip_prefix("terraform")
56        .map(str::trim_start)
57        .unwrap_or("");
58    let sub_cmd = sub.split_whitespace().next().unwrap_or("");
59
60    match sub_cmd {
61        "plan" => Some(compress_plan(output)),
62        "apply" => Some(compress_apply(output)),
63        "init" => Some(compress_init(output)),
64        "validate" => Some(compress_validate(output)),
65        _ => Some(compress_generic(output)),
66    }
67}
68
69fn compress_plan(output: &str) -> String {
70    let mut kept = Vec::new();
71
72    for line in output.lines() {
73        if is_provider_init_noise(line) {
74            continue;
75        }
76        let tl = line.trim_start();
77        if tl.starts_with("- Installed ") || tl.starts_with("- Installing ") {
78            continue;
79        }
80
81        if let Some(caps) = plan_summary_re().captures(line) {
82            let add = caps.get(1).map(|m| m.as_str()).unwrap_or("0");
83            let chg = caps.get(2).map(|m| m.as_str()).unwrap_or("0");
84            let des = caps.get(3).map(|m| m.as_str()).unwrap_or("0");
85            kept.push(format!("+ {add} added, ~ {chg} changed, - {des} destroyed"));
86            continue;
87        }
88
89        let l = line.to_ascii_lowercase();
90        if l.contains("no changes.") || l.contains("infrastructure matches the configuration") {
91            kept.push("No changes.".to_string());
92            continue;
93        }
94
95        let is_diag = tl.contains('╷')
96            || tl.contains('│')
97            || tl.contains('╵')
98            || l.contains("error:")
99            || (l.contains("error ")
100                && (l.contains("terraform") || l.contains("plan") || l.contains("provider")))
101            || l.contains("warning:")
102            || l.contains("warning ");
103        if is_diag {
104            kept.push(line.trim().to_string());
105        }
106    }
107
108    if kept.is_empty() {
109        "terraform plan (no summary parsed)".to_string()
110    } else {
111        kept.join("\n")
112    }
113}
114
115fn compress_apply(output: &str) -> String {
116    let mut results = Vec::new();
117    let mut errors = Vec::new();
118
119    for line in output.lines() {
120        if is_provider_init_noise(line) {
121            continue;
122        }
123        let tl = line.trim();
124        if tl.is_empty() {
125            continue;
126        }
127
128        if let Some(caps) = apply_summary_re().captures(line) {
129            let a = caps.get(1).map(|m| m.as_str()).unwrap_or("0");
130            let c = caps.get(2).map(|m| m.as_str()).unwrap_or("0");
131            let d = caps.get(3).map(|m| m.as_str()).unwrap_or("0");
132            results.push(format!(
133                "Apply complete: +{a} added, ~{c} changed, -{d} destroyed"
134            ));
135            continue;
136        }
137
138        let ll = tl.to_ascii_lowercase();
139        if ll.contains("error")
140            && (ll.contains("apply") || ll.contains("terraform") || tl.contains('╷'))
141        {
142            errors.push(tl.to_string());
143        } else if ll.starts_with("creation complete")
144            || ll.starts_with("modification complete")
145            || ll.starts_with("destruction complete")
146            || ll.starts_with("destroy complete")
147        {
148            results.push(tl.to_string());
149        }
150    }
151
152    let mut out = Vec::new();
153    if !results.is_empty() {
154        out.push(results.join("\n"));
155    }
156    if !errors.is_empty() {
157        out.push(format!("errors:\n{}", errors.join("\n")));
158    }
159    if out.is_empty() {
160        "terraform apply (no summary parsed)".to_string()
161    } else {
162        out.join("\n\n")
163    }
164}
165
166fn compress_init(output: &str) -> String {
167    let mut providers: Vec<String> = Vec::new();
168    let mut success = false;
169
170    for line in output.lines() {
171        let tl = line.trim();
172        if tl.is_empty() {
173            continue;
174        }
175        let ll = tl.to_ascii_lowercase();
176        if ll.contains("terraform has been successfully initialized")
177            || ll.contains("initialization complete")
178        {
179            success = true;
180        }
181        if let Some(caps) = installed_provider_re().captures(tl) {
182            let name = caps.get(1).map(|m| m.as_str()).unwrap_or("?");
183            let ver = caps.get(2).map(|m| m.as_str()).unwrap_or("?");
184            providers.push(format!("{name} v{ver}"));
185            continue;
186        }
187        if let Some(caps) = provider_version_re().captures(tl) {
188            let reg = caps.get(1).map(|m| m.as_str()).unwrap_or("?");
189            let ver = caps.get(2).map(|m| m.as_str()).unwrap_or("?");
190            providers.push(format!("{reg} {ver}"));
191        }
192    }
193
194    let status = if success {
195        "Terraform initialized"
196    } else {
197        "terraform init"
198    };
199
200    if providers.is_empty() {
201        status.to_string()
202    } else {
203        format!("{status}\n{}", providers.join(", "))
204    }
205}
206
207fn compress_validate(output: &str) -> String {
208    let mut errs = Vec::new();
209    for line in output.lines() {
210        let tl = line.trim();
211        if tl.is_empty() {
212            continue;
213        }
214        let ll = tl.to_ascii_lowercase();
215        if ll.contains("success!") && ll.contains("configuration is valid") {
216            return "Success".to_string();
217        }
218        if ll.contains("error") || tl.starts_with('╷') || tl.starts_with('│') {
219            errs.push(tl.to_string());
220        }
221    }
222    if errs.is_empty() {
223        "Success".to_string()
224    } else {
225        errs.join("\n")
226    }
227}
228
229fn compress_generic(output: &str) -> String {
230    let mut lines: Vec<String> = output
231        .lines()
232        .filter(|l| !is_provider_init_noise(l))
233        .map(|l| l.trim().to_string())
234        .filter(|l| !l.is_empty())
235        .collect();
236    if lines.len() > 40 {
237        let n = lines.len();
238        lines = lines.split_off(n - 25);
239        format!("... (truncated)\n{}", lines.join("\n"))
240    } else {
241        lines.join("\n")
242    }
243}