Skip to main content

grit_lib/diff/
presentation.rs

1//! Structured diff outcomes helpers shared by the CLI (hunk ids, listing rules, rename notices).
2
3use super::changes::FileChange;
4use super::detail::LineStat;
5use super::detail::{DiffDetail, FileDiff as ListedFileDiff};
6use super::hunk_id::{hunk_ids, DiffSide, HunkId};
7use super::options::DiffOptions;
8use super::structured::StructuredHunk;
9use super::{DiffStatus, InexactRenameDetectionSkipped, TreeDiffStructured};
10
11/// One structured hunk optionally decorated with a stable [`HunkId`].
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct AnnotatedStructuredHunk {
14    /// The hunk body and line metadata.
15    pub hunk: StructuredHunk,
16    /// Stable id when assigned (staged/unstaged with peer hunks).
17    pub id: Option<HunkId>,
18    /// 0-based index within the file when ids are assigned.
19    pub index: Option<usize>,
20}
21
22/// Assign stable hunk ids and indices for staged/unstaged diffs.
23#[must_use]
24pub fn annotate_structured_hunks(
25    side: DiffSide,
26    path: &str,
27    hunks: Vec<StructuredHunk>,
28    peer_hunks: &[StructuredHunk],
29    assign_ids: bool,
30) -> Vec<AnnotatedStructuredHunk> {
31    let assign = assign_ids && matches!(side, DiffSide::Unstaged | DiffSide::Staged);
32    let ids = if assign {
33        hunk_ids(side, path, &hunks, peer_hunks)
34    } else {
35        Vec::new()
36    };
37    hunks
38        .into_iter()
39        .enumerate()
40        .map(|(index, hunk)| AnnotatedStructuredHunk {
41            hunk,
42            id: if assign {
43                Some(ids[index].clone())
44            } else {
45                None
46            },
47            index: if assign { Some(index) } else { None },
48        })
49        .collect()
50}
51
52/// Whether a working-tree [`FileChange`] should appear in a whitespace-filtered patch listing.
53#[must_use]
54pub fn include_file_change_in_patch(change: &FileChange, options: &DiffOptions) -> bool {
55    let ws = options.whitespace;
56    if !ws.is_active() {
57        return true;
58    }
59    if matches!(
60        change.status,
61        DiffStatus::Renamed
62            | DiffStatus::Copied
63            | DiffStatus::Added
64            | DiffStatus::Deleted
65            | DiffStatus::TypeChanged
66    ) {
67        return true;
68    }
69    if change.old_mode != change.new_mode {
70        return true;
71    }
72    if change.binary {
73        return change.content_changed;
74    }
75    !change.structured(options.clone()).hunks.is_empty()
76}
77
78/// Whether callers should surface rename-limit skip metadata to the user.
79#[must_use]
80pub fn should_report_inexact_rename_skipped(skipped: &InexactRenameDetectionSkipped) -> bool {
81    skipped.unmatched_sources > 0 || skipped.unmatched_destinations > 0
82}
83
84/// Map a listed file row from [`super::Diff::files_for_entries`].
85#[must_use]
86pub fn presentation_hunks_from_listed(
87    f: &ListedFileDiff,
88    detail: DiffDetail,
89) -> Option<Vec<AnnotatedStructuredHunk>> {
90    if detail != DiffDetail::Patch {
91        return None;
92    }
93    f.structured.as_ref().map(|structured| {
94        annotate_structured_hunks(
95            DiffSide::Other,
96            &f.path,
97            structured.hunks.clone(),
98            &[],
99            false,
100        )
101    })
102}
103
104/// Map a tree structured diff row into annotated hunks.
105#[must_use]
106pub fn presentation_hunks_from_tree(t: &TreeDiffStructured) -> Vec<AnnotatedStructuredHunk> {
107    let path = t
108        .entry
109        .new_path
110        .clone()
111        .or_else(|| t.entry.old_path.clone())
112        .unwrap_or_default();
113    annotate_structured_hunks(
114        DiffSide::Other,
115        &path,
116        t.structured.hunks.clone(),
117        &[],
118        false,
119    )
120}
121
122/// Map a worktree [`FileChange`] into annotated hunks.
123#[must_use]
124pub fn presentation_hunks_from_file_change(
125    change: &FileChange,
126    options: DiffOptions,
127    side: DiffSide,
128    peer_hunks: &[StructuredHunk],
129    assign_hunk_ids: bool,
130) -> Vec<AnnotatedStructuredHunk> {
131    let structured = change.structured(options);
132    annotate_structured_hunks(
133        side,
134        &change.path,
135        structured.hunks,
136        peer_hunks,
137        assign_hunk_ids,
138    )
139}
140
141/// Line stat for a targets [`super::targets::FileDiff`] row under a given detail mode.
142#[must_use]
143pub fn line_stat_for_target_file(
144    f: &super::targets::FileDiff,
145    detail: DiffDetail,
146) -> Option<LineStat> {
147    if f.binary {
148        return None;
149    }
150    if detail == DiffDetail::Stat {
151        f.line_stat.or_else(|| Some(LineStat::from_hunks(&f.hunks)))
152    } else {
153        None
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160    use crate::diff::structured::{
161        SideBytes, StructuredLine, StructuredLineKind, StructuredSegment,
162    };
163    use crate::diff::WhitespaceMode;
164    use crate::objects::{FileMode, ObjectId};
165
166    fn sample_hunk(body: &str) -> StructuredHunk {
167        StructuredHunk {
168            old_start: 1,
169            new_start: 1,
170            old_lines: 1,
171            new_lines: 1,
172            context: None,
173            lines: vec![StructuredLine {
174                kind: StructuredLineKind::Add,
175                old: None,
176                new: Some(1),
177                segments: vec![StructuredSegment {
178                    text: body.into(),
179                    emphasis: false,
180                }],
181                no_newline_at_eof: false,
182            }],
183        }
184    }
185
186    #[test]
187    fn annotate_hunks_assign_indices_on_staged_side() {
188        let hunk = sample_hunk("same");
189        let annotated = annotate_structured_hunks(DiffSide::Staged, "f.txt", vec![hunk], &[], true);
190        assert_eq!(annotated[0].index, Some(0));
191        assert!(annotated[0].id.is_some());
192    }
193
194    #[test]
195    fn include_file_change_drops_whitespace_only_modification() {
196        let change = FileChange {
197            path: "x".into(),
198            old_path: None,
199            status: DiffStatus::Modified,
200            old_mode: FileMode::REGULAR,
201            new_mode: FileMode::REGULAR,
202            old_oid: ObjectId::from_hex("0000000000000000000000000000000000000001").unwrap(),
203            new_oid: ObjectId::from_hex("0000000000000000000000000000000000000002").unwrap(),
204            old_bytes: SideBytes::from_bytes(b"a\n".to_vec()),
205            new_bytes: SideBytes::from_bytes(b"a\n".to_vec()),
206            binary: false,
207            content_changed: true,
208            similarity: None,
209        };
210        let opts = DiffOptions::default().with_whitespace(WhitespaceMode::ignore_all_space());
211        assert!(!include_file_change_in_patch(&change, &opts));
212    }
213}