1use std::collections::HashMap;
22use std::collections::hash_map;
23use std::iter;
24use std::ops::Range;
25use std::sync::Arc;
26
27use bstr::BStr;
28use bstr::BString;
29use itertools::Itertools as _;
30use pollster::FutureExt as _;
31
32use crate::backend::BackendError;
33use crate::backend::BackendResult;
34use crate::backend::CommitId;
35use crate::commit::Commit;
36use crate::conflicts::ConflictMarkerStyle;
37use crate::conflicts::ConflictMaterializeOptions;
38use crate::conflicts::MaterializedTreeValue;
39use crate::conflicts::materialize_merge_result_to_bytes;
40use crate::conflicts::materialize_tree_value;
41use crate::diff::ContentDiff;
42use crate::diff::DiffHunkKind;
43use crate::files::FileMergeHunkLevel;
44use crate::fileset::FilesetExpression;
45use crate::graph::GraphEdge;
46use crate::merge::SameChange;
47use crate::merged_tree::MergedTree;
48use crate::repo::Repo;
49use crate::repo_path::RepoPath;
50use crate::repo_path::RepoPathBuf;
51use crate::revset::ResolvedRevsetExpression;
52use crate::revset::RevsetEvaluationError;
53use crate::revset::RevsetExpression;
54use crate::revset::RevsetFilterPredicate;
55use crate::store::Store;
56use crate::tree_merge::MergeOptions;
57
58#[derive(Clone, Debug)]
60pub struct FileAnnotation {
61 line_map: OriginalLineMap,
62 text: BString,
63}
64
65impl FileAnnotation {
66 pub fn line_origins(&self) -> impl Iterator<Item = (Result<&LineOrigin, &LineOrigin>, &BStr)> {
75 itertools::zip_eq(&self.line_map, self.text.split_inclusive(|b| *b == b'\n'))
76 .map(|(line_origin, line)| (line_origin.as_ref(), line.as_ref()))
77 }
78
79 pub fn lines(&self) -> impl Iterator<Item = (Result<&CommitId, &CommitId>, &BStr)> {
88 itertools::zip_eq(
89 self.commit_ids(),
90 self.text
91 .split_inclusive(|b| *b == b'\n')
92 .map(AsRef::as_ref),
93 )
94 }
95
96 pub fn line_ranges(
103 &self,
104 ) -> impl Iterator<Item = (Result<&CommitId, &CommitId>, Range<usize>)> {
105 let ranges = self
106 .text
107 .split_inclusive(|b| *b == b'\n')
108 .scan(0, |total, line| {
109 let start = *total;
110 *total += line.len();
111 Some(start..*total)
112 });
113 itertools::zip_eq(self.commit_ids(), ranges)
114 }
115
116 pub fn compact_line_ranges(
120 &self,
121 ) -> impl Iterator<Item = (Result<&CommitId, &CommitId>, Range<usize>)> {
122 let mut ranges = self.line_ranges();
123 let mut acc = ranges.next();
124 iter::from_fn(move || {
125 let (acc_commit_id, acc_range) = acc.as_mut()?;
126 for (cur_commit_id, cur_range) in ranges.by_ref() {
127 if *acc_commit_id == cur_commit_id {
128 acc_range.end = cur_range.end;
129 } else {
130 return acc.replace((cur_commit_id, cur_range));
131 }
132 }
133 acc.take()
134 })
135 }
136
137 pub fn text(&self) -> &BStr {
139 self.text.as_ref()
140 }
141
142 fn commit_ids(&self) -> impl Iterator<Item = Result<&CommitId, &CommitId>> {
143 self.line_map.iter().map(|line_origin| {
144 line_origin
145 .as_ref()
146 .map(|origin| &origin.commit_id)
147 .map_err(|origin| &origin.commit_id)
148 })
149 }
150}
151
152#[derive(Clone, Debug)]
154pub struct FileAnnotator {
155 file_path: RepoPathBuf,
157 starting_text: BString,
158 state: AnnotationState,
159}
160
161impl FileAnnotator {
162 pub fn from_commit(starting_commit: &Commit, file_path: &RepoPath) -> BackendResult<Self> {
166 let source = Source::load(starting_commit, file_path)?;
167 Ok(Self::with_source(starting_commit.id(), file_path, source))
168 }
169
170 pub fn with_file_content(
177 starting_commit_id: &CommitId,
178 file_path: &RepoPath,
179 starting_text: impl Into<Vec<u8>>,
180 ) -> Self {
181 let source = Source::new(BString::new(starting_text.into()));
182 Self::with_source(starting_commit_id, file_path, source)
183 }
184
185 fn with_source(
186 starting_commit_id: &CommitId,
187 file_path: &RepoPath,
188 mut source: Source,
189 ) -> Self {
190 source.fill_line_map();
191 let starting_text = source.text.clone();
192 let state = AnnotationState {
193 original_line_map: (0..source.line_map.len())
194 .map(|line_number| {
195 Err(LineOrigin {
196 commit_id: starting_commit_id.clone(),
197 line_number,
198 })
199 })
200 .collect(),
201 commit_source_map: HashMap::from([(starting_commit_id.clone(), source)]),
202 num_unresolved_roots: 0,
203 };
204 Self {
205 file_path: file_path.to_owned(),
206 starting_text,
207 state,
208 }
209 }
210
211 pub fn compute(
217 &mut self,
218 repo: &dyn Repo,
219 domain: &Arc<ResolvedRevsetExpression>,
220 ) -> Result<(), RevsetEvaluationError> {
221 process_commits(repo, &mut self.state, domain, &self.file_path)
222 }
223
224 pub fn pending_commits(&self) -> impl Iterator<Item = &CommitId> {
226 self.state.commit_source_map.keys()
227 }
228
229 pub fn to_annotation(&self) -> FileAnnotation {
231 FileAnnotation {
235 line_map: self.state.original_line_map.clone(),
236 text: self.starting_text.clone(),
237 }
238 }
239}
240
241#[derive(Clone, Debug)]
243struct AnnotationState {
244 original_line_map: OriginalLineMap,
245 commit_source_map: HashMap<CommitId, Source>,
247 num_unresolved_roots: usize,
249}
250
251#[derive(Clone, Debug)]
253struct Source {
254 line_map: Vec<(usize, usize)>,
257 text: BString,
259}
260
261impl Source {
262 fn new(text: BString) -> Self {
263 Self {
264 line_map: Vec::new(),
265 text,
266 }
267 }
268
269 fn load(commit: &Commit, file_path: &RepoPath) -> Result<Self, BackendError> {
270 let tree = commit.tree()?;
271 let text = get_file_contents(commit.store(), file_path, &tree).block_on()?;
272 Ok(Self::new(text))
273 }
274
275 fn fill_line_map(&mut self) {
276 let lines = self.text.split_inclusive(|b| *b == b'\n');
277 self.line_map = lines.enumerate().map(|(i, _)| (i, i)).collect();
278 }
279}
280
281type OriginalLineMap = Vec<Result<LineOrigin, LineOrigin>>;
284
285#[derive(Clone, Debug, Eq, PartialEq)]
287pub struct LineOrigin {
288 pub commit_id: CommitId,
290 pub line_number: usize,
292}
293
294fn process_commits(
297 repo: &dyn Repo,
298 state: &mut AnnotationState,
299 domain: &Arc<ResolvedRevsetExpression>,
300 file_name: &RepoPath,
301) -> Result<(), RevsetEvaluationError> {
302 let predicate = RevsetFilterPredicate::File(FilesetExpression::file_path(file_name.to_owned()));
303 let heads = RevsetExpression::commits(state.commit_source_map.keys().cloned().collect());
309 let revset = heads
310 .union(&domain.intersection(&heads.ancestors()).filtered(predicate))
311 .evaluate(repo)?;
312
313 state.num_unresolved_roots = 0;
314 for node in revset.iter_graph() {
315 let (commit_id, edge_list) = node?;
316 process_commit(repo, file_name, state, &commit_id, &edge_list)?;
317 if state.commit_source_map.len() == state.num_unresolved_roots {
318 break;
320 }
321 }
322 Ok(())
323}
324
325fn process_commit(
329 repo: &dyn Repo,
330 file_name: &RepoPath,
331 state: &mut AnnotationState,
332 current_commit_id: &CommitId,
333 edges: &[GraphEdge<CommitId>],
334) -> Result<(), BackendError> {
335 let Some(mut current_source) = state.commit_source_map.remove(current_commit_id) else {
336 return Ok(());
337 };
338
339 for parent_edge in edges {
340 let parent_commit_id = &parent_edge.target;
341 let parent_source = match state.commit_source_map.entry(parent_commit_id.clone()) {
342 hash_map::Entry::Occupied(entry) => entry.into_mut(),
343 hash_map::Entry::Vacant(entry) => {
344 let commit = repo.store().get_commit(entry.key())?;
345 entry.insert(Source::load(&commit, file_name)?)
346 }
347 };
348
349 let mut current_lines = current_source.line_map.iter().copied().peekable();
358 let mut new_current_line_map = Vec::new();
359 let mut new_parent_line_map = Vec::new();
360 copy_same_lines_with(
361 ¤t_source.text,
362 &parent_source.text,
363 |current_start, parent_start, count| {
364 new_current_line_map
365 .extend(current_lines.peeking_take_while(|&(cur, _)| cur < current_start));
366 while let Some((current, starting)) =
367 current_lines.next_if(|&(cur, _)| cur < current_start + count)
368 {
369 let parent = parent_start + (current - current_start);
370 new_parent_line_map.push((parent, starting));
371 }
372 },
373 );
374 new_current_line_map.extend(current_lines);
375 current_source.line_map = new_current_line_map;
376 parent_source.line_map = if parent_source.line_map.is_empty() {
377 new_parent_line_map
378 } else {
379 itertools::merge(parent_source.line_map.iter().copied(), new_parent_line_map).collect()
380 };
381 if parent_source.line_map.is_empty() {
382 state.commit_source_map.remove(parent_commit_id);
383 } else if parent_edge.is_missing() {
384 for &(parent_line_number, starting_line_number) in &parent_source.line_map {
388 state.original_line_map[starting_line_number] = Err(LineOrigin {
389 commit_id: parent_commit_id.clone(),
390 line_number: parent_line_number,
391 });
392 }
393 state.num_unresolved_roots += 1;
394 }
395 }
396
397 for (current_line_number, starting_line_number) in current_source.line_map {
401 state.original_line_map[starting_line_number] = Ok(LineOrigin {
402 commit_id: current_commit_id.clone(),
403 line_number: current_line_number,
404 });
405 }
406
407 Ok(())
408}
409
410fn copy_same_lines_with(
413 current_contents: &[u8],
414 parent_contents: &[u8],
415 mut copy: impl FnMut(usize, usize, usize),
416) {
417 let diff = ContentDiff::by_line([current_contents, parent_contents]);
418 let mut current_line_counter: usize = 0;
419 let mut parent_line_counter: usize = 0;
420 for hunk in diff.hunks() {
421 match hunk.kind {
422 DiffHunkKind::Matching => {
423 let count = hunk.contents[0].split_inclusive(|b| *b == b'\n').count();
424 copy(current_line_counter, parent_line_counter, count);
425 current_line_counter += count;
426 parent_line_counter += count;
427 }
428 DiffHunkKind::Different => {
429 let current_output = hunk.contents[0];
430 let parent_output = hunk.contents[1];
431 current_line_counter += current_output.split_inclusive(|b| *b == b'\n').count();
432 parent_line_counter += parent_output.split_inclusive(|b| *b == b'\n').count();
433 }
434 }
435 }
436}
437
438async fn get_file_contents(
439 store: &Store,
440 path: &RepoPath,
441 tree: &MergedTree,
442) -> Result<BString, BackendError> {
443 let file_value = tree.path_value_async(path).await?;
444 let effective_file_value = materialize_tree_value(store, path, file_value).await?;
445 match effective_file_value {
446 MaterializedTreeValue::File(mut file) => Ok(file.read_all(path).await?.into()),
447 MaterializedTreeValue::FileConflict(file) => {
448 let options = ConflictMaterializeOptions {
450 marker_style: ConflictMarkerStyle::Diff,
451 marker_len: None,
452 merge: MergeOptions {
453 hunk_level: FileMergeHunkLevel::Line,
454 same_change: SameChange::Accept,
455 },
456 };
457 Ok(materialize_merge_result_to_bytes(&file.contents, &options))
458 }
459 _ => Ok(BString::default()),
460 }
461}
462
463#[cfg(test)]
464mod tests {
465 use super::*;
466
467 fn make_line_origin(commit_id: &CommitId, line_number: usize) -> LineOrigin {
468 LineOrigin {
469 commit_id: commit_id.clone(),
470 line_number,
471 }
472 }
473
474 #[test]
475 fn test_lines_iterator_empty() {
476 let annotation = FileAnnotation {
477 line_map: vec![],
478 text: "".into(),
479 };
480 assert_eq!(annotation.line_origins().collect_vec(), vec![]);
481 assert_eq!(annotation.lines().collect_vec(), vec![]);
482 assert_eq!(annotation.line_ranges().collect_vec(), vec![]);
483 assert_eq!(annotation.compact_line_ranges().collect_vec(), vec![]);
484 }
485
486 #[test]
487 fn test_lines_iterator_with_content() {
488 let commit_id1 = CommitId::from_hex("111111");
489 let commit_id2 = CommitId::from_hex("222222");
490 let commit_id3 = CommitId::from_hex("333333");
491 let annotation = FileAnnotation {
492 line_map: vec![
493 Ok(make_line_origin(&commit_id1, 0)),
494 Ok(make_line_origin(&commit_id2, 1)),
495 Ok(make_line_origin(&commit_id3, 2)),
496 ],
497 text: "foo\n\nbar\n".into(),
498 };
499 assert_eq!(
500 annotation.line_origins().collect_vec(),
501 vec![
502 (Ok(&make_line_origin(&commit_id1, 0)), "foo\n".as_ref()),
503 (Ok(&make_line_origin(&commit_id2, 1)), "\n".as_ref()),
504 (Ok(&make_line_origin(&commit_id3, 2)), "bar\n".as_ref()),
505 ]
506 );
507 assert_eq!(
508 annotation.lines().collect_vec(),
509 vec![
510 (Ok(&commit_id1), "foo\n".as_ref()),
511 (Ok(&commit_id2), "\n".as_ref()),
512 (Ok(&commit_id3), "bar\n".as_ref()),
513 ]
514 );
515 assert_eq!(
516 annotation.line_ranges().collect_vec(),
517 vec![
518 (Ok(&commit_id1), 0..4),
519 (Ok(&commit_id2), 4..5),
520 (Ok(&commit_id3), 5..9),
521 ]
522 );
523 assert_eq!(
524 annotation.compact_line_ranges().collect_vec(),
525 vec![
526 (Ok(&commit_id1), 0..4),
527 (Ok(&commit_id2), 4..5),
528 (Ok(&commit_id3), 5..9),
529 ]
530 );
531 }
532
533 #[test]
534 fn test_lines_iterator_compaction() {
535 let commit_id1 = CommitId::from_hex("111111");
536 let commit_id2 = CommitId::from_hex("222222");
537 let commit_id3 = CommitId::from_hex("333333");
538 let annotation = FileAnnotation {
539 line_map: vec![
540 Ok(make_line_origin(&commit_id1, 0)),
541 Ok(make_line_origin(&commit_id1, 1)),
542 Ok(make_line_origin(&commit_id2, 2)),
543 Ok(make_line_origin(&commit_id1, 3)),
544 Ok(make_line_origin(&commit_id3, 4)),
545 Ok(make_line_origin(&commit_id3, 5)),
546 Ok(make_line_origin(&commit_id3, 6)),
547 ],
548 text: "\n".repeat(7).into(),
549 };
550 assert_eq!(
551 annotation.compact_line_ranges().collect_vec(),
552 vec![
553 (Ok(&commit_id1), 0..2),
554 (Ok(&commit_id2), 2..3),
555 (Ok(&commit_id1), 3..4),
556 (Ok(&commit_id3), 4..7),
557 ]
558 );
559 }
560}