jj_lib/
annotate.rs

1// Copyright 2024 The Jujutsu Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Methods that allow annotation (attribution and blame) for a file in a
16//! repository.
17//!
18//! TODO: Add support for different blame layers with a trait in the future.
19//! Like commit metadata and more.
20
21use 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/// Annotation results for a specific file
59#[derive(Clone, Debug)]
60pub struct FileAnnotation {
61    line_map: OriginalLineMap,
62    text: BString,
63}
64
65impl FileAnnotation {
66    /// Returns iterator over `(line_origin, line)`s.
67    ///
68    /// For each line, `Ok(line_origin)` returns information about the
69    /// originator commit of the line. If no originator commit was found
70    /// within the domain, `Err(line_origin)` should be set. It points to the
71    /// commit outside of the domain where the search stopped.
72    ///
73    /// The `line` includes newline character.
74    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    /// Returns iterator over `(commit_id, line)`s.
80    ///
81    /// For each line, `Ok(commit_id)` points to the originator commit of the
82    /// line. If no originator commit was found within the domain,
83    /// `Err(commit_id)` should be set. It points to the commit outside of the
84    /// domain where the search stopped.
85    ///
86    /// The `line` includes newline character.
87    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    /// Returns iterator over `(commit_id, line_range)`s.
97    ///
98    /// See [`Self::lines()`] for `commit_id`s.
99    ///
100    /// The `line_range` is a slice range in the file `text`. Consecutive ranges
101    /// having the same `commit_id` are not compacted.
102    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    /// Returns iterator over compacted `(commit_id, line_range)`s.
117    ///
118    /// Consecutive ranges having the same `commit_id` are merged into one.
119    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    /// File content at the starting commit.
138    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/// Annotation process for a specific file.
153#[derive(Clone, Debug)]
154pub struct FileAnnotator {
155    // If we add copy-tracing support, file_path might be tracked by state.
156    file_path: RepoPathBuf,
157    starting_text: BString,
158    state: AnnotationState,
159}
160
161impl FileAnnotator {
162    /// Initializes annotator for a specific file in the `starting_commit`.
163    ///
164    /// If the file is not found, the result would be empty.
165    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    /// Initializes annotator for a specific file path starting with the given
171    /// content.
172    ///
173    /// The file content at the `starting_commit` is set to `starting_text`.
174    /// This is typically one of the file contents in the conflict or
175    /// merged-parent tree.
176    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    /// Computes line-by-line annotation within the `domain`.
212    ///
213    /// The `domain` expression narrows the range of ancestors to search. It
214    /// will be intersected as `domain & ::pending_commits & files(file_path)`.
215    /// The `pending_commits` is assumed to be included in the `domain`.
216    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    /// Remaining commit ids to visit from.
225    pub fn pending_commits(&self) -> impl Iterator<Item = &CommitId> {
226        self.state.commit_source_map.keys()
227    }
228
229    /// Returns the current state as line-oriented annotation.
230    pub fn to_annotation(&self) -> FileAnnotation {
231        // Just clone the line map. We might want to change the underlying data
232        // model something akin to interleaved delta in order to get annotation
233        // at a certain ancestor commit without recomputing.
234        FileAnnotation {
235            line_map: self.state.original_line_map.clone(),
236            text: self.starting_text.clone(),
237        }
238    }
239}
240
241/// Intermediate state of file annotation.
242#[derive(Clone, Debug)]
243struct AnnotationState {
244    original_line_map: OriginalLineMap,
245    /// Commits to file line mappings and contents.
246    commit_source_map: HashMap<CommitId, Source>,
247    /// Number of unresolved root commits in `commit_source_map`.
248    num_unresolved_roots: usize,
249}
250
251/// Line mapping and file content at a certain commit.
252#[derive(Clone, Debug)]
253struct Source {
254    /// Mapping of line numbers in the file at the current commit to the
255    /// starting file, sorted by the line numbers at the current commit.
256    line_map: Vec<(usize, usize)>,
257    /// File content at the current commit.
258    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
281/// List of origins for each line, indexed by line numbers in the
282/// starting file.
283type OriginalLineMap = Vec<Result<LineOrigin, LineOrigin>>;
284
285/// Information about the origin of an annotated line.
286#[derive(Clone, Debug, Eq, PartialEq)]
287pub struct LineOrigin {
288    /// Commit ID where the line was introduced.
289    pub commit_id: CommitId,
290    /// 0-based line number of the line in the origin commit.
291    pub line_number: usize,
292}
293
294/// Starting from the source commits, compute changes at that commit relative to
295/// its direct parents, updating the mappings as we go.
296fn 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    // TODO: If the domain isn't a contiguous range, changes masked out by it
304    // might not be caught by the closest ancestor revision. For example,
305    // domain=merges() would pick up almost nothing because merge revisions
306    // are usually empty. Perhaps, we want to query `files(file_path,
307    // within_sub_graph=domain)`, not `domain & files(file_path)`.
308    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            // No more lines to propagate to ancestors.
319            break;
320        }
321    }
322    Ok(())
323}
324
325/// For a given commit, for each parent, we compare the version in the parent
326/// tree with the current version, updating the mappings for any lines in
327/// common. If the parent doesn't have the file, we skip it.
328fn 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        // For two versions of the same file, for all the lines in common,
350        // overwrite the new mapping in the results for the new commit. Let's
351        // say I have a file in commit A and commit B. We know that according to
352        // local line_map, in commit A, line 3 corresponds to line 7 of the
353        // starting file. Now, line 3 in Commit A corresponds to line 6 in
354        // commit B. Then, we update local line_map to say that "Commit B line 6
355        // goes to line 7 of the starting file". We repeat this for all lines in
356        // common in the two commits.
357        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            &current_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            // If an omitted parent had the file, leave these lines unresolved.
385            // The origin of the unresolved lines is represented as
386            // Err(LineOrigin { parent_commit_id, parent_line_number }).
387            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    // Once we've looked at all parents of a commit, any leftover lines must be
398    // original to the current commit, so we save this information in
399    // original_line_map.
400    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
410/// For two files, calls `copy(current_start, parent_start, count)` for each
411/// range of contiguous lines in common (e.g. line 8-10 maps to line 9-11.)
412fn 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            // TODO: track line origins without materializing
449            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}