Skip to main content

arbor_graph/
diff.rs

1//! Git-diff blast radius computation shared by CLI and MCP.
2
3use crate::{ArborGraph, NodeId};
4use arbor_core::NodeKind;
5use serde::{Deserialize, Serialize};
6use std::collections::{HashMap, HashSet};
7use std::path::Path;
8
9/// Summary of blast radius for changed files (matches CLI `arbor diff` output).
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct BlastRadiusSummary {
12    pub changed_files: Vec<String>,
13    pub changed_symbols: usize,
14    pub direct_callers: usize,
15    pub indirect_callers: usize,
16    pub entrypoints_affected: usize,
17    pub files_likely_updates: usize,
18    pub blast_radius_nodes: usize,
19    pub mermaid_diagram: Option<String>,
20    pub risk_level: String,
21}
22
23fn normalize_slashes(input: &str) -> String {
24    input.replace('\\', "/")
25}
26
27/// Whether a graph node's file path matches a git-changed path.
28pub fn node_matches_changed_file(node_file: &str, changed_file: &str, project_root: &Path) -> bool {
29    let node_norm = normalize_slashes(node_file);
30    let changed_norm = normalize_slashes(changed_file);
31
32    if node_norm.ends_with(&changed_norm) {
33        return true;
34    }
35
36    let abs = project_root.join(&changed_norm);
37    let abs_norm = normalize_slashes(&abs.to_string_lossy());
38    node_norm == abs_norm
39}
40
41/// Collect node IDs whose files appear in the changed-files list.
42///
43/// This is *file* granularity: every symbol in a touched file is treated as
44/// changed. For a one-line edit in a 60-symbol file that overstates the blast
45/// radius by roughly 60x. Prefer [`changed_node_ids_for_ranges`] whenever the
46/// caller has the diff hunks — which any PR-driven integration does.
47pub fn changed_node_ids(
48    graph: &ArborGraph,
49    changed_files: &[String],
50    project_root: &Path,
51) -> Vec<NodeId> {
52    graph
53        .node_indexes()
54        .filter(|idx| {
55            graph.get(*idx).is_some_and(|node| {
56                changed_files
57                    .iter()
58                    .any(|f| node_matches_changed_file(&node.file, f, project_root))
59            })
60        })
61        .collect()
62}
63
64/// A contiguous run of changed lines within one file.
65///
66/// Lines are 1-indexed and both bounds are inclusive, matching how editors and
67/// `CodeNode::line_start`/`line_end` count.
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69pub struct ChangedRange {
70    pub file: String,
71    pub start_line: u32,
72    pub end_line: u32,
73}
74
75impl ChangedRange {
76    pub fn new(file: impl Into<String>, start_line: u32, end_line: u32) -> Self {
77        Self {
78            file: file.into(),
79            start_line,
80            end_line,
81        }
82    }
83
84    /// Whether this range overlaps an inclusive `[start, end]` span.
85    fn overlaps(&self, start: u32, end: u32) -> bool {
86        self.start_line <= end && start <= self.end_line
87    }
88}
89
90/// Symbols touched by a set of changed line ranges.
91#[derive(Debug, Clone, Default)]
92pub struct ChangedSymbols {
93    /// Nodes overlapping at least one changed range, in graph order.
94    pub node_ids: Vec<NodeId>,
95
96    /// Files that changed but where no symbol overlapped the changed lines.
97    ///
98    /// Usually an import block, a top-level constant, a comment, or a
99    /// whitespace-only edit. Surfacing these lets a report say "this file
100    /// changed outside any tracked symbol" instead of silently reporting
101    /// zero impact — an honest unknown rather than an invisible one.
102    pub files_without_symbol_hits: Vec<String>,
103}
104
105/// Collect node IDs whose line spans overlap the given changed ranges.
106///
107/// A symbol counts as changed when any changed line falls inside its span.
108/// Symbols elsewhere in the same file are left out, which is the whole point:
109/// editing one function should not implicate its 59 neighbours.
110///
111/// Nodes whose line span is unset (`line_end == 0`, which some fallback
112/// parsers produce) cannot be positioned, so they are included whenever their
113/// file is touched. That is the conservative choice — better a slightly wide
114/// radius than a silently missing symbol.
115///
116/// A container (a module, class, trait, struct or enum) counts only when a
117/// changed line inside it falls outside all of its members: editing a method
118/// changes the method, not `mod mac` or `class Session` around it. A field, a
119/// `use` or the header itself still counts. Functions are not containers here:
120/// changing a closure inside one changes what the function does.
121pub fn changed_node_ids_for_ranges(
122    graph: &ArborGraph,
123    ranges: &[ChangedRange],
124    project_root: &Path,
125) -> ChangedSymbols {
126    let mut node_ids = Vec::new();
127    let mut files_hit: HashSet<String> = HashSet::new();
128
129    for idx in graph.node_indexes() {
130        let Some(node) = graph.get(idx) else {
131            continue;
132        };
133
134        for range in ranges {
135            if !node_matches_changed_file(&node.file, &range.file, project_root) {
136                continue;
137            }
138
139            // Position-unknown nodes fall back to file granularity.
140            let positioned = node.line_end > 0;
141            if !positioned || range.overlaps(node.line_start, node.line_end) {
142                node_ids.push(idx);
143                files_hit.insert(range.file.clone());
144                break;
145            }
146        }
147    }
148
149    let node_ids = drop_explained_containers(graph, node_ids, ranges, project_root);
150
151    let mut files_without_symbol_hits: Vec<String> = ranges
152        .iter()
153        .map(|r| r.file.clone())
154        .filter(|f| !files_hit.contains(f))
155        .collect();
156    files_without_symbol_hits.sort();
157    files_without_symbol_hits.dedup();
158
159    ChangedSymbols {
160        node_ids,
161        files_without_symbol_hits,
162    }
163}
164
165fn is_container(kind: NodeKind) -> bool {
166    matches!(
167        kind,
168        NodeKind::Module
169            | NodeKind::Class
170            | NodeKind::Interface
171            | NodeKind::Struct
172            | NodeKind::Enum
173    )
174}
175
176/// Removes containers whose changed lines all fall inside their members.
177fn drop_explained_containers(
178    graph: &ArborGraph,
179    node_ids: Vec<NodeId>,
180    ranges: &[ChangedRange],
181    project_root: &Path,
182) -> Vec<NodeId> {
183    let containers: Vec<NodeId> = node_ids
184        .iter()
185        .copied()
186        .filter(|id| {
187            graph
188                .get(*id)
189                .is_some_and(|node| is_container(node.kind) && node.line_end > 0)
190        })
191        .collect();
192    if containers.is_empty() {
193        return node_ids;
194    }
195
196    // Positioned spans of every symbol in the files that hold a container.
197    let files: HashSet<&str> = containers
198        .iter()
199        .filter_map(|id| graph.get(*id).map(|node| node.file.as_str()))
200        .collect();
201    let mut spans: HashMap<&str, Vec<(u32, u32)>> = HashMap::new();
202    for idx in graph.node_indexes() {
203        if let Some(node) = graph.get(idx) {
204            if node.line_end > 0 && files.contains(node.file.as_str()) {
205                spans
206                    .entry(node.file.as_str())
207                    .or_default()
208                    .push((node.line_start, node.line_end));
209            }
210        }
211    }
212
213    let explained: HashSet<NodeId> = containers
214        .into_iter()
215        .filter(|id| {
216            let Some(container) = graph.get(*id) else {
217                return false;
218            };
219            let (start, end) = (container.line_start, container.line_end);
220            let mut members: Vec<(u32, u32)> = spans
221                .get(container.file.as_str())
222                .map(|all| {
223                    all.iter()
224                        .copied()
225                        .filter(|&(s, e)| s >= start && e <= end && (s, e) != (start, end))
226                        .collect()
227                })
228                .unwrap_or_default();
229            members.sort_unstable();
230            ranges
231                .iter()
232                .filter(|range| {
233                    node_matches_changed_file(&container.file, &range.file, project_root)
234                })
235                .filter(|range| range.overlaps(start, end))
236                .all(|range| {
237                    covered(
238                        range.start_line.max(start),
239                        range.end_line.min(end),
240                        &members,
241                    )
242                })
243        })
244        .collect();
245
246    node_ids
247        .into_iter()
248        .filter(|id| !explained.contains(id))
249        .collect()
250}
251
252/// Whether every line in `[start, end]` lies inside one of the sorted `spans`.
253fn covered(start: u32, end: u32, spans: &[(u32, u32)]) -> bool {
254    let mut next = start;
255    for &(s, e) in spans {
256        if s > next {
257            break;
258        }
259        if e >= next {
260            next = e.saturating_add(1);
261            if next > end {
262                return true;
263            }
264        }
265    }
266    next > end
267}
268
269/// Extract changed line ranges from a unified diff patch for one file.
270///
271/// Reads the `+` side of each `@@ -a,b +c,d @@` header, so the ranges refer to
272/// line numbers in the *new* file — the same numbering the indexed graph uses.
273///
274/// The full hunk span is returned, including its context lines. Context is
275/// deliberately kept: a hunk that only deletes lines has no added lines to
276/// point at, but the deletion still changes the enclosing symbol, and the
277/// surrounding context is what locates it. Over-including by the three context
278/// lines either side is immaterial next to the alternative of taking the whole
279/// file.
280///
281/// Malformed headers are skipped rather than failing the parse — a diff that
282/// partially parses still yields a far better radius than no ranges at all.
283pub fn parse_unified_diff_ranges(patch: &str, file: &str) -> Vec<ChangedRange> {
284    let mut ranges = Vec::new();
285
286    for line in patch.lines() {
287        if !line.starts_with("@@") {
288            continue;
289        }
290
291        // `@@ -12,7 +12,9 @@ fn context()` → we want the `+12,9`.
292        let Some(rest) = line.strip_prefix("@@") else {
293            continue;
294        };
295        let Some(plus) = rest.split('+').nth(1) else {
296            continue;
297        };
298        let spec = plus.split_whitespace().next().unwrap_or("");
299        let mut parts = spec.split(',');
300
301        let Some(Ok(start)) = parts.next().map(str::parse::<u32>) else {
302            continue;
303        };
304        // An omitted count means a single line.
305        let count = match parts.next() {
306            Some(c) => match c.parse::<u32>() {
307                Ok(n) => n,
308                Err(_) => continue,
309            },
310            None => 1,
311        };
312
313        if count == 0 {
314            // Pure deletion: the new file has no lines here. Anchor on the
315            // insertion point so the enclosing symbol is still found.
316            ranges.push(ChangedRange::new(file, start.max(1), start.max(1)));
317        } else {
318            ranges.push(ChangedRange::new(file, start, start + count - 1));
319        }
320    }
321
322    ranges
323}
324
325fn risk_level_for(blast_radius_nodes: usize) -> String {
326    if blast_radius_nodes > 50 {
327        "critical".to_string()
328    } else if blast_radius_nodes > 25 {
329        "high".to_string()
330    } else if blast_radius_nodes > 10 {
331        "medium".to_string()
332    } else {
333        "low".to_string()
334    }
335}
336
337/// Compute blast radius summary from an indexed graph and changed file list.
338pub fn compute_blast_radius(
339    graph: &ArborGraph,
340    changed_files: Vec<String>,
341    changed_node_ids: Vec<NodeId>,
342    max_depth: usize,
343    project_root: &Path,
344) -> BlastRadiusSummary {
345    let mut direct_callers = HashSet::new();
346    let mut indirect_callers = HashSet::new();
347    let mut affected_nodes = HashSet::new();
348    let mut affected_files = HashSet::new();
349
350    for node_id in changed_node_ids.iter().copied() {
351        let analysis = graph.analyze_impact(node_id, max_depth);
352
353        for up in &analysis.upstream {
354            affected_nodes.insert(up.node_info.id.clone());
355            affected_files.insert(up.node_info.file.clone());
356            if up.hop_distance <= 1 {
357                direct_callers.insert(up.node_info.id.clone());
358            } else {
359                indirect_callers.insert(up.node_info.id.clone());
360            }
361        }
362
363        for down in &analysis.downstream {
364            affected_nodes.insert(down.node_info.id.clone());
365            affected_files.insert(down.node_info.file.clone());
366        }
367    }
368
369    let entrypoints_affected = affected_nodes
370        .iter()
371        .filter_map(|id| graph.get_index(id))
372        .filter(|idx| graph.analyze_impact(*idx, 1).upstream.is_empty())
373        .count();
374
375    let changed_norm: Vec<String> = changed_files.iter().map(|f| normalize_slashes(f)).collect();
376    let files_likely_updates = affected_files
377        .iter()
378        .filter(|f| {
379            let f_norm = normalize_slashes(f);
380            !changed_norm.iter().any(|c| {
381                f_norm.ends_with(c)
382                    || f_norm == normalize_slashes(&project_root.join(c).to_string_lossy())
383            })
384        })
385        .count();
386
387    let mut mermaid_lines = Vec::new();
388    mermaid_lines.push("graph TD".to_string());
389    mermaid_lines.push(
390        "  classDef changed fill:#ef4444,stroke:#333,stroke-width:2px,color:#fff;".to_string(),
391    );
392    mermaid_lines.push(
393        "  classDef caller fill:#f59e0b,stroke:#333,stroke-width:1px,color:#fff;".to_string(),
394    );
395
396    let mut added_edges = HashSet::new();
397    let mut changed_node_names = HashSet::new();
398    let mut direct_caller_names = HashSet::new();
399
400    for node_id in changed_node_ids.iter().copied().take(5) {
401        if let Some(node) = graph.get(node_id) {
402            let target_name = node.name.replace([':', '<', '>', '(', ')', '[', ']'], "_");
403            changed_node_names.insert(target_name.clone());
404
405            let analysis = graph.analyze_impact(node_id, max_depth);
406
407            let mut caller_count = 0;
408            for up in &analysis.upstream {
409                if up.hop_distance == 1 {
410                    let caller_name = up
411                        .node_info
412                        .name
413                        .replace([':', '<', '>', '(', ')', '[', ']'], "_");
414                    direct_caller_names.insert(caller_name.clone());
415
416                    let edge = format!(
417                        "  {}[{}] --> {}[{}]",
418                        caller_name, up.node_info.name, target_name, node.name
419                    );
420                    if added_edges.insert(edge.clone()) {
421                        mermaid_lines.push(edge);
422                        caller_count += 1;
423                        if caller_count >= 3 {
424                            break;
425                        }
426                    }
427                }
428            }
429        }
430    }
431
432    for name in &changed_node_names {
433        mermaid_lines.push(format!("  class {} changed;", name));
434    }
435    for name in &direct_caller_names {
436        if !changed_node_names.contains(name) {
437            mermaid_lines.push(format!("  class {} caller;", name));
438        }
439    }
440
441    let mermaid_diagram = if mermaid_lines.len() > 3 {
442        Some(mermaid_lines.join("\n"))
443    } else {
444        None
445    };
446
447    let blast_radius_nodes = affected_nodes.len();
448
449    BlastRadiusSummary {
450        changed_files,
451        changed_symbols: changed_node_ids.len(),
452        direct_callers: direct_callers.len(),
453        indirect_callers: indirect_callers.len(),
454        entrypoints_affected,
455        files_likely_updates,
456        blast_radius_nodes,
457        mermaid_diagram,
458        risk_level: risk_level_for(blast_radius_nodes),
459    }
460}
461
462#[cfg(test)]
463mod tests {
464    use super::*;
465    use crate::ArborGraph;
466    use arbor_core::{CodeNode, NodeKind};
467
468    #[test]
469    fn compute_blast_radius_empty_changes() {
470        let graph = ArborGraph::new();
471        let summary = compute_blast_radius(&graph, vec![], vec![], 5, Path::new("."));
472        assert_eq!(summary.blast_radius_nodes, 0);
473        assert_eq!(summary.risk_level, "low");
474    }
475
476    #[test]
477    fn changed_node_ids_finds_nodes_in_file() {
478        let mut graph = ArborGraph::new();
479        let node = CodeNode::new("foo", "foo", NodeKind::Function, "src/lib.rs");
480        let id = graph.add_node(node);
481
482        let ids = changed_node_ids(&graph, &["src/lib.rs".to_string()], Path::new("."));
483        assert_eq!(ids.len(), 1);
484        assert_eq!(ids[0], id);
485    }
486
487    /// A 3-symbol file: `a` on 1-10, `b` on 20-30, `c` on 40-50.
488    fn three_symbol_file() -> (ArborGraph, NodeId, NodeId, NodeId) {
489        let mut graph = ArborGraph::new();
490        let a = graph
491            .add_node(CodeNode::new("a", "a", NodeKind::Function, "src/lib.rs").with_lines(1, 10));
492        let b = graph
493            .add_node(CodeNode::new("b", "b", NodeKind::Function, "src/lib.rs").with_lines(20, 30));
494        let c = graph
495            .add_node(CodeNode::new("c", "c", NodeKind::Function, "src/lib.rs").with_lines(40, 50));
496        (graph, a, b, c)
497    }
498
499    /// `mod mac` (1-40) holding `capture` (5-15) and `finish` (20-30), plus a
500    /// struct (45-50) with no member nodes, and a function with a nested
501    /// closure node.
502    fn container_file() -> (ArborGraph, NodeId, NodeId, NodeId, NodeId, NodeId) {
503        let mut graph = ArborGraph::new();
504        let file = "src/lib.rs";
505        let module =
506            graph.add_node(CodeNode::new("mac", "mac", NodeKind::Module, file).with_lines(1, 40));
507        let capture = graph.add_node(
508            CodeNode::new("capture", "mac.capture", NodeKind::Function, file).with_lines(5, 15),
509        );
510        let finish = graph.add_node(
511            CodeNode::new("finish", "mac.finish", NodeKind::Function, file).with_lines(20, 30),
512        );
513        let config = graph
514            .add_node(CodeNode::new("Config", "Config", NodeKind::Struct, file).with_lines(45, 50));
515        let outer = graph
516            .add_node(CodeNode::new("outer", "outer", NodeKind::Function, file).with_lines(60, 80));
517        graph.add_node(
518            CodeNode::new("handler", "outer.handler", NodeKind::Function, file).with_lines(65, 70),
519        );
520        (graph, module, capture, finish, config, outer)
521    }
522
523    fn changed(graph: &ArborGraph, ranges: &[(u32, u32)]) -> Vec<NodeId> {
524        let ranges: Vec<ChangedRange> = ranges
525            .iter()
526            .map(|&(s, e)| ChangedRange::new("src/lib.rs", s, e))
527            .collect();
528        let mut ids = changed_node_ids_for_ranges(graph, &ranges, Path::new(".")).node_ids;
529        ids.sort();
530        ids
531    }
532
533    #[test]
534    fn an_edit_inside_a_member_does_not_change_its_container() {
535        let (graph, _module, capture, finish, _, _) = container_file();
536        assert_eq!(changed(&graph, &[(8, 9)]), vec![capture]);
537        let mut both = vec![capture, finish];
538        both.sort();
539        assert_eq!(changed(&graph, &[(8, 9), (25, 25)]), both);
540    }
541
542    #[test]
543    fn an_edit_outside_every_member_changes_the_container() {
544        let (graph, module, capture, _, config, _) = container_file();
545        // The module header, or a line between members.
546        assert_eq!(changed(&graph, &[(1, 1)]), vec![module]);
547        assert_eq!(changed(&graph, &[(17, 17)]), vec![module]);
548        // One range across a member and the module's own lines: both.
549        let mut both = vec![module, capture];
550        both.sort();
551        assert_eq!(changed(&graph, &[(14, 17)]), both);
552        // A struct field: no member nodes, so the struct itself changed.
553        assert_eq!(changed(&graph, &[(47, 47)]), vec![config]);
554    }
555
556    #[test]
557    fn a_function_still_changes_when_its_closure_does() {
558        let (graph, _, _, _, _, outer) = container_file();
559        let ids = changed(&graph, &[(66, 66)]);
560        assert!(
561            ids.contains(&outer),
562            "functions are not containers: {ids:?}"
563        );
564        assert_eq!(ids.len(), 2);
565    }
566
567    #[test]
568    fn coverage_merges_adjacent_and_overlapping_spans() {
569        assert!(covered(5, 15, &[(5, 10), (11, 15)]));
570        assert!(covered(5, 15, &[(1, 12), (8, 20)]));
571        assert!(!covered(5, 15, &[(5, 10), (12, 15)]));
572        assert!(!covered(5, 15, &[]));
573    }
574
575    #[test]
576    fn ranges_select_only_the_edited_symbol() {
577        let (graph, _a, b, _c) = three_symbol_file();
578        let ranges = vec![ChangedRange::new("src/lib.rs", 22, 23)];
579
580        let changed = changed_node_ids_for_ranges(&graph, &ranges, Path::new("."));
581        assert_eq!(
582            changed.node_ids,
583            vec![b],
584            "editing inside b must not implicate a or c"
585        );
586        assert!(changed.files_without_symbol_hits.is_empty());
587    }
588
589    #[test]
590    fn file_granularity_overstates_by_the_symbol_count() {
591        // The regression this whole API exists to prevent.
592        let (graph, _, _, _) = three_symbol_file();
593        let by_file = changed_node_ids(&graph, &["src/lib.rs".to_string()], Path::new("."));
594        let by_range = changed_node_ids_for_ranges(
595            &graph,
596            &[ChangedRange::new("src/lib.rs", 22, 23)],
597            Path::new("."),
598        );
599
600        assert_eq!(by_file.len(), 3);
601        assert_eq!(by_range.node_ids.len(), 1);
602    }
603
604    #[test]
605    fn range_spanning_two_symbols_selects_both() {
606        let (graph, _a, b, c) = three_symbol_file();
607        let ranges = vec![ChangedRange::new("src/lib.rs", 25, 45)];
608
609        let changed = changed_node_ids_for_ranges(&graph, &ranges, Path::new("."));
610        assert_eq!(changed.node_ids, vec![b, c]);
611    }
612
613    #[test]
614    fn boundary_lines_count_as_overlap() {
615        let (graph, a, _b, _c) = three_symbol_file();
616
617        // Touching exactly the first and last line of `a`.
618        for line in [1u32, 10u32] {
619            let changed = changed_node_ids_for_ranges(
620                &graph,
621                &[ChangedRange::new("src/lib.rs", line, line)],
622                Path::new("."),
623            );
624            assert_eq!(changed.node_ids, vec![a], "line {line} should hit a");
625        }
626    }
627
628    #[test]
629    fn change_between_symbols_reports_no_symbol_hit() {
630        let (graph, _, _, _) = three_symbol_file();
631        // Line 15 sits in the gap between `a` and `b` — an import or comment.
632        let changed = changed_node_ids_for_ranges(
633            &graph,
634            &[ChangedRange::new("src/lib.rs", 15, 15)],
635            Path::new("."),
636        );
637
638        assert!(changed.node_ids.is_empty());
639        assert_eq!(
640            changed.files_without_symbol_hits,
641            vec!["src/lib.rs".to_string()],
642            "unmatched changes must be surfaced, not silently dropped"
643        );
644    }
645
646    #[test]
647    fn unpositioned_nodes_fall_back_to_file_granularity() {
648        let mut graph = ArborGraph::new();
649        // line_end == 0: some fallback parsers do not record positions.
650        let id = graph.add_node(CodeNode::new("x", "x", NodeKind::Function, "src/lib.rs"));
651
652        let changed = changed_node_ids_for_ranges(
653            &graph,
654            &[ChangedRange::new("src/lib.rs", 999, 999)],
655            Path::new("."),
656        );
657        assert_eq!(changed.node_ids, vec![id]);
658    }
659
660    #[test]
661    fn ranges_in_other_files_are_ignored() {
662        let (graph, _a, _b, _c) = three_symbol_file();
663        let changed = changed_node_ids_for_ranges(
664            &graph,
665            &[ChangedRange::new("src/other.rs", 1, 100)],
666            Path::new("."),
667        );
668        assert!(changed.node_ids.is_empty());
669        assert_eq!(changed.files_without_symbol_hits, vec!["src/other.rs"]);
670    }
671
672    #[test]
673    fn parses_standard_hunk_headers() {
674        let patch = "\
675@@ -12,7 +12,9 @@ fn context()
676-old
677+new
678@@ -40,3 +42,3 @@
679 ctx";
680        let ranges = parse_unified_diff_ranges(patch, "src/lib.rs");
681        assert_eq!(
682            ranges,
683            vec![
684                ChangedRange::new("src/lib.rs", 12, 20),
685                ChangedRange::new("src/lib.rs", 42, 44),
686            ]
687        );
688    }
689
690    #[test]
691    fn parses_hunk_header_with_omitted_count() {
692        // `+5` with no comma means exactly one line.
693        let ranges = parse_unified_diff_ranges("@@ -5 +5 @@\n+x", "a.rs");
694        assert_eq!(ranges, vec![ChangedRange::new("a.rs", 5, 5)]);
695    }
696
697    #[test]
698    fn pure_deletion_anchors_on_insertion_point() {
699        // `+7,0`: the new file has no lines here, but the deletion still
700        // changes whatever symbol surrounds line 7.
701        let ranges = parse_unified_diff_ranges("@@ -7,3 +7,0 @@", "a.rs");
702        assert_eq!(ranges, vec![ChangedRange::new("a.rs", 7, 7)]);
703    }
704
705    #[test]
706    fn malformed_headers_are_skipped_not_fatal() {
707        let patch = "\
708@@ garbage @@
709@@ -1,2 +1,2 @@
710+ok
711@@ -x,y +z,w @@";
712        let ranges = parse_unified_diff_ranges(patch, "a.rs");
713        assert_eq!(ranges, vec![ChangedRange::new("a.rs", 1, 2)]);
714    }
715
716    #[test]
717    fn empty_patch_yields_no_ranges() {
718        assert!(parse_unified_diff_ranges("", "a.rs").is_empty());
719        assert!(parse_unified_diff_ranges("no hunks here", "a.rs").is_empty());
720    }
721
722    #[test]
723    fn end_to_end_patch_to_symbols() {
724        let (graph, _a, b, _c) = three_symbol_file();
725        // A hunk covering lines 21-24 — inside `b` only.
726        let patch = "@@ -21,4 +21,4 @@\n-old\n+new";
727        let ranges = parse_unified_diff_ranges(patch, "src/lib.rs");
728        let changed = changed_node_ids_for_ranges(&graph, &ranges, Path::new("."));
729        assert_eq!(changed.node_ids, vec![b]);
730    }
731}