1use crate::quote_path::format_diff_path_with_prefix;
7use crate::userdiff::FuncnameMatcher;
8
9use super::core::{
10 blank_line_ignorable, compacted_line_ops_for_options, count_line_changes_with_options,
11 extract_function_context, imara_unified_hunk_slices, patience_compacted_line_ops,
12 unified_body_from_ops, unified_hunk_body_for_diff_options,
13};
14use super::detail::LineStat;
15use super::options::{DiffAlgorithm, DiffOptions};
16use super::unified_emit::{LineSide, UnifiedEmitOptions};
17use super::WhitespaceMode;
18
19const NO_NEWLINE_MARKER: &str = "\\ No newline at end of file\n";
21
22#[non_exhaustive]
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum DiffLabel<'a> {
26 DevNull,
28 Path {
33 prefix: &'a str,
35 path: &'a str,
37 },
38 Verbatim(&'a str),
40}
41
42#[non_exhaustive]
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
45pub enum PathQuoting {
46 #[default]
49 EscapeNonAscii,
50 KeepNonAscii,
53}
54
55#[non_exhaustive]
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
58pub enum NoNewlineMarker {
59 #[default]
61 Emit,
62 Omit,
64}
65
66#[non_exhaustive]
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
69pub enum IndentHeuristic {
70 #[default]
72 Enabled,
73 Disabled,
75}
76
77#[non_exhaustive]
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
80pub enum HunkExtent {
81 #[default]
83 Context,
84 Function,
86}
87
88#[non_exhaustive]
110#[derive(Debug, Clone)]
111pub struct UnifiedDiffOptions<'a> {
112 pub old_label: Option<DiffLabel<'a>>,
114 pub new_label: Option<DiffLabel<'a>>,
116 pub path_quoting: PathQuoting,
118 pub context_lines: usize,
120 pub inter_hunk_context: usize,
123 pub funcname: Option<&'a FuncnameMatcher>,
127 pub algorithm: DiffAlgorithm,
130 pub indent_heuristic: IndentHeuristic,
132 pub extent: HunkExtent,
134 pub anchors: Vec<String>,
137 pub whitespace: WhitespaceMode,
140 pub no_newline_marker: NoNewlineMarker,
142}
143
144impl Default for UnifiedDiffOptions<'_> {
145 fn default() -> Self {
146 Self {
147 old_label: None,
148 new_label: None,
149 path_quoting: PathQuoting::default(),
150 context_lines: 3,
151 inter_hunk_context: 0,
152 funcname: None,
153 algorithm: DiffAlgorithm::default(),
154 indent_heuristic: IndentHeuristic::default(),
155 extent: HunkExtent::default(),
156 anchors: Vec::new(),
157 whitespace: WhitespaceMode::default(),
158 no_newline_marker: NoNewlineMarker::default(),
159 }
160 }
161}
162
163impl<'a> UnifiedDiffOptions<'a> {
164 #[must_use]
166 pub fn new() -> Self {
167 Self::default()
168 }
169
170 #[must_use]
172 pub fn with_paths(self, old_path: &'a str, new_path: &'a str) -> Self {
173 self.with_labels(
174 DiffLabel::Path {
175 prefix: "a/",
176 path: old_path,
177 },
178 DiffLabel::Path {
179 prefix: "b/",
180 path: new_path,
181 },
182 )
183 }
184
185 #[must_use]
187 pub fn with_labels(mut self, old: DiffLabel<'a>, new: DiffLabel<'a>) -> Self {
188 self.old_label = Some(old);
189 self.new_label = Some(new);
190 self
191 }
192
193 #[must_use]
195 pub fn with_path_quoting(mut self, path_quoting: PathQuoting) -> Self {
196 self.path_quoting = path_quoting;
197 self
198 }
199
200 #[must_use]
202 pub fn with_context_lines(mut self, context_lines: usize) -> Self {
203 self.context_lines = context_lines;
204 self
205 }
206
207 #[must_use]
209 pub fn with_inter_hunk_context(mut self, inter_hunk_context: usize) -> Self {
210 self.inter_hunk_context = inter_hunk_context;
211 self
212 }
213
214 #[must_use]
216 pub fn with_funcname(mut self, matcher: &'a FuncnameMatcher) -> Self {
217 self.funcname = Some(matcher);
218 self
219 }
220
221 #[must_use]
223 pub fn with_algorithm(mut self, algorithm: DiffAlgorithm) -> Self {
224 self.algorithm = algorithm;
225 self
226 }
227
228 #[must_use]
230 pub fn with_indent_heuristic(mut self, indent_heuristic: IndentHeuristic) -> Self {
231 self.indent_heuristic = indent_heuristic;
232 self
233 }
234
235 #[must_use]
237 pub fn with_extent(mut self, extent: HunkExtent) -> Self {
238 self.extent = extent;
239 self
240 }
241
242 #[must_use]
244 pub fn with_anchors<I, S>(mut self, anchors: I) -> Self
245 where
246 I: IntoIterator<Item = S>,
247 S: Into<String>,
248 {
249 self.anchors = anchors.into_iter().map(Into::into).collect();
250 self
251 }
252
253 #[must_use]
255 pub fn with_whitespace(mut self, whitespace: WhitespaceMode) -> Self {
256 self.whitespace = whitespace;
257 self
258 }
259
260 #[must_use]
262 pub fn with_no_newline_marker(mut self, marker: NoNewlineMarker) -> Self {
263 self.no_newline_marker = marker;
264 self
265 }
266
267 fn line_options(&self) -> DiffOptions {
269 DiffOptions {
270 context_lines: self.context_lines,
271 inter_hunk_context: self.inter_hunk_context,
272 algorithm: self.algorithm,
273 indent_heuristic: self.indent_heuristic == IndentHeuristic::Enabled,
274 whitespace: self.whitespace,
275 function_context: self.extent == HunkExtent::Function,
276 ..DiffOptions::default()
277 }
278 }
279
280 fn emit_options(&self) -> UnifiedEmitOptions {
281 UnifiedEmitOptions {
282 context_lines: self.context_lines,
283 inter_hunk_context: self.inter_hunk_context,
284 function_context: self.extent == HunkExtent::Function,
285 }
286 }
287
288 fn needs_rendered_counts(&self) -> bool {
291 !self.anchors.is_empty() || self.whitespace.ignore_blank_lines
292 }
293}
294
295impl From<&DiffOptions> for UnifiedDiffOptions<'_> {
299 fn from(options: &DiffOptions) -> Self {
300 Self {
301 context_lines: options.context_lines,
302 inter_hunk_context: options.inter_hunk_context,
303 algorithm: options.algorithm,
304 indent_heuristic: if options.indent_heuristic {
305 IndentHeuristic::Enabled
306 } else {
307 IndentHeuristic::Disabled
308 },
309 extent: if options.function_context {
310 HunkExtent::Function
311 } else {
312 HunkExtent::Context
313 },
314 whitespace: options.whitespace,
315 ..Self::default()
316 }
317 }
318}
319
320#[must_use]
342pub fn unified_diff(old: &str, new: &str, options: &UnifiedDiffOptions<'_>) -> String {
343 let body = hunk_body(old, new, options);
344 if body.is_empty() {
345 return String::new();
346 }
347 let mut out = String::with_capacity(body.len() + 128);
348 if let Some(label) = &options.old_label {
349 push_label_line(&mut out, "--- ", label, options.path_quoting);
350 }
351 if let Some(label) = &options.new_label {
352 push_label_line(&mut out, "+++ ", label, options.path_quoting);
353 }
354 push_hunks_with_funcnames(&mut out, &body, old, options.funcname);
355 if options.no_newline_marker == NoNewlineMarker::Omit {
356 out = out
359 .split_inclusive('\n')
360 .filter(|line| *line != NO_NEWLINE_MARKER)
361 .collect();
362 }
363 out
364}
365
366#[must_use]
380pub fn line_change_counts(old: &str, new: &str, options: &UnifiedDiffOptions<'_>) -> LineStat {
381 if !options.needs_rendered_counts() {
382 let (insertions, deletions) =
383 count_line_changes_with_options(old, new, &options.line_options());
384 return LineStat {
385 insertions,
386 deletions,
387 };
388 }
389 hunk_body(old, new, options)
390 .lines()
391 .fold(LineStat::default(), |mut stat, line| {
392 match line.as_bytes().first() {
393 Some(b'+') => stat.insertions += 1,
394 Some(b'-') => stat.deletions += 1,
395 _ => {}
396 }
397 stat
398 })
399}
400
401fn hunk_body(old: &str, new: &str, options: &UnifiedDiffOptions<'_>) -> String {
403 if options.anchors.is_empty() && options.extent == HunkExtent::Context {
404 return unified_hunk_body_for_diff_options(old, new, &options.line_options());
405 }
406 let before = LineSide::from_text(old);
407 let after = LineSide::from_text(new);
408 let ops = if options.anchors.is_empty() {
409 compacted_line_ops_for_options(old, new, &options.line_options())
410 } else {
411 let anchored: Vec<bool> = after
412 .lines()
413 .map(|line| {
414 options
415 .anchors
416 .iter()
417 .any(|anchor| line.body.starts_with(anchor.as_str()))
418 })
419 .collect();
420 patience_compacted_line_ops(
421 &before,
422 &after,
423 options.indent_heuristic == IndentHeuristic::Enabled,
424 options.whitespace,
425 &anchored,
426 )
427 };
428 let ws = options.whitespace;
429 unified_body_from_ops(
430 &before,
431 &after,
432 &ops,
433 ws,
434 options.emit_options(),
435 options.funcname,
436 ws.ignore_blank_lines.then(|| blank_line_ignorable(ws)),
437 )
438}
439
440fn push_label_line(out: &mut String, lead: &str, label: &DiffLabel<'_>, quoting: PathQuoting) {
441 out.push_str(lead);
442 match *label {
443 DiffLabel::DevNull => out.push_str("/dev/null"),
444 DiffLabel::Verbatim(text) => out.push_str(text),
445 DiffLabel::Path { prefix, path } => {
446 let quote_non_ascii = quoting == PathQuoting::EscapeNonAscii;
447 out.push_str(&format_diff_path_with_prefix(prefix, path, quote_non_ascii));
448 if path.contains(' ') {
449 out.push('\t');
450 }
451 }
452 }
453 out.push('\n');
454}
455
456fn push_hunks_with_funcnames(
458 out: &mut String,
459 body: &str,
460 old: &str,
461 funcname: Option<&FuncnameMatcher>,
462) {
463 let old_lines: Vec<&str> = old.lines().collect();
464 for hunk in imara_unified_hunk_slices(body) {
465 let Some((header, rest)) = hunk.split_once('\n') else {
466 out.push_str(hunk);
467 continue;
468 };
469 out.push_str(header);
470 if let Some(name) = extract_function_context(header, &old_lines, funcname, None) {
471 out.push(' ');
472 out.push_str(&name);
473 }
474 out.push('\n');
475 out.push_str(rest);
476 }
477}
478
479#[cfg(test)]
480mod tests {
481 use super::*;
482
483 #[test]
484 fn default_has_git_defaults_and_no_labels() {
485 let options = UnifiedDiffOptions::default();
486 assert_eq!(options.context_lines, 3);
487 assert_eq!(options.inter_hunk_context, 0);
488 assert_eq!(options.algorithm, DiffAlgorithm::Myers);
489 assert_eq!(options.indent_heuristic, IndentHeuristic::Enabled);
490 assert_eq!(options.extent, HunkExtent::Context);
491 assert!(options.old_label.is_none() && options.new_label.is_none());
492 assert_eq!(options.no_newline_marker, NoNewlineMarker::Emit);
493 assert_eq!(options.path_quoting, PathQuoting::EscapeNonAscii);
494 }
495
496 #[test]
497 fn labels_quote_and_tab_like_git() {
498 let mut out = String::new();
499 let label = DiffLabel::Path {
500 prefix: "a/",
501 path: "my file",
502 };
503 push_label_line(&mut out, "--- ", &label, PathQuoting::EscapeNonAscii);
504 push_label_line(
505 &mut out,
506 "+++ ",
507 &DiffLabel::DevNull,
508 PathQuoting::default(),
509 );
510 push_label_line(
511 &mut out,
512 "+++ ",
513 &DiffLabel::Verbatim("x y"),
514 PathQuoting::default(),
515 );
516 assert_eq!(out, "--- a/my file\t\n+++ /dev/null\n+++ x y\n");
517
518 let mut quoted = String::new();
519 let label = DiffLabel::Path {
520 prefix: "b/",
521 path: "caf\u{e9}",
522 };
523 push_label_line(&mut quoted, "+++ ", &label, PathQuoting::EscapeNonAscii);
524 assert_eq!(quoted, "+++ \"b/caf\\303\\251\"\n");
525 let mut kept = String::new();
526 push_label_line(&mut kept, "+++ ", &label, PathQuoting::KeepNonAscii);
527 assert_eq!(kept, "+++ b/caf\u{e9}\n");
528 }
529
530 #[test]
531 fn omit_marker_drops_no_newline_lines() {
532 let options = UnifiedDiffOptions::new().with_no_newline_marker(NoNewlineMarker::Omit);
533 assert_eq!(unified_diff("a", "b", &options), "@@ -1 +1 @@\n-a\n+b\n");
534 }
535
536 #[test]
537 fn omit_marker_keeps_source_lines_that_read_like_the_marker() {
538 let omit = UnifiedDiffOptions::new().with_no_newline_marker(NoNewlineMarker::Omit);
539 let marker = "\\ No newline at end of file";
540 let cases = [
541 (
542 format!("{marker}\nold\n"),
543 format!("{marker}\nnew\n"),
544 format!("@@ -1,2 +1,2 @@\n {marker}\n-old\n+new\n"),
545 ),
546 (
547 "a\n".to_owned(),
548 format!("a\n{marker}\n"),
549 format!("@@ -1 +1,2 @@\n a\n+{marker}\n"),
550 ),
551 (
552 format!("a\n{marker}\n"),
553 "a\n".to_owned(),
554 format!("@@ -1,2 +1 @@\n a\n-{marker}\n"),
555 ),
556 (
557 format!("{marker}\nx"),
558 format!("{marker}\ny"),
559 format!("@@ -1,2 +1,2 @@\n {marker}\n-x\n+y\n"),
560 ),
561 ];
562 for (old, new, expected) in cases {
563 assert_eq!(
564 unified_diff(&old, &new, &omit),
565 expected,
566 "{old:?} -> {new:?}"
567 );
568 }
569 }
570
571 #[test]
572 fn equal_sides_render_nothing_even_with_labels() {
573 let options = UnifiedDiffOptions::new().with_paths("f", "f");
574 assert_eq!(unified_diff("same\n", "same\n", &options), "");
575 }
576
577 #[test]
578 fn from_diff_options_carries_line_settings() {
579 let diff = DiffOptions::default()
580 .with_context_lines(1)
581 .with_inter_hunk_context(4)
582 .with_algorithm(DiffAlgorithm::Patience)
583 .with_indent_heuristic(false)
584 .with_whitespace(WhitespaceMode::ignore_all_space());
585 let options = UnifiedDiffOptions::from(&diff);
586 assert_eq!(options.context_lines, 1);
587 assert_eq!(options.inter_hunk_context, 4);
588 assert_eq!(options.algorithm, DiffAlgorithm::Patience);
589 assert_eq!(options.indent_heuristic, IndentHeuristic::Disabled);
590 assert_eq!(options.whitespace, WhitespaceMode::ignore_all_space());
591 assert!(options.old_label.is_none());
592 }
593
594 #[test]
595 fn anchored_counts_follow_rendered_patch() {
596 let old = "a\nb\nc\n";
597 let new = "c\na\nb\n";
598 let anchored = UnifiedDiffOptions::new().with_anchors(["c"]);
599 let stat = line_change_counts(old, new, &anchored);
600 assert_eq!((stat.insertions, stat.deletions), (2, 2));
601 assert_eq!(
602 unified_diff(old, new, &anchored),
603 "@@ -1,3 +1,3 @@\n-a\n-b\n c\n+a\n+b\n"
604 );
605 let plain = line_change_counts(old, new, &UnifiedDiffOptions::new());
606 assert_eq!((plain.insertions, plain.deletions), (1, 1));
607 }
608}