Skip to main content

grit_lib/diff/
tree_options.rs

1//! Options for the metadata diffs on [`Diff`](super::Diff): which paths, which pairings.
2
3use crate::parallel::ThreadPolicy;
4use crate::pathspec::Pathspec;
5use crate::submodule_ignore::SubmoduleIgnoreMode;
6
7use super::core::{DiffPostprocessOptions, GIT_DIFF_DEFAULT_BREAK_SCORE, GIT_DIFF_MAX_SCORE};
8use super::options::RenameDetection;
9
10/// Copy detection policy for tree, index and work-tree diffs (Git `-C`).
11#[non_exhaustive]
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
13pub enum CopyDetection {
14    /// Do not detect copies.
15    #[default]
16    Off,
17    /// Pair added paths with paths changed in the same diff when content is at least this
18    /// percent similar (Git `-C<n>`).
19    Similarity(u8),
20    /// Like [`Self::Similarity`], but every path of the old side is a copy source, changed or
21    /// not (Git `-C<n> --find-copies-harder`).
22    FindHarder(u8),
23}
24
25impl CopyDetection {
26    /// Copy similarity threshold in percent, or `None` when [`Self::Off`].
27    #[must_use]
28    pub fn threshold_percent(self) -> Option<u32> {
29        match self {
30            Self::Off => None,
31            Self::Similarity(p) | Self::FindHarder(p) => Some(u32::from(p)),
32        }
33    }
34}
35
36/// Break-rewrite policy (Git `-B`): split a heavily rewritten modification into a deletion and an
37/// addition so rename and copy detection can pair its halves.
38#[non_exhaustive]
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
40pub enum BreakRewrites {
41    /// Never break modifications.
42    #[default]
43    Off,
44    /// Break a modification whose rewritten share reaches this score, on Git's internal scale
45    /// from `0` to [`BreakRewrites::MAX_SCORE`].
46    Score(u64),
47}
48
49impl BreakRewrites {
50    /// Top of the score scale [`Self::Score`] uses (100% rewritten).
51    pub const MAX_SCORE: u64 = GIT_DIFF_MAX_SCORE;
52
53    /// Git's default for a bare `-B` (50% of [`Self::MAX_SCORE`]).
54    pub const DEFAULT: Self = Self::Score(GIT_DIFF_DEFAULT_BREAK_SCORE);
55
56    /// Break at `percent` of [`Self::MAX_SCORE`] (Git `-B<n>%`); values above 100 saturate.
57    #[must_use]
58    pub fn percent(percent: u8) -> Self {
59        Self::Score(Self::MAX_SCORE * u64::from(percent.min(100)) / 100)
60    }
61
62    /// Score on the [`Self::MAX_SCORE`] scale, or `None` when [`Self::Off`].
63    #[must_use]
64    pub fn score(self) -> Option<u64> {
65        match self {
66            Self::Off => None,
67            Self::Score(score) => Some(score),
68        }
69    }
70}
71
72/// Options shared by the metadata diffs on [`Diff`](super::Diff): [`Diff::tree_to_tree`],
73/// [`Diff::commits`], [`Diff::index_to_tree`], [`Diff::index_to_worktree`],
74/// [`Diff::tree_to_worktree`] and [`Diff::detect_renames`].
75///
76/// The default compares every path with no rename, copy or break pairing (like
77/// `git diff-tree -r`). Configuration such as `diff.renameLimit` and `core.autocrlf` is read
78/// from the repository by the handle.
79///
80/// [`Diff::tree_to_tree`]: super::Diff::tree_to_tree
81/// [`Diff::commits`]: super::Diff::commits
82/// [`Diff::index_to_tree`]: super::Diff::index_to_tree
83/// [`Diff::index_to_worktree`]: super::Diff::index_to_worktree
84/// [`Diff::tree_to_worktree`]: super::Diff::tree_to_worktree
85/// [`Diff::detect_renames`]: super::Diff::detect_renames
86#[non_exhaustive]
87#[derive(Debug, Clone)]
88pub struct TreeDiffOptions {
89    /// Rename pairing (Git `-M`). Defaults to [`RenameDetection::Off`].
90    pub renames: RenameDetection,
91    /// Copy pairing (Git `-C`). Defaults to [`CopyDetection::Off`].
92    pub copies: CopyDetection,
93    /// Break-rewrite splitting (Git `-B`). Defaults to [`BreakRewrites::Off`].
94    pub break_rewrites: BreakRewrites,
95    /// Also report changed subtrees themselves, not only the paths inside them (Git
96    /// `diff-tree -t`). Applies to tree and commit diffs.
97    pub show_tree_entries: bool,
98    /// Path prefix prepended to every reported path (empty for the repository root). Applies to
99    /// tree and commit diffs, whose trees are then subtrees at that prefix.
100    pub prefix: String,
101    /// Worker limits for rename scoring and work-tree stat; `None` uses the repository's
102    /// [`thread_policy`](crate::repo::Repository::thread_policy).
103    pub threads: Option<ThreadPolicy>,
104    /// Report only paths this pathspec selects; `None` reports every path. Tree walks skip
105    /// directories the pathspec cannot reach.
106    pub pathspec: Option<Pathspec>,
107    /// Which submodule (gitlink) changes to report. [`SubmoduleIgnoreMode::All`] omits gitlink
108    /// paths entirely.
109    pub submodules: SubmoduleIgnoreMode,
110    /// Index-to-work-tree only: adopt fresh stat data for unchanged entries in the same scan,
111    /// so a later index write makes the next diff cheaper. The outcome reports whether the
112    /// in-memory index changed in
113    /// [`DiffEntriesResult::index_stat_refreshed`](super::DiffEntriesResult::index_stat_refreshed).
114    pub refresh_index_stat: bool,
115    /// Index-to-work-tree only: status shortcuts. A tracked file whose size changed is reported
116    /// as modified without being read, with a null work-tree `new_oid`, and intent-to-add
117    /// entries are not hashed. Leave off when the contents of the changes are loaded next.
118    pub for_status: bool,
119}
120
121impl Default for TreeDiffOptions {
122    fn default() -> Self {
123        Self {
124            renames: RenameDetection::Off,
125            copies: CopyDetection::Off,
126            break_rewrites: BreakRewrites::Off,
127            show_tree_entries: false,
128            prefix: String::new(),
129            threads: None,
130            pathspec: None,
131            submodules: SubmoduleIgnoreMode::None,
132            refresh_index_stat: false,
133            for_status: false,
134        }
135    }
136}
137
138impl TreeDiffOptions {
139    /// Sets [`renames`](Self::renames).
140    #[must_use]
141    pub fn with_renames(mut self, renames: RenameDetection) -> Self {
142        self.renames = renames;
143        self
144    }
145
146    /// Sets [`copies`](Self::copies).
147    #[must_use]
148    pub fn with_copies(mut self, copies: CopyDetection) -> Self {
149        self.copies = copies;
150        self
151    }
152
153    /// Sets [`break_rewrites`](Self::break_rewrites).
154    #[must_use]
155    pub fn with_break_rewrites(mut self, break_rewrites: BreakRewrites) -> Self {
156        self.break_rewrites = break_rewrites;
157        self
158    }
159
160    /// Sets [`show_tree_entries`](Self::show_tree_entries).
161    #[must_use]
162    pub fn with_show_tree_entries(mut self, show_tree_entries: bool) -> Self {
163        self.show_tree_entries = show_tree_entries;
164        self
165    }
166
167    /// Sets [`prefix`](Self::prefix).
168    #[must_use]
169    pub fn with_prefix(mut self, prefix: impl Into<String>) -> Self {
170        self.prefix = prefix.into();
171        self
172    }
173
174    /// Sets [`threads`](Self::threads).
175    #[must_use]
176    pub fn with_threads(mut self, threads: Option<ThreadPolicy>) -> Self {
177        self.threads = threads;
178        self
179    }
180
181    /// Sets [`pathspec`](Self::pathspec).
182    #[must_use]
183    pub fn with_pathspec(mut self, pathspec: Option<Pathspec>) -> Self {
184        self.pathspec = pathspec;
185        self
186    }
187
188    /// Sets [`submodules`](Self::submodules).
189    #[must_use]
190    pub fn with_submodules(mut self, submodules: SubmoduleIgnoreMode) -> Self {
191        self.submodules = submodules;
192        self
193    }
194
195    /// Sets [`refresh_index_stat`](Self::refresh_index_stat).
196    #[must_use]
197    pub fn with_refresh_index_stat(mut self, refresh_index_stat: bool) -> Self {
198        self.refresh_index_stat = refresh_index_stat;
199        self
200    }
201
202    /// Sets [`for_status`](Self::for_status).
203    #[must_use]
204    pub fn with_for_status(mut self, for_status: bool) -> Self {
205        self.for_status = for_status;
206        self
207    }
208
209    /// Whether any rename, copy or break pairing runs after the path walk.
210    pub(crate) fn pairs_entries(&self) -> bool {
211        self.renames != RenameDetection::Off
212            || self.copies != CopyDetection::Off
213            || self.break_rewrites != BreakRewrites::Off
214    }
215
216    /// Pathspec strings to match, empty for every path.
217    pub(crate) fn pathspec_specs(&self) -> &[String] {
218        self.pathspec.as_ref().map_or(&[], Pathspec::specs)
219    }
220
221    /// Equivalent post-processing options; `materialize_worktree_oid` is set for
222    /// tree-to-work-tree diffs, where `-B` fills the work-tree side's blob id like Git.
223    pub(crate) fn postprocess_options(
224        &self,
225        materialize_worktree_oid: bool,
226    ) -> DiffPostprocessOptions {
227        DiffPostprocessOptions {
228            break_score: self.break_rewrites.score(),
229            rename_threshold: self
230                .renames
231                .threshold_percent()
232                .unwrap_or(super::RENAME_DETECTION_DISABLED),
233            copy_threshold: self.copies.threshold_percent(),
234            find_copies_harder: matches!(self.copies, CopyDetection::FindHarder(_)),
235            materialize_break_worktree_new_oid: materialize_worktree_oid,
236        }
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    #[test]
245    fn defaults_pair_nothing() {
246        let opts = TreeDiffOptions::default();
247        assert_eq!(opts.renames, RenameDetection::Off);
248        assert_eq!(opts.copies, CopyDetection::Off);
249        assert_eq!(opts.break_rewrites, BreakRewrites::Off);
250        assert!(!opts.pairs_entries());
251        assert!(opts.pathspec_specs().is_empty());
252    }
253
254    #[test]
255    fn postprocess_options_map_every_field() {
256        let opts = TreeDiffOptions::default()
257            .with_renames(RenameDetection::Similarity(40))
258            .with_copies(CopyDetection::FindHarder(60))
259            .with_break_rewrites(BreakRewrites::DEFAULT);
260        assert!(opts.pairs_entries());
261        let pp = opts.postprocess_options(true);
262        assert_eq!(pp.rename_threshold, 40);
263        assert_eq!(pp.copy_threshold, Some(60));
264        assert!(pp.find_copies_harder);
265        assert_eq!(pp.break_score, Some(GIT_DIFF_DEFAULT_BREAK_SCORE));
266        assert!(pp.materialize_break_worktree_new_oid);
267
268        let off = TreeDiffOptions::default().postprocess_options(false);
269        assert_eq!(
270            off.rename_threshold,
271            super::super::RENAME_DETECTION_DISABLED
272        );
273        assert_eq!(off.copy_threshold, None);
274        assert!(!off.find_copies_harder);
275    }
276
277    #[test]
278    fn break_rewrites_percent_scales_and_saturates() {
279        assert_eq!(BreakRewrites::percent(50), BreakRewrites::DEFAULT);
280        assert_eq!(
281            BreakRewrites::percent(200).score(),
282            Some(BreakRewrites::MAX_SCORE)
283        );
284        assert_eq!(BreakRewrites::Off.score(), None);
285        assert_eq!(CopyDetection::Similarity(30).threshold_percent(), Some(30));
286        assert_eq!(CopyDetection::Off.threshold_percent(), None);
287    }
288}