use std::borrow::Cow;
use std::io::Write;
use std::path::Path;
use unicode_segmentation::UnicodeSegmentation;
use super::draw;
use crate::config::Config;
use crate::delta::{DiffType, Source, State, StateMachine};
use crate::{features, utils};
const DIFF_PREFIXES: [&str; 6] = ["a/", "b/", "c/", "i/", "o/", "w/"];
#[derive(Debug, PartialEq, Eq)]
pub enum FileEvent {
Added,
Change,
Copy,
Rename,
Removed,
NoEvent,
}
impl StateMachine<'_> {
pub fn handle_diff_header_mode_line(&mut self) -> std::io::Result<bool> {
let mut handled_line = false;
if let Some(line_suf) = self.line.strip_prefix("old mode ") {
self.state = State::DiffHeader(DiffType::Unified);
if self.should_handle() && !self.config.color_only {
self.mode_info = line_suf.to_string();
handled_line = true;
}
} else if let Some(line_suf) = self.line.strip_prefix("new mode ") {
self.state = State::DiffHeader(DiffType::Unified);
if self.should_handle() && !self.config.color_only && !self.mode_info.is_empty() {
self.mode_info = match (self.mode_info.as_str(), line_suf) {
("100644", "100755") => "mode +x".to_string(),
("100755", "100644") => "mode -x".to_string(),
_ => format!(
"mode {} {} {}",
self.mode_info, self.config.right_arrow, line_suf
),
};
handled_line = true;
}
}
Ok(handled_line)
}
fn should_write_generic_diff_header_header_line(&mut self) -> std::io::Result<bool> {
if self.config.color_only {
let mut row = Vec::new();
write_generic_diff_header_header_line(
&self.line,
&self.raw_line,
&mut row,
&mut self.mode_info,
self.config,
"",
)?;
self.write_color_only_header_row(&row)?;
Ok(true)
} else {
Ok(false)
}
}
#[inline]
fn test_diff_header_minus_line(&self) -> bool {
(matches!(self.state, State::DiffHeader(_)) || self.source == Source::DiffUnified)
&& ((self.line.starts_with("--- ") && self.minus_line_counter.three_dashes_expected())
|| self.line.starts_with("rename from ")
|| self.line.starts_with("copy from "))
}
pub fn handle_diff_header_minus_line(&mut self) -> std::io::Result<bool> {
if !self.test_diff_header_minus_line() {
return Ok(false);
}
let (mut path_or_mode, file_event) =
parse_diff_header_line(&self.line, self.source == Source::GitDiff);
utils::path::relativize_path_maybe(&mut path_or_mode, self.config);
self.minus_file = path_or_mode;
self.minus_file_event = file_event;
if self.source == Source::DiffUnified {
self.state = State::DiffHeader(DiffType::Unified);
self.plus_file.clear();
self.painter
.set_syntax(get_filename_from_marker_line(&self.line));
} else {
self.painter
.set_syntax(get_filename_from_diff_header_line_file_path(
&self.minus_file,
));
}
self.painter.paint_buffered_minus_and_plus_lines();
self.should_write_generic_diff_header_header_line()
}
#[inline]
fn test_diff_header_plus_line(&self) -> bool {
(matches!(self.state, State::DiffHeader(_)) || self.source == Source::DiffUnified)
&& (self.line.starts_with("+++ ")
|| self.line.starts_with("rename to ")
|| self.line.starts_with("copy to "))
}
pub fn handle_diff_header_plus_line(&mut self) -> std::io::Result<bool> {
if !self.test_diff_header_plus_line() {
return Ok(false);
}
let mut handled_line = false;
let (mut path_or_mode, file_event) =
parse_diff_header_line(&self.line, self.source == Source::GitDiff);
utils::path::relativize_path_maybe(&mut path_or_mode, self.config);
self.plus_file = path_or_mode;
self.plus_file_event = file_event;
if let Some(filename) = get_filename_from_diff_header_line_file_path(&self.plus_file) {
self.painter.set_syntax(Some(filename));
}
self.current_file_pair = Some((self.minus_file.clone(), self.plus_file.clone()));
self.painter.paint_buffered_minus_and_plus_lines();
if self.should_write_generic_diff_header_header_line()? {
handled_line = true;
} else if self.should_handle()
&& self.handled_diff_header_header_line_file_pair != self.current_file_pair
{
self.painter.emit()?;
self._handle_diff_header_header_line(self.source == Source::DiffUnified)?;
self.handled_diff_header_header_line_file_pair
.clone_from(&self.current_file_pair);
}
Ok(handled_line)
}
#[inline]
fn test_diff_header_file_operation_line(&self) -> bool {
(matches!(self.state, State::DiffHeader(_)) || self.source == Source::DiffUnified)
&& (self.line.starts_with("deleted file mode ")
|| self.line.starts_with("new file mode "))
}
pub fn handle_diff_header_file_operation_line(&mut self) -> std::io::Result<bool> {
if !self.test_diff_header_file_operation_line() {
return Ok(false);
}
let mut handled_line = false;
let (_mode_info, file_event) =
parse_diff_header_line(&self.line, self.source == Source::GitDiff);
let name = get_repeated_file_path_from_diff_line(&self.diff_line).unwrap_or_default();
match file_event {
FileEvent::Removed => {
self.minus_file = name;
self.plus_file = "/dev/null".into();
self.minus_file_event = FileEvent::Change;
self.plus_file_event = FileEvent::Change;
self.current_file_pair = Some((self.minus_file.clone(), self.plus_file.clone()));
}
FileEvent::Added => {
self.minus_file = "/dev/null".into();
self.plus_file = name;
self.minus_file_event = FileEvent::Change;
self.plus_file_event = FileEvent::Change;
self.current_file_pair = Some((self.minus_file.clone(), self.plus_file.clone()));
}
_ => (),
}
if self.should_write_generic_diff_header_header_line()?
|| (self.should_handle()
&& self.handled_diff_header_header_line_file_pair != self.current_file_pair)
{
handled_line = true;
}
Ok(handled_line)
}
pub(crate) fn diff_header_osc(&self) -> String {
match self.painter.diff_line_metadata.as_ref() {
Some(md) => {
let file = if self.plus_file == "/dev/null" {
&self.minus_file
} else {
&self.plus_file
};
let file = file
.strip_suffix(super::diff_header_misc::BINARY_FILE_SUFFIX)
.unwrap_or(file);
if file.is_empty() {
String::new()
} else {
md.osc_for_file_header(file)
}
}
None => String::new(),
}
}
pub(crate) fn write_color_only_header_row(&mut self, row: &[u8]) -> std::io::Result<()> {
if self.painter.diff_line_metadata.is_none() {
return self.painter.writer.write_all(row);
}
let osc = self.diff_header_osc();
if osc.is_empty() {
self.held_header_rows.extend_from_slice(row);
return Ok(());
}
let held = std::mem::take(&mut self.held_header_rows);
features::diff_line_metadata::write_with_header_osc(self.painter.writer, &osc, |w| {
w.write_all(&held)?;
w.write_all(row)
})
}
pub(crate) fn release_held_header_rows(&mut self) -> std::io::Result<()> {
let held = std::mem::take(&mut self.held_header_rows);
self.painter.writer.write_all(&held)
}
fn _handle_diff_header_header_line(&mut self, comparing: bool) -> std::io::Result<()> {
let line = get_file_change_description_from_file_paths(
&self.minus_file,
&self.plus_file,
comparing,
&self.minus_file_event,
&self.plus_file_event,
self.config,
);
let osc = self.diff_header_osc();
write_generic_diff_header_header_line(
&line,
&line,
self.painter.writer,
&mut self.mode_info,
self.config,
&osc,
)
}
#[inline]
fn test_pending_line_with_diff_name(&self) -> bool {
matches!(self.state, State::DiffHeader(_)) || self.source == Source::DiffUnified
}
pub fn handle_pending_line_with_diff_name(&mut self) -> std::io::Result<()> {
if !self.test_pending_line_with_diff_name() {
return Ok(());
}
if !self.mode_info.is_empty() {
let format_label = |label: &str| {
if !label.is_empty() {
format!("{label} ")
} else {
"".to_string()
}
};
let format_file = |file| match (
self.config.hyperlinks,
utils::path::absolute_path(file, self.config),
) {
(true, Some(absolute_path)) => features::hyperlinks::format_osc8_file_hyperlink(
absolute_path,
None,
file,
self.config,
),
_ => Cow::from(file),
};
let label = format_label(&self.config.file_modified_label);
let name = get_repeated_file_path_from_diff_line(&self.diff_line).unwrap_or_default();
let line = format!("{}{}", label, format_file(&name));
let osc = self.diff_header_osc();
write_generic_diff_header_header_line(
&line,
&line,
self.painter.writer,
&mut self.mode_info,
self.config,
&osc,
)
} else if !self.config.color_only
&& self.should_handle()
&& self.handled_diff_header_header_line_file_pair != self.current_file_pair
{
self._handle_diff_header_header_line(self.source == Source::DiffUnified)?;
self.handled_diff_header_header_line_file_pair
.clone_from(&self.current_file_pair);
Ok(())
} else {
Ok(())
}
}
}
pub fn write_generic_diff_header_header_line(
line: &str,
raw_line: &str,
writer: &mut dyn Write,
mode_info: &mut String,
config: &Config,
metadata_osc: &str,
) -> std::io::Result<()> {
if config.file_style.is_omitted && !config.color_only {
return Ok(());
}
let (mut draw_fn, pad, decoration_ansi_term_style) =
draw::get_draw_function(config.file_style.decoration_style);
if !config.color_only {
writeln!(writer)?;
}
crate::features::diff_line_metadata::write_with_header_osc(writer, metadata_osc, |w| {
draw_fn(
w,
&format!("{}{}", line, if pad { " " } else { "" }),
&format!("{}{}", raw_line, if pad { " " } else { "" }),
mode_info,
&config.decorations_width,
config.file_style,
decoration_ansi_term_style,
)
})?;
if !mode_info.is_empty() {
mode_info.clear();
}
Ok(())
}
#[allow(clippy::tabs_in_doc_comments)]
pub fn continues_file_header(line: &str) -> bool {
[
"index ",
"old mode ",
"new mode ",
"deleted file mode ",
"new file mode ",
"similarity index ",
"dissimilarity index ",
"rename from ",
"rename to ",
"copy from ",
"copy to ",
"--- ",
"+++ ",
"Binary files ",
]
.iter()
.any(|prefix| line.starts_with(prefix))
}
fn get_filename_from_marker_line(line: &str) -> Option<&str> {
line.split('\t')
.next()
.and_then(|column| column.split(' ').nth(1))
.and_then(get_filename_from_diff_header_line_file_path)
}
fn get_filename_from_diff_header_line_file_path(path: &str) -> Option<&str> {
Path::new(path).file_name().and_then(|filename| {
if path != "/dev/null" {
filename.to_str()
} else {
None
}
})
}
fn parse_diff_header_line(line: &str, git_diff_name: bool) -> (String, FileEvent) {
match line {
line if line.starts_with("--- ") || line.starts_with("+++ ") => {
let offset = 4;
let file = _parse_file_path(&line[offset..], git_diff_name);
(file, FileEvent::Change)
}
line if line.starts_with("rename from ") => {
(line[12..].to_string(), FileEvent::Rename) }
line if line.starts_with("rename to ") => {
(line[10..].to_string(), FileEvent::Rename) }
line if line.starts_with("copy from ") => {
(line[10..].to_string(), FileEvent::Copy) }
line if line.starts_with("copy to ") => {
(line[8..].to_string(), FileEvent::Copy) }
line if line.starts_with("new file mode ") => {
(line[14..].to_string(), FileEvent::Added) }
line if line.starts_with("deleted file mode ") => {
(line[18..].to_string(), FileEvent::Removed) }
_ => ("".to_string(), FileEvent::NoEvent),
}
}
pub fn get_repeated_file_path_from_diff_line(line: &str) -> Option<String> {
if let Some(line) = line.strip_prefix("diff --git ") {
let line: Vec<&str> = line.graphemes(true).collect();
let midpoint = line.len() / 2;
if line[midpoint] == " " {
let first_path = _parse_file_path(&line[..midpoint].join(""), true);
let second_path = _parse_file_path(&line[midpoint + 1..].join(""), true);
if first_path == second_path {
return Some(first_path);
}
}
}
None
}
fn remove_surrounding_quotes(path: &str) -> &str {
if path.starts_with('"') && path.ends_with('"') {
&path[1..path.len() - 1]
} else {
path
}
}
fn _parse_file_path(path: &str, git_diff_name: bool) -> String {
let path = remove_surrounding_quotes(path);
match path.strip_suffix('\t').unwrap_or(path) {
"/dev/null" => "/dev/null",
path if git_diff_name && DIFF_PREFIXES.iter().any(|s| path.starts_with(s)) => &path[2..],
path if git_diff_name => path,
path => path.split('\t').next().unwrap_or(""),
}
.to_string()
}
pub fn get_file_change_description_from_file_paths(
minus_file: &str,
plus_file: &str,
comparing: bool,
minus_file_event: &FileEvent,
plus_file_event: &FileEvent,
config: &Config,
) -> String {
let format_label = |label: &str| {
if !label.is_empty() {
format!("{label} ")
} else {
"".to_string()
}
};
if comparing {
format!(
"{}{} {} {}",
format_label(&config.file_modified_label),
minus_file,
config.right_arrow,
plus_file
)
} else {
let format_file = |file| {
let formatted_file = if let Some(regex_replacement) = &config.file_regex_replacement {
regex_replacement.execute(file)
} else {
Cow::from(file)
};
match (config.hyperlinks, utils::path::absolute_path(file, config)) {
(true, Some(absolute_path)) => features::hyperlinks::format_osc8_file_hyperlink(
absolute_path,
None,
&formatted_file,
config,
),
_ => formatted_file,
}
};
match (minus_file, plus_file, minus_file_event, plus_file_event) {
(minus_file, plus_file, _, _) if minus_file == plus_file => format!(
"{}{}",
format_label(&config.file_modified_label),
format_file(minus_file)
),
(minus_file, "/dev/null", _, _) => format!(
"{}{}",
format_label(&config.file_removed_label),
format_file(minus_file)
),
("/dev/null", plus_file, _, _) => format!(
"{}{}",
format_label(&config.file_added_label),
format_file(plus_file)
),
(minus_file, plus_file, file_event, _) => format!(
"{}{} {} {}",
format_label(match file_event {
FileEvent::Rename => &config.file_renamed_label,
FileEvent::Copy => &config.file_copied_label,
_ => &config.file_modified_label,
}),
format_file(minus_file),
config.right_arrow,
format_file(plus_file)
),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::integration_test_utils::{
make_config_from_args, run_delta_with_diff_line_metadata, DeltaTest,
};
use insta::assert_snapshot;
#[test]
fn test_get_filename_from_marker_line() {
assert_eq!(
get_filename_from_marker_line("--- src/one.rs 2019-11-20 06:47:56.000000000 +0100"),
Some("one.rs")
);
}
#[test]
fn test_get_filename_from_diff_header_line() {
assert_eq!(
get_filename_from_diff_header_line_file_path("a/src/parse.rs"),
Some("parse.rs")
);
assert_eq!(
get_filename_from_diff_header_line_file_path("b/src/pa rse.rs"),
Some("pa rse.rs")
);
assert_eq!(
get_filename_from_diff_header_line_file_path("src/pa rse.rs"),
Some("pa rse.rs")
);
assert_eq!(
get_filename_from_diff_header_line_file_path("wat hello.rs"),
Some("wat hello.rs")
);
assert_eq!(
get_filename_from_diff_header_line_file_path("/dev/null"),
None
);
assert_eq!(
get_filename_from_diff_header_line_file_path("Dockerfile"),
Some("Dockerfile")
);
assert_eq!(
get_filename_from_diff_header_line_file_path("Makefile"),
Some("Makefile")
);
assert_eq!(
get_filename_from_diff_header_line_file_path("a/src/Makefile"),
Some("Makefile")
);
assert_eq!(
get_filename_from_diff_header_line_file_path("src/Makefile"),
Some("Makefile")
);
}
#[test]
fn test_get_file_path_from_git_diff_header_line() {
assert_eq!(
parse_diff_header_line("--- /dev/null", true),
("/dev/null".to_string(), FileEvent::Change)
);
for prefix in &DIFF_PREFIXES {
assert_eq!(
parse_diff_header_line(&format!("--- {prefix}src/delta.rs"), true),
("src/delta.rs".to_string(), FileEvent::Change)
);
}
assert_eq!(
parse_diff_header_line("--- src/delta.rs", true),
("src/delta.rs".to_string(), FileEvent::Change)
);
assert_eq!(
parse_diff_header_line("+++ src/delta.rs", true),
("src/delta.rs".to_string(), FileEvent::Change)
);
assert_eq!(
parse_diff_header_line("+++ \".\\delta.rs\"", true),
(".\\delta.rs".to_string(), FileEvent::Change)
);
}
#[test]
fn test_get_file_path_from_git_diff_header_line_containing_spaces() {
assert_eq!(
parse_diff_header_line("+++ a/my src/delta.rs", true),
("my src/delta.rs".to_string(), FileEvent::Change)
);
assert_eq!(
parse_diff_header_line("+++ my src/delta.rs", true),
("my src/delta.rs".to_string(), FileEvent::Change)
);
assert_eq!(
parse_diff_header_line("+++ a/src/my delta.rs", true),
("src/my delta.rs".to_string(), FileEvent::Change)
);
assert_eq!(
parse_diff_header_line("+++ a/my src/my delta.rs", true),
("my src/my delta.rs".to_string(), FileEvent::Change)
);
assert_eq!(
parse_diff_header_line("+++ b/my src/my enough/my delta.rs", true),
(
"my src/my enough/my delta.rs".to_string(),
FileEvent::Change
)
);
}
#[test]
fn test_get_file_path_from_git_diff_header_line_rename() {
assert_eq!(
parse_diff_header_line("rename from nospace/file2.el", true),
("nospace/file2.el".to_string(), FileEvent::Rename)
);
}
#[test]
fn test_get_file_path_from_git_diff_header_line_rename_containing_spaces() {
assert_eq!(
parse_diff_header_line("rename from with space/file1.el", true),
("with space/file1.el".to_string(), FileEvent::Rename)
);
}
#[test]
fn test_parse_diff_header_line() {
assert_eq!(
parse_diff_header_line("--- src/delta.rs", false),
("src/delta.rs".to_string(), FileEvent::Change)
);
assert_eq!(
parse_diff_header_line("+++ src/delta.rs", false),
("src/delta.rs".to_string(), FileEvent::Change)
);
}
#[test]
fn test_get_repeated_file_path_from_diff_line() {
assert_eq!(
get_repeated_file_path_from_diff_line("diff --git a/src/main.rs b/src/main.rs"),
Some("src/main.rs".to_string())
);
assert_eq!(
get_repeated_file_path_from_diff_line("diff --git a/a b/a"),
Some("a".to_string())
);
assert_eq!(
get_repeated_file_path_from_diff_line("diff --git a/a b b/a b"),
Some("a b".to_string())
);
assert_eq!(
get_repeated_file_path_from_diff_line("diff --git a/a b/aa"),
None
);
assert_eq!(
get_repeated_file_path_from_diff_line(
"diff --git a/.config/Code - Insiders/User/settings.json b/.config/Code - Insiders/User/settings.json"),
Some(".config/Code - Insiders/User/settings.json".to_string())
);
assert_eq!(
get_repeated_file_path_from_diff_line(r#"diff --git "a/quoted" "b/quoted""#),
Some("quoted".to_string())
);
}
#[test]
fn test_diff_header_with_mode_change_in_last_hunk() {
let input = "\
diff --git a/a.txt b/a.txt
index 44371ed..e69de29 100644
--- a/a.txt
+++ b/a.txt
@@ -1 +0,0 @@
-A-content
diff --git a/b.txt b/b.txt
old mode 100644
new mode 100755
";
let result = DeltaTest::with_args(&[]).with_input(input);
assert_snapshot!(result.output, @r"
a.txt
───────────────────────────────────────────
───┐
0: │
───┘
A-content
b.txt (mode +x)
───────────────────────────────────────────
");
}
#[test]
fn test_diff_header_with_2x_mode_change() {
let input = "\
diff --git a/a.txt b/a.txt
index 44371ed..e69de29 100644
--- a/a.txt
+++ b/a.txt
@@ -1 +0,0 @@
-A-content
diff --git a/b.txt b/b.txt
old mode 100644
new mode 100755
--- a/b.txt
+++ b/b.txt
diff --git a/c.txt b/c.txt
old mode 100644
new mode 100755
";
let result = DeltaTest::with_args(&[]).with_input(input);
assert_snapshot!(result.output, @r"
a.txt
───────────────────────────────────────────
───┐
0: │
───┘
A-content
b.txt (mode +x)
───────────────────────────────────────────
c.txt (mode +x)
───────────────────────────────────────────
");
}
pub const BIN_AND_TXT_FILE_ADDED: &str = "\
diff --git a/BIN b/BIN
new file mode 100644
index 0000000..a5d0c46
Binary files /dev/null and b/BIN differ
diff --git a/TXT b/TXT
new file mode 100644
index 0000000..323fae0
--- /dev/null
+++ b/TXT
@@ -0,0 +1 @@
+plain text";
#[test]
fn test_diff_header_relative_paths() {
let mut cfg = make_config_from_args(&["--relative-paths", "-s"]);
cfg.cwd_relative_to_repo_root = Some("src/utils/".into());
let result = DeltaTest::with_config(&cfg)
.with_input(BIN_AND_TXT_FILE_ADDED)
.output;
insta::with_settings!({filters => vec![(r"\.\.\\", "../")]}, {
assert_snapshot!(result, @r###"
added: ../../BIN (binary file)
───────────────────────────────────────────
added: ../../TXT
───────────────────────────────────────────
───┐
1: │
───┘
│ │ │ 1 │plain text
"###)
});
}
pub const DIFF_AMBIGUOUS_HEADER_3X_MINUS: &str = r#"--- a.lua
+++ b.lua
@@ -1,5 +1,4 @@
#!/usr/bin/env lua
print("Hello")
--- World?
print("..")
"#;
pub const DIFF_AMBIGUOUS_HEADER_3X_MINUS_LAST_LINE: &str = r#"--- c.lua
+++ d.lua
@@ -1,4 +1,3 @@
#!/usr/bin/env lua
print("Hello")
--- World?
"#;
pub const DIFF_AMBIGUOUS_HEADER_MULTIPLE_HUNKS: &str = r#"--- e.lua 2024-08-04 20:50:27.257726606 +0200
+++ f.lua 2024-08-04 20:50:35.345795405 +0200
@@ -3,3 +3,2 @@
print("Hello")
--- World?
print("")
@@ -7,2 +6,3 @@
print("")
+print("World")
print("")
@@ -10,2 +10 @@
print("")
--- End
"#;
#[test]
fn test_diff_header_ambiguous_3x_minus() {
let result = DeltaTest::with_args(&[])
.explain_ansi()
.with_input(DIFF_AMBIGUOUS_HEADER_3X_MINUS);
assert_snapshot!(result.output, @r###"
(normal)
(blue)a.lua ⟶ b.lua(normal)
(blue)───────────────────────────────────────────(normal)
(blue)───(blue)┐(normal)
(blue)1(normal): (blue)│(normal)
(blue)───(blue)┘(normal)
(203)#(231)!(203)/(231)usr(203)/(231)bin(203)/(231)env lua(normal)
(81)print(231)((186)"Hello"(231))(normal)
(normal 52)-- World?(normal)
(81)print(231)((186)".."(231))(normal)
"###);
}
#[test]
fn test_diff_header_ambiguous_3x_minus_concatenated() {
let result = DeltaTest::with_args(&[])
.explain_ansi()
.with_input(&format!(
"{}{}{}",
DIFF_AMBIGUOUS_HEADER_MULTIPLE_HUNKS,
DIFF_AMBIGUOUS_HEADER_3X_MINUS,
DIFF_AMBIGUOUS_HEADER_3X_MINUS_LAST_LINE
));
assert_snapshot!(result.output, @r###"
(normal)
(blue)e.lua ⟶ f.lua(normal)
(blue)───────────────────────────────────────────(normal)
(blue)───(blue)┐(normal)
(blue)3(normal): (blue)│(normal)
(blue)───(blue)┘(normal)
(81)print(231)((186)"Hello"(231))(normal)
(normal 52)-- World?(normal)
(81)print(231)((186)""(231))(normal)
(blue)───(blue)┐(normal)
(blue)6(normal): (blue)│(normal)
(blue)───(blue)┘(normal)
(81)print(231)((186)""(231))(normal)
(81 22)print(231)((186)"World"(231))(normal)
(81)print(231)((186)""(231))(normal)
(blue)────(blue)┐(normal)
(blue)10(normal): (blue)│(normal)
(blue)────(blue)┘(normal)
(81)print(231)((186)""(231))(normal)
(normal 52)-- End(normal)
(blue)a.lua ⟶ b.lua(normal)
(blue)───────────────────────────────────────────(normal)
(blue)───(blue)┐(normal)
(blue)1(normal): (blue)│(normal)
(blue)───(blue)┘(normal)
(203)#(231)!(203)/(231)usr(203)/(231)bin(203)/(231)env lua(normal)
(81)print(231)((186)"Hello"(231))(normal)
(normal 52)-- World?(normal)
(81)print(231)((186)".."(231))(normal)
(blue)c.lua ⟶ d.lua(normal)
(blue)───────────────────────────────────────────(normal)
(blue)───(blue)┐(normal)
(blue)1(normal): (blue)│(normal)
(blue)───(blue)┘(normal)
(203)#(231)!(203)/(231)usr(203)/(231)bin(203)/(231)env lua(normal)
(81)print(231)((186)"Hello"(231))(normal)
(normal 52)-- World?(normal)
"###);
}
fn visible_metadata_records(input: &str, args: &[&str]) -> String {
let config = make_config_from_args(args);
let output = run_delta_with_diff_line_metadata(input, &config);
crate::ansi::strip_ansi_codes(&output.replace("\x1b]1717;", "⟦").replace("\x1b\\", "⟧"))
}
#[test]
fn test_file_header_records_in_color_only_unified_diff() {
let input = "\
--- old1.txt
+++ new1.txt
@@ -1 +1 @@
-foo
+bar
--- old2.txt
+++ new2.txt
@@ -1 +1 @@
-foo
+bar
";
assert_snapshot!(visible_metadata_records(input, &["--color-only"]), @r"
⟦1;f;;;new1.txt⟧--- old1.txt
⟦1;f;;;new1.txt⟧+++ new1.txt
⟦1;h;1;;new1.txt⟧@@ -1 +1 @@
⟦1;f;;;new2.txt⟧--- old2.txt
⟦1;f;;;new2.txt⟧+++ new2.txt
⟦1;d;1;1;new1.txt⟧-foo
⟦1;a;1;;new1.txt⟧+bar
⟦1;h;1;;new2.txt⟧@@ -1 +1 @@
⟦1;d;1;1;new2.txt⟧-foo
⟦1;a;1;;new2.txt⟧+bar
");
}
#[test]
fn test_file_header_records_for_rename_in_color_only_mode() {
let input = "\
diff --git a/old.txt b/new.txt
similarity index 90%
rename from old.txt
rename to new.txt
";
assert_snapshot!(visible_metadata_records(input, &["--color-only"]), @r"
⟦1;f;;;new.txt⟧diff --git a/old.txt b/new.txt
⟦1;f;;;new.txt⟧similarity index 90%
⟦1;f;;;new.txt⟧rename from old.txt
⟦1;f;;;new.txt⟧rename to new.txt
");
}
#[test]
fn test_every_header_row_carries_the_file_record_in_color_only_mode() {
let input = "\
diff --git a/img.png b/img.png
index 0000000..a5d0c46 100644
Binary files a/img.png and b/img.png differ
diff --git a/run.sh b/run.sh
old mode 100644
new mode 100755
diff --git a/one.txt b/one.txt
index 257cc56..5716ca5 100644
--- a/one.txt
+++ b/one.txt
@@ -1 +1 @@
-foo
+bar
";
assert_snapshot!(visible_metadata_records(input, &["--color-only"]), @r"
⟦1;f;;;img.png⟧diff --git a/img.png b/img.png
⟦1;f;;;img.png⟧index 0000000..a5d0c46 100644
⟦1;f;;;img.png⟧Binary files a/img.png and b/img.png differ
⟦1;f;;;run.sh⟧diff --git a/run.sh b/run.sh
⟦1;f;;;run.sh⟧old mode 100644
⟦1;f;;;run.sh⟧new mode 100755
⟦1;f;;;one.txt⟧diff --git a/one.txt b/one.txt
⟦1;f;;;one.txt⟧index 257cc56..5716ca5 100644
⟦1;f;;;one.txt⟧--- a/one.txt
⟦1;f;;;one.txt⟧+++ b/one.txt
⟦1;h;1;;one.txt⟧@@ -1 +1 @@
⟦1;d;1;1;one.txt⟧-foo
⟦1;a;1;;one.txt⟧+bar
");
}
#[test]
fn test_no_file_header_record_on_only_in_row() {
let input = "\
--- dir1/f.txt
+++ dir2/f.txt
@@ -1 +1 @@
-foo
+bar
Only in dir1: g.txt
";
assert_snapshot!(visible_metadata_records(input, &[]), @r"
⟦1;f;;;dir2/f.txt⟧dir1/f.txt ⟶ dir2/f.txt
⟦1;f;;;dir2/f.txt⟧───────────────────────────────────────────
⟦1;h;1;;dir2/f.txt⟧───┐
⟦1;h;1;;dir2/f.txt⟧1: │
⟦1;h;1;;dir2/f.txt⟧───┘
⟦1;d;1;1;dir2/f.txt⟧foo
⟦1;a;1;;dir2/f.txt⟧bar
Only in dir1: g.txt
───────────────────────────────────────────
");
}
#[test]
fn test_hunk_header_record_when_hunk_header_row_is_skipped() {
let input = "\
--- a.txt
+++ b.txt
@@ -1,3 +1,3 @@
one
-two
+TWO
three
";
assert_snapshot!(visible_metadata_records(input, &["--hunk-header-style", "syntax"]), @r"
⟦1;f;;;b.txt⟧a.txt ⟶ b.txt
⟦1;f;;;b.txt⟧───────────────────────────────────────────
⟦1;h;1;;b.txt⟧
⟦1;c;1;;b.txt⟧one
⟦1;d;2;2;b.txt⟧two
⟦1;a;2;;b.txt⟧TWO
⟦1;c;3;;b.txt⟧three
");
}
#[test]
fn test_file_header_record_on_submodule_rows_names_the_submodule() {
let input = "\
diff --git a/one.txt b/one.txt
index 257cc56..5716ca5 100644
--- a/one.txt
+++ b/one.txt
@@ -1 +1 @@
-foo
+bar
Submodule sub/mod contains untracked content
Submodule sub/mod a32f27c..2d9f921 (rewind):
< make it so
";
assert_snapshot!(visible_metadata_records(input, &[]), @r"
⟦1;f;;;one.txt⟧one.txt
⟦1;f;;;one.txt⟧───────────────────────────────────────────
⟦1;h;1;;one.txt⟧───┐
⟦1;h;1;;one.txt⟧1: │
⟦1;h;1;;one.txt⟧───┘
⟦1;d;1;1;one.txt⟧foo
⟦1;a;1;;one.txt⟧bar
⟦1;f;;;sub/mod⟧Submodule sub/mod contains untracked content
⟦1;f;;;sub/mod⟧───────────────────────────────────────────
⟦1;f;;;sub/mod⟧Submodule sub/mod a32f27c..2d9f921 (rewind):
⟦1;f;;;sub/mod⟧───────────────────────────────────────────
< make it so
");
}
#[test]
fn test_no_file_header_record_on_an_unreadable_submodule_row() {
let input = "\
diff --git a/one.txt b/one.txt
index 257cc56..5716ca5 100644
--- a/one.txt
+++ b/one.txt
@@ -1 +1 @@
-foo
+bar
Submodule support was added
";
assert_snapshot!(visible_metadata_records(input, &[]), @r"
⟦1;f;;;one.txt⟧one.txt
⟦1;f;;;one.txt⟧───────────────────────────────────────────
⟦1;h;1;;one.txt⟧───┐
⟦1;h;1;;one.txt⟧1: │
⟦1;h;1;;one.txt⟧───┘
⟦1;d;1;1;one.txt⟧foo
⟦1;a;1;;one.txt⟧bar
Submodule support was added
───────────────────────────────────────────
");
}
#[test]
fn test_binary_file_header_record_carries_the_real_path() {
let input = "\
diff --git a/img.png b/img.png
index 0000000..a5d0c46 100644
Binary files a/img.png and b/img.png differ
";
assert_snapshot!(visible_metadata_records(input, &[]), @r"
⟦1;f;;;img.png⟧img.png (binary file)
⟦1;f;;;img.png⟧───────────────────────────────────────────
");
}
#[test]
fn test_diff_header_ambiguous_3x_minus_extra_and_concatenated() {
let result = DeltaTest::with_args(&[])
.explain_ansi()
.with_input(&format!(
"extra 1\n\n{}\nextra 2\n{}\nextra 3\n{}",
DIFF_AMBIGUOUS_HEADER_MULTIPLE_HUNKS,
DIFF_AMBIGUOUS_HEADER_3X_MINUS,
DIFF_AMBIGUOUS_HEADER_3X_MINUS_LAST_LINE
));
assert_snapshot!(result.output, @r###"
(normal)extra 1
(blue)e.lua ⟶ f.lua(normal)
(blue)───────────────────────────────────────────(normal)
(blue)───(blue)┐(normal)
(blue)3(normal): (blue)│(normal)
(blue)───(blue)┘(normal)
(81)print(231)((186)"Hello"(231))(normal)
(normal 52)-- World?(normal)
(81)print(231)((186)""(231))(normal)
(blue)───(blue)┐(normal)
(blue)6(normal): (blue)│(normal)
(blue)───(blue)┘(normal)
(81)print(231)((186)""(231))(normal)
(81 22)print(231)((186)"World"(231))(normal)
(81)print(231)((186)""(231))(normal)
(blue)────(blue)┐(normal)
(blue)10(normal): (blue)│(normal)
(blue)────(blue)┘(normal)
(81)print(231)((186)""(231))(normal)
(normal 52)-- End(normal)
extra 2
(blue)a.lua ⟶ b.lua(normal)
(blue)───────────────────────────────────────────(normal)
(blue)───(blue)┐(normal)
(blue)1(normal): (blue)│(normal)
(blue)───(blue)┘(normal)
(203)#(231)!(203)/(231)usr(203)/(231)bin(203)/(231)env lua(normal)
(81)print(231)((186)"Hello"(231))(normal)
(normal 52)-- World?(normal)
(81)print(231)((186)".."(231))(normal)
extra 3
(blue)c.lua ⟶ d.lua(normal)
(blue)───────────────────────────────────────────(normal)
(blue)───(blue)┐(normal)
(blue)1(normal): (blue)│(normal)
(blue)───(blue)┘(normal)
(203)#(231)!(203)/(231)usr(203)/(231)bin(203)/(231)env lua(normal)
(81)print(231)((186)"Hello"(231))(normal)
(normal 52)-- World?(normal)
"###);
}
}