| 1 | //! Diff rendering helpers for TUI previews. |
| 2 | |
| 3 | use std::borrow::Cow; |
| 4 | |
| 5 | use ratatui::style::{Modifier, Style}; |
| 6 | use ratatui::text::{Line, Span}; |
| 7 | use similar::{ChangeTag, TextDiff}; |
| 8 | use unicode_segmentation::UnicodeSegmentation; |
| 9 | use unicode_width::UnicodeWidthStr; |
| 10 | |
| 11 | use codewhale_palette as palette; |
| 12 | |
| 13 | const LINE_NUMBER_WIDTH: usize = 4; |
| 14 | const MAX_RETAINED_ROWS: usize = 512; |
| 15 | const MAX_ROW_BYTES: usize = 32 * 1024; |
| 16 | const INTRALINE_MAX_BYTES: usize = 8 * 1024; |
| 17 | const INTRALINE_MAX_TOKENS: usize = 256; |
| 18 | const INTRALINE_MAX_WORK: usize = 65_536; |
| 19 | const INTRALINE_RUN_BYTES: usize = 128 * 1024; |
| 20 | const INTRALINE_RUN_WORK: usize = 1_048_576; |
| 21 | |
| 22 | /// Below this word-level similarity a replaced line pair is rewritten, not |
| 23 | /// edited, and emphasising the changed words would light up the whole row. |
| 24 | const INTRALINE_MIN_RATIO: f32 = 0.5; |
| 25 | |
| 26 | /// Pairing stops here so a huge hunk cannot buffer word segments for every |
| 27 | /// replaced line; longer runs render line by line. |
| 28 | const INTRALINE_MAX_RUN: usize = 64; |
| 29 | |
| 30 | /// A run of text inside a changed line and whether it is part of the change. |
| 31 | type Segment = (String, bool); |
| 32 | |
| 33 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 34 | pub struct DiffFileSummary<'a> { |
| 35 | pub path: &'a str, |
| 36 | pub added: usize, |
| 37 | pub deleted: usize, |
| 38 | pub hunks: usize, |
| 39 | } |
| 40 | |
| 41 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 42 | pub struct DiffTotals { |
| 43 | pub files: usize, |
| 44 | pub added: usize, |
| 45 | pub deleted: usize, |
| 46 | pub hunks: usize, |
| 47 | } |
| 48 | |
| 49 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 50 | pub struct DiffSummaryLabels { |
| 51 | pub summary: Cow<'static, str>, |
| 52 | pub file_one: Cow<'static, str>, |
| 53 | pub file_many: Cow<'static, str>, |
| 54 | pub hunk_one: Cow<'static, str>, |
| 55 | pub hunk_many: Cow<'static, str>, |
| 56 | } |
| 57 | |
| 58 | impl Default for DiffSummaryLabels { |
| 59 | fn default() -> Self { |
| 60 | Self { |
| 61 | summary: Cow::Borrowed("summary: {files}, +{added} -{deleted}, {hunks}"), |
| 62 | file_one: Cow::Borrowed("{count} file"), |
| 63 | file_many: Cow::Borrowed("{count} files"), |
| 64 | hunk_one: Cow::Borrowed("{count} hunk"), |
| 65 | hunk_many: Cow::Borrowed("{count} hunks"), |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | impl DiffSummaryLabels { |
| 71 | fn files(&self, count: usize) -> String { |
| 72 | counted(count, &self.file_one, &self.file_many) |
| 73 | } |
| 74 | |
| 75 | fn hunks(&self, count: usize) -> String { |
| 76 | counted(count, &self.hunk_one, &self.hunk_many) |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | fn counted(count: usize, one: &str, many: &str) -> String { |
| 81 | let template = if count == 1 { one } else { many }; |
| 82 | template.replace("{count}", &count.to_string()) |
| 83 | } |
| 84 | |
| 85 | /// A rendered diff preview with an exact count of rows not retained. |
| 86 | /// |
| 87 | /// The renderer scans the complete diff so summaries and omission counts stay |
| 88 | /// truthful, retaining only a finite row window and bounded text per row. |
| 89 | #[derive(Debug, Clone)] |
| 90 | pub struct BoundedDiffRender { |
| 91 | pub lines: Vec<Line<'static>>, |
| 92 | pub origins: Vec<usize>, |
| 93 | pub omitted_rows: usize, |
| 94 | pub omitted_summary_rows: usize, |
| 95 | pub omitted_body_rows: usize, |
| 96 | pub clipped_rows: usize, |
| 97 | pub clipped_bytes: usize, |
| 98 | } |
| 99 | |
| 100 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 101 | pub struct DiffSearchResult { |
| 102 | pub total_matches: usize, |
| 103 | pub selected_index: usize, |
| 104 | pub selected_row: Option<usize>, |
| 105 | pub selected_origin: Option<usize>, |
| 106 | } |
| 107 | |
| 108 | pub fn render_diff(diff: &str, width: u16) -> Vec<Line<'static>> { |
| 109 | let mut rendered = render_diff_bounded( |
| 110 | diff, |
| 111 | width, |
| 112 | MAX_RETAINED_ROWS, |
| 113 | &DiffSummaryLabels::default(), |
| 114 | ); |
| 115 | if rendered.omitted_rows > 0 { |
| 116 | rendered.lines.pop(); |
| 117 | let notice = format!("+{} …", rendered.omitted_rows.saturating_add(1)); |
| 118 | let notice = if crate::ui_text::text_display_width(¬ice) <= usize::from(width.max(1)) { |
| 119 | notice |
| 120 | } else { |
| 121 | "…".to_string() |
| 122 | }; |
| 123 | rendered.lines.push(Line::from(Span::styled( |
| 124 | notice, |
| 125 | Style::default().fg(palette::TEXT_MUTED), |
| 126 | ))); |
| 127 | } |
| 128 | rendered.lines |
| 129 | } |
| 130 | |
| 131 | /// Render a diff summary and body within one finite total row budget. |
| 132 | #[must_use] |
| 133 | pub fn render_diff_bounded( |
| 134 | diff: &str, |
| 135 | width: u16, |
| 136 | max_rows: usize, |
| 137 | labels: &DiffSummaryLabels, |
| 138 | ) -> BoundedDiffRender { |
| 139 | render_diff_window(diff, width, 0, max_rows, labels) |
| 140 | } |
| 141 | |
| 142 | #[must_use] |
| 143 | pub fn render_diff_window( |
| 144 | diff: &str, |
| 145 | width: u16, |
| 146 | start_row: usize, |
| 147 | max_rows: usize, |
| 148 | labels: &DiffSummaryLabels, |
| 149 | ) -> BoundedDiffRender { |
| 150 | let mut collector = BoundedLineCollector::new(start_row, max_rows); |
| 151 | render_diff_into(diff, width, Some(labels), &mut collector); |
| 152 | collector.finish() |
| 153 | } |
| 154 | |
| 155 | /// Render only the diff body. Callers that already own a semantic summary use |
| 156 | /// this form so the bounded preview budget is spent on the actual red/green |
| 157 | /// evidence instead of a second, generic summary. |
| 158 | /// Allocation is bounded by the retained rows and the current replacement run; |
| 159 | /// skipped wrapped rows and no-newline markers do not accumulate in vectors. |
| 160 | #[must_use] |
| 161 | pub fn render_diff_body_bounded(diff: &str, width: u16, max_rows: usize) -> BoundedDiffRender { |
| 162 | let mut collector = BoundedLineCollector::new(0, max_rows); |
| 163 | render_diff_into(diff, width, None, &mut collector); |
| 164 | collector.finish() |
| 165 | } |
| 166 | |
| 167 | #[must_use] |
| 168 | pub fn search_diff( |
| 169 | diff: &str, |
| 170 | width: u16, |
| 171 | query: &str, |
| 172 | match_index: usize, |
| 173 | labels: &DiffSummaryLabels, |
| 174 | ) -> DiffSearchResult { |
| 175 | let query = query.trim(); |
| 176 | if query.is_empty() { |
| 177 | return DiffSearchResult::default(); |
| 178 | } |
| 179 | let mut collector = BoundedLineCollector::new(0, 0); |
| 180 | collector.search = Some((query.to_ascii_lowercase(), match_index)); |
| 181 | render_diff_into(diff, width, Some(labels), &mut collector); |
| 182 | collector.search_result |
| 183 | } |
| 184 | |
| 185 | #[must_use] |
| 186 | pub fn search_diff_from_origin( |
| 187 | diff: &str, |
| 188 | width: u16, |
| 189 | query: &str, |
| 190 | origin: usize, |
| 191 | labels: &DiffSummaryLabels, |
| 192 | ) -> DiffSearchResult { |
| 193 | let query = query.trim(); |
| 194 | if query.is_empty() { |
| 195 | return DiffSearchResult::default(); |
| 196 | } |
| 197 | let mut collector = BoundedLineCollector::new(0, 0); |
| 198 | collector.search = Some((query.to_ascii_lowercase(), 0)); |
| 199 | collector.search_origin = Some(origin); |
| 200 | render_diff_into(diff, width, Some(labels), &mut collector); |
| 201 | collector.search_result |
| 202 | } |
| 203 | |
| 204 | #[must_use] |
| 205 | pub fn diff_row_for_origin( |
| 206 | diff: &str, |
| 207 | width: u16, |
| 208 | origin: usize, |
| 209 | labels: &DiffSummaryLabels, |
| 210 | ) -> usize { |
| 211 | let mut collector = BoundedLineCollector::new(0, 0); |
| 212 | collector.anchor_origin = Some(origin); |
| 213 | render_diff_into(diff, width, Some(labels), &mut collector); |
| 214 | collector |
| 215 | .anchor_row |
| 216 | .unwrap_or_else(|| collector.total_rows.saturating_sub(1)) |
| 217 | } |
| 218 | |
| 219 | fn render_diff_into( |
| 220 | diff: &str, |
| 221 | width: u16, |
| 222 | summary: Option<&DiffSummaryLabels>, |
| 223 | collector: &mut BoundedLineCollector, |
| 224 | ) { |
| 225 | let totals = if summary.is_some() { |
| 226 | diff_totals(diff) |
| 227 | } else { |
| 228 | DiffTotals::default() |
| 229 | }; |
| 230 | let origin_offset = usize::from(totals.files > 0); |
| 231 | if let Some(labels) = summary |
| 232 | && totals.files > 0 |
| 233 | { |
| 234 | render_diff_summary(diff, totals, labels, width, collector); |
| 235 | collector.summary_rows = collector.total_rows; |
| 236 | collector.summary_retained = collector.lines.len(); |
| 237 | } |
| 238 | let mut old_line = None; |
| 239 | let mut new_line = None; |
| 240 | let mut lines = diff.lines().enumerate().peekable(); |
| 241 | 'line: while let Some((origin, raw)) = lines.next() { |
| 242 | let origin = origin.saturating_add(origin_offset); |
| 243 | if raw.starts_with("diff --git") |
| 244 | || raw.starts_with("index ") |
| 245 | || raw.starts_with("--- ") |
| 246 | || raw.starts_with("+++ ") |
| 247 | { |
| 248 | render_header_line(raw, width, origin, collector); |
| 249 | continue; |
| 250 | } |
| 251 | if raw.starts_with("@@") { |
| 252 | if let Some((old_start, new_start)) = parse_hunk_header(raw) { |
| 253 | old_line = Some(old_start); |
| 254 | new_line = Some(new_start); |
| 255 | } |
| 256 | render_styled_text( |
| 257 | &[raw], |
| 258 | Style::default().fg(palette::WHALE_ACTION), |
| 259 | width, |
| 260 | origin, |
| 261 | collector, |
| 262 | ); |
| 263 | continue; |
| 264 | } |
| 265 | if is_no_newline_marker(raw) { |
| 266 | render_header_line(raw, width, origin, collector); |
| 267 | continue; |
| 268 | } |
| 269 | if is_added(raw) { |
| 270 | render_plain_diff_line( |
| 271 | collector, |
| 272 | &raw[1..], |
| 273 | width, |
| 274 | origin, |
| 275 | &mut old_line, |
| 276 | &mut new_line, |
| 277 | '+', |
| 278 | ); |
| 279 | continue; |
| 280 | } |
| 281 | if is_deleted(raw) { |
| 282 | // A deleted run followed by an added run of the same length is a |
| 283 | // set of replaced lines: emphasise the words that changed within |
| 284 | // each pair. Any other shape renders line by line as before. |
| 285 | let mut removed = vec![RunLine::new(&raw[1..], origin)]; |
| 286 | let mut added: Vec<RunLine<'_>> = Vec::new(); |
| 287 | loop { |
| 288 | if let Some((marker_origin, marker)) = |
| 289 | lines.next_if(|(_, next)| is_no_newline_marker(next)) |
| 290 | { |
| 291 | let line = if added.is_empty() { |
| 292 | removed.last_mut() |
| 293 | } else { |
| 294 | added.last_mut() |
| 295 | }; |
| 296 | if let Some(line) = line { |
| 297 | line.marker(diff, marker, marker_origin.saturating_add(origin_offset)); |
| 298 | } |
| 299 | } else if added.is_empty() |
| 300 | && let Some((next_origin, next)) = lines.next_if(|(_, next)| is_deleted(next)) |
| 301 | { |
| 302 | let origin = next_origin.saturating_add(origin_offset); |
| 303 | if removed.len() < INTRALINE_MAX_RUN { |
| 304 | removed.push(RunLine::new(&next[1..], origin)); |
| 305 | } else { |
| 306 | flush_plain_run( |
| 307 | collector, |
| 308 | &removed, |
| 309 | '-', |
| 310 | width, |
| 311 | &mut old_line, |
| 312 | &mut new_line, |
| 313 | ); |
| 314 | render_plain_diff_line( |
| 315 | collector, |
| 316 | &next[1..], |
| 317 | width, |
| 318 | origin, |
| 319 | &mut old_line, |
| 320 | &mut new_line, |
| 321 | '-', |
| 322 | ); |
| 323 | continue 'line; |
| 324 | } |
| 325 | } else if let Some((next_origin, next)) = lines.next_if(|(_, next)| is_added(next)) |
| 326 | { |
| 327 | let origin = next_origin.saturating_add(origin_offset); |
| 328 | if added.len() < INTRALINE_MAX_RUN { |
| 329 | added.push(RunLine::new(&next[1..], origin)); |
| 330 | } else { |
| 331 | flush_plain_run( |
| 332 | collector, |
| 333 | &removed, |
| 334 | '-', |
| 335 | width, |
| 336 | &mut old_line, |
| 337 | &mut new_line, |
| 338 | ); |
| 339 | flush_plain_run( |
| 340 | collector, |
| 341 | &added, |
| 342 | '+', |
| 343 | width, |
| 344 | &mut old_line, |
| 345 | &mut new_line, |
| 346 | ); |
| 347 | render_plain_diff_line( |
| 348 | collector, |
| 349 | &next[1..], |
| 350 | width, |
| 351 | origin, |
| 352 | &mut old_line, |
| 353 | &mut new_line, |
| 354 | '+', |
| 355 | ); |
| 356 | continue 'line; |
| 357 | } |
| 358 | } else { |
| 359 | break; |
| 360 | } |
| 361 | } |
| 362 | let mut byte_budget = INTRALINE_RUN_BYTES; |
| 363 | let mut work_budget = INTRALINE_RUN_WORK; |
| 364 | let pairs: Vec<_> = if removed.len() == added.len() { |
| 365 | removed |
| 366 | .iter() |
| 367 | .zip(&added) |
| 368 | .map(|(old, new)| { |
| 369 | intraline_segments( |
| 370 | old.content, |
| 371 | new.content, |
| 372 | &mut byte_budget, |
| 373 | &mut work_budget, |
| 374 | ) |
| 375 | }) |
| 376 | .collect() |
| 377 | } else { |
| 378 | Vec::new() |
| 379 | }; |
| 380 | for (sign, run) in [('-', &removed), ('+', &added)] { |
| 381 | for (index, line) in run.iter().enumerate() { |
| 382 | let emphasis = |
| 383 | pairs |
| 384 | .get(index) |
| 385 | .and_then(|pair| pair.as_ref()) |
| 386 | .map(|(old, new)| { |
| 387 | if sign == '-' { |
| 388 | old.as_slice() |
| 389 | } else { |
| 390 | new.as_slice() |
| 391 | } |
| 392 | }); |
| 393 | let style = if sign == '-' { |
| 394 | deleted_style() |
| 395 | } else { |
| 396 | added_style() |
| 397 | }; |
| 398 | render_diff_line( |
| 399 | line.content, |
| 400 | width, |
| 401 | old_line, |
| 402 | new_line, |
| 403 | sign, |
| 404 | style, |
| 405 | emphasis, |
| 406 | line.origin, |
| 407 | collector, |
| 408 | ); |
| 409 | increment_line(sign, &mut old_line, &mut new_line); |
| 410 | line.render_markers(width, collector); |
| 411 | } |
| 412 | } |
| 413 | continue; |
| 414 | } |
| 415 | if let Some(content) = raw.strip_prefix(' ') { |
| 416 | render_diff_line( |
| 417 | content, |
| 418 | width, |
| 419 | old_line, |
| 420 | new_line, |
| 421 | ' ', |
| 422 | Style::default().fg(palette::TEXT_PRIMARY), |
| 423 | None, |
| 424 | origin, |
| 425 | collector, |
| 426 | ); |
| 427 | increment_line(' ', &mut old_line, &mut new_line); |
| 428 | continue; |
| 429 | } |
| 430 | render_header_line(raw, width, origin, collector); |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | struct RunLine<'a> { |
| 435 | content: &'a str, |
| 436 | origin: usize, |
| 437 | markers: &'a str, |
| 438 | marker_origin: usize, |
| 439 | } |
| 440 | |
| 441 | impl<'a> RunLine<'a> { |
| 442 | fn new(content: &'a str, origin: usize) -> Self { |
| 443 | Self { |
| 444 | content, |
| 445 | origin, |
| 446 | markers: "", |
| 447 | marker_origin: 0, |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | fn marker(&mut self, diff: &'a str, marker: &'a str, origin: usize) { |
| 452 | let start = if self.markers.is_empty() { |
| 453 | self.marker_origin = origin; |
| 454 | marker.as_ptr() as usize - diff.as_ptr() as usize |
| 455 | } else { |
| 456 | self.markers.as_ptr() as usize - diff.as_ptr() as usize |
| 457 | }; |
| 458 | let end = marker.as_ptr() as usize - diff.as_ptr() as usize + marker.len(); |
| 459 | self.markers = &diff[start..end]; |
| 460 | } |
| 461 | |
| 462 | fn render_markers(&self, width: u16, collector: &mut BoundedLineCollector) { |
| 463 | for (index, marker) in self.markers.lines().enumerate() { |
| 464 | render_header_line( |
| 465 | marker, |
| 466 | width, |
| 467 | self.marker_origin.saturating_add(index), |
| 468 | collector, |
| 469 | ); |
| 470 | } |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | struct BoundedLineCollector { |
| 475 | lines: Vec<Line<'static>>, |
| 476 | origins: Vec<usize>, |
| 477 | start_row: usize, |
| 478 | max_rows: usize, |
| 479 | total_rows: usize, |
| 480 | summary_rows: usize, |
| 481 | summary_retained: usize, |
| 482 | clipped_rows: usize, |
| 483 | clipped_bytes: usize, |
| 484 | search: Option<(String, usize)>, |
| 485 | search_origin: Option<usize>, |
| 486 | search_origin_found: bool, |
| 487 | search_result: DiffSearchResult, |
| 488 | anchor_origin: Option<usize>, |
| 489 | anchor_row: Option<usize>, |
| 490 | } |
| 491 | |
| 492 | #[derive(Clone, Copy)] |
| 493 | struct RowCapture { |
| 494 | start: usize, |
| 495 | end: usize, |
| 496 | search: bool, |
| 497 | bytes: usize, |
| 498 | columns: usize, |
| 499 | } |
| 500 | |
| 501 | impl RowCapture { |
| 502 | fn keeps(self, row: usize) -> bool { |
| 503 | self.search || (self.start..self.end).contains(&row) |
| 504 | } |
| 505 | } |
| 506 | |
| 507 | impl BoundedLineCollector { |
| 508 | fn new(start_row: usize, max_rows: usize) -> Self { |
| 509 | let max_rows = max_rows.min(MAX_RETAINED_ROWS); |
| 510 | Self { |
| 511 | lines: Vec::with_capacity(max_rows.min(256)), |
| 512 | origins: Vec::with_capacity(max_rows.min(256)), |
| 513 | start_row, |
| 514 | max_rows, |
| 515 | total_rows: 0, |
| 516 | summary_rows: 0, |
| 517 | summary_retained: 0, |
| 518 | clipped_rows: 0, |
| 519 | clipped_bytes: 0, |
| 520 | search: None, |
| 521 | search_origin: None, |
| 522 | search_origin_found: false, |
| 523 | search_result: DiffSearchResult::default(), |
| 524 | anchor_origin: None, |
| 525 | anchor_row: None, |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | fn capture(&self, bytes: usize, columns: usize) -> RowCapture { |
| 530 | RowCapture { |
| 531 | start: self.start_row.saturating_sub(self.total_rows), |
| 532 | end: self |
| 533 | .start_row |
| 534 | .saturating_add(self.max_rows) |
| 535 | .saturating_sub(self.total_rows), |
| 536 | search: self.search.is_some(), |
| 537 | bytes, |
| 538 | columns, |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | fn push( |
| 543 | &mut self, |
| 544 | row: WrappedRow, |
| 545 | origin: usize, |
| 546 | prefix: &str, |
| 547 | make_line: impl FnOnce(String) -> Line<'static>, |
| 548 | ) { |
| 549 | if self.anchor_row.is_none() && self.anchor_origin.is_some_and(|target| origin >= target) { |
| 550 | self.anchor_row = Some(self.total_rows); |
| 551 | } |
| 552 | if let Some((query, selected)) = &self.search { |
| 553 | let mut text = String::with_capacity(prefix.len().saturating_add(row.text.len())); |
| 554 | text.push_str(prefix); |
| 555 | text.push_str(&row.text); |
| 556 | if text.to_ascii_lowercase().contains(query) { |
| 557 | let selected = match self.search_origin { |
| 558 | Some(target) => { |
| 559 | let first = self.search_result.total_matches == 0; |
| 560 | let anchored = !self.search_origin_found && origin >= target; |
| 561 | self.search_origin_found |= anchored; |
| 562 | first || anchored |
| 563 | } |
| 564 | None => self.search_result.total_matches == *selected, |
| 565 | }; |
| 566 | if selected { |
| 567 | self.search_result.selected_index = self.search_result.total_matches; |
| 568 | self.search_result.selected_row = Some(self.total_rows); |
| 569 | self.search_result.selected_origin = Some(origin); |
| 570 | } |
| 571 | self.search_result.total_matches = |
| 572 | self.search_result.total_matches.saturating_add(1); |
| 573 | } |
| 574 | } |
| 575 | if self.total_rows >= self.start_row && self.lines.len() < self.max_rows { |
| 576 | if row.clipped_bytes > 0 { |
| 577 | self.clipped_rows = self.clipped_rows.saturating_add(1); |
| 578 | self.clipped_bytes = self.clipped_bytes.saturating_add(row.clipped_bytes); |
| 579 | } |
| 580 | self.lines.push(make_line(row.text)); |
| 581 | self.origins.push(origin); |
| 582 | } |
| 583 | self.total_rows = self.total_rows.saturating_add(1); |
| 584 | } |
| 585 | |
| 586 | fn finish(self) -> BoundedDiffRender { |
| 587 | BoundedDiffRender { |
| 588 | omitted_rows: self.total_rows.saturating_sub(self.lines.len()), |
| 589 | omitted_summary_rows: self.summary_rows.saturating_sub(self.summary_retained), |
| 590 | omitted_body_rows: self |
| 591 | .total_rows |
| 592 | .saturating_sub(self.summary_rows) |
| 593 | .saturating_sub(self.lines.len().saturating_sub(self.summary_retained)), |
| 594 | lines: self.lines, |
| 595 | origins: self.origins, |
| 596 | clipped_rows: self.clipped_rows, |
| 597 | clipped_bytes: self.clipped_bytes, |
| 598 | } |
| 599 | } |
| 600 | } |
| 601 | |
| 602 | pub fn summarize_diff(diff: &str) -> impl Iterator<Item = DiffFileSummary<'_>> { |
| 603 | let mut lines = diff.lines(); |
| 604 | let mut current: Option<DiffFileSummary<'_>> = None; |
| 605 | std::iter::from_fn(move || { |
| 606 | for raw in lines.by_ref() { |
| 607 | if raw.starts_with("diff --git ") { |
| 608 | let previous = current.take(); |
| 609 | current = Some(DiffFileSummary { |
| 610 | path: parse_diff_git_path(raw).unwrap_or("<file>"), |
| 611 | added: 0, |
| 612 | deleted: 0, |
| 613 | hunks: 0, |
| 614 | }); |
| 615 | if let Some(summary) = previous |
| 616 | && summary.has_changes() |
| 617 | { |
| 618 | return Some(summary); |
| 619 | } |
| 620 | } else if raw.starts_with("+++ ") { |
| 621 | let path = raw.trim_start_matches("+++ ").trim_start_matches("b/"); |
| 622 | if path != "/dev/null" { |
| 623 | current.get_or_insert_with(DiffFileSummary::empty).path = path; |
| 624 | } |
| 625 | } else if raw.starts_with("@@") { |
| 626 | let summary = current.get_or_insert_with(DiffFileSummary::empty); |
| 627 | summary.hunks = summary.hunks.saturating_add(1); |
| 628 | } else if is_added(raw) { |
| 629 | let summary = current.get_or_insert_with(DiffFileSummary::empty); |
| 630 | summary.added = summary.added.saturating_add(1); |
| 631 | } else if is_deleted(raw) { |
| 632 | let summary = current.get_or_insert_with(DiffFileSummary::empty); |
| 633 | summary.deleted = summary.deleted.saturating_add(1); |
| 634 | } |
| 635 | } |
| 636 | current.take().filter(DiffFileSummary::has_changes) |
| 637 | }) |
| 638 | } |
| 639 | |
| 640 | #[must_use] |
| 641 | pub fn diff_totals(diff: &str) -> DiffTotals { |
| 642 | summarize_diff(diff).fold(DiffTotals::default(), |mut totals, summary| { |
| 643 | totals.files = totals.files.saturating_add(1); |
| 644 | totals.added = totals.added.saturating_add(summary.added); |
| 645 | totals.deleted = totals.deleted.saturating_add(summary.deleted); |
| 646 | totals.hunks = totals.hunks.saturating_add(summary.hunks); |
| 647 | totals |
| 648 | }) |
| 649 | } |
| 650 | |
| 651 | #[must_use] |
| 652 | pub fn diff_summary_label(diff: &str) -> Option<String> { |
| 653 | let totals = diff_totals(diff); |
| 654 | (totals.files > 0).then(|| { |
| 655 | format!( |
| 656 | "{} file{} +{} -{}", |
| 657 | totals.files, |
| 658 | if totals.files == 1 { "" } else { "s" }, |
| 659 | totals.added, |
| 660 | totals.deleted, |
| 661 | ) |
| 662 | }) |
| 663 | } |
| 664 | |
| 665 | impl DiffFileSummary<'_> { |
| 666 | fn empty() -> Self { |
| 667 | Self { |
| 668 | path: "<file>", |
| 669 | added: 0, |
| 670 | deleted: 0, |
| 671 | hunks: 0, |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | fn has_changes(&self) -> bool { |
| 676 | self.added > 0 || self.deleted > 0 || self.hunks > 0 |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | fn parse_diff_git_path(line: &str) -> Option<&str> { |
| 681 | line.split_whitespace() |
| 682 | .nth(3) |
| 683 | .map(|path| path.trim_start_matches("b/")) |
| 684 | } |
| 685 | |
| 686 | fn render_diff_summary( |
| 687 | diff: &str, |
| 688 | totals: DiffTotals, |
| 689 | labels: &DiffSummaryLabels, |
| 690 | width: u16, |
| 691 | collector: &mut BoundedLineCollector, |
| 692 | ) { |
| 693 | render_styled_text( |
| 694 | &[&labels |
| 695 | .summary |
| 696 | .replace("{files}", &labels.files(totals.files)) |
| 697 | .replace("{added}", &totals.added.to_string()) |
| 698 | .replace("{deleted}", &totals.deleted.to_string()) |
| 699 | .replace("{hunks}", &labels.hunks(totals.hunks))], |
| 700 | Style::default() |
| 701 | .fg(palette::TEXT_PRIMARY) |
| 702 | .add_modifier(Modifier::BOLD), |
| 703 | width, |
| 704 | 0, |
| 705 | collector, |
| 706 | ); |
| 707 | for summary in summarize_diff(diff) { |
| 708 | let counts = format!( |
| 709 | " +{} -{} {}", |
| 710 | summary.added, |
| 711 | summary.deleted, |
| 712 | labels.hunks(summary.hunks) |
| 713 | ); |
| 714 | render_styled_text( |
| 715 | &[" ", summary.path, &counts], |
| 716 | Style::default().fg(palette::TEXT_MUTED), |
| 717 | width, |
| 718 | 0, |
| 719 | collector, |
| 720 | ); |
| 721 | } |
| 722 | } |
| 723 | |
| 724 | fn parse_hunk_header(line: &str) -> Option<(usize, usize)> { |
| 725 | let mut parts = line.split_whitespace(); |
| 726 | parts.next()?; |
| 727 | let old = parts.next()?.trim_start_matches('-'); |
| 728 | let new = parts.next()?.trim_start_matches('+'); |
| 729 | Some(( |
| 730 | old.split(',').next()?.parse().ok()?, |
| 731 | new.split(',').next()?.parse().ok()?, |
| 732 | )) |
| 733 | } |
| 734 | |
| 735 | fn render_header_line(line: &str, width: u16, origin: usize, collector: &mut BoundedLineCollector) { |
| 736 | render_styled_text( |
| 737 | &[line], |
| 738 | Style::default() |
| 739 | .fg(palette::WHALE_ACTION) |
| 740 | .add_modifier(Modifier::BOLD), |
| 741 | width, |
| 742 | origin, |
| 743 | collector, |
| 744 | ); |
| 745 | } |
| 746 | |
| 747 | fn is_added(raw: &str) -> bool { |
| 748 | raw.starts_with('+') && !raw.starts_with("+++") |
| 749 | } |
| 750 | |
| 751 | fn is_deleted(raw: &str) -> bool { |
| 752 | raw.starts_with('-') && !raw.starts_with("---") |
| 753 | } |
| 754 | |
| 755 | fn is_no_newline_marker(raw: &str) -> bool { |
| 756 | raw.starts_with("\\ No newline") |
| 757 | } |
| 758 | |
| 759 | fn added_style() -> Style { |
| 760 | Style::default() |
| 761 | .fg(palette::DIFF_ADDED) |
| 762 | .bg(palette::DIFF_ADDED_BG) |
| 763 | } |
| 764 | |
| 765 | fn deleted_style() -> Style { |
| 766 | Style::default() |
| 767 | .fg(palette::STATUS_ERROR) |
| 768 | .bg(palette::DIFF_DELETED_BG) |
| 769 | } |
| 770 | |
| 771 | /// Split a replaced line pair into word runs (unicode word boundaries, so |
| 772 | /// punctuation stays out of the emphasis), flagging the runs that differ. |
| 773 | /// |
| 774 | /// Over-budget pairs and pairs sharing too few words stay plainly tinted. |
| 775 | fn intraline_segments( |
| 776 | old: &str, |
| 777 | new: &str, |
| 778 | byte_budget: &mut usize, |
| 779 | work_budget: &mut usize, |
| 780 | ) -> Option<(Vec<Segment>, Vec<Segment>)> { |
| 781 | let bytes = old.len().checked_add(new.len())?; |
| 782 | if bytes > INTRALINE_MAX_BYTES || bytes > *byte_budget { |
| 783 | return None; |
| 784 | } |
| 785 | let old_tokens = old |
| 786 | .split_word_bounds() |
| 787 | .take(INTRALINE_MAX_TOKENS + 1) |
| 788 | .count(); |
| 789 | let new_tokens = new |
| 790 | .split_word_bounds() |
| 791 | .take(INTRALINE_MAX_TOKENS + 1) |
| 792 | .count(); |
| 793 | let work = old_tokens.checked_mul(new_tokens)?.max(bytes); |
| 794 | if old_tokens > INTRALINE_MAX_TOKENS |
| 795 | || new_tokens > INTRALINE_MAX_TOKENS |
| 796 | || work > INTRALINE_MAX_WORK |
| 797 | || work > *work_budget |
| 798 | { |
| 799 | return None; |
| 800 | } |
| 801 | *byte_budget -= bytes; |
| 802 | *work_budget -= work; |
| 803 | let diff = TextDiff::from_unicode_words(old, new); |
| 804 | let mut old_segments = Vec::new(); |
| 805 | let mut new_segments = Vec::new(); |
| 806 | let mut changed = false; |
| 807 | let mut shared_words = 0usize; |
| 808 | let mut total_words = 0usize; |
| 809 | for change in diff.iter_all_changes() { |
| 810 | let text = change.value(); |
| 811 | let is_word = text.chars().any(char::is_alphanumeric); |
| 812 | match change.tag() { |
| 813 | ChangeTag::Equal => { |
| 814 | if is_word { |
| 815 | shared_words += 2; |
| 816 | total_words += 2; |
| 817 | } |
| 818 | push_segment(&mut old_segments, text, false); |
| 819 | push_segment(&mut new_segments, text, false); |
| 820 | } |
| 821 | ChangeTag::Delete => { |
| 822 | changed = true; |
| 823 | total_words += usize::from(is_word); |
| 824 | push_segment(&mut old_segments, text, true); |
| 825 | } |
| 826 | ChangeTag::Insert => { |
| 827 | changed = true; |
| 828 | total_words += usize::from(is_word); |
| 829 | push_segment(&mut new_segments, text, true); |
| 830 | } |
| 831 | } |
| 832 | } |
| 833 | if !changed || total_words == 0 { |
| 834 | return None; |
| 835 | } |
| 836 | let ratio = shared_words as f32 / total_words as f32; |
| 837 | (ratio >= INTRALINE_MIN_RATIO).then_some((old_segments, new_segments)) |
| 838 | } |
| 839 | |
| 840 | fn push_segment(segments: &mut Vec<Segment>, text: &str, emphasised: bool) { |
| 841 | match segments.last_mut() { |
| 842 | Some((run, flag)) if *flag == emphasised => run.push_str(text), |
| 843 | _ => segments.push((text.to_string(), emphasised)), |
| 844 | } |
| 845 | } |
| 846 | |
| 847 | /// Paint a retained wrapped chunk, mapping its non-whitespace characters back |
| 848 | /// to source flags. A mismatch keeps the whole row plainly tinted. |
| 849 | fn emphasised_chunk( |
| 850 | chunk: &str, |
| 851 | style: Style, |
| 852 | source: &[(char, bool)], |
| 853 | mut cursor: usize, |
| 854 | ) -> Option<Vec<Span<'static>>> { |
| 855 | let emphasis = style.add_modifier(Modifier::BOLD | Modifier::REVERSED); |
| 856 | let mut spans = Vec::new(); |
| 857 | let mut run = String::new(); |
| 858 | let mut run_flag = false; |
| 859 | let mut prev_flag = false; |
| 860 | for ch in chunk.chars() { |
| 861 | let flag = if ch.is_whitespace() { |
| 862 | prev_flag && source.get(cursor).is_some_and(|(_, next)| *next) |
| 863 | } else { |
| 864 | let (expected, flag) = *source.get(cursor)?; |
| 865 | if expected != ch { |
| 866 | return None; |
| 867 | } |
| 868 | cursor += 1; |
| 869 | prev_flag = flag; |
| 870 | flag |
| 871 | }; |
| 872 | if flag != run_flag && !run.is_empty() { |
| 873 | spans.push(Span::styled( |
| 874 | std::mem::take(&mut run), |
| 875 | if run_flag { emphasis } else { style }, |
| 876 | )); |
| 877 | } |
| 878 | run_flag = flag; |
| 879 | run.push(ch); |
| 880 | } |
| 881 | if !run.is_empty() { |
| 882 | spans.push(Span::styled(run, if run_flag { emphasis } else { style })); |
| 883 | } |
| 884 | Some(spans) |
| 885 | } |
| 886 | |
| 887 | fn increment_line(marker: char, old_line: &mut Option<usize>, new_line: &mut Option<usize>) { |
| 888 | if marker != '+' |
| 889 | && let Some(line) = old_line.as_mut() |
| 890 | { |
| 891 | *line = line.saturating_add(1); |
| 892 | } |
| 893 | if marker != '-' |
| 894 | && let Some(line) = new_line.as_mut() |
| 895 | { |
| 896 | *line = line.saturating_add(1); |
| 897 | } |
| 898 | } |
| 899 | |
| 900 | fn render_plain_diff_line( |
| 901 | collector: &mut BoundedLineCollector, |
| 902 | content: &str, |
| 903 | width: u16, |
| 904 | origin: usize, |
| 905 | old_line: &mut Option<usize>, |
| 906 | new_line: &mut Option<usize>, |
| 907 | marker: char, |
| 908 | ) { |
| 909 | let style = match marker { |
| 910 | '-' => deleted_style(), |
| 911 | '+' => added_style(), |
| 912 | _ => Style::default().fg(palette::TEXT_PRIMARY), |
| 913 | }; |
| 914 | render_diff_line( |
| 915 | content, width, *old_line, *new_line, marker, style, None, origin, collector, |
| 916 | ); |
| 917 | increment_line(marker, old_line, new_line); |
| 918 | } |
| 919 | |
| 920 | fn flush_plain_run( |
| 921 | collector: &mut BoundedLineCollector, |
| 922 | lines: &[RunLine<'_>], |
| 923 | sign: char, |
| 924 | width: u16, |
| 925 | old_line: &mut Option<usize>, |
| 926 | new_line: &mut Option<usize>, |
| 927 | ) { |
| 928 | for line in lines { |
| 929 | render_plain_diff_line( |
| 930 | collector, |
| 931 | line.content, |
| 932 | width, |
| 933 | line.origin, |
| 934 | old_line, |
| 935 | new_line, |
| 936 | sign, |
| 937 | ); |
| 938 | line.render_markers(width, collector); |
| 939 | } |
| 940 | } |
| 941 | |
| 942 | fn render_diff_line( |
| 943 | content: &str, |
| 944 | width: u16, |
| 945 | old_line: Option<usize>, |
| 946 | new_line: Option<usize>, |
| 947 | marker: char, |
| 948 | style: Style, |
| 949 | emphasis: Option<&[Segment]>, |
| 950 | origin: usize, |
| 951 | collector: &mut BoundedLineCollector, |
| 952 | ) { |
| 953 | let width = width.max(1); |
| 954 | let full_prefix = format_line_numbers(old_line, new_line, marker); |
| 955 | let prefix = if full_prefix.width() < usize::from(width) { |
| 956 | full_prefix |
| 957 | } else if width > 2 { |
| 958 | format!("{marker} ") |
| 959 | } else if width == 2 { |
| 960 | marker.to_string() |
| 961 | } else { |
| 962 | String::new() |
| 963 | }; |
| 964 | let prefix_width = prefix.width(); |
| 965 | // The whole logical row carries the change tint — numbers included. A |
| 966 | // bare gutter next to a painted body read as two unrelated strips. |
| 967 | let gutter_style = match style.bg { |
| 968 | Some(bg) => Style::default().fg(palette::TEXT_MUTED).bg(bg), |
| 969 | None => Style::default().fg(palette::TEXT_MUTED), |
| 970 | }; |
| 971 | let available = usize::from(width.saturating_sub(prefix_width as u16).max(1)); |
| 972 | let source = emphasis.map(|segments| { |
| 973 | segments |
| 974 | .iter() |
| 975 | .flat_map(|(run, flag)| { |
| 976 | run.chars() |
| 977 | .filter(|ch| !ch.is_whitespace()) |
| 978 | .map(move |ch| (ch, *flag)) |
| 979 | }) |
| 980 | .collect::<Vec<_>>() |
| 981 | }); |
| 982 | let capture = collector.capture(MAX_ROW_BYTES.saturating_sub(prefix.len()), available); |
| 983 | let continuation = " ".repeat(prefix_width); |
| 984 | wrap_parts(&[content], available, prefix_width, capture, |row| { |
| 985 | let gutter = if row.index == 0 { |
| 986 | prefix.as_str() |
| 987 | } else { |
| 988 | continuation.as_str() |
| 989 | }; |
| 990 | let nonspace_start = row.nonspace_start; |
| 991 | let clipped = row.clipped_bytes > 0; |
| 992 | collector.push(row, origin, gutter, |text| { |
| 993 | let mut spans = vec![Span::styled(gutter.to_string(), gutter_style)]; |
| 994 | if !clipped |
| 995 | && let Some(painted) = source |
| 996 | .as_ref() |
| 997 | .and_then(|source| emphasised_chunk(&text, style, source, nonspace_start)) |
| 998 | { |
| 999 | spans.extend(painted); |
| 1000 | } else { |
| 1001 | spans.push(Span::styled(text, style)); |
| 1002 | } |
| 1003 | Line::from(spans) |
| 1004 | }); |
| 1005 | }); |
| 1006 | } |
| 1007 | |
| 1008 | fn format_line_numbers(old_line: Option<usize>, new_line: Option<usize>, marker: char) -> String { |
| 1009 | let old = old_line |
| 1010 | .filter(|_| marker != '+') |
| 1011 | .map(|value| format!("{value:>LINE_NUMBER_WIDTH$}")) |
| 1012 | .unwrap_or_else(|| " ".repeat(LINE_NUMBER_WIDTH)); |
| 1013 | let new = new_line |
| 1014 | .filter(|_| marker != '-') |
| 1015 | .map(|value| format!("{value:>LINE_NUMBER_WIDTH$}")) |
| 1016 | .unwrap_or_else(|| " ".repeat(LINE_NUMBER_WIDTH)); |
| 1017 | format!("{old} {new} {marker} ") |
| 1018 | } |
| 1019 | |
| 1020 | fn render_styled_text( |
| 1021 | parts: &[&str], |
| 1022 | style: Style, |
| 1023 | width: u16, |
| 1024 | origin: usize, |
| 1025 | collector: &mut BoundedLineCollector, |
| 1026 | ) { |
| 1027 | let capture = collector.capture(MAX_ROW_BYTES, usize::from(width.max(1))); |
| 1028 | wrap_parts(parts, usize::from(width.max(1)), 0, capture, |row| { |
| 1029 | collector.push(row, origin, "", |text| { |
| 1030 | Line::from(Span::styled(text, style)) |
| 1031 | }); |
| 1032 | }); |
| 1033 | } |
| 1034 | |
| 1035 | struct WrappedRow { |
| 1036 | text: String, |
| 1037 | index: usize, |
| 1038 | nonspace_start: usize, |
| 1039 | clipped_bytes: usize, |
| 1040 | } |
| 1041 | |
| 1042 | struct RowBuffer { |
| 1043 | text: String, |
| 1044 | bytes: usize, |
| 1045 | nonspace_start: usize, |
| 1046 | nonspace_end: usize, |
| 1047 | keep: bool, |
| 1048 | limit: usize, |
| 1049 | columns: usize, |
| 1050 | stopped: bool, |
| 1051 | extra_clipped_bytes: usize, |
| 1052 | } |
| 1053 | |
| 1054 | impl RowBuffer { |
| 1055 | fn new(keep: bool, limit: usize, columns: usize, nonspace_start: usize) -> Self { |
| 1056 | Self { |
| 1057 | text: String::new(), |
| 1058 | bytes: 0, |
| 1059 | nonspace_start, |
| 1060 | nonspace_end: nonspace_start, |
| 1061 | keep, |
| 1062 | limit, |
| 1063 | columns, |
| 1064 | stopped: false, |
| 1065 | extra_clipped_bytes: 0, |
| 1066 | } |
| 1067 | } |
| 1068 | |
| 1069 | fn push(&mut self, text: &str) { |
| 1070 | self.append(text, text.chars().filter(|ch| !ch.is_whitespace()).count()); |
| 1071 | } |
| 1072 | |
| 1073 | fn whitespace(&mut self, text: &str) { |
| 1074 | self.append(text, 0); |
| 1075 | } |
| 1076 | |
| 1077 | fn lead(&mut self, lead: &DisplayLead) { |
| 1078 | self.whitespace(&lead.text); |
| 1079 | let omitted = lead.bytes.saturating_sub(lead.text.len()); |
| 1080 | self.bytes = self.bytes.saturating_add(omitted); |
| 1081 | self.stopped |= omitted > 0; |
| 1082 | } |
| 1083 | |
| 1084 | fn append(&mut self, text: &str, nonspace: usize) { |
| 1085 | self.bytes = self.bytes.saturating_add(text.len()); |
| 1086 | self.nonspace_end = self.nonspace_end.saturating_add(nonspace); |
| 1087 | if !self.keep || self.stopped { |
| 1088 | return; |
| 1089 | } |
| 1090 | let remaining = self.limit.saturating_sub(self.text.len()); |
| 1091 | let kept = if text.len() <= remaining { |
| 1092 | text.len() |
| 1093 | } else { |
| 1094 | self.stopped = true; |
| 1095 | text.grapheme_indices(true) |
| 1096 | .take_while(|(start, grapheme)| start.saturating_add(grapheme.len()) <= remaining) |
| 1097 | .map(|(start, grapheme)| start + grapheme.len()) |
| 1098 | .last() |
| 1099 | .unwrap_or(0) |
| 1100 | }; |
| 1101 | self.reserve(kept); |
| 1102 | self.text.push_str(&text[..kept]); |
| 1103 | } |
| 1104 | |
| 1105 | fn reserve(&mut self, additional: usize) { |
| 1106 | let needed = self.text.len().saturating_add(additional); |
| 1107 | if needed > self.text.capacity() { |
| 1108 | let capacity = needed |
| 1109 | .max(self.text.capacity().saturating_mul(2)) |
| 1110 | .max(64) |
| 1111 | .min(self.limit); |
| 1112 | self.text |
| 1113 | .reserve_exact(capacity.saturating_sub(self.text.len())); |
| 1114 | } |
| 1115 | } |
| 1116 | |
| 1117 | fn finish(mut self, index: usize) -> WrappedRow { |
| 1118 | let mut clipped_bytes = 0; |
| 1119 | if self.keep && self.bytes > self.text.len() { |
| 1120 | let marker = "…"; |
| 1121 | let byte_limit = self.limit.saturating_sub(marker.len()); |
| 1122 | let column_limit = self |
| 1123 | .columns |
| 1124 | .saturating_sub(crate::ui_text::text_display_width(marker)); |
| 1125 | let mut width = 0usize; |
| 1126 | let mut kept = 0usize; |
| 1127 | for (start, grapheme) in self.text.grapheme_indices(true) { |
| 1128 | let next_width = |
| 1129 | width.saturating_add(crate::ui_text::grapheme_display_width(grapheme)); |
| 1130 | let end = start.saturating_add(grapheme.len()); |
| 1131 | if next_width > column_limit || end > byte_limit { |
| 1132 | break; |
| 1133 | } |
| 1134 | width = next_width; |
| 1135 | kept = end; |
| 1136 | } |
| 1137 | self.text.truncate(kept); |
| 1138 | clipped_bytes = self.bytes.saturating_sub(self.text.len()); |
| 1139 | self.reserve(marker.len()); |
| 1140 | self.text.push_str(marker); |
| 1141 | } |
| 1142 | WrappedRow { |
| 1143 | text: self.text, |
| 1144 | index, |
| 1145 | nonspace_start: self.nonspace_start, |
| 1146 | clipped_bytes: clipped_bytes.saturating_add(self.extra_clipped_bytes), |
| 1147 | } |
| 1148 | } |
| 1149 | } |
| 1150 | |
| 1151 | struct DisplayLead { |
| 1152 | text: String, |
| 1153 | bytes: usize, |
| 1154 | width: usize, |
| 1155 | } |
| 1156 | |
| 1157 | fn needs_normalization(text: &str) -> bool { |
| 1158 | if text.is_ascii() { |
| 1159 | return text.bytes().any(|byte| byte < b' ' || byte == 127); |
| 1160 | } |
| 1161 | text.len() > crate::ui_text::MAX_DISPLAY_GRAPHEME_BYTES |
| 1162 | || text.chars().any(|ch| { |
| 1163 | codewhale_sanitize::sanitize::is_bidi_control(ch) |
| 1164 | || ch.is_control() |
| 1165 | || matches!(ch, '\u{2028}' | '\u{2029}') |
| 1166 | }) |
| 1167 | } |
| 1168 | |
| 1169 | fn word_width(word: &str) -> Option<(usize, bool)> { |
| 1170 | let normalize = needs_normalization(word); |
| 1171 | if !normalize { |
| 1172 | return Some((crate::ui_text::text_display_width(word), false)); |
| 1173 | } |
| 1174 | let mut width = 0usize; |
| 1175 | let mut any = false; |
| 1176 | crate::ui_text::display_graphemes(std::iter::once((word, 0)), 0, |grapheme| { |
| 1177 | any |= !grapheme.text.is_empty(); |
| 1178 | width = width.saturating_add(grapheme.width); |
| 1179 | }); |
| 1180 | any.then_some((width, true)) |
| 1181 | } |
| 1182 | |
| 1183 | fn word_graphemes(word: &str, normalize: bool, mut emit: impl FnMut(&str, usize)) { |
| 1184 | if normalize { |
| 1185 | crate::ui_text::display_graphemes(std::iter::once((word, 0)), 0, |grapheme| { |
| 1186 | let mut clipped = grapheme.clipped_bytes; |
| 1187 | for text in grapheme.text.graphemes(true) { |
| 1188 | emit(text, clipped); |
| 1189 | clipped = 0; |
| 1190 | } |
| 1191 | }); |
| 1192 | } else { |
| 1193 | for text in word.graphemes(true) { |
| 1194 | emit(text, 0); |
| 1195 | } |
| 1196 | } |
| 1197 | } |
| 1198 | |
| 1199 | fn wrap_parts( |
| 1200 | parts: &[&str], |
| 1201 | width: usize, |
| 1202 | start_column: usize, |
| 1203 | capture: RowCapture, |
| 1204 | mut emit: impl FnMut(WrappedRow), |
| 1205 | ) { |
| 1206 | let width = width.max(1); |
| 1207 | let mut lead_parts = Vec::with_capacity(parts.len()); |
| 1208 | for part in parts { |
| 1209 | let length = part.len() - part.trim_start().len(); |
| 1210 | lead_parts.push(&part[..length]); |
| 1211 | if length < part.len() { |
| 1212 | break; |
| 1213 | } |
| 1214 | } |
| 1215 | let mut lead_buffer = RowBuffer::new(true, MAX_ROW_BYTES, usize::MAX, 0); |
| 1216 | let mut lead_width = 0usize; |
| 1217 | if lead_parts.iter().any(|part| needs_normalization(part)) { |
| 1218 | crate::ui_text::display_graphemes( |
| 1219 | lead_parts.iter().map(|&part| (part, 0)), |
| 1220 | start_column, |
| 1221 | |grapheme| { |
| 1222 | lead_buffer.whitespace(grapheme.text); |
| 1223 | lead_width = lead_width.saturating_add(grapheme.width); |
| 1224 | }, |
| 1225 | ); |
| 1226 | } else { |
| 1227 | for part in &lead_parts { |
| 1228 | lead_buffer.whitespace(part); |
| 1229 | lead_width = lead_width.saturating_add(crate::ui_text::text_display_width(part)); |
| 1230 | } |
| 1231 | } |
| 1232 | let lead = DisplayLead { |
| 1233 | text: lead_buffer.text, |
| 1234 | bytes: lead_buffer.bytes, |
| 1235 | width: lead_width, |
| 1236 | }; |
| 1237 | let mut row_index = 0usize; |
| 1238 | let mut current = RowBuffer::new(capture.keeps(row_index), capture.bytes, capture.columns, 0); |
| 1239 | let repeat_lead = lead.width < width; |
| 1240 | let repeat_width = if repeat_lead { lead.width } else { 0 }; |
| 1241 | let mut current_width = 0usize; |
| 1242 | let mut has_word = false; |
| 1243 | let flush = |current: RowBuffer, row_index: &mut usize, emit: &mut dyn FnMut(WrappedRow)| { |
| 1244 | let next_nonspace = current.nonspace_end; |
| 1245 | emit(current.finish(*row_index)); |
| 1246 | *row_index = row_index.saturating_add(1); |
| 1247 | RowBuffer::new( |
| 1248 | capture.keeps(*row_index), |
| 1249 | capture.bytes, |
| 1250 | capture.columns, |
| 1251 | next_nonspace, |
| 1252 | ) |
| 1253 | }; |
| 1254 | if repeat_lead { |
| 1255 | current.lead(&lead); |
| 1256 | current_width = lead.width; |
| 1257 | } else { |
| 1258 | let mut visit = |text: &str| { |
| 1259 | let cell_width = crate::ui_text::grapheme_display_width(text); |
| 1260 | if current_width.saturating_add(cell_width) > width && current_width > 0 { |
| 1261 | let next = |
| 1262 | RowBuffer::new(false, capture.bytes, capture.columns, current.nonspace_end); |
| 1263 | current = flush( |
| 1264 | std::mem::replace(&mut current, next), |
| 1265 | &mut row_index, |
| 1266 | &mut emit, |
| 1267 | ); |
| 1268 | current_width = 0; |
| 1269 | } |
| 1270 | if cell_width > width { |
| 1271 | current.push("…"); |
| 1272 | current.extra_clipped_bytes = |
| 1273 | current.extra_clipped_bytes.saturating_add(text.len()); |
| 1274 | current_width = current_width.saturating_add(1); |
| 1275 | } else { |
| 1276 | current.whitespace(text); |
| 1277 | current_width = current_width.saturating_add(cell_width); |
| 1278 | } |
| 1279 | }; |
| 1280 | if lead_parts.iter().any(|part| needs_normalization(part)) { |
| 1281 | crate::ui_text::display_graphemes( |
| 1282 | lead_parts.iter().map(|&part| (part, 0)), |
| 1283 | start_column, |
| 1284 | |grapheme| { |
| 1285 | for text in grapheme.text.graphemes(true) { |
| 1286 | visit(text); |
| 1287 | } |
| 1288 | }, |
| 1289 | ); |
| 1290 | } else { |
| 1291 | for part in &lead_parts { |
| 1292 | for text in part.graphemes(true) { |
| 1293 | visit(text); |
| 1294 | } |
| 1295 | } |
| 1296 | } |
| 1297 | } |
| 1298 | for word in parts.iter().flat_map(|part| part.split_whitespace()) { |
| 1299 | let Some((word_width, normalize)) = word_width(word) else { |
| 1300 | continue; |
| 1301 | }; |
| 1302 | if word_width > width { |
| 1303 | if has_word { |
| 1304 | current = flush(current, &mut row_index, &mut emit); |
| 1305 | if repeat_lead { |
| 1306 | current.lead(&lead); |
| 1307 | } |
| 1308 | current_width = repeat_width; |
| 1309 | } |
| 1310 | word_graphemes(word, normalize, |text, clipped| { |
| 1311 | let grapheme_width = crate::ui_text::grapheme_display_width(text); |
| 1312 | if current_width.saturating_add(grapheme_width) > width && current_width > 0 { |
| 1313 | let next = |
| 1314 | RowBuffer::new(false, capture.bytes, capture.columns, current.nonspace_end); |
| 1315 | current = flush( |
| 1316 | std::mem::replace(&mut current, next), |
| 1317 | &mut row_index, |
| 1318 | &mut emit, |
| 1319 | ); |
| 1320 | current_width = 0; |
| 1321 | } |
| 1322 | if grapheme_width > width { |
| 1323 | current.push("…"); |
| 1324 | current.extra_clipped_bytes = current |
| 1325 | .extra_clipped_bytes |
| 1326 | .saturating_add(text.len()) |
| 1327 | .saturating_add(clipped); |
| 1328 | current_width = current_width.saturating_add(1); |
| 1329 | } else { |
| 1330 | current.push(text); |
| 1331 | current.extra_clipped_bytes = |
| 1332 | current.extra_clipped_bytes.saturating_add(clipped); |
| 1333 | current_width = current_width.saturating_add(grapheme_width); |
| 1334 | } |
| 1335 | }); |
| 1336 | has_word = current.nonspace_end > current.nonspace_start; |
| 1337 | continue; |
| 1338 | } |
| 1339 | let additional = if has_word { |
| 1340 | word_width.saturating_add(1) |
| 1341 | } else { |
| 1342 | word_width |
| 1343 | }; |
| 1344 | if current_width.saturating_add(additional) > width && has_word { |
| 1345 | current = flush(current, &mut row_index, &mut emit); |
| 1346 | if repeat_lead { |
| 1347 | current.lead(&lead); |
| 1348 | } |
| 1349 | current_width = repeat_width; |
| 1350 | has_word = false; |
| 1351 | } |
| 1352 | if has_word { |
| 1353 | current.whitespace(" "); |
| 1354 | current_width = current_width.saturating_add(1); |
| 1355 | } |
| 1356 | if current_width.saturating_add(word_width) > width && !has_word && current_width > 0 { |
| 1357 | current = flush(current, &mut row_index, &mut emit); |
| 1358 | current_width = 0; |
| 1359 | } |
| 1360 | if current_width == 0 |
| 1361 | && current.bytes == 0 |
| 1362 | && repeat_width > 0 |
| 1363 | && word_width.saturating_add(repeat_width) <= width |
| 1364 | { |
| 1365 | current.lead(&lead); |
| 1366 | current_width = repeat_width; |
| 1367 | } |
| 1368 | if normalize { |
| 1369 | crate::ui_text::display_graphemes(std::iter::once((word, 0)), 0, |grapheme| { |
| 1370 | current.push(grapheme.text); |
| 1371 | current.extra_clipped_bytes = current |
| 1372 | .extra_clipped_bytes |
| 1373 | .saturating_add(grapheme.clipped_bytes); |
| 1374 | }); |
| 1375 | } else { |
| 1376 | current.push(word); |
| 1377 | } |
| 1378 | current_width = current_width.saturating_add(word_width); |
| 1379 | has_word = true; |
| 1380 | } |
| 1381 | if has_word || current.bytes > 0 || row_index == 0 { |
| 1382 | emit(current.finish(row_index)); |
| 1383 | } |
| 1384 | } |
| 1385 | |
| 1386 | #[cfg(test)] |
| 1387 | fn wrap_text(text: &str, width: usize) -> Vec<String> { |
| 1388 | let mut lines = Vec::new(); |
| 1389 | wrap_parts( |
| 1390 | &[text], |
| 1391 | width, |
| 1392 | 0, |
| 1393 | RowCapture { |
| 1394 | start: 0, |
| 1395 | end: MAX_RETAINED_ROWS, |
| 1396 | search: false, |
| 1397 | bytes: MAX_ROW_BYTES, |
| 1398 | columns: width.max(1), |
| 1399 | }, |
| 1400 | |row| { |
| 1401 | if row.index < MAX_RETAINED_ROWS { |
| 1402 | lines.push(row.text); |
| 1403 | } |
| 1404 | }, |
| 1405 | ); |
| 1406 | lines |
| 1407 | } |
| 1408 | |
| 1409 | #[cfg(test)] |
| 1410 | mod tests { |
| 1411 | use super::*; |
| 1412 | |
| 1413 | fn line_text(line: &Line<'static>) -> String { |
| 1414 | line.spans |
| 1415 | .iter() |
| 1416 | .map(|span| span.content.as_ref()) |
| 1417 | .collect() |
| 1418 | } |
| 1419 | |
| 1420 | fn diff_content_text(line: &Line<'static>) -> Option<String> { |
| 1421 | line.spans |
| 1422 | .get(1..) |
| 1423 | .filter(|rest| !rest.is_empty()) |
| 1424 | .map(|rest| rest.iter().map(|span| span.content.as_ref()).collect()) |
| 1425 | } |
| 1426 | |
| 1427 | fn emphasised_text(line: &Line<'static>) -> String { |
| 1428 | line.spans |
| 1429 | .iter() |
| 1430 | .filter(|span| span.style.add_modifier.contains(Modifier::REVERSED)) |
| 1431 | .map(|span| span.content.as_ref()) |
| 1432 | .collect() |
| 1433 | } |
| 1434 | |
| 1435 | fn rendered_body(diff: &str, width: u16) -> Vec<Line<'static>> { |
| 1436 | render_diff_body_bounded(diff, width, MAX_RETAINED_ROWS).lines |
| 1437 | } |
| 1438 | |
| 1439 | /// Text between the gutter and the first emphasised span, so a test can |
| 1440 | /// pin where on the row the emphasis starts. |
| 1441 | fn text_before_emphasis(line: &Line<'static>) -> String { |
| 1442 | line.spans |
| 1443 | .iter() |
| 1444 | .skip(1) |
| 1445 | .take_while(|span| !span.style.add_modifier.contains(Modifier::REVERSED)) |
| 1446 | .map(|span| span.content.as_ref()) |
| 1447 | .collect() |
| 1448 | } |
| 1449 | |
| 1450 | fn emphasis_per_row(diff: &str, width: u16) -> Vec<String> { |
| 1451 | rendered_body(diff, width) |
| 1452 | .iter() |
| 1453 | .skip(1) // hunk header |
| 1454 | .map(emphasised_text) |
| 1455 | .collect() |
| 1456 | } |
| 1457 | |
| 1458 | #[test] |
| 1459 | fn replaced_line_pair_emphasises_only_the_changed_words() { |
| 1460 | let diff = "\ |
| 1461 | @@ -1,1 +1,1 @@ |
| 1462 | - let total = price * quantity; |
| 1463 | + let total = price * count; |
| 1464 | "; |
| 1465 | let rendered = rendered_body(diff, 80); |
| 1466 | assert_eq!(emphasis_per_row(diff, 80), vec!["quantity", "count"]); |
| 1467 | let content = rendered |
| 1468 | .iter() |
| 1469 | .filter_map(diff_content_text) |
| 1470 | .collect::<Vec<_>>(); |
| 1471 | assert_eq!( |
| 1472 | content, |
| 1473 | vec![ |
| 1474 | " let total = price * quantity;".to_string(), |
| 1475 | " let total = price * count;".to_string() |
| 1476 | ], |
| 1477 | "emphasis must not alter the line text" |
| 1478 | ); |
| 1479 | } |
| 1480 | |
| 1481 | #[test] |
| 1482 | fn every_pair_in_a_replaced_run_is_emphasised_in_order() { |
| 1483 | let diff = "\ |
| 1484 | @@ -1,2 +1,2 @@ |
| 1485 | -let alpha = 1; |
| 1486 | -let beta = 2; |
| 1487 | +let alpha = 10; |
| 1488 | +let beta = 20; |
| 1489 | "; |
| 1490 | assert_eq!(emphasis_per_row(diff, 80), vec!["1", "2", "10", "20"]); |
| 1491 | } |
| 1492 | |
| 1493 | #[test] |
| 1494 | fn a_rewrite_inside_a_replaced_run_stays_plain_while_its_neighbour_is_emphasised() { |
| 1495 | let diff = "\ |
| 1496 | @@ -1,2 +1,2 @@ |
| 1497 | -let x = 1; |
| 1498 | -fn old_name() {} |
| 1499 | +let x = 2; |
| 1500 | +return None; |
| 1501 | "; |
| 1502 | assert_eq!(emphasis_per_row(diff, 80), vec!["1", "", "2", ""]); |
| 1503 | } |
| 1504 | |
| 1505 | #[test] |
| 1506 | fn lines_sharing_only_syntax_are_not_emphasised() { |
| 1507 | // Whitespace, `=` and `;` agree; every word differs but `let`. |
| 1508 | let diff = "\ |
| 1509 | @@ -1,1 +1,1 @@ |
| 1510 | -let alpha = beta; |
| 1511 | +let gamma = delta; |
| 1512 | "; |
| 1513 | assert_eq!(emphasis_per_row(diff, 80), vec!["", ""]); |
| 1514 | } |
| 1515 | |
| 1516 | #[test] |
| 1517 | fn unequal_runs_render_without_emphasis() { |
| 1518 | let unequal = "\ |
| 1519 | @@ -1,2 +1,1 @@ |
| 1520 | -let a = 1; |
| 1521 | -let b = 2; |
| 1522 | +let a = 1; let b = 2; |
| 1523 | "; |
| 1524 | assert_eq!(emphasis_per_row(unequal, 80), vec!["", "", ""]); |
| 1525 | } |
| 1526 | |
| 1527 | #[test] |
| 1528 | fn emphasis_follows_unicode_word_boundaries() { |
| 1529 | let diff = "\ |
| 1530 | @@ -1,1 +1,1 @@ |
| 1531 | -café au lait, naïve |
| 1532 | +café au thé, naïve |
| 1533 | "; |
| 1534 | assert_eq!(emphasis_per_row(diff, 80), vec!["lait", "thé"]); |
| 1535 | } |
| 1536 | |
| 1537 | #[test] |
| 1538 | fn no_newline_marker_does_not_break_pairing() { |
| 1539 | let diff = "\ |
| 1540 | @@ -1,1 +1,1 @@ |
| 1541 | -old line |
| 1542 | \\ No newline at end of file |
| 1543 | +new line |
| 1544 | \\ No newline at end of file |
| 1545 | "; |
| 1546 | let rendered = rendered_body(diff, 80); |
| 1547 | let rows: Vec<String> = rendered.iter().map(emphasised_text).collect(); |
| 1548 | assert_eq!(rows, vec!["", "old", "", "new", ""]); |
| 1549 | let text: Vec<String> = rendered.iter().map(line_text).collect(); |
| 1550 | assert_eq!( |
| 1551 | text.iter() |
| 1552 | .filter(|row| row.contains("No newline at end of file")) |
| 1553 | .count(), |
| 1554 | 2, |
| 1555 | "markers are still shown: {text:?}" |
| 1556 | ); |
| 1557 | } |
| 1558 | |
| 1559 | #[test] |
| 1560 | fn pure_insertion_no_newline_marker_is_a_header_row() { |
| 1561 | let diff = "\ |
| 1562 | @@ -1,0 +1,1 @@ |
| 1563 | +inserted |
| 1564 | \\ No newline at end of file |
| 1565 | context |
| 1566 | "; |
| 1567 | let rendered = rendered_body(diff, 80); |
| 1568 | let marker = rendered |
| 1569 | .iter() |
| 1570 | .find(|line| line_text(line).contains("No newline at end of file")) |
| 1571 | .expect("marker row"); |
| 1572 | assert!(marker.spans[0].style.add_modifier.contains(Modifier::BOLD)); |
| 1573 | |
| 1574 | let context = rendered |
| 1575 | .iter() |
| 1576 | .find(|line| line_text(line).contains("context")) |
| 1577 | .expect("context row"); |
| 1578 | assert!( |
| 1579 | line_text(context).starts_with(" 1 2 "), |
| 1580 | "context numbering was changed by the marker: {context:?}" |
| 1581 | ); |
| 1582 | } |
| 1583 | |
| 1584 | #[test] |
| 1585 | fn emphasis_lands_on_the_right_chunk_of_a_wrapped_indented_line() { |
| 1586 | // Gutter is 12 columns; width 40 leaves 28 for text. With the 8-space |
| 1587 | // indent re-inserted on every continuation chunk, the line wraps as |
| 1588 | // " let total =" / " compute(alpha, beta," / |
| 1589 | // " gamma, quantity);" — the change sits on the third chunk. |
| 1590 | let diff = "\ |
| 1591 | @@ -1,1 +1,1 @@ |
| 1592 | - let total = compute(alpha, beta, gamma, quantity); |
| 1593 | + let total = compute(alpha, beta, gamma, count); |
| 1594 | "; |
| 1595 | let rendered = rendered_body(diff, 40); |
| 1596 | let rows: Vec<String> = rendered.iter().map(emphasised_text).collect(); |
| 1597 | assert_eq!(rows, vec!["", "", "", "quantity", "", "", "count"]); |
| 1598 | assert_eq!( |
| 1599 | diff_content_text(&rendered[3]).as_deref(), |
| 1600 | Some(" gamma, quantity);") |
| 1601 | ); |
| 1602 | assert_eq!(text_before_emphasis(&rendered[3]), " gamma, "); |
| 1603 | assert_eq!(text_before_emphasis(&rendered[6]), " gamma, "); |
| 1604 | // Row text is untouched by the emphasis. |
| 1605 | assert_eq!( |
| 1606 | diff_content_text(&rendered[6]).as_deref(), |
| 1607 | Some(" gamma, count);") |
| 1608 | ); |
| 1609 | } |
| 1610 | |
| 1611 | #[test] |
| 1612 | fn emphasis_survives_wrapping_without_changing_text() { |
| 1613 | let diff = "\ |
| 1614 | @@ -1,1 +1,1 @@ |
| 1615 | -alpha beta gamma delta epsilon zeta eta theta iota kappa |
| 1616 | +alpha beta gamma delta epsilon zeta eta THETA iota kappa |
| 1617 | "; |
| 1618 | let rendered = rendered_body(diff, 30); |
| 1619 | let rows: Vec<String> = rendered.iter().map(emphasised_text).collect(); |
| 1620 | // 18 text columns: "alpha beta gamma" / "delta epsilon zeta" / |
| 1621 | // "eta theta iota" / "kappa" — the change sits on the third chunk. |
| 1622 | assert_eq!(rows, vec!["", "", "", "theta", "", "", "", "THETA", ""]); |
| 1623 | assert_eq!(text_before_emphasis(&rendered[3]), "eta "); |
| 1624 | assert_eq!(text_before_emphasis(&rendered[7]), "eta "); |
| 1625 | // Wrapping drops the space at each break; everything else survives. |
| 1626 | let body: String = rendered |
| 1627 | .iter() |
| 1628 | .skip(1) |
| 1629 | .filter_map(diff_content_text) |
| 1630 | .collect::<String>() |
| 1631 | .split_whitespace() |
| 1632 | .collect(); |
| 1633 | assert_eq!( |
| 1634 | body, |
| 1635 | "alphabetagammadeltaepsilonzetaetathetaiotakappa\ |
| 1636 | alphabetagammadeltaepsilonzetaetaTHETAiotakappa" |
| 1637 | ); |
| 1638 | } |
| 1639 | |
| 1640 | #[test] |
| 1641 | fn summarizes_multi_file_diff() { |
| 1642 | let diff = "\ |
| 1643 | diff --git a/src/a.rs b/src/a.rs |
| 1644 | --- a/src/a.rs |
| 1645 | +++ b/src/a.rs |
| 1646 | @@ -1,2 +1,3 @@ |
| 1647 | line |
| 1648 | +new |
| 1649 | -old |
| 1650 | diff --git a/src/b.rs b/src/b.rs |
| 1651 | --- a/src/b.rs |
| 1652 | +++ b/src/b.rs |
| 1653 | @@ -10,0 +11,2 @@ |
| 1654 | +one |
| 1655 | +two |
| 1656 | "; |
| 1657 | |
| 1658 | let summaries = summarize_diff(diff).collect::<Vec<_>>(); |
| 1659 | assert_eq!(summaries.len(), 2); |
| 1660 | assert_eq!(summaries[0].path, "src/a.rs"); |
| 1661 | assert_eq!(summaries[0].added, 1); |
| 1662 | assert_eq!(summaries[0].deleted, 1); |
| 1663 | assert_eq!(summaries[1].path, "src/b.rs"); |
| 1664 | assert_eq!(summaries[1].added, 2); |
| 1665 | assert_eq!(summaries[1].deleted, 0); |
| 1666 | assert_eq!(diff_summary_label(diff).as_deref(), Some("2 files +3 -1")); |
| 1667 | } |
| 1668 | |
| 1669 | #[test] |
| 1670 | fn render_diff_prepends_summary_and_gutter_markers() { |
| 1671 | let diff = "\ |
| 1672 | diff --git a/src/a.rs b/src/a.rs |
| 1673 | --- a/src/a.rs |
| 1674 | +++ b/src/a.rs |
| 1675 | @@ -1,2 +1,3 @@ |
| 1676 | line |
| 1677 | +new |
| 1678 | -old |
| 1679 | "; |
| 1680 | |
| 1681 | let rendered = render_diff(diff, 80); |
| 1682 | let text = rendered.iter().map(line_text).collect::<Vec<_>>(); |
| 1683 | assert!(text[0].contains("summary: 1 file, +1 -1, 1 hunk")); |
| 1684 | assert!(text.iter().any(|line| line.contains("src/a.rs +1 -1"))); |
| 1685 | assert!( |
| 1686 | text.iter().any(|line| line.contains(" + new")), |
| 1687 | "added line should carry + gutter: {text:?}" |
| 1688 | ); |
| 1689 | assert!( |
| 1690 | text.iter().any(|line| line.contains(" - old")), |
| 1691 | "deleted line should carry - gutter: {text:?}" |
| 1692 | ); |
| 1693 | } |
| 1694 | |
| 1695 | #[test] |
| 1696 | fn render_diff_tints_the_gutter_with_the_row() { |
| 1697 | let diff = "\ |
| 1698 | diff --git a/src/a.rs b/src/a.rs |
| 1699 | --- a/src/a.rs |
| 1700 | +++ b/src/a.rs |
| 1701 | @@ -1,2 +1,3 @@ |
| 1702 | line |
| 1703 | +new |
| 1704 | -old |
| 1705 | "; |
| 1706 | |
| 1707 | let rendered = render_diff(diff, 80); |
| 1708 | let gutter_bg = |needle: &str| { |
| 1709 | rendered |
| 1710 | .iter() |
| 1711 | .find(|line| line_text(line).contains(needle)) |
| 1712 | .expect("diff row renders") |
| 1713 | .spans |
| 1714 | .first() |
| 1715 | .expect("gutter span") |
| 1716 | .style |
| 1717 | .bg |
| 1718 | }; |
| 1719 | assert_eq!( |
| 1720 | gutter_bg("+ new"), |
| 1721 | Some(palette::DIFF_ADDED_BG), |
| 1722 | "added numbers share the added tint" |
| 1723 | ); |
| 1724 | assert_eq!( |
| 1725 | gutter_bg("- old"), |
| 1726 | Some(palette::DIFF_DELETED_BG), |
| 1727 | "deleted numbers share the deleted tint" |
| 1728 | ); |
| 1729 | assert_eq!( |
| 1730 | gutter_bg(" line"), |
| 1731 | None, |
| 1732 | "context numbers stay on the bare ground" |
| 1733 | ); |
| 1734 | } |
| 1735 | |
| 1736 | #[test] |
| 1737 | fn wrap_text_preserves_leading_whitespace_without_extra_space() { |
| 1738 | assert_eq!(wrap_text(" let y = 2;", 80), vec![" let y = 2;"]); |
| 1739 | assert_eq!( |
| 1740 | wrap_text(" println!(\"hello\");", 80), |
| 1741 | vec![" println!(\"hello\");"] |
| 1742 | ); |
| 1743 | } |
| 1744 | |
| 1745 | #[test] |
| 1746 | fn render_diff_preserves_leading_whitespace_exactly() { |
| 1747 | let diff = "\ |
| 1748 | diff --git a/src/lib.rs b/src/lib.rs |
| 1749 | --- a/src/lib.rs |
| 1750 | +++ b/src/lib.rs |
| 1751 | @@ -1,2 +1,3 @@ |
| 1752 | fn main() { |
| 1753 | + let y = 2; |
| 1754 | + println!(\"{y}\"); |
| 1755 | } |
| 1756 | "; |
| 1757 | |
| 1758 | let rendered = render_diff(diff, 80); |
| 1759 | let content = rendered |
| 1760 | .iter() |
| 1761 | .filter_map(diff_content_text) |
| 1762 | .collect::<Vec<_>>(); |
| 1763 | |
| 1764 | assert!( |
| 1765 | content.iter().any(|line| line == " let y = 2;"), |
| 1766 | "added line should keep exact 4-space indent: {content:?}" |
| 1767 | ); |
| 1768 | assert!( |
| 1769 | content |
| 1770 | .iter() |
| 1771 | .any(|line| line == " println!(\"{y}\");"), |
| 1772 | "added line should keep exact 8-space indent: {content:?}" |
| 1773 | ); |
| 1774 | } |
| 1775 | |
| 1776 | #[test] |
| 1777 | fn wrap_text_breaks_overlong_cjk_runs() { |
| 1778 | let text = "这是一个非常长的中文字符串".repeat(10); |
| 1779 | let lines = wrap_text(&text, 16); |
| 1780 | |
| 1781 | for line in &lines { |
| 1782 | assert!(line.width() <= 16, "line {line:?} exceeds width 16"); |
| 1783 | } |
| 1784 | |
| 1785 | assert_eq!(lines.join(""), text); |
| 1786 | } |
| 1787 | |
| 1788 | #[test] |
| 1789 | fn wrap_text_breaks_overlong_words_between_graphemes() { |
| 1790 | // A ZWJ family and a skin-toned thumbs-up are one two-column grapheme |
| 1791 | // each, the way Ratatui counts cells. |
| 1792 | let word = "ab\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}\u{1f44d}\u{1f3fd}cd"; |
| 1793 | for width in 2..=6 { |
| 1794 | let lines = wrap_text(word, width); |
| 1795 | let rejoined: Vec<&str> = lines.iter().flat_map(|line| line.graphemes(true)).collect(); |
| 1796 | assert_eq!( |
| 1797 | rejoined, |
| 1798 | word.graphemes(true).collect::<Vec<_>>(), |
| 1799 | "width {width} split a grapheme: {lines:?}" |
| 1800 | ); |
| 1801 | for line in &lines { |
| 1802 | assert!(line.width() <= width, "line {line:?} exceeds width {width}"); |
| 1803 | } |
| 1804 | } |
| 1805 | } |
| 1806 | |
| 1807 | #[test] |
| 1808 | fn bounded_body_retains_only_budget_and_counts_wrapped_omissions() { |
| 1809 | let mut diff = String::from( |
| 1810 | "diff --git a/src/generated.rs b/src/generated.rs\n\ |
| 1811 | --- a/src/generated.rs\n\ |
| 1812 | +++ b/src/generated.rs\n\ |
| 1813 | @@ -1,0 +1,3000 @@\n", |
| 1814 | ); |
| 1815 | for index in 0..3_000 { |
| 1816 | use std::fmt::Write as _; |
| 1817 | writeln!( |
| 1818 | diff, |
| 1819 | "+ generated_{index:04} = a deliberately long value that wraps narrowly" |
| 1820 | ) |
| 1821 | .expect("append generated diff"); |
| 1822 | } |
| 1823 | |
| 1824 | let full_row_count = render_diff_body_bounded(&diff, 32, 0).omitted_rows; |
| 1825 | let rendered = render_diff_body_bounded(&diff, 32, 14); |
| 1826 | |
| 1827 | assert_eq!(rendered.lines.len(), 14); |
| 1828 | assert_eq!( |
| 1829 | rendered.omitted_rows, |
| 1830 | full_row_count.saturating_sub(rendered.lines.len()) |
| 1831 | ); |
| 1832 | let retained = rendered.lines.iter().map(line_text).collect::<Vec<_>>(); |
| 1833 | assert!( |
| 1834 | retained |
| 1835 | .iter() |
| 1836 | .any(|line| line.contains("@@ -1,0 +1,3000 @@")) |
| 1837 | ); |
| 1838 | assert!( |
| 1839 | retained |
| 1840 | .iter() |
| 1841 | .any(|line| line.contains(" + generated_0000")), |
| 1842 | "retained rows preserve gutters and leading whitespace: {retained:?}" |
| 1843 | ); |
| 1844 | } |
| 1845 | } |
| 1846 |