Debian Codegraph @

src/handlers/diff_header.rs

raw symbols SCIP
1 use std::borrow::Cow;
2 use std::path::Path;
3
4 use unicode_segmentation::UnicodeSegmentation;
5
6 use super::draw;
7 use crate::config::Config;
8 use crate::delta::{DiffType, Source, State, StateMachine};
9 use crate::paint::Painter;
10 use crate::{features, utils};
11
12 // https://git-scm.com/docs/git-config#Documentation/git-config.txt-diffmnemonicPrefix
13 const DIFF_PREFIXES: [&str; 6] = ["a/", "b/", "c/", "i/", "o/", "w/"];
14
15 #[derive(Debug, PartialEq, Eq)]
16 pub enum FileEvent {
17 Added,
18 Change,
19 Copy,
20 Rename,
21 Removed,
22 NoEvent,
23 }
24
25 impl StateMachine<'_> {
26 /// Check for the old mode|new mode lines and cache their info for later use.
27 pub fn handle_diff_header_mode_line(&mut self) -> std::io::Result<bool> {
28 let mut handled_line = false;
29 if let Some(line_suf) = self.line.strip_prefix("old mode ") {
30 self.state = State::DiffHeader(DiffType::Unified);
31 if self.should_handle() && !self.config.color_only {
32 self.mode_info = line_suf.to_string();
33 handled_line = true;
34 }
35 } else if let Some(line_suf) = self.line.strip_prefix("new mode ") {
36 self.state = State::DiffHeader(DiffType::Unified);
37 if self.should_handle() && !self.config.color_only && !self.mode_info.is_empty() {
38 self.mode_info = match (self.mode_info.as_str(), line_suf) {
39 // 100755 for executable and 100644 for non-executable are the only file modes Git records.
40 // https://medium.com/@tahteche/how-git-treats-changes-in-file-permissions-f71874ca239d
41 ("100644", "100755") => "mode +x".to_string(),
42 ("100755", "100644") => "mode -x".to_string(),
43 _ => format!(
44 "mode {} {} {}",
45 self.mode_info, self.config.right_arrow, line_suf
46 ),
47 };
48 handled_line = true;
49 }
50 }
51 Ok(handled_line)
52 }
53
54 fn should_write_generic_diff_header_header_line(&mut self) -> std::io::Result<bool> {
55 // In color_only mode, raw_line's structure shouldn't be changed.
56 // So it needs to avoid fn _handle_diff_header_header_line
57 // (it connects the plus_file and minus_file),
58 // and to call fn handle_generic_diff_header_header_line directly.
59 if self.config.color_only {
60 write_generic_diff_header_header_line(
61 &self.line,
62 &self.raw_line,
63 &mut self.painter,
64 &mut self.mode_info,
65 self.config,
66 )?;
67 Ok(true)
68 } else {
69 Ok(false)
70 }
71 }
72
73 #[inline]
74 fn test_diff_header_minus_line(&self) -> bool {
75 (matches!(self.state, State::DiffHeader(_)) || self.source == Source::DiffUnified)
76 && ((self.line.starts_with("--- ") && self.minus_line_counter.three_dashes_expected())
77 || self.line.starts_with("rename from ")
78 || self.line.starts_with("copy from "))
79 }
80
81 /// Check for and handle the "--- filename ..." line.
82 pub fn handle_diff_header_minus_line(&mut self) -> std::io::Result<bool> {
83 if !self.test_diff_header_minus_line() {
84 return Ok(false);
85 }
86
87 let (mut path_or_mode, file_event) =
88 parse_diff_header_line(&self.line, self.source == Source::GitDiff);
89
90 utils::path::relativize_path_maybe(&mut path_or_mode, self.config);
91 self.minus_file = path_or_mode;
92 self.minus_file_event = file_event;
93
94 if self.source == Source::DiffUnified {
95 self.state = State::DiffHeader(DiffType::Unified);
96 self.painter
97 .set_syntax(get_filename_from_marker_line(&self.line));
98 } else {
99 self.painter
100 .set_syntax(get_filename_from_diff_header_line_file_path(
101 &self.minus_file,
102 ));
103 }
104
105 self.painter.paint_buffered_minus_and_plus_lines();
106 self.should_write_generic_diff_header_header_line()
107 }
108
109 #[inline]
110 fn test_diff_header_plus_line(&self) -> bool {
111 (matches!(self.state, State::DiffHeader(_)) || self.source == Source::DiffUnified)
112 && (self.line.starts_with("+++ ")
113 || self.line.starts_with("rename to ")
114 || self.line.starts_with("copy to "))
115 }
116
117 /// Check for and handle the "+++ filename ..." line.
118 pub fn handle_diff_header_plus_line(&mut self) -> std::io::Result<bool> {
119 if !self.test_diff_header_plus_line() {
120 return Ok(false);
121 }
122 let mut handled_line = false;
123 let (mut path_or_mode, file_event) =
124 parse_diff_header_line(&self.line, self.source == Source::GitDiff);
125
126 utils::path::relativize_path_maybe(&mut path_or_mode, self.config);
127 self.plus_file = path_or_mode;
128 self.plus_file_event = file_event;
129 self.painter
130 .set_syntax(get_filename_from_diff_header_line_file_path(
131 &self.plus_file,
132 ));
133 self.current_file_pair = Some((self.minus_file.clone(), self.plus_file.clone()));
134
135 self.painter.paint_buffered_minus_and_plus_lines();
136 if self.should_write_generic_diff_header_header_line()? {
137 handled_line = true;
138 } else if self.should_handle()
139 && self.handled_diff_header_header_line_file_pair != self.current_file_pair
140 {
141 self.painter.emit()?;
142 self._handle_diff_header_header_line(self.source == Source::DiffUnified)?;
143 self.handled_diff_header_header_line_file_pair
144 .clone_from(&self.current_file_pair);
145 }
146 Ok(handled_line)
147 }
148
149 #[inline]
150 fn test_diff_header_file_operation_line(&self) -> bool {
151 (matches!(self.state, State::DiffHeader(_)) || self.source == Source::DiffUnified)
152 && (self.line.starts_with("deleted file mode ")
153 || self.line.starts_with("new file mode "))
154 }
155
156 /// Check for and handle the "deleted file ..." line.
157 pub fn handle_diff_header_file_operation_line(&mut self) -> std::io::Result<bool> {
158 if !self.test_diff_header_file_operation_line() {
159 return Ok(false);
160 }
161 let mut handled_line = false;
162 let (_mode_info, file_event) =
163 parse_diff_header_line(&self.line, self.source == Source::GitDiff);
164 let name = get_repeated_file_path_from_diff_line(&self.diff_line).unwrap_or_default();
165 match file_event {
166 FileEvent::Removed => {
167 self.minus_file = name;
168 self.plus_file = "/dev/null".into();
169 self.minus_file_event = FileEvent::Change;
170 self.plus_file_event = FileEvent::Change;
171 self.current_file_pair = Some((self.minus_file.clone(), self.plus_file.clone()));
172 }
173 FileEvent::Added => {
174 self.minus_file = "/dev/null".into();
175 self.plus_file = name;
176 self.minus_file_event = FileEvent::Change;
177 self.plus_file_event = FileEvent::Change;
178 self.current_file_pair = Some((self.minus_file.clone(), self.plus_file.clone()));
179 }
180 _ => (),
181 }
182
183 if self.should_write_generic_diff_header_header_line()?
184 || (self.should_handle()
185 && self.handled_diff_header_header_line_file_pair != self.current_file_pair)
186 {
187 handled_line = true;
188 }
189 Ok(handled_line)
190 }
191
192 /// Construct file change line from minus and plus file and write with DiffHeader styling.
193 fn _handle_diff_header_header_line(&mut self, comparing: bool) -> std::io::Result<()> {
194 let line = get_file_change_description_from_file_paths(
195 &self.minus_file,
196 &self.plus_file,
197 comparing,
198 &self.minus_file_event,
199 &self.plus_file_event,
200 self.config,
201 );
202 // FIXME: no support for 'raw'
203 write_generic_diff_header_header_line(
204 &line,
205 &line,
206 &mut self.painter,
207 &mut self.mode_info,
208 self.config,
209 )
210 }
211
212 #[inline]
213 fn test_pending_line_with_diff_name(&self) -> bool {
214 matches!(self.state, State::DiffHeader(_)) || self.source == Source::DiffUnified
215 }
216
217 pub fn handle_pending_line_with_diff_name(&mut self) -> std::io::Result<()> {
218 if !self.test_pending_line_with_diff_name() {
219 return Ok(());
220 }
221
222 if !self.mode_info.is_empty() {
223 let format_label = |label: &str| {
224 if !label.is_empty() {
225 format!("{label} ")
226 } else {
227 "".to_string()
228 }
229 };
230 let format_file = |file| match (
231 self.config.hyperlinks,
232 utils::path::absolute_path(file, self.config),
233 ) {
234 (true, Some(absolute_path)) => features::hyperlinks::format_osc8_file_hyperlink(
235 absolute_path,
236 None,
237 file,
238 self.config,
239 ),
240 _ => Cow::from(file),
241 };
242 let label = format_label(&self.config.file_modified_label);
243 let name = get_repeated_file_path_from_diff_line(&self.diff_line).unwrap_or_default();
244 let line = format!("{}{}", label, format_file(&name));
245 write_generic_diff_header_header_line(
246 &line,
247 &line,
248 &mut self.painter,
249 &mut self.mode_info,
250 self.config,
251 )
252 } else if !self.config.color_only
253 && self.should_handle()
254 && self.handled_diff_header_header_line_file_pair != self.current_file_pair
255 {
256 self._handle_diff_header_header_line(self.source == Source::DiffUnified)?;
257 self.handled_diff_header_header_line_file_pair
258 .clone_from(&self.current_file_pair);
259 Ok(())
260 } else {
261 Ok(())
262 }
263 }
264 }
265
266 /// Write `line` with DiffHeader styling.
267 pub fn write_generic_diff_header_header_line(
268 line: &str,
269 raw_line: &str,
270 painter: &mut Painter,
271 mode_info: &mut String,
272 config: &Config,
273 ) -> std::io::Result<()> {
274 // If file_style is "omit", we'll skip the process and print nothing.
275 // However in the case of color_only mode,
276 // we won't skip because we can't change raw_line structure.
277 if config.file_style.is_omitted && !config.color_only {
278 return Ok(());
279 }
280 let (mut draw_fn, pad, decoration_ansi_term_style) =
281 draw::get_draw_function(config.file_style.decoration_style);
282 if !config.color_only {
283 // Maintain 1-1 correspondence between input and output lines.
284 writeln!(painter.writer)?;
285 }
286 draw_fn(
287 painter.writer,
288 &format!("{}{}", line, if pad { " " } else { "" }),
289 &format!("{}{}", raw_line, if pad { " " } else { "" }),
290 mode_info,
291 &config.decorations_width,
292 config.file_style,
293 decoration_ansi_term_style,
294 )?;
295 if !mode_info.is_empty() {
296 mode_info.truncate(0);
297 }
298 Ok(())
299 }
300
301 #[allow(clippy::tabs_in_doc_comments)]
302 /// Given input like
303 /// "--- a/zero/one.rs 2019-11-20 06:16:08.000000000 +0100"
304 /// Return "one.rs"
305 fn get_filename_from_marker_line(line: &str) -> Option<&str> {
306 line.split('\t')
307 .next()
308 .and_then(|column| column.split(' ').nth(1))
309 .and_then(get_filename_from_diff_header_line_file_path)
310 }
311
312 fn get_filename_from_diff_header_line_file_path(path: &str) -> Option<&str> {
313 Path::new(path).file_name().and_then(|filename| {
314 if path != "/dev/null" {
315 filename.to_str()
316 } else {
317 None
318 }
319 })
320 }
321
322 fn parse_diff_header_line(line: &str, git_diff_name: bool) -> (String, FileEvent) {
323 match line {
324 line if line.starts_with("--- ") || line.starts_with("+++ ") => {
325 let offset = 4;
326 let file = _parse_file_path(&line[offset..], git_diff_name);
327 (file, FileEvent::Change)
328 }
329 line if line.starts_with("rename from ") => {
330 (line[12..].to_string(), FileEvent::Rename) // "rename from ".len()
331 }
332 line if line.starts_with("rename to ") => {
333 (line[10..].to_string(), FileEvent::Rename) // "rename to ".len()
334 }
335 line if line.starts_with("copy from ") => {
336 (line[10..].to_string(), FileEvent::Copy) // "copy from ".len()
337 }
338 line if line.starts_with("copy to ") => {
339 (line[8..].to_string(), FileEvent::Copy) // "copy to ".len()
340 }
341 line if line.starts_with("new file mode ") => {
342 (line[14..].to_string(), FileEvent::Added) // "new file mode ".len()
343 }
344 line if line.starts_with("deleted file mode ") => {
345 (line[18..].to_string(), FileEvent::Removed) // "deleted file mode ".len()
346 }
347 _ => ("".to_string(), FileEvent::NoEvent),
348 }
349 }
350
351 /// Given input like "diff --git a/src/my file.rs b/src/my file.rs"
352 /// return Some("src/my file.rs")
353 pub fn get_repeated_file_path_from_diff_line(line: &str) -> Option<String> {
354 if let Some(line) = line.strip_prefix("diff --git ") {
355 let line: Vec<&str> = line.graphemes(true).collect();
356 let midpoint = line.len() / 2;
357 if line[midpoint] == " " {
358 let first_path = _parse_file_path(&line[..midpoint].join(""), true);
359 let second_path = _parse_file_path(&line[midpoint + 1..].join(""), true);
360 if first_path == second_path {
361 return Some(first_path);
362 }
363 }
364 }
365 None
366 }
367
368 fn remove_surrounding_quotes(path: &str) -> &str {
369 if path.starts_with('"') && path.ends_with('"') {
370 // Indexing into the UTF-8 string is safe because of the previous test
371 &path[1..path.len() - 1]
372 } else {
373 path
374 }
375 }
376
377 fn _parse_file_path(path: &str, git_diff_name: bool) -> String {
378 // When git config 'core.quotepath = true' (the default), and `path` contains
379 // non-ASCII characters, a backslash, or a quote; then it is quoted, so remove
380 // these quotes. Characters may also be escaped, but these are left as-is.
381 let path = remove_surrounding_quotes(path);
382 // It appears that, if the file name contains a space, git appends a tab
383 // character in the diff metadata lines, e.g.
384 // $ git diff --no-index "a b" "c d" | cat -A
385 // diff·--git·a/a·b·b/c·d␊
386 // index·d00491f..0cfbf08·100644␊
387 // ---·a/a·b├──┤␊
388 // +++·b/c·d├──┤␊
389 match path.strip_suffix('\t').unwrap_or(path) {
390 "/dev/null" => "/dev/null",
391 path if git_diff_name && DIFF_PREFIXES.iter().any(|s| path.starts_with(s)) => &path[2..],
392 path if git_diff_name => path,
393 path => path.split('\t').next().unwrap_or(""),
394 }
395 .to_string()
396 }
397
398 pub fn get_file_change_description_from_file_paths(
399 minus_file: &str,
400 plus_file: &str,
401 comparing: bool,
402 minus_file_event: &FileEvent,
403 plus_file_event: &FileEvent,
404 config: &Config,
405 ) -> String {
406 let format_label = |label: &str| {
407 if !label.is_empty() {
408 format!("{label} ")
409 } else {
410 "".to_string()
411 }
412 };
413 if comparing {
414 format!(
415 "{}{} {} {}",
416 format_label(&config.file_modified_label),
417 minus_file,
418 config.right_arrow,
419 plus_file
420 )
421 } else {
422 let format_file = |file| {
423 let formatted_file = if let Some(regex_replacement) = &config.file_regex_replacement {
424 regex_replacement.execute(file)
425 } else {
426 Cow::from(file)
427 };
428 match (config.hyperlinks, utils::path::absolute_path(file, config)) {
429 (true, Some(absolute_path)) => features::hyperlinks::format_osc8_file_hyperlink(
430 absolute_path,
431 None,
432 &formatted_file,
433 config,
434 ),
435 _ => formatted_file,
436 }
437 };
438 match (minus_file, plus_file, minus_file_event, plus_file_event) {
439 (minus_file, plus_file, _, _) if minus_file == plus_file => format!(
440 "{}{}",
441 format_label(&config.file_modified_label),
442 format_file(minus_file)
443 ),
444 (minus_file, "/dev/null", _, _) => format!(
445 "{}{}",
446 format_label(&config.file_removed_label),
447 format_file(minus_file)
448 ),
449 ("/dev/null", plus_file, _, _) => format!(
450 "{}{}",
451 format_label(&config.file_added_label),
452 format_file(plus_file)
453 ),
454 // minus_file_event == plus_file_event
455 (minus_file, plus_file, file_event, _) => format!(
456 "{}{} {} {}",
457 format_label(match file_event {
458 FileEvent::Rename => &config.file_renamed_label,
459 FileEvent::Copy => &config.file_copied_label,
460 _ => &config.file_modified_label,
461 }),
462 format_file(minus_file),
463 config.right_arrow,
464 format_file(plus_file)
465 ),
466 }
467 }
468 }
469
470 #[cfg(test)]
471 mod tests {
472 use super::*;
473 use crate::tests::integration_test_utils::{make_config_from_args, DeltaTest};
474 use insta::assert_snapshot;
475
476 #[test]
477 fn test_get_filename_from_marker_line() {
478 assert_eq!(
479 get_filename_from_marker_line("--- src/one.rs 2019-11-20 06:47:56.000000000 +0100"),
480 Some("one.rs")
481 );
482 }
483
484 #[test]
485 fn test_get_filename_from_diff_header_line() {
486 assert_eq!(
487 get_filename_from_diff_header_line_file_path("a/src/parse.rs"),
488 Some("parse.rs")
489 );
490 assert_eq!(
491 get_filename_from_diff_header_line_file_path("b/src/pa rse.rs"),
492 Some("pa rse.rs")
493 );
494 assert_eq!(
495 get_filename_from_diff_header_line_file_path("src/pa rse.rs"),
496 Some("pa rse.rs")
497 );
498 assert_eq!(
499 get_filename_from_diff_header_line_file_path("wat hello.rs"),
500 Some("wat hello.rs")
501 );
502 assert_eq!(
503 get_filename_from_diff_header_line_file_path("/dev/null"),
504 None
505 );
506 assert_eq!(
507 get_filename_from_diff_header_line_file_path("Dockerfile"),
508 Some("Dockerfile")
509 );
510 assert_eq!(
511 get_filename_from_diff_header_line_file_path("Makefile"),
512 Some("Makefile")
513 );
514 assert_eq!(
515 get_filename_from_diff_header_line_file_path("a/src/Makefile"),
516 Some("Makefile")
517 );
518 assert_eq!(
519 get_filename_from_diff_header_line_file_path("src/Makefile"),
520 Some("Makefile")
521 );
522 }
523
524 // We should only strip the prefixes if they are "a/" or "b/". This will be correct except for
525 // the case of a user with `diff.noprefix = true` who has directories named "a" or "b", which
526 // is an irresolvable ambiguity. Ideally one would only strip the prefixes if we have confirmed
527 // that we are looking at something like
528 //
529 // --- a/src/parse.rs
530 // +++ b/src/parse.rs
531 //
532 // as opposed to something like
533 //
534 // --- a/src/parse.rs
535 // +++ sibling_of_a/src/parse.rs
536 //
537 // but we don't attempt that currently.
538 #[test]
539 fn test_get_file_path_from_git_diff_header_line() {
540 assert_eq!(
541 parse_diff_header_line("--- /dev/null", true),
542 ("/dev/null".to_string(), FileEvent::Change)
543 );
544 for prefix in &DIFF_PREFIXES {
545 assert_eq!(
546 parse_diff_header_line(&format!("--- {prefix}src/delta.rs"), true),
547 ("src/delta.rs".to_string(), FileEvent::Change)
548 );
549 }
550 assert_eq!(
551 parse_diff_header_line("--- src/delta.rs", true),
552 ("src/delta.rs".to_string(), FileEvent::Change)
553 );
554 assert_eq!(
555 parse_diff_header_line("+++ src/delta.rs", true),
556 ("src/delta.rs".to_string(), FileEvent::Change)
557 );
558
559 assert_eq!(
560 parse_diff_header_line("+++ \".\\delta.rs\"", true),
561 (".\\delta.rs".to_string(), FileEvent::Change)
562 );
563 }
564
565 #[test]
566 fn test_get_file_path_from_git_diff_header_line_containing_spaces() {
567 assert_eq!(
568 parse_diff_header_line("+++ a/my src/delta.rs", true),
569 ("my src/delta.rs".to_string(), FileEvent::Change)
570 );
571 assert_eq!(
572 parse_diff_header_line("+++ my src/delta.rs", true),
573 ("my src/delta.rs".to_string(), FileEvent::Change)
574 );
575 assert_eq!(
576 parse_diff_header_line("+++ a/src/my delta.rs", true),
577 ("src/my delta.rs".to_string(), FileEvent::Change)
578 );
579 assert_eq!(
580 parse_diff_header_line("+++ a/my src/my delta.rs", true),
581 ("my src/my delta.rs".to_string(), FileEvent::Change)
582 );
583 assert_eq!(
584 parse_diff_header_line("+++ b/my src/my enough/my delta.rs", true),
585 (
586 "my src/my enough/my delta.rs".to_string(),
587 FileEvent::Change
588 )
589 );
590 }
591
592 #[test]
593 fn test_get_file_path_from_git_diff_header_line_rename() {
594 assert_eq!(
595 parse_diff_header_line("rename from nospace/file2.el", true),
596 ("nospace/file2.el".to_string(), FileEvent::Rename)
597 );
598 }
599
600 #[test]
601 fn test_get_file_path_from_git_diff_header_line_rename_containing_spaces() {
602 assert_eq!(
603 parse_diff_header_line("rename from with space/file1.el", true),
604 ("with space/file1.el".to_string(), FileEvent::Rename)
605 );
606 }
607
608 #[test]
609 fn test_parse_diff_header_line() {
610 assert_eq!(
611 parse_diff_header_line("--- src/delta.rs", false),
612 ("src/delta.rs".to_string(), FileEvent::Change)
613 );
614 assert_eq!(
615 parse_diff_header_line("+++ src/delta.rs", false),
616 ("src/delta.rs".to_string(), FileEvent::Change)
617 );
618 }
619
620 #[test]
621 fn test_get_repeated_file_path_from_diff_line() {
622 assert_eq!(
623 get_repeated_file_path_from_diff_line("diff --git a/src/main.rs b/src/main.rs"),
624 Some("src/main.rs".to_string())
625 );
626 assert_eq!(
627 get_repeated_file_path_from_diff_line("diff --git a/a b/a"),
628 Some("a".to_string())
629 );
630 assert_eq!(
631 get_repeated_file_path_from_diff_line("diff --git a/a b b/a b"),
632 Some("a b".to_string())
633 );
634 assert_eq!(
635 get_repeated_file_path_from_diff_line("diff --git a/a b/aa"),
636 None
637 );
638 assert_eq!(
639 get_repeated_file_path_from_diff_line(
640 "diff --git a/.config/Code - Insiders/User/settings.json b/.config/Code - Insiders/User/settings.json"),
641 Some(".config/Code - Insiders/User/settings.json".to_string())
642 );
643 assert_eq!(
644 get_repeated_file_path_from_diff_line(r#"diff --git "a/quoted" "b/quoted""#),
645 Some("quoted".to_string())
646 );
647 }
648
649 #[test]
650 fn test_diff_header_with_mode_change_in_last_hunk() {
651 let input = "\
652 diff --git a/a.txt b/a.txt
653 index 44371ed..e69de29 100644
654 --- a/a.txt
655 +++ b/a.txt
656 @@ -1 +0,0 @@
657 -A-content
658 diff --git a/b.txt b/b.txt
659 old mode 100644
660 new mode 100755
661 ";
662
663 let result = DeltaTest::with_args(&[]).with_input(input);
664
665 assert_snapshot!(result.output, @r"
666 a.txt
667 ───────────────────────────────────────────
668
669 ───┐
670 0: │
671 ───┘
672 A-content
673
674 b.txt (mode +x)
675 ───────────────────────────────────────────
676 ");
677 }
678
679 #[test]
680 fn test_diff_header_with_2x_mode_change() {
681 let input = "\
682 diff --git a/a.txt b/a.txt
683 index 44371ed..e69de29 100644
684 --- a/a.txt
685 +++ b/a.txt
686 @@ -1 +0,0 @@
687 -A-content
688 diff --git a/b.txt b/b.txt
689 old mode 100644
690 new mode 100755
691 --- a/b.txt
692 +++ b/b.txt
693 diff --git a/c.txt b/c.txt
694 old mode 100644
695 new mode 100755
696 ";
697
698 let result = DeltaTest::with_args(&[]).with_input(input);
699
700 assert_snapshot!(result.output, @r"
701 a.txt
702 ───────────────────────────────────────────
703
704 ───┐
705 0: │
706 ───┘
707 A-content
708
709 b.txt (mode +x)
710 ───────────────────────────────────────────
711
712 c.txt (mode +x)
713 ───────────────────────────────────────────
714 ");
715 }
716
717 pub const BIN_AND_TXT_FILE_ADDED: &str = "\
718 diff --git a/BIN b/BIN
719 new file mode 100644
720 index 0000000..a5d0c46
721 Binary files /dev/null and b/BIN differ
722 diff --git a/TXT b/TXT
723 new file mode 100644
724 index 0000000..323fae0
725 --- /dev/null
726 +++ b/TXT
727 @@ -0,0 +1 @@
728 +plain text";
729
730 #[test]
731 fn test_diff_header_relative_paths() {
732 // rustfmt ignores the assert macro arguments, so do the setup outside
733 let mut cfg = make_config_from_args(&["--relative-paths", "-s"]);
734 cfg.cwd_relative_to_repo_root = Some("src/utils/".into());
735 let result = DeltaTest::with_config(&cfg)
736 .with_input(BIN_AND_TXT_FILE_ADDED)
737 .output;
738 // convert windows '..\' to unix '../' paths
739 insta::with_settings!({filters => vec![(r"\.\.\\", "../")]}, {
740 assert_snapshot!(result, @r###"
741
742 added: ../../BIN (binary file)
743 ───────────────────────────────────────────
744
745 added: ../../TXT
746 ───────────────────────────────────────────
747
748 ───┐
749 1: │
750 ───┘
751 │ │ │ 1 │plain text
752 "###)
753 });
754 }
755
756 pub const DIFF_AMBIGUOUS_HEADER_3X_MINUS: &str = r#"--- a.lua
757 +++ b.lua
758 @@ -1,5 +1,4 @@
759 #!/usr/bin/env lua
760
761 print("Hello")
762 --- World?
763 print("..")
764 "#;
765 pub const DIFF_AMBIGUOUS_HEADER_3X_MINUS_LAST_LINE: &str = r#"--- c.lua
766 +++ d.lua
767 @@ -1,4 +1,3 @@
768 #!/usr/bin/env lua
769
770 print("Hello")
771 --- World?
772 "#;
773
774 pub const DIFF_AMBIGUOUS_HEADER_MULTIPLE_HUNKS: &str = r#"--- e.lua 2024-08-04 20:50:27.257726606 +0200
775 +++ f.lua 2024-08-04 20:50:35.345795405 +0200
776 @@ -3,3 +3,2 @@
777 print("Hello")
778 --- World?
779 print("")
780 @@ -7,2 +6,3 @@
781 print("")
782 +print("World")
783 print("")
784 @@ -10,2 +10 @@
785 print("")
786 --- End
787 "#;
788
789 #[test]
790 fn test_diff_header_ambiguous_3x_minus() {
791 // check ansi output to ensure output is highlighted
792 let result = DeltaTest::with_args(&[])
793 .explain_ansi()
794 .with_input(DIFF_AMBIGUOUS_HEADER_3X_MINUS);
795
796 assert_snapshot!(result.output, @r###"
797 (normal)
798 (blue)a.lua ⟶ b.lua(normal)
799 (blue)───────────────────────────────────────────(normal)
800
801 (blue)───(blue)┐(normal)
802 (blue)1(normal): (blue)│(normal)
803 (blue)───(blue)┘(normal)
804 (203)#(231)!(203)/(231)usr(203)/(231)bin(203)/(231)env lua(normal)
805
806 (81)print(231)((186)"Hello"(231))(normal)
807 (normal 52)-- World?(normal)
808 (81)print(231)((186)".."(231))(normal)
809
810 "###);
811 }
812
813 #[test]
814 fn test_diff_header_ambiguous_3x_minus_concatenated() {
815 let result = DeltaTest::with_args(&[])
816 .explain_ansi()
817 .with_input(&format!(
818 "{}{}{}",
819 DIFF_AMBIGUOUS_HEADER_MULTIPLE_HUNKS,
820 DIFF_AMBIGUOUS_HEADER_3X_MINUS,
821 DIFF_AMBIGUOUS_HEADER_3X_MINUS_LAST_LINE
822 ));
823
824 assert_snapshot!(result.output, @r###"
825 (normal)
826 (blue)e.lua ⟶ f.lua(normal)
827 (blue)───────────────────────────────────────────(normal)
828
829 (blue)───(blue)┐(normal)
830 (blue)3(normal): (blue)│(normal)
831 (blue)───(blue)┘(normal)
832 (81)print(231)((186)"Hello"(231))(normal)
833 (normal 52)-- World?(normal)
834 (81)print(231)((186)""(231))(normal)
835
836 (blue)───(blue)┐(normal)
837 (blue)6(normal): (blue)│(normal)
838 (blue)───(blue)┘(normal)
839 (81)print(231)((186)""(231))(normal)
840 (81 22)print(231)((186)"World"(231))(normal)
841 (81)print(231)((186)""(231))(normal)
842
843 (blue)────(blue)┐(normal)
844 (blue)10(normal): (blue)│(normal)
845 (blue)────(blue)┘(normal)
846 (81)print(231)((186)""(231))(normal)
847 (normal 52)-- End(normal)
848
849 (blue)a.lua ⟶ b.lua(normal)
850 (blue)───────────────────────────────────────────(normal)
851
852 (blue)───(blue)┐(normal)
853 (blue)1(normal): (blue)│(normal)
854 (blue)───(blue)┘(normal)
855 (203)#(231)!(203)/(231)usr(203)/(231)bin(203)/(231)env lua(normal)
856
857 (81)print(231)((186)"Hello"(231))(normal)
858 (normal 52)-- World?(normal)
859 (81)print(231)((186)".."(231))(normal)
860
861 (blue)c.lua ⟶ d.lua(normal)
862 (blue)───────────────────────────────────────────(normal)
863
864 (blue)───(blue)┐(normal)
865 (blue)1(normal): (blue)│(normal)
866 (blue)───(blue)┘(normal)
867 (203)#(231)!(203)/(231)usr(203)/(231)bin(203)/(231)env lua(normal)
868
869 (81)print(231)((186)"Hello"(231))(normal)
870 (normal 52)-- World?(normal)
871 "###);
872 }
873
874 #[test]
875 fn test_diff_header_ambiguous_3x_minus_extra_and_concatenated() {
876 let result = DeltaTest::with_args(&[])
877 .explain_ansi()
878 .with_input(&format!(
879 "extra 1\n\n{}\nextra 2\n{}\nextra 3\n{}",
880 DIFF_AMBIGUOUS_HEADER_MULTIPLE_HUNKS,
881 DIFF_AMBIGUOUS_HEADER_3X_MINUS,
882 DIFF_AMBIGUOUS_HEADER_3X_MINUS_LAST_LINE
883 ));
884
885 assert_snapshot!(result.output, @r###"
886 (normal)extra 1
887
888
889 (blue)e.lua ⟶ f.lua(normal)
890 (blue)───────────────────────────────────────────(normal)
891
892 (blue)───(blue)┐(normal)
893 (blue)3(normal): (blue)│(normal)
894 (blue)───(blue)┘(normal)
895 (81)print(231)((186)"Hello"(231))(normal)
896 (normal 52)-- World?(normal)
897 (81)print(231)((186)""(231))(normal)
898
899 (blue)───(blue)┐(normal)
900 (blue)6(normal): (blue)│(normal)
901 (blue)───(blue)┘(normal)
902 (81)print(231)((186)""(231))(normal)
903 (81 22)print(231)((186)"World"(231))(normal)
904 (81)print(231)((186)""(231))(normal)
905
906 (blue)────(blue)┐(normal)
907 (blue)10(normal): (blue)│(normal)
908 (blue)────(blue)┘(normal)
909 (81)print(231)((186)""(231))(normal)
910 (normal 52)-- End(normal)
911
912 extra 2
913
914 (blue)a.lua ⟶ b.lua(normal)
915 (blue)───────────────────────────────────────────(normal)
916
917 (blue)───(blue)┐(normal)
918 (blue)1(normal): (blue)│(normal)
919 (blue)───(blue)┘(normal)
920 (203)#(231)!(203)/(231)usr(203)/(231)bin(203)/(231)env lua(normal)
921
922 (81)print(231)((186)"Hello"(231))(normal)
923 (normal 52)-- World?(normal)
924 (81)print(231)((186)".."(231))(normal)
925
926 extra 3
927
928 (blue)c.lua ⟶ d.lua(normal)
929 (blue)───────────────────────────────────────────(normal)
930
931 (blue)───(blue)┐(normal)
932 (blue)1(normal): (blue)│(normal)
933 (blue)───(blue)┘(normal)
934 (203)#(231)!(203)/(231)usr(203)/(231)bin(203)/(231)env lua(normal)
935
936 (81)print(231)((186)"Hello"(231))(normal)
937 (normal 52)-- World?(normal)
938 "###);
939 }
940 }