grit-lib 0.5.32

Core library for the grit Git implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Shared line-diff options for structured hunks, log patches, and tree diffs.

use crate::config::ConfigSet;

use super::filter::DiffFilter;
use super::{indent_heuristic_from_config, WhitespaceMode};

/// Line diff algorithm names matching Git's `diff.algorithm` and `--diff-algorithm`.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DiffAlgorithm {
    /// Git default (`myers` / `default`).
    #[default]
    Myers,
    /// Minimal diff (`minimal`).
    Minimal,
    /// Patience diff (`patience`).
    Patience,
    /// Histogram diff (`histogram`).
    Histogram,
}

/// Unknown value for [`DiffAlgorithm`](DiffAlgorithm)'s [`FromStr`](std::str::FromStr) implementation.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("unknown diff algorithm `{0}`")]
pub struct UnknownDiffAlgorithm(pub String);

impl std::str::FromStr for DiffAlgorithm {
    type Err = UnknownDiffAlgorithm;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_lowercase().as_str() {
            "myers" | "default" => Ok(Self::Myers),
            "minimal" => Ok(Self::Minimal),
            "patience" => Ok(Self::Patience),
            "histogram" => Ok(Self::Histogram),
            other => Err(UnknownDiffAlgorithm(other.to_owned())),
        }
    }
}

/// u32 rename APIs: thresholds `0`–`100` run detection at that Git `-M` percent;
/// [`RENAME_DETECTION_DISABLED`] (101) and above skip detection (legacy postprocess and `--no-renames` plumbing).
pub const RENAME_DETECTION_DISABLED: u32 = 101;

/// Rename detection policy for tree diffs.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RenameDetection {
    /// Do not detect renames.
    Off,
    /// Detect renames when similarity is at least this percent (Git `-M` default 50).
    Similarity(u8),
}

impl Default for RenameDetection {
    /// 50% similarity, Git's default for `-M` and `diff.renames=true`.
    fn default() -> Self {
        Self::Similarity(50)
    }
}

impl RenameDetection {
    /// Git rename threshold, or `None` when renames are disabled.
    #[must_use]
    pub fn threshold_percent(self) -> Option<u32> {
        match self {
            Self::Off => None,
            Self::Similarity(p) => Some(u32::from(p)),
        }
    }
}

/// Changed-file count above which word-level inline emphasis is skipped (human TTY diffs).
pub const WORD_LEVEL_INLINE_MAX_CHANGED_FILES: usize = 64;

/// Line-diff options shared by structured output, log patches, and benchmarks.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct DiffOptions {
    /// Unchanged context lines around each change (Git `-U`, default 3).
    pub context_lines: usize,
    /// `--inter-hunk-context` (default 0).
    pub inter_hunk_context: usize,
    /// Line diff algorithm.
    pub algorithm: DiffAlgorithm,
    /// Apply Git's indent heuristic when generating hunks.
    pub indent_heuristic: bool,
    /// Rename detection applied by [`Diff::files_for_entries`](super::Diff::files_for_entries) and tree content loaders when
    /// entries are not already paired (default similarity 50 via [`RenameDetection::Similarity`], Git `-M`).
    pub renames: RenameDetection,
    /// `--diff-filter` status selection (applied after rename detection).
    pub filter: Option<DiffFilter>,
    /// Whitespace comparison rules for line diffs.
    pub whitespace: WhitespaceMode,
    /// When false, skip intra-line word emphasis (line-level hunks only).
    pub word_level_inline: bool,
    /// Expand hunks to enclosing function boundaries (`git diff -W`).
    pub function_context: bool,
    /// For [`super::diff_paths`] only: count lines without building hunks.
    pub(crate) no_index_stat_only: bool,
}

impl Default for DiffOptions {
    fn default() -> Self {
        Self {
            context_lines: 3,
            inter_hunk_context: 0,
            algorithm: DiffAlgorithm::Myers,
            indent_heuristic: true,
            renames: RenameDetection::default(),
            filter: None,
            whitespace: WhitespaceMode::default(),
            word_level_inline: true,
            function_context: false,
            no_index_stat_only: false,
        }
    }
}

impl PartialEq for DiffOptions {
    fn eq(&self, other: &Self) -> bool {
        self.context_lines == other.context_lines
            && self.inter_hunk_context == other.inter_hunk_context
            && self.algorithm == other.algorithm
            && self.indent_heuristic == other.indent_heuristic
            && self.renames == other.renames
            && self.filter == other.filter
            && self.whitespace == other.whitespace
            && self.word_level_inline == other.word_level_inline
            && self.function_context == other.function_context
            && self.no_index_stat_only == other.no_index_stat_only
    }
}

impl DiffOptions {
    /// Builder-style update of context lines (`-U`).
    #[must_use]
    pub fn with_context_lines(mut self, context_lines: usize) -> Self {
        self.context_lines = context_lines;
        self
    }

    /// Builder-style update of inter-hunk context.
    #[must_use]
    pub fn with_inter_hunk_context(mut self, inter_hunk_context: usize) -> Self {
        self.inter_hunk_context = inter_hunk_context;
        self
    }

    /// Builder-style update of the line diff algorithm.
    #[must_use]
    pub fn with_algorithm(mut self, algorithm: DiffAlgorithm) -> Self {
        self.algorithm = algorithm;
        self
    }

    /// Builder-style update of the indent heuristic flag.
    #[must_use]
    pub fn with_indent_heuristic(mut self, indent_heuristic: bool) -> Self {
        self.indent_heuristic = indent_heuristic;
        self
    }

    /// Builder-style update of rename detection.
    #[must_use]
    pub fn with_renames(mut self, renames: RenameDetection) -> Self {
        self.renames = renames;
        self
    }

    /// Builder-style update of diff status filter.
    #[must_use]
    pub fn with_filter(mut self, filter: Option<DiffFilter>) -> Self {
        self.filter = filter;
        self
    }

    /// Similarity percent for rename detection, or `None` when [`RenameDetection::Off`].
    #[must_use]
    pub fn rename_similarity_threshold(&self) -> Option<u32> {
        match self.renames {
            RenameDetection::Off => None,
            RenameDetection::Similarity(p) => Some(u32::from(p)),
        }
    }

    /// u32 threshold for rename pairing (`apply_rename_detection_to_diff_entries`) and related APIs.
    #[must_use]
    pub fn rename_threshold_u32(&self) -> u32 {
        self.rename_similarity_threshold()
            .unwrap_or(RENAME_DETECTION_DISABLED)
    }

    /// Builder-style update of word-level inline emphasis.
    #[must_use]
    pub fn with_word_level_inline(mut self, word_level_inline: bool) -> Self {
        self.word_level_inline = word_level_inline;
        self
    }

    /// Builder-style update of whitespace comparison rules.
    #[must_use]
    pub fn with_whitespace(mut self, whitespace: WhitespaceMode) -> Self {
        self.whitespace = whitespace;
        self
    }

    /// When true, [`super::diff_paths`] counts lines instead of building hunks.
    #[must_use]
    pub fn with_no_index_stat_only(mut self, stat_only: bool) -> Self {
        self.no_index_stat_only = stat_only;
        self
    }

    /// Turn off word-level inline when `changed_files` exceeds
    /// [`WORD_LEVEL_INLINE_MAX_CHANGED_FILES`].
    #[must_use]
    pub fn cap_word_level_inline_for_changed_files(self, changed_files: usize) -> Self {
        let mut opts = self;
        if opts.word_level_inline && changed_files > WORD_LEVEL_INLINE_MAX_CHANGED_FILES {
            opts.word_level_inline = false;
        }
        opts
    }

    /// Read `diff.algorithm`, `diff.context`, `diff.interHunkContext`, `diff.indentHeuristic`,
    /// and `diff.renames` from repository config.
    #[must_use]
    pub fn from_config(config: &ConfigSet) -> Self {
        let mut opts = Self::default();
        if let Some(name) = config.value("diff.algorithm") {
            if let Ok(parsed) = name.parse::<DiffAlgorithm>() {
                opts.algorithm = parsed;
            }
        }
        if let Some(v) = config.value("diff.context") {
            if let Ok(n) = v.parse::<usize>() {
                opts.context_lines = n;
            }
        }
        if let Some(v) = config.value("diff.interHunkContext") {
            if let Ok(n) = v.parse::<usize>() {
                opts.inter_hunk_context = n;
            }
        }
        opts.indent_heuristic = indent_heuristic_from_config(config);
        opts.renames = renames_from_config(config);
        if config.bool_with_default("diff.ignoreSpaceChange", false) {
            opts.whitespace.ignore_space_change = true;
        }
        opts
    }

    /// Resolve indent heuristic with optional CLI overrides (log/diff plumbing).
    #[must_use]
    pub fn resolve_indent_heuristic(
        config: &ConfigSet,
        cli_indent_heuristic: bool,
        cli_no_indent_heuristic: bool,
    ) -> bool {
        crate::diff::core::resolve_indent_heuristic(
            config,
            cli_indent_heuristic,
            cli_no_indent_heuristic,
        )
    }

    /// Like [`Self::resolve_indent_heuristic`], with a structured CLI override enum.
    #[must_use]
    pub fn resolve_indent_heuristic_with_override(
        config: &ConfigSet,
        cli_override: IndentHeuristicOverride,
    ) -> bool {
        let (cli_on, cli_off) = match cli_override {
            IndentHeuristicOverride::FromConfig => (false, false),
            IndentHeuristicOverride::ForceOn => (true, false),
            IndentHeuristicOverride::ForceOff => (false, true),
        };
        Self::resolve_indent_heuristic(config, cli_on, cli_off)
    }
}

/// CLI override for `diff.indentHeuristic` when building [`DiffOptions`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum IndentHeuristicOverride {
    /// Use `diff.indentHeuristic` from config (Git default: on when unset).
    #[default]
    FromConfig,
    /// Force the heuristic on (`--indent-heuristic`).
    ForceOn,
    /// Force the heuristic off (`--no-indent-heuristic`).
    ForceOff,
}

/// `diff.renames`: `false` disables; `true` or copy modes use default similarity.
#[must_use]
pub fn renames_from_config(config: &ConfigSet) -> RenameDetection {
    match config.value("diff.renames") {
        Some(v) => {
            let v = v.trim();
            if v.eq_ignore_ascii_case("false")
                || v.eq_ignore_ascii_case("no")
                || v.eq_ignore_ascii_case("off")
                || v == "0"
            {
                RenameDetection::Off
            } else {
                RenameDetection::default()
            }
        }
        None => RenameDetection::default(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{ConfigFile, ConfigScope, ConfigSet};

    fn config_from(snippet: &str) -> ConfigSet {
        let file = ConfigFile::parse(std::path::Path::new("test"), snippet, ConfigScope::Local)
            .expect("parse");
        let mut set = ConfigSet::new();
        set.merge(&file);
        set
    }

    #[test]
    fn diff_algorithm_from_str_roundtrip_and_error() {
        for (s, expected) in [
            ("myers", DiffAlgorithm::Myers),
            ("default", DiffAlgorithm::Myers),
            ("MYERS", DiffAlgorithm::Myers),
            ("minimal", DiffAlgorithm::Minimal),
            ("patience", DiffAlgorithm::Patience),
            ("histogram", DiffAlgorithm::Histogram),
        ] {
            assert_eq!(s.parse::<DiffAlgorithm>().expect("parse"), expected);
        }
        assert!(matches!(
            "bogus".parse::<DiffAlgorithm>(),
            Err(UnknownDiffAlgorithm(_))
        ));
    }

    #[test]
    fn diff_options_from_config_reads_algorithm_context_renames() {
        let cfg = config_from(
            "[diff]\n\
             \talgorithm = patience\n\
             \tcontext = 5\n\
             \tinterHunkContext = 2\n\
             \tindentHeuristic = false\n\
             \trenames = false\n",
        );
        let opts = DiffOptions::from_config(&cfg);
        assert_eq!(opts.algorithm, DiffAlgorithm::Patience);
        assert_eq!(opts.context_lines, 5);
        assert_eq!(opts.inter_hunk_context, 2);
        assert!(!opts.indent_heuristic);
        assert_eq!(opts.renames, RenameDetection::Off);

        for on in [
            "",
            "[diff]\n\trenames = true\n",
            "[diff]\n\trenames = copies\n",
        ] {
            assert_eq!(
                DiffOptions::from_config(&config_from(on)).renames,
                RenameDetection::Similarity(50),
                "config {on:?}"
            );
        }
        assert_eq!(
            DiffOptions::default().renames,
            RenameDetection::Similarity(50)
        );

        for off in ["no", "0", "off", "OFF"] {
            let cfg = config_from(&format!("[diff]\n\trenames = {off}\n"));
            assert_eq!(
                DiffOptions::from_config(&cfg).renames,
                RenameDetection::Off,
                "renames={off}"
            );
        }
    }

    #[test]
    fn cap_word_level_inline_for_changed_files() {
        let on = DiffOptions {
            word_level_inline: true,
            ..DiffOptions::default()
        };
        assert!(
            on.clone()
                .cap_word_level_inline_for_changed_files(WORD_LEVEL_INLINE_MAX_CHANGED_FILES)
                .word_level_inline
        );
        assert!(
            !on.cap_word_level_inline_for_changed_files(WORD_LEVEL_INLINE_MAX_CHANGED_FILES + 1)
                .word_level_inline
        );
    }
}