use std::collections::{BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use crate::{DiffDocument, FileDiff, FileId, HunkId, RowId};
const DEFAULT_CONTEXT_LINES: usize = 3;
pub(crate) const FULL_CONTEXT_LINES: usize = 999_999;
#[derive(Clone, Debug)]
pub(crate) struct ContextState {
context_lines: usize,
expanded_files: BTreeSet<FileId>,
}
#[derive(Clone, Debug)]
pub(crate) struct ContextPlan {
pub(crate) state: ContextState,
pub(crate) context_lines: usize,
pub(crate) files: Vec<(PathBuf, FileId)>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ContextChange {
Increase,
Decrease,
ToggleFile,
}
impl ContextState {
pub(crate) fn new() -> Self {
Self {
context_lines: DEFAULT_CONTEXT_LINES,
expanded_files: BTreeSet::new(),
}
}
pub(crate) fn is_expanded(&self, file: FileId) -> bool {
self.expanded_files.contains(&file)
}
pub(crate) fn plan(
&self,
change: ContextChange,
file_ids: &[FileId],
document: &DiffDocument,
) -> Option<ContextPlan> {
let mut next = self.clone();
match change {
ContextChange::Increase => next.context_lines = next.context_lines.saturating_add(1),
ContextChange::Decrease => {
next.context_lines = next.context_lines.checked_sub(1)?;
}
ContextChange::ToggleFile => {
let all_expanded = file_ids
.iter()
.all(|file_id| next.expanded_files.contains(file_id));
for file_id in file_ids.iter().copied() {
if all_expanded {
next.expanded_files.remove(&file_id);
} else {
next.expanded_files.insert(file_id);
}
}
}
}
let mut target_context = None;
let mut files = Vec::with_capacity(file_ids.len());
for file_id in file_ids.iter().copied() {
let Some(file) = document
.files
.iter()
.find(|candidate| candidate.id == file_id)
else {
continue;
};
let Some(path) = file.path() else {
continue;
};
let previous = Self::context_size(&self.expanded_files, file_id, self.context_lines);
let target = Self::context_size(&next.expanded_files, file_id, next.context_lines);
if previous == target {
continue;
}
debug_assert!(target_context.is_none_or(|shared| shared == target));
target_context = Some(target);
files.push((path.to_path_buf(), file_id));
}
Some(ContextPlan {
state: next,
context_lines: target_context?,
files,
})
}
fn context_size(expanded: &BTreeSet<FileId>, file: FileId, default: usize) -> usize {
if expanded.contains(&file) {
FULL_CONTEXT_LINES
} else {
default
}
}
}
impl Default for ContextState {
fn default() -> Self {
Self::new()
}
}
impl FileDiff {
pub(crate) fn path(&self) -> Option<&Path> {
self.header
.new_path
.as_deref()
.or(self.header.old_path.as_deref())
}
pub(crate) fn remap_ids(&mut self, next_hunk_id: &mut usize, next_row_id: &mut usize) {
for hunk in &mut self.hunks {
hunk.id = HunkId::new(*next_hunk_id);
*next_hunk_id += 1;
for line in &mut hunk.lines {
line.id = RowId::new(*next_row_id);
*next_row_id += 1;
}
}
}
}
pub(crate) fn rebuild<F, E>(
next_ids: (usize, usize),
files: &[(PathBuf, FileId)],
target_context_lines: usize,
fetch: F,
) -> Result<Option<Vec<FileDiff>>, E>
where
F: FnOnce(usize, &[&Path]) -> Result<Vec<FileDiff>, E>,
{
let paths = files
.iter()
.map(|(path, _)| path.as_path())
.collect::<Vec<_>>();
let mut replacements = HashMap::new();
for file in fetch(target_context_lines, &paths)? {
let Some(path) = file.path() else {
return Ok(None);
};
replacements.insert(path.to_path_buf(), file);
}
let (mut next_hunk_id, mut next_row_id) = next_ids;
let mut rebuilt = Vec::with_capacity(files.len());
for (path, file_id) in files {
let Some(mut replacement) = replacements.remove(path) else {
return Ok(None);
};
replacement.id = *file_id;
replacement.remap_ids(&mut next_hunk_id, &mut next_row_id);
rebuilt.push(replacement);
}
Ok(Some(rebuilt))
}
pub(crate) fn next_ids(files: &[FileDiff]) -> (usize, usize) {
let mut next_hunk_id = 0;
let mut next_row_id = 0;
for file in files {
for hunk in &file.hunks {
next_hunk_id = next_hunk_id.max(*hunk.id + 1);
for line in &hunk.lines {
next_row_id = next_row_id.max(*line.id + 1);
}
}
}
(next_hunk_id, next_row_id)
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use crate::Decode;
use super::*;
fn base_document() -> DiffDocument {
DiffDocument::decode_str(
"\
diff --git a/a.txt b/a.txt
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.txt
+++ b/a.txt
@@ -3 +3 @@
-one
+ONE
",
)
.unwrap()
}
fn expanded_files() -> Vec<FileDiff> {
DiffDocument::decode_str(
"\
diff --git a/a.txt b/a.txt
index 1111111111111111111111111111111111111111..2222222222222222222222222222222222222222 100644
--- a/a.txt
+++ b/a.txt
@@ -1,5 +1,5 @@
ctx1
ctx2
-one
+ONE
ctx4
ctx5
",
)
.unwrap()
.files
}
#[test]
fn increase_plans_one_line_wider() {
let document = base_document();
let plan = ContextState::new()
.plan(ContextChange::Increase, &[FileId::new(0)], &document)
.unwrap();
assert_eq!(plan.context_lines, DEFAULT_CONTEXT_LINES + 1);
assert_eq!(plan.files, vec![(PathBuf::from("a.txt"), FileId::new(0))]);
}
#[test]
fn toggle_file_expands_then_collapses() {
let document = base_document();
let expand = ContextState::new()
.plan(ContextChange::ToggleFile, &[FileId::new(0)], &document)
.unwrap();
assert_eq!(expand.context_lines, FULL_CONTEXT_LINES);
let collapse = expand
.state
.plan(ContextChange::ToggleFile, &[FileId::new(0)], &document)
.unwrap();
assert_eq!(collapse.context_lines, DEFAULT_CONTEXT_LINES);
}
#[test]
fn rebuild_remaps_ids_above_existing_document() {
let document = base_document();
let (next_hunk, next_row) = next_ids(&document.files);
let files = vec![(PathBuf::from("a.txt"), FileId::new(0))];
let rebuilt = rebuild((next_hunk, next_row), &files, 5, |_, _| {
Ok::<_, ()>(expanded_files())
})
.unwrap()
.unwrap();
let hunk = &rebuilt[0].hunks[0];
assert_eq!(hunk.id, HunkId::new(next_hunk));
for (offset, line) in hunk.lines.iter().enumerate() {
assert_eq!(line.id, RowId::new(next_row + offset));
}
}
#[test]
fn decrease_below_zero_has_no_plan() {
let document = base_document();
let mut state = ContextState::new();
for _ in 0..DEFAULT_CONTEXT_LINES {
state = state
.plan(ContextChange::Decrease, &[FileId::new(0)], &document)
.unwrap()
.state;
}
assert!(
state
.plan(ContextChange::Decrease, &[FileId::new(0)], &document)
.is_none()
);
}
#[test]
fn no_target_files_has_no_plan() {
let document = base_document();
assert!(
ContextState::new()
.plan(ContextChange::Increase, &[], &document)
.is_none()
);
}
}