| 1 | use std::borrow::Cow; |
| 2 | use std::collections::HashMap; |
| 3 | use std::io::{self, BufRead, IsTerminal, Write}; |
| 4 | |
| 5 | use bytelines::ByteLines; |
| 6 | |
| 7 | use crate::ansi; |
| 8 | use crate::config::delta_unreachable; |
| 9 | use crate::config::Config; |
| 10 | use crate::config::GrepType; |
| 11 | use crate::features; |
| 12 | use crate::handlers::grep; |
| 13 | use crate::handlers::hunk_header::{AmbiguousDiffMinusCounter, ParsedHunkHeader}; |
| 14 | use crate::handlers::{self, merge_conflict}; |
| 15 | use crate::paint::Painter; |
| 16 | use crate::style::DecorationStyle; |
| 17 | use crate::utils; |
| 18 | |
| 19 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 20 | pub enum State { |
| 21 | CommitMeta, // In commit metadata section |
| 22 | DiffHeader(DiffType), // In diff metadata section, between (possible) commit metadata and first hunk |
| 23 | HunkHeader(DiffType, ParsedHunkHeader, String, String), // In hunk metadata line (diff_type, parsed, line, raw_line) |
| 24 | HunkZero(DiffType, Option<String>), // In hunk; unchanged line (prefix, raw_line) |
| 25 | HunkMinus(DiffType, Option<String>), // In hunk; removed line (diff_type, raw_line) |
| 26 | HunkPlus(DiffType, Option<String>), // In hunk; added line (diff_type, raw_line) |
| 27 | MergeConflict(MergeParents, merge_conflict::MergeConflictCommit), |
| 28 | SubmoduleLog, // In a submodule section, with gitconfig diff.submodule = log |
| 29 | SubmoduleShort(String), // In a submodule section, with gitconfig diff.submodule = short |
| 30 | Blame(String), // In a line of `git blame` output (key). |
| 31 | GitShowFile, // In a line of `git show $revision:./path/to/file.ext` output |
| 32 | Grep(GrepType, grep::LineType, String, Option<usize>), // In a line of `git grep` output (grep_type, line_type, path, line_number) |
| 33 | Unknown, |
| 34 | // The following elements are created when a line is wrapped to display it: |
| 35 | HunkZeroWrapped, // Wrapped unchanged line |
| 36 | HunkMinusWrapped, // Wrapped removed line |
| 37 | HunkPlusWrapped, // Wrapped added line |
| 38 | } |
| 39 | |
| 40 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 41 | pub enum DiffType { |
| 42 | Unified, |
| 43 | // https://git-scm.com/docs/git-diff#_combined_diff_format |
| 44 | Combined(MergeParents, InMergeConflict), |
| 45 | } |
| 46 | |
| 47 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 48 | pub enum MergeParents { |
| 49 | Number(usize), // Number of parent commits == (number of @s in hunk header) - 1 |
| 50 | Prefix(String), // Hunk line prefix, length == number of parent commits |
| 51 | Unknown, |
| 52 | } |
| 53 | |
| 54 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 55 | pub enum InMergeConflict { |
| 56 | Yes, |
| 57 | No, |
| 58 | } |
| 59 | |
| 60 | impl DiffType { |
| 61 | pub fn n_parents(&self) -> usize { |
| 62 | use DiffType::*; |
| 63 | use MergeParents::*; |
| 64 | match self { |
| 65 | Combined(Prefix(prefix), _) => prefix.len(), |
| 66 | Combined(Number(n_parents), _) => *n_parents, |
| 67 | Unified => 1, |
| 68 | Combined(Unknown, _) => delta_unreachable("Number of merge parents must be known."), |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | #[derive(Debug, PartialEq, Eq)] |
| 74 | pub enum Source { |
| 75 | GitDiff, // Coming from a `git diff` command |
| 76 | DiffUnified, // Coming from a `diff -u` command |
| 77 | Unknown, |
| 78 | } |
| 79 | |
| 80 | // Possible transitions, with actions on entry: |
| 81 | // |
| 82 | // |
| 83 | // | from \ to | CommitMeta | DiffHeader | HunkHeader | HunkZero | HunkMinus | HunkPlus | |
| 84 | // |-------------+-------------+-------------+-------------+-------------+-------------+----------| |
| 85 | // | CommitMeta | emit | emit | | | | | |
| 86 | // | DiffHeader | | emit | emit | | | | |
| 87 | // | HunkHeader | | | | emit | push | push | |
| 88 | // | HunkZero | emit | emit | emit | emit | push | push | |
| 89 | // | HunkMinus | flush, emit | flush, emit | flush, emit | flush, emit | push | push | |
| 90 | // | HunkPlus | flush, emit | flush, emit | flush, emit | flush, emit | flush, push | push | |
| 91 | |
| 92 | pub struct StateMachine<'a> { |
| 93 | pub line: String, |
| 94 | pub raw_line: String, |
| 95 | pub state: State, |
| 96 | pub source: Source, |
| 97 | pub minus_file: String, |
| 98 | pub plus_file: String, |
| 99 | pub minus_file_event: handlers::diff_header::FileEvent, |
| 100 | pub plus_file_event: handlers::diff_header::FileEvent, |
| 101 | pub diff_line: String, |
| 102 | pub mode_info: String, |
| 103 | pub painter: Painter<'a>, |
| 104 | pub config: &'a Config, |
| 105 | |
| 106 | // When a file is modified, we use lines starting with '---' or '+++' to obtain the file name. |
| 107 | // When a file is renamed without changes, we use lines starting with 'rename' to obtain the |
| 108 | // file name (there is no diff hunk and hence no lines starting with '---' or '+++'). But when |
| 109 | // a file is renamed with changes, both are present, and we rely on the following variables to |
| 110 | // avoid emitting the file meta header line twice (#245). |
| 111 | pub current_file_pair: Option<(String, String)>, |
| 112 | pub handled_diff_header_header_line_file_pair: Option<(String, String)>, |
| 113 | pub blame_key_colors: HashMap<String, String>, |
| 114 | pub minus_line_counter: AmbiguousDiffMinusCounter, |
| 115 | } |
| 116 | |
| 117 | pub fn delta<I>(lines: ByteLines<I>, writer: &mut dyn Write, config: &Config) -> std::io::Result<()> |
| 118 | where |
| 119 | I: BufRead, |
| 120 | { |
| 121 | StateMachine::new(writer, config).consume(lines) |
| 122 | } |
| 123 | |
| 124 | impl<'a> StateMachine<'a> { |
| 125 | pub fn new(writer: &'a mut dyn Write, config: &'a Config) -> Self { |
| 126 | Self { |
| 127 | line: "".to_string(), |
| 128 | raw_line: "".to_string(), |
| 129 | state: State::Unknown, |
| 130 | source: Source::Unknown, |
| 131 | minus_file: "".to_string(), |
| 132 | plus_file: "".to_string(), |
| 133 | minus_file_event: handlers::diff_header::FileEvent::NoEvent, |
| 134 | plus_file_event: handlers::diff_header::FileEvent::NoEvent, |
| 135 | diff_line: "".to_string(), |
| 136 | mode_info: "".to_string(), |
| 137 | current_file_pair: None, |
| 138 | handled_diff_header_header_line_file_pair: None, |
| 139 | painter: Painter::new(writer, config), |
| 140 | config, |
| 141 | blame_key_colors: HashMap::new(), |
| 142 | minus_line_counter: AmbiguousDiffMinusCounter::not_needed(), |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | fn consume<I>(&mut self, mut lines: ByteLines<I>) -> std::io::Result<()> |
| 147 | where |
| 148 | I: BufRead, |
| 149 | { |
| 150 | while let Some(Ok(raw_line_bytes)) = lines.next() { |
| 151 | self.ingest_line(raw_line_bytes); |
| 152 | |
| 153 | if self.source == Source::Unknown { |
| 154 | self.source = detect_source(&self.line); |
| 155 | // Handle (rare) plain `diff -u file1 file2` header. Done here to avoid having |
| 156 | // to introduce and handle a Source::DiffUnifiedAmbiguous variant everywhere. |
| 157 | if self.line.starts_with("--- ") { |
| 158 | self.minus_line_counter = AmbiguousDiffMinusCounter::prepare_to_count(); |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | // Every method named handle_* must return std::io::Result<bool>. |
| 163 | // The bool indicates whether the line has been handled by that |
| 164 | // method (in which case no subsequent handlers are permitted to |
| 165 | // handle it). |
| 166 | let _ = self.handle_commit_meta_header_line()? |
| 167 | || self.handle_diff_stat_line()? |
| 168 | || self.handle_diff_header_diff_line()? |
| 169 | || self.handle_diff_header_file_operation_line()? |
| 170 | || self.handle_diff_header_minus_line()? |
| 171 | || self.handle_diff_header_plus_line()? |
| 172 | || self.handle_hunk_header_line()? |
| 173 | || self.handle_diff_header_mode_line()? |
| 174 | || self.handle_diff_header_misc_line()? |
| 175 | || self.handle_submodule_log_line()? |
| 176 | || self.handle_submodule_short_line()? |
| 177 | || self.handle_merge_conflict_line()? |
| 178 | || self.handle_hunk_line()? |
| 179 | || self.handle_git_show_file_line()? |
| 180 | || self.handle_blame_line()? |
| 181 | || self.handle_grep_line()? |
| 182 | || self.should_skip_line() |
| 183 | || self.emit_line_unchanged()?; |
| 184 | } |
| 185 | |
| 186 | self.handle_pending_line_with_diff_name()?; |
| 187 | self.painter.paint_buffered_minus_and_plus_lines(); |
| 188 | self.painter.emit()?; |
| 189 | Ok(()) |
| 190 | } |
| 191 | |
| 192 | fn ingest_line(&mut self, raw_line_bytes: &[u8]) { |
| 193 | match String::from_utf8(raw_line_bytes.to_vec()) { |
| 194 | Ok(utf8) => self.ingest_line_utf8(utf8), |
| 195 | Err(_) => { |
| 196 | let raw_line = String::from_utf8_lossy(raw_line_bytes); |
| 197 | let truncated_len = utils::round_char_boundary::floor_char_boundary( |
| 198 | &raw_line, |
| 199 | self.config.max_line_length, |
| 200 | ); |
| 201 | self.raw_line = raw_line[..truncated_len].to_string(); |
| 202 | self.line.clone_from(&self.raw_line); |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | fn ingest_line_utf8(&mut self, raw_line: String) { |
| 208 | self.raw_line = raw_line; |
| 209 | // When a file has \r\n line endings, git sometimes adds ANSI escape sequences between the |
| 210 | // \r and \n, in which case byte_lines does not remove the \r. Remove it now. [EndCRLF] |
| 211 | // TODO: Limit the number of characters we examine when looking for the \r? |
| 212 | if let Some(cr_index) = self.raw_line.rfind('\r') { |
| 213 | if ansi::measure_text_width(&self.raw_line[cr_index + 1..]) == 0 { |
| 214 | self.raw_line = format!( |
| 215 | "{}{}", |
| 216 | &self.raw_line[..cr_index], |
| 217 | &self.raw_line[cr_index + 1..] |
| 218 | ); |
| 219 | } |
| 220 | } |
| 221 | if self.config.max_line_length > 0 |
| 222 | && self.raw_line.len() > self.config.max_line_length |
| 223 | // Do not truncate long hunk headers |
| 224 | && !self.raw_line.starts_with("@@") |
| 225 | // Do not truncate ripgrep --json output |
| 226 | && !self.raw_line.starts_with('{') |
| 227 | { |
| 228 | self.raw_line = ansi::truncate_str( |
| 229 | &self.raw_line, |
| 230 | self.config.max_line_length, |
| 231 | &self.config.truncation_symbol, |
| 232 | ) |
| 233 | .to_string() |
| 234 | }; |
| 235 | self.line = ansi::strip_ansi_codes(&self.raw_line); |
| 236 | } |
| 237 | |
| 238 | /// Skip file metadata lines unless a raw diff style has been requested. |
| 239 | pub fn should_skip_line(&self) -> bool { |
| 240 | matches!(self.state, State::DiffHeader(_)) |
| 241 | && self.should_handle() |
| 242 | && !self.config.color_only |
| 243 | } |
| 244 | |
| 245 | /// Emit unchanged any line that delta does not handle. |
| 246 | pub fn emit_line_unchanged(&mut self) -> std::io::Result<bool> { |
| 247 | self.painter.emit()?; |
| 248 | writeln!( |
| 249 | self.painter.writer, |
| 250 | "{}", |
| 251 | format_raw_line(&self.raw_line, self.config) |
| 252 | )?; |
| 253 | let handled_line = true; |
| 254 | Ok(handled_line) |
| 255 | } |
| 256 | |
| 257 | /// Should a handle_* function be called on this element? |
| 258 | // TODO: I'm not sure the above description is accurate; I think this |
| 259 | // function needs a more accurate name. |
| 260 | pub fn should_handle(&self) -> bool { |
| 261 | let style = self.config.get_style(&self.state); |
| 262 | !(style.is_raw && style.decoration_style == DecorationStyle::NoDecoration) |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | /// If output is going to a tty, emit hyperlinks if requested. |
| 267 | // Although raw output should basically be emitted unaltered, we do this. |
| 268 | pub fn format_raw_line<'a>(line: &'a str, config: &Config) -> Cow<'a, str> { |
| 269 | if config.hyperlinks && io::stdout().is_terminal() { |
| 270 | features::hyperlinks::format_commit_line_with_osc8_commit_hyperlink(line, config) |
| 271 | } else { |
| 272 | Cow::from(line) |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | /// Try to detect what is producing the input for delta. |
| 277 | /// |
| 278 | /// Currently can detect: |
| 279 | /// * git diff |
| 280 | /// * diff -u |
| 281 | fn detect_source(line: &str) -> Source { |
| 282 | if line.starts_with("commit ") |
| 283 | || line.starts_with("diff --git ") |
| 284 | || line.starts_with("diff --cc ") |
| 285 | || line.starts_with("diff --combined ") |
| 286 | { |
| 287 | Source::GitDiff |
| 288 | } else if line.starts_with("diff -u") |
| 289 | || line.starts_with("diff -ru") |
| 290 | || line.starts_with("diff -r -u") |
| 291 | || line.starts_with("diff -U") |
| 292 | || line.starts_with("--- ") |
| 293 | || line.starts_with("Only in ") |
| 294 | { |
| 295 | Source::DiffUnified |
| 296 | } else { |
| 297 | Source::Unknown |
| 298 | } |
| 299 | } |