Skip to main content

blyte_cli/
fallback_check.rs

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