gix_diff/blob/mod.rs
1//! For using text diffs, please have a look at the [`imara-diff` documentation](https://docs.rs/imara-diff),
2//! maintained by [Pascal Kuthe](https://github.com/pascalkuthe).
3use std::{collections::HashMap, path::PathBuf};
4
5use bstr::BString;
6pub use imara_diff::*;
7
8/// Facilities to render a computed [`Diff`] as unified diff output.
9pub mod unified_diff;
10pub use unified_diff::impls::UnifiedDiff;
11
12/// Compute a diff with Git's slider heuristics to produce more intuitive diffs.
13///
14/// This function uses [`Diff`] from `imara-diff`
15/// that supports postprocessing with slider heuristics. The slider heuristics move
16/// diff hunks to more intuitive locations based on indentation and other factors,
17/// resulting in diffs that are more readable and match Git's output more closely.
18///
19/// # Examples
20///
21/// ```
22/// use gix_diff::blob::{diff_with_slider_heuristics, Algorithm, InternedInput};
23///
24/// let before = "fn foo() {\n let x = 1;\n}\n";
25/// let after = "fn foo() {\n let x = 2;\n}\n";
26///
27/// let input = InternedInput::new(before, after);
28/// let diff = diff_with_slider_heuristics(Algorithm::Histogram, &input);
29///
30/// // The diff now has slider heuristics applied
31/// assert_eq!(diff.count_removals(), 1);
32/// assert_eq!(diff.count_additions(), 1);
33/// ```
34pub fn diff_with_slider_heuristics<T: AsRef<[u8]>>(algorithm: Algorithm, input: &InternedInput<T>) -> Diff {
35 let mut diff = Diff::compute(algorithm, input);
36 diff.postprocess_lines(input);
37 diff
38}
39
40///
41pub mod pipeline;
42
43///
44pub mod platform;
45
46/// Information about the diff performed to detect similarity.
47#[derive(Debug, Default, Clone, Copy, PartialEq, PartialOrd)]
48pub struct DiffLineStats {
49 /// The amount of lines to remove from the source to get to the destination.
50 pub removals: u32,
51 /// The amount of lines to add to the source to get to the destination.
52 pub insertions: u32,
53 /// The amount of lines of the previous state, in the source.
54 pub before: usize,
55 /// The amount of lines of the new state, in the destination.
56 pub after: usize,
57 /// A range from 0 to 1.0, where 1.0 is a perfect match and 0.5 is a similarity of 50%.
58 /// Similarity is the ratio between all lines in the previous blob and the current blob,
59 /// calculated as `(old_lines_count - new_lines_count) as f32 / old_lines_count.max(new_lines_count) as f32`.
60 pub similarity: f32,
61}
62
63/// A way to classify a resource suitable for diffing.
64#[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
65pub enum ResourceKind {
66 /// The source of a rewrite, rename or copy operation, or generally the old version of a resource.
67 OldOrSource,
68 /// The destination of a rewrite, rename or copy operation, or generally the new version of a resource.
69 NewOrDestination,
70}
71
72/// A set of values to define how to diff something that is associated with it using `git-attributes`, relevant for regular files.
73///
74/// Some values are related to diffing, some are related to conversions.
75#[derive(Default, Debug, Clone, PartialEq, Eq)]
76pub struct Driver {
77 /// The name of the driver, as referred to by `[diff "name"]` in the git configuration.
78 pub name: BString,
79 /// The command to execute to perform the diff entirely like `<command> old-file old-hex old-mode new-file new-hex new-mode`.
80 ///
81 /// Please note that we don't make this call ourselves, but use it to determine that we should not run the our standard
82 /// built-in algorithm but bail instead as the output of such a program isn't standardized.
83 pub command: Option<BString>,
84 /// The per-driver algorithm to use.
85 pub algorithm: Option<Algorithm>,
86 /// The external filter program to call like `<binary_to_text_command> /path/to/blob` which outputs a textual version of the provided
87 /// binary file.
88 /// Note that it's invoked with a shell if arguments are given.
89 /// Further, if present, it will always be executed, whether `is_binary` is set or not.
90 pub binary_to_text_command: Option<BString>,
91 /// `Some(true)` if this driver deals with binary files, which means that a `binary_to_text_command` should be used to convert binary
92 /// into a textual representation.
93 /// Without such a command, anything that is considered binary is not diffed, but only the size of its data is made available.
94 /// If `Some(false)`, it won't be considered binary, and the its data will not be sampled for the null-byte either.
95 /// Leaving it to `None` means binary detection is automatic, and is based on the presence of the `0` byte in the first 8kB of the buffer.
96 pub is_binary: Option<bool>,
97}
98
99/// A conversion pipeline to take an object or path from what's stored in `git` to what can be diffed, while
100/// following the guidance of git-attributes at the respective path to learn if diffing should happen or if
101/// the content is considered binary.
102///
103/// There are two different conversion flows, where the target of the flow is a buffer with diffable content:
104// TODO: update this with information about possible directions.
105///
106/// * `worktree on disk` -> `text conversion`
107/// * `object` -> `worktree-filters` -> `text conversion`
108#[derive(Clone)]
109pub struct Pipeline {
110 /// A way to read data directly from the worktree.
111 pub roots: pipeline::WorktreeRoots,
112 /// A pipeline to convert objects from what's stored in `git` to its worktree version.
113 pub worktree_filter: gix_filter::Pipeline,
114 /// Options affecting the way we read files.
115 pub options: pipeline::Options,
116 /// Drivers to help customize the conversion behaviour depending on the location of items.
117 drivers: Vec<Driver>,
118 /// Pre-configured attributes to obtain additional diff-related information.
119 attrs: gix_filter::attributes::search::Outcome,
120 /// A buffer to manipulate paths
121 path: PathBuf,
122}
123
124/// A utility for performing a diff of two blobs, including flexible conversions, conversion-caching
125/// acquisition of diff information.
126/// Note that this instance will not call external filters as their output can't be known programmatically,
127/// but it allows to prepare their input if the caller wishes to perform this task.
128///
129/// Optimized for NxM lookups with built-in caching.
130#[derive(Clone)]
131pub struct Platform {
132 /// The old version of a diff-able blob, if set.
133 old: Option<platform::CacheKey>,
134 /// The new version of a diff-able blob, if set.
135 new: Option<platform::CacheKey>,
136
137 /// Options to alter how diffs should be performed.
138 pub options: platform::Options,
139 /// A way to convert objects into a diff-able format.
140 pub filter: Pipeline,
141 /// A way to access .gitattributes
142 pub attr_stack: gix_worktree::Stack,
143
144 /// The way we convert resources into diffable states.
145 pub filter_mode: pipeline::Mode,
146 /// A continuously growing cache keeping ready-for-diff blobs by their path in the worktree,
147 /// as that is what affects their final diff-able state.
148 ///
149 /// That way, expensive rewrite-checks with NxM matrix checks would be as fast as possible,
150 /// avoiding duplicate work.
151 diff_cache: HashMap<platform::CacheKey, platform::CacheValue>,
152 /// A list of previously used buffers, ready for re-use.
153 free_list: Vec<Vec<u8>>,
154}
155
156mod impls {
157 use crate::blob::ResourceKind;
158
159 impl std::fmt::Display for ResourceKind {
160 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161 f.write_str(match self {
162 ResourceKind::OldOrSource => "old",
163 ResourceKind::NewOrDestination => "new",
164 })
165 }
166 }
167}