use std::borrow::Cow;
use std::path::{Path, PathBuf};
use rustc_hash::{FxHashMap, FxHashSet};
use crate::unified_diff::{DiffEvent, DiffFileHeader, unified_diff_events};
pub const MAX_DIFF_BYTES: u64 = 10 * 1024 * 1024;
pub const MAX_ADDED_LINES: usize = 1_000_000;
#[derive(Debug, Default, Clone)]
pub struct DiffIndex {
added_lines: FxHashMap<String, FxHashSet<u64>>,
changed_paths: FxHashSet<String>,
touched_files: FxHashSet<String>,
added_line_count: usize,
total_added_lines: usize,
total_removed_lines: usize,
hunk_count: usize,
rename_pairs: FxHashMap<String, String>,
base: Option<PathBuf>,
root_offset: String,
base_lines: Box<BaseLineMap>,
}
#[derive(Debug, Default, Clone)]
struct BaseLineMap {
change_blocks: FxHashMap<String, Vec<ChangeBlock>>,
new_files: FxHashSet<String>,
lines_capped: bool,
}
#[derive(Debug, Clone, Copy)]
struct ChangeBlock {
new_start: u64,
new_len: u64,
old_start: u64,
old_len: u64,
}
impl ChangeBlock {
fn last_removed_line(self) -> Option<u64> {
(self.old_start + self.old_len)
.checked_sub(1)
.filter(|_| self.old_len > 0)
}
}
enum HeadLinePlace {
Unchanged(u64),
Added(ChangeBlock),
}
#[derive(Default)]
struct DiffParseState {
current_file: Option<String>,
new_line: u64,
old_line: u64,
}
impl DiffIndex {
#[must_use]
pub fn from_unified_diff(diff: &str) -> Self {
let mut index = Self::default();
let mut state = DiffParseState::default();
for event in unified_diff_events(diff) {
match event {
DiffEvent::File(header) => state.current_file = index.record_file(header),
DiffEvent::Hunk {
old_start,
old_len,
new_start,
new_len,
} => {
state.old_line = if old_len == 0 {
old_start + 1
} else {
old_start
};
state.new_line = if new_len == 0 {
new_start + 1
} else {
new_start
};
index.hunk_count += 1;
}
DiffEvent::Added(_) => index.record_added_line(&mut state),
DiffEvent::Removed(_) => index.record_removed_line(&mut state),
DiffEvent::Context(_) => {
state.new_line += 1;
state.old_line += 1;
}
DiffEvent::NoNewline => {}
}
}
index
}
fn record_file(&mut self, header: DiffFileHeader<'_>) -> Option<String> {
if let Some(path) = header.new_path {
let path = path.into_owned();
self.changed_paths.insert(path.clone());
self.touched_files.insert(path.clone());
if let Some(from) = header.renamed_from {
self.rename_pairs.insert(path.clone(), from.into_owned());
}
if header.is_new {
self.base_lines.new_files.insert(path.clone());
}
return Some(path);
}
let old = header.old_path.filter(|_| header.is_deleted)?.into_owned();
self.changed_paths.insert(old.clone());
Some(old)
}
fn record_added_line(&mut self, state: &mut DiffParseState) {
let Some(path) = state.current_file.as_ref() else {
return;
};
self.total_added_lines += 1;
if self.added_line_count < MAX_ADDED_LINES {
self.added_lines
.entry(path.clone())
.or_default()
.insert(state.new_line);
self.added_line_count += 1;
self.record_change_line(state, true);
} else {
self.base_lines.lines_capped = true;
}
state.new_line += 1;
}
fn record_removed_line(&mut self, state: &mut DiffParseState) {
if state.current_file.is_none() {
return;
}
self.total_removed_lines += 1;
self.record_change_line(state, false);
state.old_line += 1;
}
fn record_change_line(&mut self, state: &DiffParseState, added: bool) {
let Some(path) = state.current_file.as_ref() else {
return;
};
let blocks = self
.base_lines
.change_blocks
.entry(path.clone())
.or_default();
let continues = blocks.last().is_some_and(|block| {
block.new_start + block.new_len == state.new_line
&& block.old_start + block.old_len == state.old_line
});
if !continues {
blocks.push(ChangeBlock {
new_start: state.new_line,
new_len: 0,
old_start: state.old_line,
old_len: 0,
});
}
if let Some(block) = blocks.last_mut() {
if added {
block.new_len += 1;
} else {
block.old_len += 1;
}
}
}
#[must_use]
pub fn base_line_range(&self, path: &str, start: u64, end: u64) -> Option<(u64, u64)> {
let map = &self.base_lines;
if map.lines_capped || start > end || map.new_files.contains(path) {
return None;
}
let blocks = map.change_blocks.get(path).map_or(&[][..], Vec::as_slice);
let (base_start, base_end) =
match (head_line_place(blocks, start), head_line_place(blocks, end)) {
(HeadLinePlace::Added(first), HeadLinePlace::Added(last))
if first.new_start == last.new_start =>
{
(first.old_start, first.last_removed_line()?)
}
(start_place, end_place) => {
let base_start = match start_place {
HeadLinePlace::Unchanged(line) => line,
HeadLinePlace::Added(block) => {
block.last_removed_line().unwrap_or(block.old_start)
}
};
let base_end = match end_place {
HeadLinePlace::Unchanged(line) => line,
HeadLinePlace::Added(block) if block.old_len > 0 => block.old_start,
HeadLinePlace::Added(block) => block.old_start.checked_sub(1)?,
};
(base_start, base_end)
}
};
(base_start <= base_end).then_some((base_start, base_end))
}
#[must_use]
pub fn old_path_for(&self, head_path: &str) -> Option<&str> {
self.rename_pairs.get(head_path).map(String::as_str)
}
#[must_use]
pub fn added_line_count(&self) -> usize {
self.added_line_count
}
#[must_use]
pub fn filter_scope_size(&self) -> usize {
if self.added_line_count >= MAX_ADDED_LINES {
return self.added_line_count;
}
let files_without_lines = self
.touched_files
.iter()
.filter(|path| !self.added_lines.contains_key(*path))
.count();
self.added_line_count.saturating_add(files_without_lines)
}
#[must_use]
pub fn hunk_count(&self) -> usize {
self.hunk_count
}
#[must_use]
pub fn net_lines(&self) -> i64 {
let added = i64::try_from(self.total_added_lines).unwrap_or(i64::MAX);
let removed = i64::try_from(self.total_removed_lines).unwrap_or(i64::MAX);
added.saturating_sub(removed)
}
#[must_use]
pub fn changes_path(&self, path: &str) -> bool {
self.changed_paths.contains(path)
}
pub fn changed_paths(&self) -> impl Iterator<Item = &str> {
self.changed_paths.iter().map(String::as_str)
}
#[must_use]
pub fn touches_file(&self, path: &str) -> bool {
self.touched_files.contains(path)
}
#[must_use]
pub fn range_overlaps_added(&self, path: &str, start: u64, end: u64) -> bool {
self.first_added_line_in_range(path, start, end).is_some()
}
#[must_use]
pub fn first_added_line_in_range(&self, path: &str, start: u64, end: u64) -> Option<u64> {
if end < start {
return None;
}
let added = self.added_lines.get(path)?;
let lo = start.max(1);
added
.iter()
.copied()
.filter(|line| *line >= lo && *line <= end)
.min()
}
#[must_use]
pub fn line_is_added(&self, path: &str, line: u64) -> bool {
self.added_lines
.get(path)
.is_some_and(|lines| lines.contains(&line))
}
#[must_use]
pub fn line_within_added_context(&self, path: &str, line: u64, radius: u64) -> bool {
self.added_lines
.get(path)
.is_some_and(|lines| lines.iter().any(|added| line.abs_diff(*added) <= radius))
}
#[must_use]
pub fn added_lines_in(&self, path: &str) -> Option<&FxHashSet<u64>> {
self.added_lines.get(path)
}
#[must_use]
pub fn with_base(mut self, base: impl Into<PathBuf>) -> Self {
self.base = Some(base.into());
self
}
#[must_use]
pub fn with_root_offset(mut self, offset: impl Into<String>) -> Self {
let mut offset = offset.into();
offset.truncate(offset.trim_end_matches('/').len());
self.root_offset = offset;
self
}
#[must_use]
pub fn root_offset(&self) -> &str {
&self.root_offset
}
#[must_use]
pub fn key_for_root_relative<'a>(&self, rel: &'a str) -> Cow<'a, str> {
if self.root_offset.is_empty() {
return Cow::Borrowed(rel);
}
Cow::Owned(format!("{}/{rel}", self.root_offset))
}
#[must_use]
pub fn root_relative_from_key<'a>(&self, key: &'a str) -> Option<Cow<'a, str>> {
if self.root_offset.is_empty() {
return Some(Cow::Borrowed(key));
}
strip_path_component_prefix(key, &self.root_offset).map(Cow::Borrowed)
}
#[must_use]
pub fn old_path_for_root_relative<'a>(&'a self, rel: &str) -> Option<Cow<'a, str>> {
let old = self.old_path_for(&self.key_for_root_relative(rel))?;
self.root_relative_from_key(old)
}
#[must_use]
pub fn base(&self) -> Option<&Path> {
self.base.as_deref()
}
pub fn touched_files(&self) -> impl Iterator<Item = &str> {
self.touched_files.iter().map(String::as_str)
}
#[must_use]
pub fn key_for(&self, path: &Path, fallback_root: &Path) -> Option<String> {
relative_to_diff_path(path, self.base.as_deref().unwrap_or(fallback_root))
}
}
#[must_use]
pub fn relative_to_diff_path(path: &Path, root: &Path) -> Option<String> {
if let Ok(stripped) = path.strip_prefix(root) {
return Some(stripped.to_string_lossy().replace('\\', "/"));
}
if fallow_types::path_util::is_absolute_path_any_platform(path) {
return None;
}
Some(path.to_string_lossy().replace('\\', "/"))
}
#[must_use]
pub fn strip_path_component_prefix<'a>(path: &'a str, prefix: &str) -> Option<&'a str> {
path.strip_prefix(prefix)?.strip_prefix('/')
}
fn head_line_place(blocks: &[ChangeBlock], line: u64) -> HeadLinePlace {
let mut shift: i128 = 0;
for block in blocks {
if line < block.new_start {
break;
}
if line < block.new_start + block.new_len {
return HeadLinePlace::Added(*block);
}
shift += i128::from(block.old_len) - i128::from(block.new_len);
}
HeadLinePlace::Unchanged(u64::try_from(i128::from(line) + shift).unwrap_or(0))
}
#[cfg(test)]
mod tests {
use super::*;
const EDIT_DIFF: &str = "diff --git a/a.js b/a.js\n--- a/a.js\n+++ b/a.js\n@@ -7 +7 @@\n-old seven\n+new seven\n@@ -10,0 +11,2 @@\n+added eleven\n+added twelve\n@@ -20,2 +21,0 @@\n-gone twenty\n-gone twenty-one\n";
#[test]
fn base_line_range_maps_unchanged_lines_across_blocks() {
let index = DiffIndex::from_unified_diff(EDIT_DIFF);
assert_eq!(index.base_line_range("a.js", 1, 6), Some((1, 6)));
assert_eq!(index.base_line_range("a.js", 13, 21), Some((11, 19)));
assert_eq!(index.base_line_range("a.js", 22, 25), Some((22, 25)));
}
#[test]
fn base_line_range_maps_a_replaced_line_to_its_removed_line() {
let index = DiffIndex::from_unified_diff(EDIT_DIFF);
assert_eq!(index.base_line_range("a.js", 7, 7), Some((7, 7)));
assert_eq!(index.base_line_range("a.js", 1, 12), Some((1, 10)));
}
#[test]
fn base_line_range_maps_a_start_in_a_multi_line_replacement_to_its_last_removed_line() {
let index = DiffIndex::from_unified_diff(
"diff --git a/b.ts b/b.ts\n--- a/b.ts\n+++ b/b.ts\n@@ -1,3 +1,2 @@\n-one\n-two\n-three\n+ONE\n+TWO\n",
);
assert_eq!(index.base_line_range("b.ts", 2, 15), Some((3, 16)));
assert_eq!(index.base_line_range("b.ts", 1, 2), Some((1, 3)));
}
#[test]
fn base_line_range_maps_an_end_in_a_multi_line_replacement_to_its_first_removed_line() {
let index = DiffIndex::from_unified_diff(
"diff --git a/b.ts b/b.ts\n--- a/b.ts\n+++ b/b.ts\n@@ -10,3 +10,2 @@\n-ten\n-eleven\n-twelve\n+TEN\n+ELEVEN\n",
);
assert_eq!(index.base_line_range("b.ts", 1, 10), Some((1, 10)));
assert_eq!(index.base_line_range("b.ts", 1, 11), Some((1, 10)));
assert_eq!(index.base_line_range("b.ts", 12, 20), Some((13, 21)));
}
#[test]
fn base_line_range_has_no_base_line_for_pure_additions() {
let index = DiffIndex::from_unified_diff(EDIT_DIFF);
assert_eq!(index.base_line_range("a.js", 11, 12), None);
let new_file = DiffIndex::from_unified_diff(
"diff --git a/n.js b/n.js\n--- /dev/null\n+++ b/n.js\n@@ -0,0 +1,2 @@\n+one\n+two\n",
);
assert_eq!(new_file.base_line_range("n.js", 1, 2), None);
assert_eq!(new_file.base_line_range("n.js", 3, 4), None);
}
#[test]
fn base_line_range_keeps_files_outside_the_diff() {
let index = DiffIndex::from_unified_diff(EDIT_DIFF);
assert_eq!(index.base_line_range("other.js", 3, 9), Some((3, 9)));
}
#[test]
fn no_newline_marker_does_not_move_the_line_cursor() {
let index = DiffIndex::from_unified_diff(
"diff --git a/a.js b/a.js\n--- a/a.js\n+++ b/a.js\n@@ -3 +3,2 @@\n-last\n\\ No newline at end of file\n+last\n+more\n",
);
assert!(index.line_is_added("a.js", 3));
assert!(index.line_is_added("a.js", 4));
assert!(!index.line_is_added("a.js", 5));
}
#[test]
fn from_unified_diff_caps_added_lines_at_threshold() {
let header =
"diff --git a/big.txt b/big.txt\n--- a/big.txt\n+++ b/big.txt\n@@ -0,0 +1,100 @@\n";
let mut body = String::with_capacity(MAX_ADDED_LINES * 16);
for _ in 0..(MAX_ADDED_LINES + 100) {
body.push_str("+x\n");
}
let mut diff = String::with_capacity(header.len() + body.len());
diff.push_str(header);
diff.push_str(&body);
let index = DiffIndex::from_unified_diff(&diff);
assert!(
index.added_line_count() <= MAX_ADDED_LINES,
"indexed {} lines, cap is {MAX_ADDED_LINES}",
index.added_line_count()
);
assert_eq!(
Some(index.net_lines()),
i64::try_from(MAX_ADDED_LINES + 100).ok()
);
assert_eq!(index.filter_scope_size(), index.added_line_count());
assert_eq!(index.hunk_count(), 1);
assert_eq!(
index.base_line_range("other.txt", 1, 1),
None,
"a real cap still stops the base-line map"
);
}
#[test]
fn added_plus_plus_line_is_indexed_and_keeps_base_line_ranges() {
let diff = "diff --git a/src/a.js b/src/a.js\n--- a/src/a.js\n+++ b/src/a.js\n@@ -1,0 +2,2 @@ let count = 0;\n+++count;\n+--count;\n";
let index = DiffIndex::from_unified_diff(diff);
assert!(index.line_is_added("src/a.js", 2));
assert!(index.line_is_added("src/a.js", 3));
assert_eq!(index.base_line_range("src/a.js", 1, 1), Some((1, 1)));
assert_eq!(index.base_line_range("src/other.js", 4, 9), Some((4, 9)));
}
#[test]
fn header_shaped_added_line_keeps_the_current_file() {
let diff = "diff --git a/a.js b/a.js\n--- a/a.js\n+++ b/a.js\n@@ -0,0 +1,2 @@\n+++ b/other.js\n+x\n";
let index = DiffIndex::from_unified_diff(diff);
assert!(!index.changes_path("other.js"));
assert!(index.line_is_added("a.js", 1));
assert!(index.line_is_added("a.js", 2));
}
#[test]
fn quoted_and_tab_suffixed_paths_are_index_keys() {
let diff = "\
diff --git \"a/src/caf\\303\\251.ts\" \"b/src/caf\\303\\251.ts\"
--- \"a/src/caf\\303\\251.ts\"
+++ \"b/src/caf\\303\\251.ts\"
@@ -1,0 +2 @@ x
+x2
diff --git \"a/src/del \\303\\251.ts\" \"b/src/del \\303\\251.ts\"
deleted file mode 100644
--- \"a/src/del \\303\\251.ts\"\t
+++ /dev/null
@@ -1 +0,0 @@
-gone
diff --git a/src/my file.ts b/src/my file.ts
--- a/src/my file.ts\t
+++ b/src/my file.ts\t
@@ -1,0 +2 @@ y
+y2
\\ No newline at end of file
diff --git a/src/old name.ts b/src/new name.ts
similarity index 82%
rename from src/old name.ts
rename to src/new name.ts
--- a/src/old name.ts\t
+++ b/src/new name.ts\t
@@ -6,0 +7 @@ six
+seven
";
let index = DiffIndex::from_unified_diff(diff);
assert!(index.line_is_added("src/café.ts", 2));
assert!(index.changes_path("src/del é.ts"));
assert!(!index.touches_file("src/del é.ts"));
assert!(index.line_is_added("src/my file.ts", 2));
assert!(index.line_is_added("src/new name.ts", 7));
assert_eq!(
index.old_path_for("src/new name.ts"),
Some("src/old name.ts")
);
}
#[test]
fn from_unified_diff_counts_additions_removals_and_hunks() {
let diff = "\
diff --git a/src/a.ts b/src/a.ts
--- a/src/a.ts
+++ b/src/a.ts
@@ -1,3 +1,4 @@
-old
+new
+extra
+++flag
context
@@ -10,2 +11,1 @@
-removed
---flag
kept
";
let index = DiffIndex::from_unified_diff(diff);
assert_eq!(index.hunk_count(), 2);
assert_eq!(index.net_lines(), 0);
assert!(index.changes_path("src/a.ts"));
assert!(index.touches_file("src/a.ts"));
}
#[test]
fn rename_only_diff_has_no_line_or_hunk_changes() {
let diff = "\
diff --git a/src/old.ts b/src/new.ts
similarity index 100%
rename from src/old.ts
rename to src/new.ts
";
let index = DiffIndex::from_unified_diff(diff);
assert_eq!(index.hunk_count(), 0);
assert_eq!(index.net_lines(), 0);
assert!(index.changes_path("src/new.ts"));
assert!(index.touches_file("src/new.ts"));
}
#[test]
fn range_overlaps_added_hotspot_starting_before_diff_touches_inside() {
let diff = "\
diff --git a/src/big.ts b/src/big.ts
--- a/src/big.ts
+++ b/src/big.ts
@@ -114,1 +114,2 @@
ctx
+touched
";
let index = DiffIndex::from_unified_diff(diff);
assert!(index.range_overlaps_added("src/big.ts", 10, 120));
assert!(!index.range_overlaps_added("src/other.ts", 10, 120));
assert!(!index.range_overlaps_added("src/big.ts", 10, 100));
assert!(!index.range_overlaps_added("src/big.ts", 200, 100));
}
#[test]
fn rename_header_records_old_path() {
let diff = "\
diff --git a/src/old.ts b/src/new.ts
similarity index 90%
rename from src/old.ts
rename to src/new.ts
--- a/src/old.ts
+++ b/src/new.ts
@@ -1,1 +1,1 @@
-old
+new
";
let index = DiffIndex::from_unified_diff(diff);
assert_eq!(index.old_path_for("src/new.ts"), Some("src/old.ts"));
assert!(index.touches_file("src/new.ts"));
}
#[test]
fn empty_diff_has_zero_added_lines_and_no_touched_files() {
let index = DiffIndex::from_unified_diff("");
assert_eq!(index.added_line_count(), 0);
assert!(!index.touches_file("src/a.ts"));
assert_eq!(index.filter_scope_size(), 0);
}
#[test]
fn filter_scope_size_counts_added_lines_and_files_without_lines() {
let diff = "\
diff --git a/src/old.ts b/src/renamed.ts
similarity index 100%
rename from src/old.ts
rename to src/renamed.ts
diff --git a/src/a.ts b/src/a.ts
--- a/src/a.ts
+++ b/src/a.ts
@@ -1,1 +1,2 @@
keep
+added
diff --git a/bin/run.ts b/bin/run.ts
old mode 100644
new mode 100755
diff --git a/src/gone.ts b/src/gone.ts
deleted file mode 100644
--- a/src/gone.ts
+++ /dev/null
@@ -1,1 +0,0 @@
-old
";
let index = DiffIndex::from_unified_diff(diff);
assert_eq!(index.added_line_count(), 1);
assert!(
!index.touches_file("bin/run.ts"),
"a mode-only section names no head path, so the filter keeps nothing on it"
);
assert_eq!(
index.filter_scope_size(),
2,
"one added line plus the renamed file; the mode-only and deleted files \
are not touched in the head tree"
);
}
#[test]
fn delete_only_diff_records_removal_without_touching_head_file() {
let diff = "\
diff --git a/src/a.ts b/src/a.ts
--- a/src/a.ts
+++ /dev/null
@@ -1,1 +0,0 @@
-old
";
let index = DiffIndex::from_unified_diff(diff);
assert_eq!(index.added_line_count(), 0);
assert_eq!(index.hunk_count(), 1);
assert_eq!(index.net_lines(), -1);
assert!(index.changes_path("src/a.ts"));
assert!(!index.touches_file("src/a.ts"));
}
#[test]
fn relative_to_diff_path_strips_absolute_root() {
let root = Path::new("/project");
let path = Path::new("/project/src/a.ts");
assert_eq!(
relative_to_diff_path(path, root).as_deref(),
Some("src/a.ts")
);
}
#[test]
fn relative_to_diff_path_passes_through_relative() {
let root = Path::new("/project");
let path = Path::new("src/a.ts");
assert_eq!(
relative_to_diff_path(path, root).as_deref(),
Some("src/a.ts")
);
}
#[test]
fn relative_to_diff_path_returns_none_for_path_outside_root() {
let root = Path::new("/project");
let path = Path::new("/elsewhere/src/a.ts");
assert!(relative_to_diff_path(path, root).is_none());
}
#[test]
fn key_for_without_base_relativizes_against_the_fallback_root() {
let index = DiffIndex::default();
assert_eq!(
index
.key_for(Path::new("/repo/pkg/src/a.ts"), Path::new("/repo/pkg"))
.as_deref(),
Some("src/a.ts")
);
}
#[test]
fn key_for_with_base_equal_to_root_is_unchanged() {
let index = DiffIndex::default().with_base("/repo");
assert_eq!(
index
.key_for(Path::new("/repo/src/a.ts"), Path::new("/repo"))
.as_deref(),
Some("src/a.ts")
);
}
#[test]
fn key_for_with_base_above_root_yields_repo_root_relative_key() {
let index = DiffIndex::default().with_base("/repo");
assert_eq!(
index
.key_for(Path::new("/repo/pkg/src/a.ts"), Path::new("/repo/pkg"))
.as_deref(),
Some("pkg/src/a.ts")
);
}
#[test]
fn key_for_with_base_above_root_matches_a_repo_root_relative_diff() {
let diff = "\
diff --git a/pkg/src/a.ts b/pkg/src/a.ts
--- a/pkg/src/a.ts
+++ b/pkg/src/a.ts
@@ -1,0 +2,1 @@
+added
";
let index = DiffIndex::from_unified_diff(diff).with_base("/repo");
let key = index
.key_for(Path::new("/repo/pkg/src/a.ts"), Path::new("/repo/pkg"))
.expect("finding path is under the base");
assert!(index.touches_file(&key));
assert!(index.line_is_added(&key, 2));
let unbased = DiffIndex::from_unified_diff(diff);
let missed = unbased
.key_for(Path::new("/repo/pkg/src/a.ts"), Path::new("/repo/pkg"))
.expect("still relativizable");
assert_eq!(missed, "src/a.ts");
assert!(!unbased.touches_file(&missed));
}
#[test]
fn key_for_returns_none_for_path_outside_the_base() {
let index = DiffIndex::default().with_base("/repo");
assert!(
index
.key_for(Path::new("/elsewhere/a.ts"), Path::new("/repo/pkg"))
.is_none()
);
}
#[test]
fn old_path_for_root_relative_crosses_the_namespace_and_back() {
let diff = "\
diff --git a/pkg/src/old.ts b/pkg/src/new.ts
similarity index 90%
rename from pkg/src/old.ts
rename to pkg/src/new.ts
--- a/pkg/src/old.ts
+++ b/pkg/src/new.ts
@@ -1,1 +1,1 @@
-old
+new
";
let index = DiffIndex::from_unified_diff(diff)
.with_base("/repo")
.with_root_offset("pkg");
assert_eq!(
index.old_path_for_root_relative("src/new.ts").as_deref(),
Some("src/old.ts")
);
assert_eq!(index.old_path_for("pkg/src/new.ts"), Some("pkg/src/old.ts"));
assert_eq!(index.old_path_for_root_relative("src/absent.ts"), None);
}
#[test]
fn root_relative_key_round_trips() {
let index = DiffIndex::default().with_root_offset("packages/pkg");
assert_eq!(
index.key_for_root_relative("src/a.ts"),
"packages/pkg/src/a.ts"
);
assert_eq!(
index
.root_relative_from_key("packages/pkg/src/a.ts")
.as_deref(),
Some("src/a.ts")
);
assert_eq!(index.root_relative_from_key("other/src/a.ts"), None);
assert_eq!(
index.root_relative_from_key("packages/pkg-extra/a.ts"),
None
);
}
#[test]
fn empty_root_offset_is_identity() {
let index = DiffIndex::default();
assert_eq!(index.key_for_root_relative("src/a.ts"), "src/a.ts");
assert_eq!(
index.root_relative_from_key("src/a.ts").as_deref(),
Some("src/a.ts")
);
}
#[test]
fn touched_files_enumerates_diff_header_paths() {
let diff = "\
diff --git a/pkg/a.ts b/pkg/a.ts
--- a/pkg/a.ts
+++ b/pkg/a.ts
@@ -0,0 +1,1 @@
+x
";
let index = DiffIndex::from_unified_diff(diff);
assert_eq!(index.touched_files().collect::<Vec<_>>(), vec!["pkg/a.ts"]);
}
}