1use crate::config::ConfigSet;
4
5use super::filter::DiffFilter;
6use super::{indent_heuristic_from_config, WhitespaceMode};
7
8#[non_exhaustive]
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub enum DiffAlgorithm {
12 #[default]
14 Myers,
15 Minimal,
17 Patience,
19 Histogram,
21}
22
23#[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
42pub const RENAME_DETECTION_DISABLED: u32 = 101;
45
46#[non_exhaustive]
48#[derive(Debug, Clone, Copy, PartialEq, Eq)]
49pub enum RenameDetection {
50 Off,
52 Similarity(u8),
54}
55
56impl Default for RenameDetection {
57 fn default() -> Self {
59 Self::Similarity(50)
60 }
61}
62
63impl RenameDetection {
64 #[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
74pub const WORD_LEVEL_INLINE_MAX_CHANGED_FILES: usize = 64;
76
77#[non_exhaustive]
79#[derive(Debug, Clone)]
80pub struct DiffOptions {
81 pub context_lines: usize,
83 pub inter_hunk_context: usize,
85 pub algorithm: DiffAlgorithm,
87 pub indent_heuristic: bool,
89 pub renames: RenameDetection,
92 pub filter: Option<DiffFilter>,
94 pub whitespace: WhitespaceMode,
96 pub word_level_inline: bool,
98 pub function_context: bool,
100 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 #[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 #[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 #[must_use]
153 pub fn with_algorithm(mut self, algorithm: DiffAlgorithm) -> Self {
154 self.algorithm = algorithm;
155 self
156 }
157
158 #[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 #[must_use]
167 pub fn with_renames(mut self, renames: RenameDetection) -> Self {
168 self.renames = renames;
169 self
170 }
171
172 #[must_use]
174 pub fn with_filter(mut self, filter: Option<DiffFilter>) -> Self {
175 self.filter = filter;
176 self
177 }
178
179 #[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 #[must_use]
190 pub fn rename_threshold_u32(&self) -> u32 {
191 self.rename_similarity_threshold()
192 .unwrap_or(RENAME_DETECTION_DISABLED)
193 }
194
195 #[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 #[must_use]
204 pub fn with_whitespace(mut self, whitespace: WhitespaceMode) -> Self {
205 self.whitespace = whitespace;
206 self
207 }
208
209 #[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 #[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 #[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 #[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 #[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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
286#[non_exhaustive]
287pub enum IndentHeuristicOverride {
288 #[default]
290 FromConfig,
291 ForceOn,
293 ForceOff,
295}
296
297#[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}