Skip to main content

grit_lib/diff/
options.rs

1//! Shared line-diff options for structured hunks, log patches, and tree diffs.
2
3use crate::config::ConfigSet;
4
5use super::filter::DiffFilter;
6use super::{indent_heuristic_from_config, WhitespaceMode};
7
8/// Line diff algorithm names matching Git's `diff.algorithm` and `--diff-algorithm`.
9#[non_exhaustive]
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub enum DiffAlgorithm {
12    /// Git default (`myers` / `default`).
13    #[default]
14    Myers,
15    /// Minimal diff (`minimal`).
16    Minimal,
17    /// Patience diff (`patience`).
18    Patience,
19    /// Histogram diff (`histogram`).
20    Histogram,
21}
22
23/// Unknown value for [`DiffAlgorithm`](DiffAlgorithm)'s [`FromStr`](std::str::FromStr) implementation.
24#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
25#[error("unknown diff algorithm `{0}`")]
26pub struct UnknownDiffAlgorithm(pub String);
27
28impl std::str::FromStr for DiffAlgorithm {
29    type Err = UnknownDiffAlgorithm;
30
31    fn from_str(s: &str) -> Result<Self, Self::Err> {
32        match s.to_ascii_lowercase().as_str() {
33            "myers" | "default" => Ok(Self::Myers),
34            "minimal" => Ok(Self::Minimal),
35            "patience" => Ok(Self::Patience),
36            "histogram" => Ok(Self::Histogram),
37            other => Err(UnknownDiffAlgorithm(other.to_owned())),
38        }
39    }
40}
41
42/// u32 rename APIs: thresholds `0`–`100` run detection at that Git `-M` percent;
43/// [`RENAME_DETECTION_DISABLED`] (101) and above skip detection (legacy postprocess and `--no-renames` plumbing).
44pub const RENAME_DETECTION_DISABLED: u32 = 101;
45
46/// Rename detection policy for tree diffs.
47#[non_exhaustive]
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum RenameDetection {
50    /// Do not detect renames.
51    Off,
52    /// Detect renames when similarity is at least this percent (Git `-M` default 50).
53    Similarity(u8),
54}
55
56impl Default for RenameDetection {
57    /// 50% similarity, Git's default for `-M` and `diff.renames=true`.
58    fn default() -> Self {
59        Self::Similarity(50)
60    }
61}
62
63impl RenameDetection {
64    /// Git rename threshold, or `None` when renames are disabled.
65    #[must_use]
66    pub fn threshold_percent(self) -> Option<u32> {
67        match self {
68            Self::Off => None,
69            Self::Similarity(p) => Some(u32::from(p)),
70        }
71    }
72}
73
74/// Changed-file count above which word-level inline emphasis is skipped (human TTY diffs).
75pub const WORD_LEVEL_INLINE_MAX_CHANGED_FILES: usize = 64;
76
77/// Line-diff options shared by structured output, log patches, and benchmarks.
78#[non_exhaustive]
79#[derive(Debug, Clone)]
80pub struct DiffOptions {
81    /// Unchanged context lines around each change (Git `-U`, default 3).
82    pub context_lines: usize,
83    /// `--inter-hunk-context` (default 0).
84    pub inter_hunk_context: usize,
85    /// Line diff algorithm.
86    pub algorithm: DiffAlgorithm,
87    /// Apply Git's indent heuristic when generating hunks.
88    pub indent_heuristic: bool,
89    /// Rename detection applied by [`Diff::files_for_entries`](super::Diff::files_for_entries) and tree content loaders when
90    /// entries are not already paired (default similarity 50 via [`RenameDetection::Similarity`], Git `-M`).
91    pub renames: RenameDetection,
92    /// `--diff-filter` status selection (applied after rename detection).
93    pub filter: Option<DiffFilter>,
94    /// Whitespace comparison rules for line diffs.
95    pub whitespace: WhitespaceMode,
96    /// When false, skip intra-line word emphasis (line-level hunks only).
97    pub word_level_inline: bool,
98    /// Expand hunks to enclosing function boundaries (`git diff -W`).
99    pub function_context: bool,
100    /// For [`super::diff_paths`] only: count lines without building hunks.
101    pub(crate) no_index_stat_only: bool,
102}
103
104impl Default for DiffOptions {
105    fn default() -> Self {
106        Self {
107            context_lines: 3,
108            inter_hunk_context: 0,
109            algorithm: DiffAlgorithm::Myers,
110            indent_heuristic: true,
111            renames: RenameDetection::default(),
112            filter: None,
113            whitespace: WhitespaceMode::default(),
114            word_level_inline: true,
115            function_context: false,
116            no_index_stat_only: false,
117        }
118    }
119}
120
121impl PartialEq for DiffOptions {
122    fn eq(&self, other: &Self) -> bool {
123        self.context_lines == other.context_lines
124            && self.inter_hunk_context == other.inter_hunk_context
125            && self.algorithm == other.algorithm
126            && self.indent_heuristic == other.indent_heuristic
127            && self.renames == other.renames
128            && self.filter == other.filter
129            && self.whitespace == other.whitespace
130            && self.word_level_inline == other.word_level_inline
131            && self.function_context == other.function_context
132            && self.no_index_stat_only == other.no_index_stat_only
133    }
134}
135
136impl DiffOptions {
137    /// Builder-style update of context lines (`-U`).
138    #[must_use]
139    pub fn with_context_lines(mut self, context_lines: usize) -> Self {
140        self.context_lines = context_lines;
141        self
142    }
143
144    /// Builder-style update of inter-hunk context.
145    #[must_use]
146    pub fn with_inter_hunk_context(mut self, inter_hunk_context: usize) -> Self {
147        self.inter_hunk_context = inter_hunk_context;
148        self
149    }
150
151    /// Builder-style update of the line diff algorithm.
152    #[must_use]
153    pub fn with_algorithm(mut self, algorithm: DiffAlgorithm) -> Self {
154        self.algorithm = algorithm;
155        self
156    }
157
158    /// Builder-style update of the indent heuristic flag.
159    #[must_use]
160    pub fn with_indent_heuristic(mut self, indent_heuristic: bool) -> Self {
161        self.indent_heuristic = indent_heuristic;
162        self
163    }
164
165    /// Builder-style update of rename detection.
166    #[must_use]
167    pub fn with_renames(mut self, renames: RenameDetection) -> Self {
168        self.renames = renames;
169        self
170    }
171
172    /// Builder-style update of diff status filter.
173    #[must_use]
174    pub fn with_filter(mut self, filter: Option<DiffFilter>) -> Self {
175        self.filter = filter;
176        self
177    }
178
179    /// Similarity percent for rename detection, or `None` when [`RenameDetection::Off`].
180    #[must_use]
181    pub fn rename_similarity_threshold(&self) -> Option<u32> {
182        match self.renames {
183            RenameDetection::Off => None,
184            RenameDetection::Similarity(p) => Some(u32::from(p)),
185        }
186    }
187
188    /// u32 threshold for rename pairing (`apply_rename_detection_to_diff_entries`) and related APIs.
189    #[must_use]
190    pub fn rename_threshold_u32(&self) -> u32 {
191        self.rename_similarity_threshold()
192            .unwrap_or(RENAME_DETECTION_DISABLED)
193    }
194
195    /// Builder-style update of word-level inline emphasis.
196    #[must_use]
197    pub fn with_word_level_inline(mut self, word_level_inline: bool) -> Self {
198        self.word_level_inline = word_level_inline;
199        self
200    }
201
202    /// Builder-style update of whitespace comparison rules.
203    #[must_use]
204    pub fn with_whitespace(mut self, whitespace: WhitespaceMode) -> Self {
205        self.whitespace = whitespace;
206        self
207    }
208
209    /// When true, [`super::diff_paths`] counts lines instead of building hunks.
210    #[must_use]
211    pub fn with_no_index_stat_only(mut self, stat_only: bool) -> Self {
212        self.no_index_stat_only = stat_only;
213        self
214    }
215
216    /// Turn off word-level inline when `changed_files` exceeds
217    /// [`WORD_LEVEL_INLINE_MAX_CHANGED_FILES`].
218    #[must_use]
219    pub fn cap_word_level_inline_for_changed_files(self, changed_files: usize) -> Self {
220        let mut opts = self;
221        if opts.word_level_inline && changed_files > WORD_LEVEL_INLINE_MAX_CHANGED_FILES {
222            opts.word_level_inline = false;
223        }
224        opts
225    }
226
227    /// Read `diff.algorithm`, `diff.context`, `diff.interHunkContext`, `diff.indentHeuristic`,
228    /// and `diff.renames` from repository config.
229    #[must_use]
230    pub fn from_config(config: &ConfigSet) -> Self {
231        let mut opts = Self::default();
232        if let Some(name) = config.value("diff.algorithm") {
233            if let Ok(parsed) = name.parse::<DiffAlgorithm>() {
234                opts.algorithm = parsed;
235            }
236        }
237        if let Some(v) = config.value("diff.context") {
238            if let Ok(n) = v.parse::<usize>() {
239                opts.context_lines = n;
240            }
241        }
242        if let Some(v) = config.value("diff.interHunkContext") {
243            if let Ok(n) = v.parse::<usize>() {
244                opts.inter_hunk_context = n;
245            }
246        }
247        opts.indent_heuristic = indent_heuristic_from_config(config);
248        opts.renames = renames_from_config(config);
249        if config.bool_with_default("diff.ignoreSpaceChange", false) {
250            opts.whitespace.ignore_space_change = true;
251        }
252        opts
253    }
254
255    /// Resolve indent heuristic with optional CLI overrides (log/diff plumbing).
256    #[must_use]
257    pub fn resolve_indent_heuristic(
258        config: &ConfigSet,
259        cli_indent_heuristic: bool,
260        cli_no_indent_heuristic: bool,
261    ) -> bool {
262        crate::diff::core::resolve_indent_heuristic(
263            config,
264            cli_indent_heuristic,
265            cli_no_indent_heuristic,
266        )
267    }
268
269    /// Like [`Self::resolve_indent_heuristic`], with a structured CLI override enum.
270    #[must_use]
271    pub fn resolve_indent_heuristic_with_override(
272        config: &ConfigSet,
273        cli_override: IndentHeuristicOverride,
274    ) -> bool {
275        let (cli_on, cli_off) = match cli_override {
276            IndentHeuristicOverride::FromConfig => (false, false),
277            IndentHeuristicOverride::ForceOn => (true, false),
278            IndentHeuristicOverride::ForceOff => (false, true),
279        };
280        Self::resolve_indent_heuristic(config, cli_on, cli_off)
281    }
282}
283
284/// CLI override for `diff.indentHeuristic` when building [`DiffOptions`].
285#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
286#[non_exhaustive]
287pub enum IndentHeuristicOverride {
288    /// Use `diff.indentHeuristic` from config (Git default: on when unset).
289    #[default]
290    FromConfig,
291    /// Force the heuristic on (`--indent-heuristic`).
292    ForceOn,
293    /// Force the heuristic off (`--no-indent-heuristic`).
294    ForceOff,
295}
296
297/// `diff.renames`: `false` disables; `true` or copy modes use default similarity.
298#[must_use]
299pub fn renames_from_config(config: &ConfigSet) -> RenameDetection {
300    match config.value("diff.renames") {
301        Some(v) => {
302            let v = v.trim();
303            if v.eq_ignore_ascii_case("false")
304                || v.eq_ignore_ascii_case("no")
305                || v.eq_ignore_ascii_case("off")
306                || v == "0"
307            {
308                RenameDetection::Off
309            } else {
310                RenameDetection::default()
311            }
312        }
313        None => RenameDetection::default(),
314    }
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320    use crate::config::{ConfigFile, ConfigScope, ConfigSet};
321
322    fn config_from(snippet: &str) -> ConfigSet {
323        let file = ConfigFile::parse(std::path::Path::new("test"), snippet, ConfigScope::Local)
324            .expect("parse");
325        let mut set = ConfigSet::new();
326        set.merge(&file);
327        set
328    }
329
330    #[test]
331    fn diff_algorithm_from_str_roundtrip_and_error() {
332        for (s, expected) in [
333            ("myers", DiffAlgorithm::Myers),
334            ("default", DiffAlgorithm::Myers),
335            ("MYERS", DiffAlgorithm::Myers),
336            ("minimal", DiffAlgorithm::Minimal),
337            ("patience", DiffAlgorithm::Patience),
338            ("histogram", DiffAlgorithm::Histogram),
339        ] {
340            assert_eq!(s.parse::<DiffAlgorithm>().expect("parse"), expected);
341        }
342        assert!(matches!(
343            "bogus".parse::<DiffAlgorithm>(),
344            Err(UnknownDiffAlgorithm(_))
345        ));
346    }
347
348    #[test]
349    fn diff_options_from_config_reads_algorithm_context_renames() {
350        let cfg = config_from(
351            "[diff]\n\
352             \talgorithm = patience\n\
353             \tcontext = 5\n\
354             \tinterHunkContext = 2\n\
355             \tindentHeuristic = false\n\
356             \trenames = false\n",
357        );
358        let opts = DiffOptions::from_config(&cfg);
359        assert_eq!(opts.algorithm, DiffAlgorithm::Patience);
360        assert_eq!(opts.context_lines, 5);
361        assert_eq!(opts.inter_hunk_context, 2);
362        assert!(!opts.indent_heuristic);
363        assert_eq!(opts.renames, RenameDetection::Off);
364
365        for on in [
366            "",
367            "[diff]\n\trenames = true\n",
368            "[diff]\n\trenames = copies\n",
369        ] {
370            assert_eq!(
371                DiffOptions::from_config(&config_from(on)).renames,
372                RenameDetection::Similarity(50),
373                "config {on:?}"
374            );
375        }
376        assert_eq!(
377            DiffOptions::default().renames,
378            RenameDetection::Similarity(50)
379        );
380
381        for off in ["no", "0", "off", "OFF"] {
382            let cfg = config_from(&format!("[diff]\n\trenames = {off}\n"));
383            assert_eq!(
384                DiffOptions::from_config(&cfg).renames,
385                RenameDetection::Off,
386                "renames={off}"
387            );
388        }
389    }
390
391    #[test]
392    fn cap_word_level_inline_for_changed_files() {
393        let on = DiffOptions {
394            word_level_inline: true,
395            ..DiffOptions::default()
396        };
397        assert!(
398            on.clone()
399                .cap_word_level_inline_for_changed_files(WORD_LEVEL_INLINE_MAX_CHANGED_FILES)
400                .word_level_inline
401        );
402        assert!(
403            !on.cap_word_level_inline_for_changed_files(WORD_LEVEL_INLINE_MAX_CHANGED_FILES + 1)
404                .word_level_inline
405        );
406    }
407}