Skip to main content

blyte_cli/
fallback_check.rs

1//! Flags added lines in a unified diff that match common fallback patterns.
2
3use std::path::{Component, Path};
4
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct Finding {
7    pub file: String,
8    pub line: usize,
9    pub pattern: &'static str,
10}
11
12/// Added lines of a unified diff (`git diff` output) that match a fallback pattern.
13pub fn added_fallbacks(diff: &str) -> Vec<Finding> {
14    let lines: Vec<&str> = diff.lines().collect();
15    let mut findings = Vec::new();
16
17    let mut current_file: Option<(&str, &str)> = None; // (path, ext)
18    let mut current_line: usize = 0;
19    let mut in_hunk = false;
20    let mut ignore_hunk = false;
21    let mut after_cfg_test = false;
22
23    for (idx, &raw_line) in lines.iter().enumerate() {
24        if let Some(rest) = raw_line.strip_prefix("+++ ") {
25            in_hunk = false;
26            ignore_hunk = false;
27            after_cfg_test = false;
28            current_line = 0;
29            if rest == "/dev/null" {
30                current_file = None;
31            } else {
32                let path = rest.strip_prefix("b/").unwrap_or(rest);
33                if is_test_file(path) {
34                    current_file = None;
35                } else {
36                    let ext = Path::new(path)
37                        .extension()
38                        .and_then(|s| s.to_str())
39                        .unwrap_or("");
40                    if is_supported_ext(ext) {
41                        current_file = Some((path, ext));
42                    } else {
43                        current_file = None;
44                    }
45                }
46            }
47            continue;
48        }
49
50        if let Some(after_at) = raw_line.strip_prefix("@@ ") {
51            if let Some((coords, _)) = after_at.split_once("@@") {
52                if let Some(plus_part) = coords.split_whitespace().find_map(|t| t.strip_prefix('+'))
53                {
54                    let c_str = plus_part.split(',').next().unwrap_or(plus_part);
55                    if let Ok(c) = c_str.parse::<usize>() {
56                        current_line = c;
57                        in_hunk = true;
58                        let is_rust = current_file.map(|(_, ext)| ext == "rs").unwrap_or(false);
59                        ignore_hunk = is_rust && raw_line.contains("mod tests");
60                    }
61                }
62            }
63            continue;
64        }
65
66        let Some((file_path, ext)) = current_file else {
67            continue;
68        };
69        if !in_hunk {
70            continue;
71        }
72
73        if let Some(content) = raw_line.strip_prefix(' ') {
74            current_line += 1;
75            if ext == "rs" && content.contains("#[cfg(test)]") {
76                after_cfg_test = true;
77            }
78            continue;
79        }
80
81        if raw_line.starts_with('-') {
82            continue;
83        }
84
85        if let Some(content) = raw_line.strip_prefix('+') {
86            let line_no = current_line;
87            current_line += 1;
88
89            if ext == "rs" && content.contains("#[cfg(test)]") {
90                after_cfg_test = true;
91            }
92
93            if ignore_hunk || after_cfg_test || is_comment(content, ext) {
94                continue;
95            }
96
97            for pattern in match_line(content, ext, &lines, idx) {
98                findings.push(Finding {
99                    file: file_path.to_string(),
100                    line: line_no,
101                    pattern,
102                });
103            }
104        }
105    }
106
107    findings
108}
109
110/// One `== checks` flag for the findings, or `None` when there are none.
111pub fn flag(findings: &[Finding]) -> Option<String> {
112    if findings.is_empty() {
113        return None;
114    }
115    let n = findings.len();
116    let listed: Vec<String> = findings
117        .iter()
118        .take(3)
119        .map(|f| format!("{}:{} {}", f.file, f.line, f.pattern))
120        .collect();
121    let more = if n > 3 {
122        format!(" and {} more", n - 3)
123    } else {
124        String::new()
125    };
126    let raw = format!(
127        "possible fallbacks added ({n}): {}{more}: check each against the task",
128        listed.join(", ")
129    );
130    Some(sanitize_flag(raw))
131}
132
133fn sanitize_flag(flag: String) -> String {
134    let single_line = flag.lines().next().unwrap_or("").to_string();
135    if single_line.chars().count() > 200 {
136        single_line.chars().take(200).collect()
137    } else {
138        single_line
139    }
140}
141
142fn is_supported_ext(ext: &str) -> bool {
143    matches!(
144        ext,
145        "rs" | "py" | "js" | "jsx" | "mjs" | "ts" | "tsx" | "sh" | "bash" | "yml" | "yaml"
146    )
147}
148
149fn is_test_file(path: &str) -> bool {
150    let p = Path::new(path);
151    for comp in p.components() {
152        if let Component::Normal(os) = comp {
153            if let Some(s) = os.to_str() {
154                if matches!(
155                    s,
156                    "tests"
157                        | "test"
158                        | "__tests__"
159                        | "benches"
160                        | "examples"
161                        | "fixtures"
162                        | "testdata"
163                ) {
164                    return true;
165                }
166            }
167        }
168    }
169    if let Some(file_name) = p.file_name().and_then(|s| s.to_str()) {
170        if file_name.starts_with("test_") || file_name == "conftest.py" {
171            return true;
172        }
173        if let (Some(stem), Some(ext)) = (
174            p.file_stem().and_then(|s| s.to_str()),
175            p.extension().and_then(|s| s.to_str()),
176        ) {
177            if !ext.is_empty()
178                && (stem.ends_with("_test") || stem.ends_with(".test") || stem.ends_with(".spec"))
179            {
180                return true;
181            }
182        }
183    }
184    false
185}
186
187fn is_comment(content: &str, ext: &str) -> bool {
188    let trimmed = content.trim_start();
189    if trimmed.starts_with("//") || trimmed.starts_with('*') || trimmed.starts_with("--") {
190        return true;
191    }
192    if trimmed.starts_with('#') {
193        if ext == "rs" && (trimmed.starts_with("#[") || trimmed.starts_with("#!")) {
194            return false;
195        }
196        return true;
197    }
198    false
199}
200
201fn match_line(content: &str, ext: &str, diff_lines: &[&str], idx: usize) -> Vec<&'static str> {
202    let mut out = Vec::new();
203    match ext {
204        "rs" => {
205            if content.contains(".unwrap_or(") {
206                out.push("unwrap_or");
207            }
208            if content.contains(".unwrap_or_default(") {
209                out.push("unwrap_or_default");
210            }
211            if content.contains(".unwrap_or_else(") {
212                out.push("unwrap_or_else");
213            }
214        }
215        "py" => {
216            if matches_py_except_pass(content, diff_lines, idx) {
217                out.push("except-pass");
218            }
219            if matches_py_get_default(content) {
220                out.push("get-default");
221            }
222            if matches_py_or_literal(content) {
223                out.push("or-literal");
224            }
225        }
226        "js" | "jsx" | "mjs" | "ts" | "tsx" => {
227            if content.contains("??") {
228                out.push("nullish");
229            }
230            if matches_js_or_literal(content) {
231                out.push("or-literal");
232            }
233            if matches_js_empty_catch(content) {
234                out.push("empty-catch");
235            }
236        }
237        "sh" | "bash" | "yml" | "yaml" => {
238            if content.contains("|| true") || content.contains("|| :") {
239                out.push("or-true");
240            }
241            if matches_shell_param_default(content) {
242                out.push("param-default");
243            }
244        }
245        _ => {}
246    }
247    out
248}
249
250fn matches_py_except_pass(content: &str, diff_lines: &[&str], idx: usize) -> bool {
251    let trimmed = content.trim_start();
252    let after_except = if let Some(rest) = trimmed.strip_prefix("except:") {
253        Some(rest)
254    } else if let Some(rest) = trimmed.strip_prefix("except Exception") {
255        if rest.starts_with(':') || rest.starts_with(char::is_whitespace) {
256            rest.split_once(':').map(|(_, r)| r)
257        } else {
258            None
259        }
260    } else if let Some(rest) = trimmed.strip_prefix("except BaseException") {
261        if rest.starts_with(':') || rest.starts_with(char::is_whitespace) {
262            rest.split_once(':').map(|(_, r)| r)
263        } else {
264            None
265        }
266    } else {
267        None
268    };
269
270    let Some(after_colon) = after_except else {
271        return false;
272    };
273
274    let inline = after_colon.split('#').next().unwrap_or(after_colon).trim();
275    if !inline.is_empty() {
276        return is_pass_continue_or_return(inline);
277    }
278
279    for &next_raw in &diff_lines[idx + 1..] {
280        if next_raw.starts_with("+++ ")
281            || next_raw.starts_with("@@ ")
282            || next_raw.starts_with("diff --git ")
283            || next_raw.starts_with(' ')
284        {
285            break;
286        }
287        if let Some(added) = next_raw.strip_prefix('+') {
288            let added_trim = added.trim();
289            if added_trim.is_empty() {
290                continue;
291            }
292            let stmt = added_trim.split('#').next().unwrap_or(added_trim).trim();
293            return is_pass_continue_or_return(stmt);
294        }
295    }
296    false
297}
298
299fn is_pass_continue_or_return(s: &str) -> bool {
300    s == "pass" || s == "continue" || s.starts_with("return")
301}
302
303fn matches_py_get_default(content: &str) -> bool {
304    let bytes = content.as_bytes();
305    for i in 0..bytes.len() {
306        let rest = &content[i..];
307        let args_start = if let Some(after) = rest.strip_prefix(".get(") {
308            Some(after)
309        } else if let Some(after) = rest.strip_prefix("getenv(") {
310            let prev_ok = i == 0 || {
311                let b = bytes[i - 1];
312                !b.is_ascii_alphanumeric() && b != b'_'
313            };
314            if prev_ok {
315                Some(after)
316            } else {
317                None
318            }
319        } else {
320            None
321        };
322        if let Some(after_open) = args_start {
323            if has_top_level_comma(after_open) {
324                return true;
325            }
326        }
327    }
328    false
329}
330
331fn has_top_level_comma(s: &str) -> bool {
332    let mut depth = 0usize;
333    let mut in_str: Option<char> = None;
334    let mut chars = s.chars();
335    while let Some(c) = chars.next() {
336        if let Some(q) = in_str {
337            if c == '\\' {
338                let _ = chars.next();
339            } else if c == q {
340                in_str = None;
341            }
342            continue;
343        }
344        match c {
345            '"' | '\'' => in_str = Some(c),
346            '(' | '[' | '{' => depth += 1,
347            ')' => {
348                if depth == 0 {
349                    return false;
350                }
351                depth -= 1;
352            }
353            ']' | '}' => {
354                depth = depth.saturating_sub(1);
355            }
356            ',' if depth == 0 => return true,
357            _ => {}
358        }
359    }
360    false
361}
362
363fn matches_py_or_literal(content: &str) -> bool {
364    let mut search = content;
365    while let Some(pos) = search.find(" or ") {
366        let after = &search[pos + 4..];
367        let after_trimmed = after.trim_start_matches([' ', '\t']);
368        if let Some(c) = after_trimmed.chars().next() {
369            if matches!(c, '"' | '\'' | '[' | '{' | '(' | '0'..='9') {
370                return true;
371            }
372        }
373        search = after;
374    }
375    false
376}
377
378fn matches_js_or_literal(content: &str) -> bool {
379    let mut search = content;
380    while let Some(pos) = search.find("||") {
381        let after = &search[pos + 2..];
382        let after_trimmed = after.trim_start_matches([' ', '\t']);
383        if let Some(c) = after_trimmed.chars().next() {
384            if matches!(c, '"' | '\'' | '`' | '[' | '{' | '0'..='9') {
385                return true;
386            }
387        }
388        search = after;
389    }
390    false
391}
392
393fn matches_js_empty_catch(content: &str) -> bool {
394    let bytes = content.as_bytes();
395    for i in 0..bytes.len() {
396        let Some(after_catch) = content[i..].strip_prefix("catch") else {
397            continue;
398        };
399        let prev_ok = i == 0 || {
400            let b = bytes[i - 1];
401            !b.is_ascii_alphanumeric() && b != b'_' && b != b'$'
402        };
403        let next_ok = after_catch
404            .chars()
405            .next()
406            .map(|c| !c.is_ascii_alphanumeric() && c != '_' && c != '$')
407            .unwrap_or(false);
408        if !prev_ok || !next_ok {
409            continue;
410        }
411        let mut rest = after_catch.trim_start();
412        if let Some(after_open_paren) = rest.strip_prefix('(') {
413            let mut depth = 1usize;
414            let mut end_idx = None;
415            for (idx, ch) in after_open_paren.char_indices() {
416                match ch {
417                    '(' => depth += 1,
418                    ')' => {
419                        depth -= 1;
420                        if depth == 0 {
421                            end_idx = Some(idx + 1);
422                            break;
423                        }
424                    }
425                    _ => {}
426                }
427            }
428            let Some(end) = end_idx else {
429                continue;
430            };
431            rest = after_open_paren[end..].trim_start();
432        }
433        if let Some(after_brace) = rest.strip_prefix('{') {
434            if after_brace == "}"
435                || after_brace == " }"
436                || after_brace.trim_start().starts_with('}')
437            {
438                return true;
439            }
440        }
441    }
442    false
443}
444
445fn matches_shell_param_default(content: &str) -> bool {
446    let mut search = content;
447    while let Some(pos) = search.find("${") {
448        let after = &search[pos + 2..];
449        let inside = after.split('}').next().unwrap_or(after);
450        if inside.contains(":-") {
451            return true;
452        }
453        search = after;
454    }
455    false
456}