//! Chunk staging (C8 C3): the changed chunks of one file, and staging, //! unstaging or reverting a single one. //! //! **Three texts.** A file has a working text (the caller passes it: the //! editor buffer, which may hold unsaved changes), its version in the //! index (`:0:`) and its version at HEAD (under the old name when //! the index holds a staged rename). *Unstaged* chunks compare the index //! with the working text, *staged* chunks HEAD with the index. //! //! **Lines.** Texts split at `\n`, `\r\n` and a lone `\r`, and lines //! compare without their break, so a CRLF working copy against an LF index //! (`core.autocrlf`) shows no change, and neither does a missing final //! break alone. A UTF-8 byte order mark of a stored blob does not count //! either. The diff is Myers' (`similar`) with adjacent deletes and inserts //! merged, exactly as the gutter's `git.lineChanges`, so chunks and //! markers line up. //! //! **Staging and unstaging** build a minimal patch against the index blob //! as stored (its own line breaks, BOM and final break) that replaces the //! chunk's lines, with up to [`CONTEXT`] lines of context, and run //! `git apply --cached` with it. Unstaging builds the patch that puts //! HEAD's lines back into the index (the same as `git apply --cached //! --reverse` of the staged chunk). New lines take the line break the //! target already uses; the final break follows the source when the chunk //! reaches the end of both texts. git checks the context and refuses a //! patch that no longer fits. //! //! **Reverting** returns the byte edit that puts the index's lines back //! into the working text; the engine applies it to the editor buffer, so //! it is undoable there. //! //! **Stale chunks.** [`FileChunks::token`] hashes the working text, the //! index blob, the HEAD blob and HEAD's path. Every action takes the token //! the chunks were shown with and refuses with [`VcsError::Stale`] when //! the texts changed since. //! //! **Refused:** binary and too large files, files without an index entry //! (untracked, conflicted), and patches over lines broken by a lone `\r`. use std::ops::Range; use std::time::{Duration, Instant}; use similar::DiffOp; use similar::algorithms::{Capture, Replace, myers}; use crate::repo::{BINARY_PROBE, Object, SMALL_CAP}; use crate::runner::Call; use crate::{Repo, VcsError}; /// Lines of context around a chunk in the patches. pub const CONTEXT: usize = 3; /// Most chunks listed per side. pub const MAX_CHUNKS: usize = 10_000; /// Most removed and added lines each chunk carries for display. pub const MAX_SHOWN_LINES: usize = 500; /// Longest the line diff may take before it settles for a coarser result. const DIFF_DEADLINE: Duration = Duration::from_secs(1); /// The byte order mark git keeps in a stored blob. const BOM: &str = "\u{feff}"; /// A changed range: lines `old` of one text are replaced by lines `new` of /// the other (0-based, the end exclusive; an empty range is an insertion /// or deletion point). #[derive(Debug, Clone, PartialEq, Eq)] pub struct Hunk { /// Lines of the older text. pub old: Range, /// Lines of the newer text. pub new: Range, } /// One chunk as the actions and the UI see it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Chunk { /// Lines of the older side (the index for unstaged chunks, HEAD for /// staged ones). pub old: Range, /// Lines of the newer side (the working text, or the index). pub new: Range, /// Lines of the working text the chunk covers: `new` for unstaged /// chunks; for staged ones the index lines mapped through the unstaged /// changes (empty where the lines were removed or rewritten since). pub lines: Range, /// The removed lines without breaks, at most [`MAX_SHOWN_LINES`]. pub removed: Vec, /// The added lines without breaks, at most [`MAX_SHOWN_LINES`]. pub added: Vec, /// Whether `removed` or `added` was cut. pub truncated: bool, } /// The chunks of one file. #[derive(Debug, Clone, PartialEq, Eq)] pub struct FileChunks { /// Identifies the texts the chunks were computed from; actions refuse /// a different one. pub token: String, /// Index → working text, in line order. pub unstaged: Vec, /// HEAD → index, in line order. pub staged: Vec, /// The file's path at HEAD (project-relative) when the index holds it /// as a rename; `None` otherwise. pub head_path: Option, } /// A text edit: replace bytes `range` of the working text with `insert`. #[derive(Debug, Clone, PartialEq, Eq)] pub struct TextEdit { /// Byte range in the working text, on UTF-8 boundaries. pub range: Range, /// The replacement. pub insert: String, } /// Splits `text` into lines that keep their break (`\n`, `\r\n` or a lone /// `\r`); no empty line after a final break. pub fn split_lines(text: &str) -> Vec<&str> { let mut lines = Vec::new(); let mut rest = text; while !rest.is_empty() { let end = match rest.find(['\n', '\r']) { Some(at) if rest.get(at..at + 2) == Some("\r\n") => at + 2, Some(at) => at + 1, None => rest.len(), }; lines.push(rest.get(..end).unwrap_or(rest)); rest = rest.get(end..).unwrap_or_default(); } lines } /// A line without its break. pub fn content(line: &str) -> &str { line.strip_suffix("\r\n") .or_else(|| line.strip_suffix('\n')) .or_else(|| line.strip_suffix('\r')) .unwrap_or(line) } /// Whether a line ends with a break. fn terminated(line: &str) -> bool { line.ends_with(['\n', '\r']) } /// The changed ranges between two texts, comparing lines without their /// breaks; the diff gives up refining after `deadline` (an empty list /// when it cannot finish at all). /// /// `similar`'s `Compact` step is left out on purpose: in 2.7.0 it can move /// a delete to a wrong position in the new text. pub fn line_hunks(old: &str, new: &str, deadline: Option) -> Vec { let old: Vec<&str> = split_lines(old).into_iter().map(content).collect(); let new: Vec<&str> = split_lines(new).into_iter().map(content).collect(); let mut hook = Replace::new(Capture::new()); if myers::diff_deadline(&mut hook, &old, 0..old.len(), &new, 0..new.len(), deadline).is_err() { return Vec::new(); } hook.into_inner() .into_ops() .iter() .filter_map(|op| match *op { DiffOp::Equal { .. } => None, DiffOp::Insert { old_index, new_index, new_len, } => Some(Hunk { old: old_index..old_index, new: new_index..new_index + new_len, }), DiffOp::Delete { old_index, old_len, new_index, } => Some(Hunk { old: old_index..old_index + old_len, new: new_index..new_index, }), DiffOp::Replace { old_index, old_len, new_index, new_len, } => Some(Hunk { old: old_index..old_index + old_len, new: new_index..new_index + new_len, }), }) .collect() } /// Maps a line boundary of the older text of `hunks` into the newer one. /// /// # Parameters /// - `hunks`: the changes, in order. /// - `line`: the boundary (a line number, or the line count). /// - `end`: inside a changed range, map to its end rather than its start. fn map_line(hunks: &[Hunk], line: usize, end: bool) -> usize { let mut at = line; for hunk in hunks { if line <= hunk.old.start { break; } if line < hunk.old.end { return if end { hunk.new.end } else { hunk.new.start }; } at = at .saturating_sub(hunk.old.len()) .saturating_add(hunk.new.len()); } at } /// The first line break of `text`, if any. fn eol_of(text: &str) -> Option<&'static str> { let at = text.find(['\n', '\r'])?; Some(match text.get(at..at + 2) { Some("\r\n") => "\r\n", _ if text.get(at..=at) == Some("\r") => "\r", _ => "\n", }) } /// FNV-1a over the parts, each followed by a separator byte. fn token(parts: &[&[u8]]) -> String { let mut hash: u64 = 0xcbf2_9ce4_8422_2325; for part in parts { for byte in part.iter().chain(std::iter::once(&0xff)) { hash ^= u64::from(*byte); hash = hash.wrapping_mul(0x0100_0000_01b3); } } format!("{hash:016x}") } /// Shown lines of `lines` in `range`, capped; the flag says whether they /// were cut. fn shown(lines: &[&str], range: &Range) -> (Vec, bool) { let all = lines.get(range.clone()).unwrap_or_default(); let out = all .iter() .take(MAX_SHOWN_LINES) .map(|l| content(l).to_string()) .collect(); (out, all.len() > MAX_SHOWN_LINES) } /// The lines that replace a target range: the source's lines in `range` /// with the target's line break `eol`; the source's last line keeps having /// no break when the target range reaches the end of the target. fn replacement(source: &[&str], range: &Range, at_end: bool, eol: &str) -> Vec { let last = source.len().checked_sub(1); source .get(range.clone()) .unwrap_or_default() .iter() .enumerate() .map(|(i, line)| { if at_end && Some(range.start + i) == last && !terminated(line) { line.to_string() } else { format!("{}{eol}", content(line)) } }) .collect() } /// Widens a change so its patch stays valid: /// - an insertion after a last target line without a break takes that /// line along (it gains the break); /// - a deletion of the first lines of a target with a BOM takes the next /// line along (it carries the BOM on). /// /// # Parameters /// - `target`, `source`: the lines of the text that changes and of the /// text whose lines it takes. /// - `hunk`: `old` lines of the target, `new` lines of the source. /// - `bom`: whether the target's first line starts with a BOM. fn widen(target: &[&str], source: &[&str], mut hunk: Hunk, bom: bool) -> Hunk { let last_open = target.last().is_some_and(|l| !terminated(l)); if hunk.old.start == target.len() && last_open && hunk.old.start > 0 && hunk.new.start > 0 { hunk.old.start -= 1; hunk.new.start -= 1; } if bom && hunk.old.start == 0 && hunk.new.is_empty() && hunk.old.end < target.len() && hunk.new.end < source.len() { hunk.old.end += 1; hunk.new.end += 1; } hunk } /// The replacement for `hunk.old` of `target` from `hunk.new` of `source`, /// with the target's break (else the source's, else `\n`) and the BOM kept /// on the first line. fn replacement_for(target: &[&str], source: &[&str], hunk: &Hunk, bom: bool) -> Vec { let target_text: String = target.concat(); let source_text: String = source.concat(); let eol = eol_of(&target_text) .or_else(|| eol_of(&source_text)) .unwrap_or("\n"); let at_end = hunk.old.end == target.len(); let mut lines = replacement(source, &hunk.new, at_end, eol); if bom && hunk.old.start == 0 && let Some(first) = lines.first_mut() { first.insert_str(0, BOM); } lines } /// Whether a path needs git's C-style quoting in a patch header. fn needs_quotes(path: &str) -> bool { path.chars() .any(|c| c.is_control() || c == '"' || c == '\\') } /// A patch header name: `a/` or `b/`, quoted like git does /// when it holds control characters, quotes or backslashes. fn header_name(prefix: &str, path: &str) -> String { let name = format!("{prefix}{path}"); if !needs_quotes(&name) { return name; } let mut out = String::from("\""); for c in name.chars() { match c { '"' => out.push_str("\\\""), '\\' => out.push_str("\\\\"), '\t' => out.push_str("\\t"), '\n' => out.push_str("\\n"), '\r' => out.push_str("\\r"), c if c.is_control() => { let mut buf = [0u8; 4]; for byte in c.encode_utf8(&mut buf).bytes() { out.push_str(&format!("\\{byte:03o}")); } } c => out.push(c), } } out.push('"'); out } /// Appends one patch line; a line without a break gets git's marker. fn push_line(out: &mut String, sign: char, line: &str) { out.push(sign); out.push_str(line); if !line.ends_with('\n') { out.push_str("\n\\ No newline at end of file\n"); } } /// Builds a patch that replaces lines `range` of `target` (a blob as /// stored) with `replacement` (lines with their breaks), with up to /// [`CONTEXT`] lines of context. /// /// # Parameters /// - `path`: the root-relative path. /// /// # Errors /// [`VcsError::ChunkRefused`] when a line involved ends with a lone `\r` /// (git's patches cannot carry it), or the range is outside the target. pub fn build_patch( path: &str, target: &str, range: Range, replacement: &[String], ) -> Result { let lines = split_lines(target); if range.start > range.end || range.end > lines.len() { return Err(VcsError::Stale); } let lone_cr = |l: &str| l.ends_with('\r'); if lines.iter().any(|l| lone_cr(l)) || replacement.iter().any(|l| lone_cr(l)) { return Err(VcsError::ChunkRefused( "lines broken by a lone carriage return cannot be staged by chunk".into(), )); } let before = range.start.saturating_sub(CONTEXT); let after = range.end.saturating_add(CONTEXT).min(lines.len()); let pre = lines.get(before..range.start).unwrap_or_default(); let removed = lines.get(range.clone()).unwrap_or_default(); let post = lines.get(range.end..after).unwrap_or_default(); let old_count = pre.len() + removed.len() + post.len(); let new_count = pre.len() + replacement.len() + post.len(); let start = |count: usize| if count == 0 { before } else { before + 1 }; let mut out = format!( "diff --git {a} {b}\n--- {a}\n+++ {b}\n@@ -{},{old_count} +{},{new_count} @@\n", start(old_count), start(new_count), a = header_name("a/", path), b = header_name("b/", path), ); for line in pre { push_line(&mut out, ' ', line); } for line in removed { push_line(&mut out, '-', line); } for line in replacement { push_line(&mut out, '+', line); } for line in post { push_line(&mut out, ' ', line); } Ok(out) } /// The texts of one file and their chunks, read for an action. struct Loaded { /// Root-relative path. path: String, /// The index blob as stored (BOM kept). index: String, /// The index blob without BOM, compared with the other texts. index_view: String, /// The HEAD blob without BOM; empty when missing at HEAD. head_view: String, /// The working text. worktree: String, /// The chunks. chunks: FileChunks, } impl Loaded { /// Whether the index blob starts with a BOM. fn bom(&self) -> bool { self.index.starts_with(BOM) } } /// Decodes a blob for chunks: UTF-8 with the BOM kept. /// /// # Errors /// [`VcsError::ChunkRefused`] for binary or too large blobs. fn blob_text(object: Object, what: &str) -> Result, VcsError> { let binary = || VcsError::ChunkRefused(format!("{what} is binary; stage the whole file")); match object { Object::Missing => Ok(None), Object::NotBlob => Err(binary()), Object::TooLarge => Err(VcsError::ChunkRefused(format!( "{what} is too large for chunks; stage the whole file" ))), Object::Blob(bytes) => { let probe = bytes .get(..BINARY_PROBE.min(bytes.len())) .unwrap_or_default(); if probe.contains(&0) { return Err(binary()); } String::from_utf8(bytes).map(Some).map_err(|_| binary()) } } } /// Computes the chunks of the three texts. /// /// # Parameters /// - `index`, `head`, `worktree`: the texts without BOM. /// - `token`: the token of the texts. /// - `head_path`: the project-relative HEAD path of a rename. pub fn compute( index: &str, head: &str, worktree: &str, token: String, head_path: Option, ) -> FileChunks { let deadline = Instant::now().checked_add(DIFF_DEADLINE); let index_lines = split_lines(index); let head_lines = split_lines(head); let work_lines = split_lines(worktree); let unstaged_hunks = line_hunks(index, worktree, deadline); let staged_hunks = line_hunks(head, index, deadline); let chunk = |old: &[&str], new: &[&str], hunk: &Hunk, lines: Range| { let (removed, cut_removed) = shown(old, &hunk.old); let (added, cut_added) = shown(new, &hunk.new); Chunk { old: hunk.old.clone(), new: hunk.new.clone(), lines, removed, added, truncated: cut_removed || cut_added, } }; let unstaged = unstaged_hunks .iter() .take(MAX_CHUNKS) .map(|h| chunk(&index_lines, &work_lines, h, h.new.clone())) .collect(); let staged = staged_hunks .iter() .take(MAX_CHUNKS) .map(|h| { let start = map_line(&unstaged_hunks, h.new.start, false); let end = map_line(&unstaged_hunks, h.new.end, true).max(start); chunk(&head_lines, &index_lines, h, start..end) }) .collect(); FileChunks { token, unstaged, staged, head_path, } } /// Parses `git diff --cached --name-status -z -M` and returns the old path /// of the entry renamed to `path`. pub fn rename_source(output: &[u8], path: &str) -> Option { let mut fields = output .split(|b| *b == 0) .map(|f| String::from_utf8_lossy(f).into_owned()); while let Some(status) = fields.next() { if status.is_empty() { continue; } if status.starts_with('R') || status.starts_with('C') { let old = fields.next()?; let new = fields.next()?; if status.starts_with('R') && new == path { return Some(old); } } else { fields.next()?; } } None } impl Repo { /// The root-relative HEAD path of `path` (the source of a staged /// rename, else `path` itself); `None` before the first commit. fn head_path_of(&self, path: &str) -> Result, VcsError> { if !self.has_head()? { return Ok(None); } let output = self .run(Call::read( self.root(), &[ "diff", "--cached", "--name-status", "-z", "-M", "--no-ext-diff", "HEAD", "--", ], SMALL_CAP, ))? .checked()?; Ok(Some( rename_source(&output.stdout, path).unwrap_or_else(|| path.to_string()), )) } /// Reads the texts of `path` and computes its chunks. fn load(&self, path: &str, worktree: &str) -> Result { let repo_path = self.to_repo_path(path)?; let index = blob_text( self.read_object(&format!(":0:{repo_path}"))?, "the staged version", )? .ok_or_else(|| { VcsError::ChunkRefused(format!( "{path} has no staged version (untracked or conflicted); stage the whole file" )) })?; let head_path = self.head_path_of(&repo_path)?; let head = match &head_path { Some(p) => blob_text(self.read_object(&format!("HEAD:{p}"))?, "the HEAD version")? .unwrap_or_default(), None => String::new(), }; let renamed = head_path .as_deref() .filter(|p| *p != repo_path) .and_then(|p| self.from_repo_path(p).or_else(|| Some(p.to_string()))); let token = token(&[ repo_path.as_bytes(), worktree.as_bytes(), index.as_bytes(), head_path.as_deref().unwrap_or_default().as_bytes(), head.as_bytes(), ]); let index_view = index.strip_prefix(BOM).unwrap_or(&index).to_string(); let head_view = head.strip_prefix(BOM).unwrap_or(&head).to_string(); let worktree_view = worktree.strip_prefix(BOM).unwrap_or(worktree); let chunks = compute(&index_view, &head_view, worktree_view, token, renamed); Ok(Loaded { path: repo_path, index, index_view, head_view, worktree: worktree_view.to_string(), chunks, }) } /// The chunks of `path` against the working text `worktree`. /// /// # Errors /// [`VcsError::InvalidPath`], [`VcsError::ChunkRefused`] for binary, /// too large or untracked files, or the runner's errors. pub fn chunks(&self, path: &str, worktree: &str) -> Result { Ok(self.load(path, worktree)?.chunks) } /// Loads `path` and checks the token. fn load_checked(&self, path: &str, worktree: &str, token: &str) -> Result { let loaded = self.load(path, worktree)?; if loaded.chunks.token != token { return Err(VcsError::Stale); } Ok(loaded) } /// Runs `git apply --cached` with `patch`. fn apply_cached(&self, patch: String) -> Result<(), VcsError> { self.run( Call::write( self.root(), &["apply", "--cached", "--whitespace=nowarn", "-"], ) .stdin(patch.into_bytes()), )? .checked()?; Ok(()) } /// Stages unstaged chunk `n` of `path`: the index takes the working /// text's lines of that chunk. /// /// # Parameters /// - `worktree`: the working text the chunks were computed from. /// - `n`: the chunk's position in [`FileChunks::unstaged`]. /// - `token`: [`FileChunks::token`] as shown. /// /// # Errors /// [`VcsError::Stale`] when the texts changed since or there is no such /// chunk; as [`Repo::chunks`]; git's refusal of the patch. pub fn stage_chunk( &self, path: &str, worktree: &str, n: usize, token: &str, ) -> Result<(), VcsError> { let _guard = self.lock(); let loaded = self.load_checked(path, worktree, token)?; let chunk = loaded.chunks.unstaged.get(n).ok_or(VcsError::Stale)?; let target = split_lines(&loaded.index); let source = split_lines(&loaded.worktree); let hunk = widen( &target, &source, Hunk { old: chunk.old.clone(), new: chunk.new.clone(), }, loaded.bom(), ); let lines = replacement_for(&target, &source, &hunk, loaded.bom()); let patch = build_patch(&loaded.path, &loaded.index, hunk.old, &lines)?; self.apply_cached(patch) } /// Unstages staged chunk `n` of `path`: the index takes HEAD's lines of /// that chunk back (for a staged rename, from the old path). /// /// # Parameters /// As [`Repo::stage_chunk`], with `n` a position in /// [`FileChunks::staged`]. /// /// # Errors /// As [`Repo::stage_chunk`]. pub fn unstage_chunk( &self, path: &str, worktree: &str, n: usize, token: &str, ) -> Result<(), VcsError> { let _guard = self.lock(); let loaded = self.load_checked(path, worktree, token)?; let chunk = loaded.chunks.staged.get(n).ok_or(VcsError::Stale)?; let target = split_lines(&loaded.index); let source = split_lines(&loaded.head_view); let hunk = widen( &target, &source, Hunk { old: chunk.new.clone(), new: chunk.old.clone(), }, loaded.bom(), ); let lines = replacement_for(&target, &source, &hunk, loaded.bom()); let patch = build_patch(&loaded.path, &loaded.index, hunk.old, &lines)?; self.apply_cached(patch) } /// The edit that reverts unstaged chunk `n` of `path` in the working /// text: its lines become the index's again. Nothing is written; the /// caller applies the edit (the engine, to the editor buffer). /// /// # Parameters /// As [`Repo::stage_chunk`]. /// /// # Returns /// The edit, in bytes of `worktree`. /// /// # Errors /// As [`Repo::stage_chunk`], without git's refusal. pub fn revert_chunk( &self, path: &str, worktree: &str, n: usize, token: &str, ) -> Result { let loaded = self.load_checked(path, worktree, token)?; let chunk = loaded.chunks.unstaged.get(n).ok_or(VcsError::Stale)?; let offset = worktree.len() - loaded.worktree.len(); let target = split_lines(&loaded.worktree); let source = split_lines(&loaded.index_view); let hunk = widen( &target, &source, Hunk { old: chunk.new.clone(), new: chunk.old.clone(), }, false, ); let lines = replacement_for(&target, &source, &hunk, false); let start: usize = target .get(..hunk.old.start) .unwrap_or_default() .iter() .map(|l| l.len()) .sum(); let len: usize = target .get(hunk.old.clone()) .unwrap_or_default() .iter() .map(|l| l.len()) .sum(); Ok(TextEdit { range: offset + start..offset + start + len, insert: lines.concat(), }) } } #[cfg(test)] mod tests { use super::*; fn hunk(old: Range, new: Range) -> Hunk { Hunk { old, new } } #[test] fn splits_lines_keeping_their_breaks() { assert_eq!(split_lines(""), Vec::<&str>::new()); assert_eq!(split_lines("a"), vec!["a"]); assert_eq!( split_lines("a\r\nb\rc\n\n"), vec!["a\r\n", "b\r", "c\n", "\n"] ); assert_eq!(content("a\r\n"), "a"); assert_eq!(content("a\r"), "a"); assert_eq!(content("a"), "a"); } #[test] fn hunks_ignore_line_breaks() { assert_eq!(line_hunks("a\nb\n", "a\r\nb", None), vec![]); assert_eq!( line_hunks("a\nb\nc\n", "a\nB\nc\nd\n", None), vec![hunk(1..2, 1..2), hunk(3..3, 3..4)] ); } #[test] fn maps_index_lines_through_unstaged_changes() { let hunks = vec![hunk(1..2, 1..4), hunk(5..7, 7..7)]; assert_eq!(map_line(&hunks, 0, false), 0); assert_eq!(map_line(&hunks, 1, false), 1); assert_eq!(map_line(&hunks, 2, false), 4); assert_eq!(map_line(&hunks, 3, true), 5); assert_eq!(map_line(&hunks, 6, false), 7); assert_eq!(map_line(&hunks, 6, true), 7); assert_eq!(map_line(&hunks, 9, false), 9); } #[test] fn patches_carry_context_and_missing_final_breaks() { let target = "1\n2\n3\n4\n5\n6\n7\n8"; let patch = build_patch("src/a b.php", target, 3..4, &["four\n".into()]).unwrap(); assert_eq!( patch, "diff --git a/src/a b.php b/src/a b.php\n--- a/src/a b.php\n+++ b/src/a b.php\n\ @@ -1,7 +1,7 @@\n 1\n 2\n 3\n-4\n+four\n 5\n 6\n 7\n" ); let patch = build_patch("a", target, 7..8, &["8\n".into(), "9".into()]).unwrap(); assert!( patch.ends_with( "@@ -5,4 +5,5 @@\n 5\n 6\n 7\n-8\n\\ No newline at end of file\n+8\n+9\n\\ No newline at end of file\n" ), "{patch}" ); let patch = build_patch("a", "", 0..0, &["x\n".into()]).unwrap(); assert!(patch.ends_with("@@ -0,0 +1,1 @@\n+x\n"), "{patch}"); assert!(build_patch("a", "x\r", 0..1, &[]).is_err()); assert!(build_patch("a", "x\n", 0..2, &[]).is_err()); } #[test] fn quotes_special_paths_like_git() { assert_eq!(header_name("a/", "plain.php"), "a/plain.php"); assert_eq!(header_name("a/", "q\"t\\.php"), "\"a/q\\\"t\\\\.php\""); assert_eq!(header_name("b/", "tab\there"), "\"b/tab\\there\""); } #[test] fn replacements_take_the_target_break_and_keep_a_missing_final_one() { let target = split_lines("a\r\nb\r\n"); let source = split_lines("a\nB\nC"); let h = hunk(1..2, 1..3); assert_eq!( replacement_for(&target, &source, &h, false), vec!["B\r\n".to_string(), "C".to_string()] ); let target = split_lines("a\nb\nc\n"); let h = hunk(1..2, 1..2); assert_eq!( replacement_for(&target, &split_lines("a\nX\nc"), &h, false), vec!["X\n".to_string()] ); } #[test] fn widens_appends_after_an_open_last_line_and_bom_deletions() { let target = split_lines("a\nb"); let source = split_lines("a\nb\nc\n"); assert_eq!( widen(&target, &source, hunk(2..2, 2..3), false), hunk(1..2, 1..3) ); let target = split_lines("\u{feff}a\nb\nc\n"); let source = split_lines("b\nc\n"); assert_eq!( widen(&target, &source, hunk(0..1, 0..0), true), hunk(0..2, 0..1) ); } #[test] fn finds_the_source_of_a_staged_rename() { let out = b"M\0x.php\0R087\0old.php\0new.php\0A\0y.php\0"; assert_eq!(rename_source(out, "new.php"), Some("old.php".into())); assert_eq!(rename_source(out, "x.php"), None); assert_eq!(rename_source(b"R1\0a", "a"), None); } #[test] fn tokens_differ_with_any_text() { let a = token(&[b"p", b"x", b"y"]); assert_eq!(a, token(&[b"p", b"x", b"y"])); assert_ne!(a, token(&[b"p", b"xy", b""])); } #[test] fn staged_chunks_map_to_working_lines() { let chunks = compute( "a\nB\nc\nd\n", "a\nb\nc\nd\n", "new\na\nB\nc\nd\n", "t".into(), None, ); assert_eq!(chunks.unstaged.len(), 1); assert_eq!(chunks.unstaged[0].lines, 0..1); assert_eq!(chunks.staged.len(), 1); assert_eq!(chunks.staged[0].lines, 2..3); assert_eq!(chunks.staged[0].removed, vec!["b".to_string()]); assert_eq!(chunks.staged[0].added, vec!["B".to_string()]); } }