.cargo/
crates/
brain/
diff/
benches/
src/
bin/
themes/
viewer/
builtins.rs
13.4 KiB
commit.rs
7.0 KiB
context.rs
10.1 KiB
decode.rs
31.0 KiB
decorate.rs
4.2 KiB
document.rs
24.7 KiB
encode.rs
4.9 KiB
highlight.rs
24.4 KiB
highlighter.rs
12.4 KiB
lib.rs
2.0 KiB
status.rs
2.0 KiB
viewer.rs
183.1 KiB
word.rs
16.8 KiB
tests/
Cargo.toml
867 B
README.md
696 B
files/
highlight/
repo/
signals/
tui/
tui-core/
tui-termion/
tui-widgets/
scripts/
src/
.gitignore
30 B
.gitsigners
198 B
AGENTS.md
1.9 KiB
CONTRIBUTING
1.7 KiB
Cargo.lock
5.4 KiB
Cargo.toml
1.9 KiB
LICENSE
1.1 KiB
README.md
245 B
STYLE
3.7 KiB
clippy.toml
213 B
crates/diff/src/document.rs
raw
| 1 | //! Unified diff document model. |
| 2 | //! |
| 3 | //! Defines the data tree (`DiffDocument` → `FileDiff` → `Hunk` → `DiffLine`) |
| 4 | //! that callers consume. The decoder that produces these values lives in |
| 5 | //! [`crate::decode`]; `document` is intentionally model-only. |
| 6 | |
| 7 | pub use rustik_repo::{Oid, OidError}; |
| 8 | |
| 9 | use rustik_repo::DiffStat; |
| 10 | use std::fmt; |
| 11 | use std::io; |
| 12 | use std::num::ParseIntError; |
| 13 | use std::path::PathBuf; |
| 14 | |
| 15 | /// Stable identifier for a file section in one diff document. |
| 16 | #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] |
| 17 | pub struct FileId(usize); |
| 18 | |
| 19 | /// Stable identifier for a hunk in one diff document. |
| 20 | #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] |
| 21 | pub struct HunkId(usize); |
| 22 | |
| 23 | /// Stable identifier for a rendered hunk row in one diff document. |
| 24 | #[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] |
| 25 | pub struct RowId(usize); |
| 26 | |
| 27 | impl FileId { |
| 28 | /// Wraps a raw index as a [`FileId`]. |
| 29 | pub const fn new(index: usize) -> Self { |
| 30 | Self(index) |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | impl HunkId { |
| 35 | /// Wraps a raw index as a [`HunkId`]. |
| 36 | pub const fn new(index: usize) -> Self { |
| 37 | Self(index) |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | impl RowId { |
| 42 | /// Wraps a raw index as a [`RowId`]. |
| 43 | pub const fn new(index: usize) -> Self { |
| 44 | Self(index) |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | impl std::ops::Deref for FileId { |
| 49 | type Target = usize; |
| 50 | |
| 51 | fn deref(&self) -> &usize { |
| 52 | &self.0 |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | impl std::ops::Deref for HunkId { |
| 57 | type Target = usize; |
| 58 | |
| 59 | fn deref(&self) -> &usize { |
| 60 | &self.0 |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | impl std::ops::Deref for RowId { |
| 65 | type Target = usize; |
| 66 | |
| 67 | fn deref(&self) -> &usize { |
| 68 | &self.0 |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | /// A complete unified diff document. |
| 73 | #[derive(Clone, Debug, Default, Eq, PartialEq)] |
| 74 | pub struct DiffDocument { |
| 75 | /// Commit preamble before the first `diff --git` section, if present. |
| 76 | pub commit: Option<crate::CommitHeader>, |
| 77 | /// File diffs in input order. |
| 78 | pub files: Vec<FileDiff>, |
| 79 | } |
| 80 | |
| 81 | /// A single file section in a unified diff. |
| 82 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 83 | pub struct FileDiff { |
| 84 | /// Stable file identifier. |
| 85 | pub id: FileId, |
| 86 | /// Metadata and raw header lines for this file. |
| 87 | pub header: FileHeader, |
| 88 | /// Hunks in input order. |
| 89 | pub hunks: Vec<Hunk>, |
| 90 | } |
| 91 | |
| 92 | /// Metadata lines that introduce a file section in a Git patch. |
| 93 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 94 | pub struct FileHeader { |
| 95 | /// Classified kind of file change. |
| 96 | pub kind: FileKind, |
| 97 | /// Path on the old side of the diff, when present. |
| 98 | pub old_path: Option<PathBuf>, |
| 99 | /// Path on the new side of the diff, when present. |
| 100 | pub new_path: Option<PathBuf>, |
| 101 | /// File mode on the old side of the diff, when present. |
| 102 | pub old_mode: Option<FileMode>, |
| 103 | /// File mode on the new side of the diff, when present. |
| 104 | pub new_mode: Option<FileMode>, |
| 105 | /// Object id on the old side of the diff, when present. |
| 106 | pub old_oid: Option<Oid>, |
| 107 | /// Object id on the new side of the diff, when present. |
| 108 | pub new_oid: Option<Oid>, |
| 109 | /// Raw header lines preserved for callers that need exact metadata. |
| 110 | pub raw: Vec<String>, |
| 111 | } |
| 112 | |
| 113 | /// File mode in a Git diff, parsed from the octal value Git records. |
| 114 | #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] |
| 115 | pub enum FileMode { |
| 116 | /// Regular file (`100644`). |
| 117 | Blob, |
| 118 | /// Executable regular file (`100755`). |
| 119 | BlobExecutable, |
| 120 | /// Symbolic link (`120000`). |
| 121 | Link, |
| 122 | /// Submodule reference, i.e. a Git commit (`160000`). |
| 123 | Commit, |
| 124 | /// Directory tree (`040000`). |
| 125 | Tree, |
| 126 | /// Any other mode, preserved as the original octal value. |
| 127 | Other(u32), |
| 128 | } |
| 129 | |
| 130 | /// Kind of file-level change described by a patch file header. |
| 131 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 132 | pub enum FileKind { |
| 133 | /// Existing file content changed. |
| 134 | Modified, |
| 135 | /// New file was added. |
| 136 | Added, |
| 137 | /// Existing file was deleted. |
| 138 | Deleted, |
| 139 | /// Existing file was renamed. |
| 140 | Renamed, |
| 141 | /// Existing file was copied. |
| 142 | Copied, |
| 143 | /// File mode changed without a more specific content kind. |
| 144 | ModeChanged, |
| 145 | /// File contains binary patch data or a binary comparison marker. |
| 146 | Binary, |
| 147 | } |
| 148 | |
| 149 | impl FileKind { |
| 150 | /// Returns the compact marker used by diff chrome. |
| 151 | pub const fn marker(self) -> char { |
| 152 | match self { |
| 153 | Self::Added => '⊕', |
| 154 | Self::Deleted => '⊖', |
| 155 | Self::Renamed => '↦', |
| 156 | Self::Copied => '⇉', |
| 157 | Self::Modified | Self::ModeChanged | Self::Binary => '⊙', |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | /// Aggregate statistics for one [`FileDiff`]. |
| 163 | #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] |
| 164 | pub struct FileStats { |
| 165 | /// Total addition lines across all hunks in the file. |
| 166 | pub additions: usize, |
| 167 | /// Total deletion lines across all hunks in the file. |
| 168 | pub deletions: usize, |
| 169 | } |
| 170 | |
| 171 | /// Aggregate statistics for one [`DiffDocument`]. |
| 172 | #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] |
| 173 | pub struct Stats { |
| 174 | /// Number of file sections in the document. |
| 175 | pub files_changed: usize, |
| 176 | /// Total addition lines across all files. |
| 177 | pub insertions: usize, |
| 178 | /// Total deletion lines across all files. |
| 179 | pub deletions: usize, |
| 180 | } |
| 181 | |
| 182 | impl From<DiffStat> for Stats { |
| 183 | fn from(stats: DiffStat) -> Self { |
| 184 | Self { |
| 185 | files_changed: stats.files_changed, |
| 186 | insertions: stats.insertions, |
| 187 | deletions: stats.deletions, |
| 188 | } |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | /// A unified diff hunk and its body lines. |
| 193 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 194 | pub struct Hunk { |
| 195 | /// Stable hunk identifier. |
| 196 | pub id: HunkId, |
| 197 | /// Parsed hunk header. |
| 198 | pub header: HunkHeader, |
| 199 | /// Lines contained in the hunk body. |
| 200 | pub lines: Vec<DiffLine>, |
| 201 | } |
| 202 | |
| 203 | /// Metadata from a unified diff hunk header. |
| 204 | /// |
| 205 | /// Example: `@@ -24,8 +24,6 @@ fn main`. |
| 206 | #[derive(Clone, Debug, Default, Eq, PartialEq)] |
| 207 | pub struct HunkHeader { |
| 208 | /// Starting line number on the old side of the diff. |
| 209 | pub old_line_no: u32, |
| 210 | /// Number of old-side lines covered by the hunk. |
| 211 | pub old_size: u32, |
| 212 | /// Starting line number on the new side of the diff. |
| 213 | pub new_line_no: u32, |
| 214 | /// Number of new-side lines covered by the hunk. |
| 215 | pub new_size: u32, |
| 216 | /// Optional trailing hunk context text. |
| 217 | pub text: String, |
| 218 | } |
| 219 | |
| 220 | /// A single line in a unified diff hunk. |
| 221 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 222 | pub struct DiffLine { |
| 223 | /// Stable row identifier. |
| 224 | pub id: RowId, |
| 225 | /// Line role inside the hunk. |
| 226 | pub kind: DiffLineKind, |
| 227 | /// Line text without the leading diff marker. |
| 228 | pub text: String, |
| 229 | } |
| 230 | |
| 231 | /// Role of a line inside a unified diff hunk. |
| 232 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 233 | pub enum DiffLineKind { |
| 234 | /// Unchanged context line. |
| 235 | Context, |
| 236 | /// Added line. |
| 237 | Addition, |
| 238 | /// Deleted line. |
| 239 | Deletion, |
| 240 | /// Marker for a file without a trailing newline. |
| 241 | NoNewline, |
| 242 | } |
| 243 | |
| 244 | /// Error produced while decoding a unified diff. |
| 245 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 246 | pub struct DecodeError { |
| 247 | /// One-based input line number where decoding failed. |
| 248 | pub line: usize, |
| 249 | /// Human-readable failure message. |
| 250 | pub message: String, |
| 251 | /// Whether this error represents a clean end-of-input signal. |
| 252 | is_eof: bool, |
| 253 | } |
| 254 | |
| 255 | impl DiffDocument { |
| 256 | /// Returns whether the document contains no changed files. |
| 257 | pub fn is_empty(&self) -> bool { |
| 258 | self.files.is_empty() |
| 259 | } |
| 260 | |
| 261 | /// Returns the totals of files changed, insertions, and deletions. |
| 262 | pub fn stats(&self) -> Stats { |
| 263 | let mut stats = Stats { |
| 264 | files_changed: self.files.len(), |
| 265 | ..Stats::default() |
| 266 | }; |
| 267 | for file in &self.files { |
| 268 | let file_stats = file.stats(); |
| 269 | stats.insertions += file_stats.additions; |
| 270 | stats.deletions += file_stats.deletions; |
| 271 | } |
| 272 | stats |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | impl FileHeader { |
| 277 | /// Returns the path callers should usually show for this file. |
| 278 | pub fn display_path(&self) -> Option<&PathBuf> { |
| 279 | self.new_path.as_ref().or(self.old_path.as_ref()) |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | impl FileMode { |
| 284 | /// Returns the octal mode value Git records on the wire. |
| 285 | pub const fn as_octal(self) -> u32 { |
| 286 | match self { |
| 287 | Self::Blob => 0o100644, |
| 288 | Self::BlobExecutable => 0o100755, |
| 289 | Self::Link => 0o120000, |
| 290 | Self::Commit => 0o160000, |
| 291 | Self::Tree => 0o040000, |
| 292 | Self::Other(value) => value, |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | /// Builds a [`FileMode`] from an octal value, mapping known modes. |
| 297 | pub const fn from_octal(value: u32) -> Self { |
| 298 | match value { |
| 299 | 0o100644 => Self::Blob, |
| 300 | 0o100755 => Self::BlobExecutable, |
| 301 | 0o120000 => Self::Link, |
| 302 | 0o160000 => Self::Commit, |
| 303 | 0o040000 => Self::Tree, |
| 304 | other => Self::Other(other), |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | /// Parses an octal mode token from a Git diff header (e.g. `"100644"`). |
| 309 | pub fn parse(input: &str) -> Option<Self> { |
| 310 | u32::from_str_radix(input.trim(), 8) |
| 311 | .ok() |
| 312 | .map(Self::from_octal) |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | impl fmt::Display for FileMode { |
| 317 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 318 | write!(f, "{:o}", self.as_octal()) |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | impl DecodeError { |
| 323 | /// Creates a decode error at a one-based line number. |
| 324 | pub fn new(line: usize, message: impl Into<String>) -> Self { |
| 325 | Self { |
| 326 | line, |
| 327 | message: message.into(), |
| 328 | is_eof: false, |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | /// Creates an end-of-input error used to signal a clean EOF to streaming |
| 333 | /// callers. [`crate::Decode::try_decode`] turns this into `Ok(None)`. |
| 334 | pub fn eof() -> Self { |
| 335 | Self { |
| 336 | line: 0, |
| 337 | message: "unexpected end of file".to_owned(), |
| 338 | is_eof: true, |
| 339 | } |
| 340 | } |
| 341 | |
| 342 | /// Returns whether this error represents end of input rather than a |
| 343 | /// malformed patch. |
| 344 | pub fn is_eof(&self) -> bool { |
| 345 | self.is_eof |
| 346 | } |
| 347 | |
| 348 | /// Returns a copy of this error with a line number when the error has none. |
| 349 | pub(crate) fn at_line(mut self, line: usize) -> Self { |
| 350 | if self.line == 0 { |
| 351 | self.line = line; |
| 352 | } |
| 353 | self |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | impl fmt::Display for DecodeError { |
| 358 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 359 | if self.line == 0 { |
| 360 | f.write_str(&self.message) |
| 361 | } else { |
| 362 | write!(f, "line {}: {}", self.line, self.message) |
| 363 | } |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | impl std::error::Error for DecodeError {} |
| 368 | |
| 369 | impl From<ParseIntError> for DecodeError { |
| 370 | fn from(error: ParseIntError) -> Self { |
| 371 | Self::new(0, error.to_string()) |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | impl From<io::Error> for DecodeError { |
| 376 | fn from(error: io::Error) -> Self { |
| 377 | Self { |
| 378 | line: 0, |
| 379 | message: error.to_string(), |
| 380 | is_eof: error.kind() == io::ErrorKind::UnexpectedEof, |
| 381 | } |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | impl fmt::Display for FileKind { |
| 386 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 387 | let name = match self { |
| 388 | Self::Modified => "modified", |
| 389 | Self::Added => "added", |
| 390 | Self::Deleted => "deleted", |
| 391 | Self::Renamed => "renamed", |
| 392 | Self::Copied => "copied", |
| 393 | Self::ModeChanged => "mode changed", |
| 394 | Self::Binary => "binary", |
| 395 | }; |
| 396 | f.write_str(name) |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | impl DiffLineKind { |
| 401 | /// Returns how many old-side lines this kind contributes to a hunk. |
| 402 | pub const fn old_len(self) -> u32 { |
| 403 | match self { |
| 404 | Self::Context | Self::Deletion => 1, |
| 405 | Self::Addition | Self::NoNewline => 0, |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | /// Returns how many new-side lines this kind contributes to a hunk. |
| 410 | pub const fn new_len(self) -> u32 { |
| 411 | match self { |
| 412 | Self::Context | Self::Addition => 1, |
| 413 | Self::Deletion | Self::NoNewline => 0, |
| 414 | } |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | impl HunkHeader { |
| 419 | /// Returns a copy with old and new line numbers shifted by the deltas. |
| 420 | pub fn shifted(&self, old_delta: i32, new_delta: i32) -> Self { |
| 421 | Self { |
| 422 | old_line_no: Self::add_delta(self.old_line_no, old_delta), |
| 423 | new_line_no: Self::add_delta(self.new_line_no, new_delta), |
| 424 | ..self.clone() |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | /// Adds a signed delta to an unsigned line number with saturation. |
| 429 | fn add_delta(line: u32, delta: i32) -> u32 { |
| 430 | if delta.is_negative() { |
| 431 | line.saturating_sub(delta.unsigned_abs()) |
| 432 | } else { |
| 433 | line.saturating_add(delta.unsigned_abs()) |
| 434 | } |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | impl Hunk { |
| 439 | /// Returns the number of old-side lines covered by the hunk body. |
| 440 | pub fn old_size(&self) -> u32 { |
| 441 | self.sizes().old |
| 442 | } |
| 443 | |
| 444 | /// Returns the number of new-side lines covered by the hunk body. |
| 445 | pub fn new_size(&self) -> u32 { |
| 446 | self.sizes().new |
| 447 | } |
| 448 | |
| 449 | /// Counts addition and deletion lines in this hunk. |
| 450 | pub fn stats(&self) -> FileStats { |
| 451 | let mut stats = FileStats::default(); |
| 452 | for line in &self.lines { |
| 453 | match line.kind { |
| 454 | DiffLineKind::Addition => stats.additions += 1, |
| 455 | DiffLineKind::Deletion => stats.deletions += 1, |
| 456 | DiffLineKind::Context | DiffLineKind::NoNewline => {} |
| 457 | } |
| 458 | } |
| 459 | stats |
| 460 | } |
| 461 | |
| 462 | /// Returns the net line offset introduced by applying this hunk. |
| 463 | pub fn delta(&self) -> i32 { |
| 464 | let sizes = self.sizes(); |
| 465 | let new_size = i32::try_from(sizes.new).unwrap_or(i32::MAX); |
| 466 | let old_size = i32::try_from(sizes.old).unwrap_or(i32::MAX); |
| 467 | new_size - old_size |
| 468 | } |
| 469 | |
| 470 | /// Splits this hunk into context-separated change groups, each with its |
| 471 | /// own recomputed header. Returns `None` when the hunk has fewer than two |
| 472 | /// change groups (nothing to split). |
| 473 | pub fn split(&self) -> Option<impl Iterator<Item = Self> + '_> { |
| 474 | let groups = self.change_groups(); |
| 475 | if groups.len() < 2 { |
| 476 | return None; |
| 477 | } |
| 478 | Some((0..groups.len()).map(move |index| { |
| 479 | let group = groups[index]; |
| 480 | let start = if index == 0 { |
| 481 | 0 |
| 482 | } else { |
| 483 | groups[index - 1].split_context_before(group) |
| 484 | }; |
| 485 | let end = groups |
| 486 | .get(index + 1) |
| 487 | .map_or(self.lines.len(), |next| group.split_context_before(*next)); |
| 488 | self.segment(start, end) |
| 489 | })) |
| 490 | } |
| 491 | |
| 492 | /// Returns half-open ranges of contiguous non-context lines. |
| 493 | fn change_groups(&self) -> Vec<ChangeGroup> { |
| 494 | let mut groups = Vec::new(); |
| 495 | let mut current = None; |
| 496 | |
| 497 | for (index, line) in self.lines.iter().enumerate() { |
| 498 | if matches!(line.kind, DiffLineKind::Context) { |
| 499 | if let Some(start) = current.take() { |
| 500 | groups.push(ChangeGroup { start, end: index }); |
| 501 | } |
| 502 | } else if current.is_none() { |
| 503 | current = Some(index); |
| 504 | } |
| 505 | } |
| 506 | if let Some(start) = current { |
| 507 | groups.push(ChangeGroup { |
| 508 | start, |
| 509 | end: self.lines.len(), |
| 510 | }); |
| 511 | } |
| 512 | groups |
| 513 | } |
| 514 | |
| 515 | /// Returns one hunk segment with line numbers and sizes recomputed. |
| 516 | fn segment(&self, start: usize, end: usize) -> Self { |
| 517 | let lines = self.lines[start..end].to_vec(); |
| 518 | let old_delta = self.lines[..start] |
| 519 | .iter() |
| 520 | .map(|l| l.kind.old_len()) |
| 521 | .sum::<u32>(); |
| 522 | let new_delta = self.lines[..start] |
| 523 | .iter() |
| 524 | .map(|l| l.kind.new_len()) |
| 525 | .sum::<u32>(); |
| 526 | let sizes = HunkSizes::from_lines(&lines); |
| 527 | |
| 528 | Self { |
| 529 | id: self.id, |
| 530 | header: HunkHeader { |
| 531 | old_line_no: self.header.old_line_no.saturating_add(old_delta), |
| 532 | old_size: sizes.old, |
| 533 | new_line_no: self.header.new_line_no.saturating_add(new_delta), |
| 534 | new_size: sizes.new, |
| 535 | text: self.header.text.clone(), |
| 536 | }, |
| 537 | lines, |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | /// Returns old-side and new-side body sizes. |
| 542 | fn sizes(&self) -> HunkSizes { |
| 543 | HunkSizes::from_lines(&self.lines) |
| 544 | } |
| 545 | |
| 546 | /// Returns a copy identifying the change independently of its context. |
| 547 | /// |
| 548 | /// Context lines are dropped, sizes are recomputed, and the header text is |
| 549 | /// cleared, so the same change produces the same patch text even when its |
| 550 | /// surrounding context or position drifts. |
| 551 | pub fn identity(&self) -> Self { |
| 552 | let lines: Vec<_> = self |
| 553 | .lines |
| 554 | .iter() |
| 555 | .filter(|line| !matches!(line.kind, DiffLineKind::Context)) |
| 556 | .cloned() |
| 557 | .collect(); |
| 558 | let sizes = HunkSizes::from_lines(&lines); |
| 559 | |
| 560 | Self { |
| 561 | id: self.id, |
| 562 | header: HunkHeader { |
| 563 | old_line_no: self.header.old_line_no, |
| 564 | old_size: sizes.old, |
| 565 | new_line_no: self.header.new_line_no, |
| 566 | new_size: sizes.new, |
| 567 | text: String::new(), |
| 568 | }, |
| 569 | lines, |
| 570 | } |
| 571 | } |
| 572 | } |
| 573 | |
| 574 | /// Old-side and new-side line counts for a hunk body. |
| 575 | #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] |
| 576 | struct HunkSizes { |
| 577 | /// Old-side line count. |
| 578 | old: u32, |
| 579 | /// New-side line count. |
| 580 | new: u32, |
| 581 | } |
| 582 | |
| 583 | impl HunkSizes { |
| 584 | /// Counts old-side and new-side contributions across diff lines. |
| 585 | fn from_lines(lines: &[DiffLine]) -> Self { |
| 586 | let mut sizes = Self::default(); |
| 587 | for line in lines { |
| 588 | sizes.old += line.kind.old_len(); |
| 589 | sizes.new += line.kind.new_len(); |
| 590 | } |
| 591 | sizes |
| 592 | } |
| 593 | } |
| 594 | |
| 595 | impl FileDiff { |
| 596 | /// Returns the sum of addition and deletion lines across all hunks. |
| 597 | pub fn stats(&self) -> FileStats { |
| 598 | let mut total = FileStats::default(); |
| 599 | for hunk in &self.hunks { |
| 600 | let hunk_stats = hunk.stats(); |
| 601 | total.additions += hunk_stats.additions; |
| 602 | total.deletions += hunk_stats.deletions; |
| 603 | } |
| 604 | total |
| 605 | } |
| 606 | |
| 607 | /// Returns a copy containing only the hunks at the given indexes. |
| 608 | pub fn selected(&self, hunks: impl IntoIterator<Item = usize>) -> Self { |
| 609 | Self { |
| 610 | id: self.id, |
| 611 | header: self.header.clone(), |
| 612 | hunks: hunks |
| 613 | .into_iter() |
| 614 | .filter_map(|ix| self.hunks.get(ix).cloned()) |
| 615 | .collect(), |
| 616 | } |
| 617 | } |
| 618 | } |
| 619 | |
| 620 | impl DiffDocument { |
| 621 | /// Returns a single-file document with the given hunks, suitable for |
| 622 | /// `git apply`. The preamble is dropped. |
| 623 | pub fn for_hunks(file: &FileDiff, hunks: impl IntoIterator<Item = Hunk>) -> Self { |
| 624 | Self { |
| 625 | commit: None, |
| 626 | files: vec![FileDiff { |
| 627 | id: file.id, |
| 628 | header: file.header.clone(), |
| 629 | hunks: hunks.into_iter().collect(), |
| 630 | }], |
| 631 | } |
| 632 | } |
| 633 | |
| 634 | /// Splits multi-change hunks into independently reviewable hunks. |
| 635 | /// |
| 636 | /// Hunk ids are reassigned sequentially across the whole document, so the |
| 637 | /// split must run before any per-hunk state is derived for pieces to keep |
| 638 | /// stable identities across reloads. |
| 639 | pub fn split_hunks(mut self) -> Self { |
| 640 | let mut next = 0; |
| 641 | for file in &mut self.files { |
| 642 | let mut hunks = Vec::with_capacity(file.hunks.len()); |
| 643 | for hunk in std::mem::take(&mut file.hunks) { |
| 644 | if let Some(split) = hunk.split() { |
| 645 | for mut hunk in split { |
| 646 | hunk.id = HunkId::new(next); |
| 647 | next += 1; |
| 648 | hunks.push(hunk); |
| 649 | } |
| 650 | } else { |
| 651 | let mut hunk = hunk; |
| 652 | hunk.id = HunkId::new(next); |
| 653 | next += 1; |
| 654 | hunks.push(hunk); |
| 655 | } |
| 656 | } |
| 657 | file.hunks = hunks; |
| 658 | } |
| 659 | self |
| 660 | } |
| 661 | } |
| 662 | |
| 663 | /// Half-open range of non-context lines inside a hunk. |
| 664 | #[derive(Clone, Copy, Debug)] |
| 665 | struct ChangeGroup { |
| 666 | /// First changed line index. |
| 667 | start: usize, |
| 668 | /// One past the final changed line index. |
| 669 | end: usize, |
| 670 | } |
| 671 | |
| 672 | impl ChangeGroup { |
| 673 | /// Returns the split point in the context before `next`. |
| 674 | const fn split_context_before(self, next: Self) -> usize { |
| 675 | self.end + (next.start - self.end) / 2 |
| 676 | } |
| 677 | } |
| 678 | |
| 679 | #[cfg(test)] |
| 680 | #[allow(clippy::unwrap_used)] |
| 681 | mod tests { |
| 682 | use super::*; |
| 683 | use crate::Decode; |
| 684 | |
| 685 | fn parse_patch(input: &str) -> DiffDocument { |
| 686 | DiffDocument::decode_str(input).unwrap() |
| 687 | } |
| 688 | |
| 689 | const PATCH: &str = "\ |
| 690 | diff --git a/a.txt b/a.txt |
| 691 | index 7898192789819278981927898192789819278981..6178079617807961780796178079617807961780 100644 |
| 692 | --- a/a.txt |
| 693 | +++ b/a.txt |
| 694 | @@ -1,3 +1,4 @@ |
| 695 | one |
| 696 | +two |
| 697 | three |
| 698 | -four |
| 699 | +five |
| 700 | "; |
| 701 | |
| 702 | #[test] |
| 703 | fn diff_line_kind_counts_old_and_new_contributions() { |
| 704 | assert_eq!(DiffLineKind::Context.old_len(), 1); |
| 705 | assert_eq!(DiffLineKind::Context.new_len(), 1); |
| 706 | assert_eq!(DiffLineKind::Addition.old_len(), 0); |
| 707 | assert_eq!(DiffLineKind::Addition.new_len(), 1); |
| 708 | assert_eq!(DiffLineKind::Deletion.old_len(), 1); |
| 709 | assert_eq!(DiffLineKind::Deletion.new_len(), 0); |
| 710 | assert_eq!(DiffLineKind::NoNewline.old_len(), 0); |
| 711 | assert_eq!(DiffLineKind::NoNewline.new_len(), 0); |
| 712 | } |
| 713 | |
| 714 | #[test] |
| 715 | fn hunk_recomputes_sizes_from_lines() { |
| 716 | let doc = parse_patch(PATCH); |
| 717 | let hunk = &doc.files[0].hunks[0]; |
| 718 | |
| 719 | assert_eq!(hunk.old_size(), 3); |
| 720 | assert_eq!(hunk.new_size(), 4); |
| 721 | assert_eq!(hunk.delta(), 1); |
| 722 | } |
| 723 | |
| 724 | #[test] |
| 725 | fn hunk_split_separates_change_groups() { |
| 726 | let doc = parse_patch(PATCH); |
| 727 | let hunk = &doc.files[0].hunks[0]; |
| 728 | let split = hunk.split().unwrap().collect::<Vec<_>>(); |
| 729 | |
| 730 | assert_eq!(split.len(), 2); |
| 731 | assert_eq!(split[0].header.old_line_no, 1); |
| 732 | assert_eq!(split[0].header.old_size, 1); |
| 733 | assert_eq!(split[0].header.new_line_no, 1); |
| 734 | assert_eq!(split[0].header.new_size, 2); |
| 735 | assert_eq!(split[1].header.old_line_no, 2); |
| 736 | assert_eq!(split[1].header.old_size, 2); |
| 737 | assert_eq!(split[1].header.new_line_no, 3); |
| 738 | assert_eq!(split[1].header.new_size, 2); |
| 739 | } |
| 740 | |
| 741 | #[test] |
| 742 | fn hunk_split_returns_none_for_single_change_group() { |
| 743 | let doc = parse_patch( |
| 744 | "\ |
| 745 | diff --git a/a b/a |
| 746 | @@ -1 +1,2 @@ |
| 747 | one |
| 748 | +two |
| 749 | ", |
| 750 | ); |
| 751 | |
| 752 | assert!(doc.files[0].hunks[0].split().is_none()); |
| 753 | } |
| 754 | |
| 755 | #[test] |
| 756 | fn hunk_header_shifted_moves_line_numbers() { |
| 757 | let header = HunkHeader::decode_str("@@ -10,3 +20,3 @@").unwrap(); |
| 758 | let shifted = header.shifted(2, -3); |
| 759 | |
| 760 | assert_eq!(shifted.old_line_no, 12); |
| 761 | assert_eq!(shifted.new_line_no, 17); |
| 762 | assert_eq!(shifted.old_size, 3); |
| 763 | assert_eq!(shifted.new_size, 3); |
| 764 | } |
| 765 | |
| 766 | #[test] |
| 767 | fn file_diff_selected_keeps_only_chosen_hunks() { |
| 768 | let doc = parse_patch(PATCH); |
| 769 | let only = doc.files[0].selected([0]); |
| 770 | |
| 771 | assert_eq!(only.hunks.len(), 1); |
| 772 | assert_eq!(only.id, doc.files[0].id); |
| 773 | } |
| 774 | |
| 775 | #[test] |
| 776 | fn document_for_hunks_drops_preamble() { |
| 777 | let with_preamble = format!("commit 1234567890abcdef1234567890abcdef12345678\n\n{PATCH}"); |
| 778 | let doc = parse_patch(&with_preamble); |
| 779 | let single = DiffDocument::for_hunks(&doc.files[0], doc.files[0].hunks.clone()); |
| 780 | |
| 781 | assert!(single.commit.is_none()); |
| 782 | assert_eq!(single.files.len(), 1); |
| 783 | assert_eq!(single.files[0].hunks.len(), doc.files[0].hunks.len()); |
| 784 | } |
| 785 | |
| 786 | #[test] |
| 787 | fn stats_aggregate_across_hunks_and_files() { |
| 788 | let doc = parse_patch(PATCH); |
| 789 | let hunk_stats = doc.files[0].hunks[0].stats(); |
| 790 | let file_stats = doc.files[0].stats(); |
| 791 | let doc_stats = doc.stats(); |
| 792 | |
| 793 | assert_eq!( |
| 794 | hunk_stats, |
| 795 | FileStats { |
| 796 | additions: 2, |
| 797 | deletions: 1 |
| 798 | } |
| 799 | ); |
| 800 | assert_eq!( |
| 801 | file_stats, |
| 802 | FileStats { |
| 803 | additions: 2, |
| 804 | deletions: 1 |
| 805 | } |
| 806 | ); |
| 807 | assert_eq!( |
| 808 | doc_stats, |
| 809 | Stats { |
| 810 | files_changed: 1, |
| 811 | insertions: 2, |
| 812 | deletions: 1, |
| 813 | } |
| 814 | ); |
| 815 | } |
| 816 | |
| 817 | #[test] |
| 818 | fn file_mode_round_trips_through_octal() { |
| 819 | for mode in [ |
| 820 | FileMode::Blob, |
| 821 | FileMode::BlobExecutable, |
| 822 | FileMode::Link, |
| 823 | FileMode::Commit, |
| 824 | FileMode::Tree, |
| 825 | FileMode::Other(0o123456), |
| 826 | ] { |
| 827 | assert_eq!(FileMode::from_octal(mode.as_octal()), mode); |
| 828 | assert_eq!(FileMode::parse(&mode.to_string()), Some(mode)); |
| 829 | } |
| 830 | assert_eq!(FileMode::parse("not-octal"), None); |
| 831 | } |
| 832 | |
| 833 | #[test] |
| 834 | fn oid_parses_hexadecimal_text() { |
| 835 | let oid = "ABC1230000000000000000000000000000000000" |
| 836 | .parse::<Oid>() |
| 837 | .unwrap(); |
| 838 | |
| 839 | assert_eq!(oid.to_string(), "abc1230000000000000000000000000000000000"); |
| 840 | assert_eq!("".parse::<Oid>(), Err(OidError)); |
| 841 | assert_eq!("not-hex".parse::<Oid>(), Err(OidError)); |
| 842 | assert_eq!("ABC123".parse::<Oid>(), Err(OidError)); |
| 843 | } |
| 844 | |
| 845 | #[test] |
| 846 | fn add_delta_saturates_at_zero() { |
| 847 | assert_eq!(HunkHeader::add_delta(5, 3), 8); |
| 848 | assert_eq!(HunkHeader::add_delta(5, -3), 2); |
| 849 | assert_eq!(HunkHeader::add_delta(2, -10), 0); |
| 850 | } |
| 851 | } |