Debian Codegraph @

rust/hg-core/src/copy_tracing.rs

raw
1 #[cfg(test)]
2 #[macro_use]
3 mod tests_support;
4
5 #[cfg(test)]
6 mod tests;
7
8 use std::cmp::Ordering;
9 use std::collections::HashMap;
10
11 use bytes_cast::unaligned;
12 use bytes_cast::BytesCast;
13 use im_rc::ordmap::Entry;
14 use im_rc::ordmap::OrdMap;
15 use im_rc::OrdSet;
16
17 use crate::utils::hg_path::HgPath;
18 use crate::utils::hg_path::HgPathBuf;
19 use crate::Revision;
20 use crate::NULL_REVISION;
21
22 pub type PathCopies = HashMap<HgPathBuf, HgPathBuf>;
23
24 type PathToken = usize;
25
26 #[derive(Clone, Debug)]
27 struct CopySource {
28 /// revision at which the copy information was added
29 rev: Revision,
30 /// the copy source, (Set to None in case of deletion of the associated
31 /// key)
32 path: Option<PathToken>,
33 /// a set of previous `CopySource.rev` value directly or indirectly
34 /// overwritten by this one.
35 overwritten: OrdSet<Revision>,
36 }
37
38 impl CopySource {
39 /// create a new CopySource
40 ///
41 /// Use this when no previous copy source existed.
42 fn new(rev: Revision, path: Option<PathToken>) -> Self {
43 Self { rev, path, overwritten: OrdSet::new() }
44 }
45
46 /// create a new CopySource from merging two others
47 ///
48 /// Use this when merging two InternalPathCopies requires active merging of
49 /// some entries.
50 fn new_from_merge(rev: Revision, winner: &Self, loser: &Self) -> Self {
51 let mut overwritten = OrdSet::new();
52 overwritten.extend(winner.overwritten.iter().copied());
53 overwritten.extend(loser.overwritten.iter().copied());
54 overwritten.insert(winner.rev);
55 overwritten.insert(loser.rev);
56 Self { rev, path: winner.path, overwritten }
57 }
58
59 /// Update the value of a pre-existing CopySource
60 ///
61 /// Use this when recording copy information from parent → child edges
62 fn overwrite(&mut self, rev: Revision, path: Option<PathToken>) {
63 self.overwritten.insert(self.rev);
64 self.rev = rev;
65 self.path = path;
66 }
67
68 /// Mark pre-existing copy information as "dropped" by a file deletion
69 ///
70 /// Use this when recording copy information from parent → child edges
71 fn mark_delete(&mut self, rev: Revision) {
72 self.overwritten.insert(self.rev);
73 self.rev = rev;
74 self.path = None;
75 }
76
77 /// Mark pre-existing copy information as "dropped" by a file deletion
78 ///
79 /// Use this when recording copy information from parent → child edges
80 fn mark_delete_with_pair(&mut self, rev: Revision, other: &Self) {
81 self.overwritten.insert(self.rev);
82 if other.rev != rev {
83 self.overwritten.insert(other.rev);
84 }
85 self.overwritten.extend(other.overwritten.iter().copied());
86 self.rev = rev;
87 self.path = None;
88 }
89
90 fn is_overwritten_by(&self, other: &Self) -> bool {
91 other.overwritten.contains(&self.rev)
92 }
93 }
94
95 // For the same "dest", content generated for a given revision will always be
96 // the same.
97 impl PartialEq for CopySource {
98 fn eq(&self, other: &Self) -> bool {
99 #[cfg(debug_assertions)]
100 {
101 if self.rev == other.rev {
102 debug_assert!(self.path == other.path);
103 debug_assert!(self.overwritten == other.overwritten);
104 }
105 }
106 self.rev == other.rev
107 }
108 }
109
110 /// maps CopyDestination to Copy Source (+ a "timestamp" for the operation)
111 type InternalPathCopies = OrdMap<PathToken, CopySource>;
112
113 /// Represent active changes that affect the copy tracing.
114 enum Action<'a> {
115 /// The parent ? children edge is removing a file
116 ///
117 /// (actually, this could be the edge from the other parent, but it does
118 /// not matters)
119 Removed(&'a HgPath),
120 /// The parent ? children edge introduce copy information between (dest,
121 /// source)
122 CopiedFromP1(&'a HgPath, &'a HgPath),
123 CopiedFromP2(&'a HgPath, &'a HgPath),
124 }
125
126 /// This express the possible "special" case we can get in a merge
127 ///
128 /// See mercurial/metadata.py for details on these values.
129 #[derive(PartialEq)]
130 enum MergeCase {
131 /// Merged: file had history on both side that needed to be merged
132 Merged,
133 /// Salvaged: file was candidate for deletion, but survived the merge
134 Salvaged,
135 /// Normal: Not one of the two cases above
136 Normal,
137 }
138
139 const COPY_MASK: u8 = 3;
140 const P1_COPY: u8 = 2;
141 const P2_COPY: u8 = 3;
142 const ACTION_MASK: u8 = 28;
143 const REMOVED: u8 = 12;
144 const MERGED: u8 = 8;
145 const SALVAGED: u8 = 16;
146
147 #[derive(BytesCast)]
148 #[repr(C)]
149 struct ChangedFilesIndexEntry {
150 flags: u8,
151
152 /// Only the end position is stored. The start is at the end of the
153 /// previous entry.
154 destination_path_end_position: unaligned::U32Be,
155
156 source_index_entry_position: unaligned::U32Be,
157 }
158
159 fn _static_assert_size_of() {
160 let _ = std::mem::transmute::<ChangedFilesIndexEntry, [u8; 9]>;
161 }
162
163 /// Represents the files affected by a changeset.
164 ///
165 /// This holds a subset of `mercurial.metadata.ChangingFiles` as we do not need
166 /// all the data categories tracked by it.
167 pub struct ChangedFiles<'a> {
168 index: &'a [ChangedFilesIndexEntry],
169 paths: &'a [u8],
170 }
171
172 impl<'a> ChangedFiles<'a> {
173 pub fn new(data: &'a [u8]) -> Self {
174 let (header, rest) = unaligned::U32Be::from_bytes(data).unwrap();
175 let nb_index_entries = header.get() as usize;
176 let (index, paths) =
177 ChangedFilesIndexEntry::slice_from_bytes(rest, nb_index_entries)
178 .unwrap();
179 Self { index, paths }
180 }
181
182 pub fn new_empty() -> Self {
183 ChangedFiles { index: &[], paths: &[] }
184 }
185
186 /// Internal function to return the filename of the entry at a given index
187 fn path(&self, idx: usize) -> &HgPath {
188 let start = if idx == 0 {
189 0
190 } else {
191 self.index[idx - 1].destination_path_end_position.get() as usize
192 };
193 let end = self.index[idx].destination_path_end_position.get() as usize;
194 HgPath::new(&self.paths[start..end])
195 }
196
197 /// Return an iterator over all the `Action` in this instance.
198 fn iter_actions(&self) -> impl Iterator<Item = Action> {
199 self.index.iter().enumerate().flat_map(move |(idx, entry)| {
200 let path = self.path(idx);
201 if (entry.flags & ACTION_MASK) == REMOVED {
202 Some(Action::Removed(path))
203 } else if (entry.flags & COPY_MASK) == P1_COPY {
204 let source_idx =
205 entry.source_index_entry_position.get() as usize;
206 Some(Action::CopiedFromP1(path, self.path(source_idx)))
207 } else if (entry.flags & COPY_MASK) == P2_COPY {
208 let source_idx =
209 entry.source_index_entry_position.get() as usize;
210 Some(Action::CopiedFromP2(path, self.path(source_idx)))
211 } else {
212 None
213 }
214 })
215 }
216
217 /// return the MergeCase value associated with a filename
218 fn get_merge_case(&self, path: &HgPath) -> MergeCase {
219 if self.index.is_empty() {
220 return MergeCase::Normal;
221 }
222 let mut low_part = 0;
223 let mut high_part = self.index.len();
224
225 while low_part < high_part {
226 let cursor = (low_part + high_part - 1) / 2;
227 match path.cmp(self.path(cursor)) {
228 Ordering::Less => low_part = cursor + 1,
229 Ordering::Greater => high_part = cursor,
230 Ordering::Equal => {
231 return match self.index[cursor].flags & ACTION_MASK {
232 MERGED => MergeCase::Merged,
233 SALVAGED => MergeCase::Salvaged,
234 _ => MergeCase::Normal,
235 };
236 }
237 }
238 }
239 MergeCase::Normal
240 }
241 }
242
243 /// A small "tokenizer" responsible of turning full HgPath into lighter
244 /// PathToken
245 ///
246 /// Dealing with small object, like integer is much faster, so HgPath input are
247 /// turned into integer "PathToken" and converted back in the end.
248 #[derive(Clone, Debug, Default)]
249 struct TwoWayPathMap {
250 token: HashMap<HgPathBuf, PathToken>,
251 path: Vec<HgPathBuf>,
252 }
253
254 impl TwoWayPathMap {
255 fn tokenize(&mut self, path: &HgPath) -> PathToken {
256 match self.token.get(path) {
257 Some(a) => *a,
258 None => {
259 let a = self.token.len();
260 let buf = path.to_owned();
261 self.path.push(buf.clone());
262 self.token.insert(buf, a);
263 a
264 }
265 }
266 }
267
268 fn untokenize(&self, token: PathToken) -> &HgPathBuf {
269 assert!(token < self.path.len(), "Unknown token: {}", token);
270 &self.path[token]
271 }
272 }
273
274 /// Same as mercurial.copies._combine_changeset_copies, but in Rust.
275 pub struct CombineChangesetCopies {
276 all_copies: HashMap<Revision, InternalPathCopies>,
277 path_map: TwoWayPathMap,
278 children_count: HashMap<Revision, usize>,
279 }
280
281 impl CombineChangesetCopies {
282 pub fn new(children_count: HashMap<Revision, usize>) -> Self {
283 Self {
284 all_copies: HashMap::new(),
285 path_map: TwoWayPathMap::default(),
286 children_count,
287 }
288 }
289
290 /// Combined the given `changes` data specific to `rev` with the data
291 /// previously given for its parents (and transitively, its ancestors).
292 pub fn add_revision(
293 &mut self,
294 rev: Revision,
295 p1: Revision,
296 p2: Revision,
297 changes: ChangedFiles<'_>,
298 ) {
299 self.add_revision_inner(rev, p1, p2, changes.iter_actions(), |path| {
300 changes.get_merge_case(path)
301 })
302 }
303
304 /// Separated out from `add_revsion` so that unit tests can call this
305 /// without synthetizing a `ChangedFiles` in binary format.
306 fn add_revision_inner<'a>(
307 &mut self,
308 rev: Revision,
309 p1: Revision,
310 p2: Revision,
311 copy_actions: impl Iterator<Item = Action<'a>>,
312 get_merge_case: impl Fn(&HgPath) -> MergeCase + Copy,
313 ) {
314 // Retrieve data computed in a previous iteration
315 let p1_copies = match p1 {
316 NULL_REVISION => None,
317 _ => get_and_clean_parent_copies(
318 &mut self.all_copies,
319 &mut self.children_count,
320 p1,
321 ), // will be None if the vertex is not to be traversed
322 };
323 let p2_copies = match p2 {
324 NULL_REVISION => None,
325 _ => get_and_clean_parent_copies(
326 &mut self.all_copies,
327 &mut self.children_count,
328 p2,
329 ), // will be None if the vertex is not to be traversed
330 };
331 // combine it with data for that revision
332 let (p1_copies, p2_copies) = chain_changes(
333 &mut self.path_map,
334 p1_copies,
335 p2_copies,
336 copy_actions,
337 rev,
338 );
339 let copies = match (p1_copies, p2_copies) {
340 (None, None) => None,
341 (c, None) => c,
342 (None, c) => c,
343 (Some(p1_copies), Some(p2_copies)) => Some(merge_copies_dict(
344 &self.path_map,
345 rev,
346 p2_copies,
347 p1_copies,
348 get_merge_case,
349 )),
350 };
351 if let Some(c) = copies {
352 self.all_copies.insert(rev, c);
353 }
354 }
355
356 /// Drop intermediate data (such as which revision a copy was from) and
357 /// return the final mapping.
358 pub fn finish(mut self, target_rev: Revision) -> PathCopies {
359 let tt_result = self
360 .all_copies
361 .remove(&target_rev)
362 .expect("target revision was not processed");
363 let mut result = PathCopies::default();
364 for (dest, tt_source) in tt_result {
365 if let Some(path) = tt_source.path {
366 let path_dest = self.path_map.untokenize(dest).to_owned();
367 let path_path = self.path_map.untokenize(path).to_owned();
368 result.insert(path_dest, path_path);
369 }
370 }
371 result
372 }
373 }
374
375 /// fetch previous computed information
376 ///
377 /// If no other children are expected to need this information, we drop it from
378 /// the cache.
379 ///
380 /// If parent is not part of the set we are expected to walk, return None.
381 fn get_and_clean_parent_copies(
382 all_copies: &mut HashMap<Revision, InternalPathCopies>,
383 children_count: &mut HashMap<Revision, usize>,
384 parent_rev: Revision,
385 ) -> Option<InternalPathCopies> {
386 let count = children_count.get_mut(&parent_rev)?;
387 *count -= 1;
388 if *count == 0 {
389 match all_copies.remove(&parent_rev) {
390 Some(c) => Some(c),
391 None => Some(InternalPathCopies::default()),
392 }
393 } else {
394 match all_copies.get(&parent_rev) {
395 Some(c) => Some(c.clone()),
396 None => Some(InternalPathCopies::default()),
397 }
398 }
399 }
400
401 /// Combine ChangedFiles with some existing PathCopies information and return
402 /// the result
403 fn chain_changes<'a>(
404 path_map: &mut TwoWayPathMap,
405 base_p1_copies: Option<InternalPathCopies>,
406 base_p2_copies: Option<InternalPathCopies>,
407 copy_actions: impl Iterator<Item = Action<'a>>,
408 current_rev: Revision,
409 ) -> (Option<InternalPathCopies>, Option<InternalPathCopies>) {
410 // Fast path the "nothing to do" case.
411 if let (None, None) = (&base_p1_copies, &base_p2_copies) {
412 return (None, None);
413 }
414
415 let mut p1_copies = base_p1_copies.clone();
416 let mut p2_copies = base_p2_copies.clone();
417 for action in copy_actions {
418 match action {
419 Action::CopiedFromP1(path_dest, path_source) => {
420 match &mut p1_copies {
421 None => (), // This is not a vertex we should proceed.
422 Some(copies) => add_one_copy(
423 current_rev,
424 path_map,
425 copies,
426 base_p1_copies.as_ref().unwrap(),
427 path_dest,
428 path_source,
429 ),
430 }
431 }
432 Action::CopiedFromP2(path_dest, path_source) => {
433 match &mut p2_copies {
434 None => (), // This is not a vertex we should proceed.
435 Some(copies) => add_one_copy(
436 current_rev,
437 path_map,
438 copies,
439 base_p2_copies.as_ref().unwrap(),
440 path_dest,
441 path_source,
442 ),
443 }
444 }
445 Action::Removed(deleted_path) => {
446 // We must drop copy information for removed file.
447 //
448 // We need to explicitly record them as dropped to
449 // propagate this information when merging two
450 // InternalPathCopies object.
451 let deleted = path_map.tokenize(deleted_path);
452
453 let p1_entry = match &mut p1_copies {
454 None => None,
455 Some(copies) => match copies.entry(deleted) {
456 Entry::Occupied(e) => Some(e),
457 Entry::Vacant(_) => None,
458 },
459 };
460 let p2_entry = match &mut p2_copies {
461 None => None,
462 Some(copies) => match copies.entry(deleted) {
463 Entry::Occupied(e) => Some(e),
464 Entry::Vacant(_) => None,
465 },
466 };
467
468 match (p1_entry, p2_entry) {
469 (None, None) => (),
470 (Some(mut e), None) => e.get_mut().mark_delete(current_rev),
471 (None, Some(mut e)) => e.get_mut().mark_delete(current_rev),
472 (Some(mut e1), Some(mut e2)) => {
473 let cs1 = e1.get_mut();
474 let cs2 = e2.get();
475 if cs1 == cs2 {
476 cs1.mark_delete(current_rev);
477 } else {
478 cs1.mark_delete_with_pair(current_rev, cs2);
479 }
480 e2.insert(cs1.clone());
481 }
482 }
483 }
484 }
485 }
486 (p1_copies, p2_copies)
487 }
488
489 // insert one new copy information in an InternalPathCopies
490 //
491 // This deal with chaining and overwrite.
492 fn add_one_copy(
493 current_rev: Revision,
494 path_map: &mut TwoWayPathMap,
495 copies: &mut InternalPathCopies,
496 base_copies: &InternalPathCopies,
497 path_dest: &HgPath,
498 path_source: &HgPath,
499 ) {
500 let dest = path_map.tokenize(path_dest);
501 let source = path_map.tokenize(path_source);
502 let entry = if let Some(v) = base_copies.get(&source) {
503 match &v.path {
504 Some(path) => Some((*(path)).to_owned()),
505 None => Some(source.to_owned()),
506 }
507 } else {
508 Some(source.to_owned())
509 };
510 // Each new entry is introduced by the children, we
511 // record this information as we will need it to take
512 // the right decision when merging conflicting copy
513 // information. See merge_copies_dict for details.
514 match copies.entry(dest) {
515 Entry::Vacant(slot) => {
516 let ttpc = CopySource::new(current_rev, entry);
517 slot.insert(ttpc);
518 }
519 Entry::Occupied(mut slot) => {
520 let ttpc = slot.get_mut();
521 ttpc.overwrite(current_rev, entry);
522 }
523 }
524 }
525
526 /// merge two copies-mapping together, minor and major
527 ///
528 /// In case of conflict, value from "major" will be picked, unless in some
529 /// cases. See inline documentation for details.
530 fn merge_copies_dict(
531 path_map: &TwoWayPathMap,
532 current_merge: Revision,
533 minor: InternalPathCopies,
534 major: InternalPathCopies,
535 get_merge_case: impl Fn(&HgPath) -> MergeCase + Copy,
536 ) -> InternalPathCopies {
537 use crate::utils::ordmap_union_with_merge;
538 use crate::utils::MergeResult;
539
540 ordmap_union_with_merge(minor, major, |&dest, src_minor, src_major| {
541 let (pick, overwrite) = compare_value(
542 current_merge,
543 || get_merge_case(path_map.untokenize(dest)),
544 src_minor,
545 src_major,
546 );
547 if overwrite {
548 let (winner, loser) = match pick {
549 MergePick::Major | MergePick::Any => (src_major, src_minor),
550 MergePick::Minor => (src_minor, src_major),
551 };
552 MergeResult::New(CopySource::new_from_merge(
553 current_merge,
554 winner,
555 loser,
556 ))
557 } else {
558 match pick {
559 MergePick::Any | MergePick::Major => MergeResult::Right,
560 MergePick::Minor => MergeResult::Left,
561 }
562 }
563 })
564 }
565
566 /// represent the side that should prevail when merging two
567 /// InternalPathCopies
568 #[derive(Debug, PartialEq)]
569 enum MergePick {
570 /// The "major" (p1) side prevails
571 Major,
572 /// The "minor" (p2) side prevails
573 Minor,
574 /// Any side could be used (because they are the same)
575 Any,
576 }
577
578 /// decide which side prevails in case of conflicting values
579 #[allow(clippy::if_same_then_else)]
580 fn compare_value(
581 current_merge: Revision,
582 merge_case_for_dest: impl Fn() -> MergeCase,
583 src_minor: &CopySource,
584 src_major: &CopySource,
585 ) -> (MergePick, bool) {
586 if src_major == src_minor {
587 (MergePick::Any, false)
588 } else if src_major.rev == current_merge {
589 // minor is different according to per minor == major check earlier
590 debug_assert!(src_minor.rev != current_merge);
591
592 // The last value comes the current merge, this value -will- win
593 // eventually.
594 (MergePick::Major, true)
595 } else if src_minor.rev == current_merge {
596 // The last value comes the current merge, this value -will- win
597 // eventually.
598 (MergePick::Minor, true)
599 } else if src_major.path == src_minor.path {
600 debug_assert!(src_major.rev != src_minor.rev);
601 // we have the same value, but from other source;
602 if src_major.is_overwritten_by(src_minor) {
603 (MergePick::Minor, false)
604 } else if src_minor.is_overwritten_by(src_major) {
605 (MergePick::Major, false)
606 } else {
607 (MergePick::Any, true)
608 }
609 } else {
610 debug_assert!(src_major.rev != src_minor.rev);
611 let action = merge_case_for_dest();
612 if src_minor.path.is_some()
613 && src_major.path.is_none()
614 && action == MergeCase::Salvaged
615 {
616 // If the file is "deleted" in the major side but was
617 // salvaged by the merge, we keep the minor side alive
618 (MergePick::Minor, true)
619 } else if src_major.path.is_some()
620 && src_minor.path.is_none()
621 && action == MergeCase::Salvaged
622 {
623 // If the file is "deleted" in the minor side but was
624 // salvaged by the merge, unconditionnaly preserve the
625 // major side.
626 (MergePick::Major, true)
627 } else if src_minor.is_overwritten_by(src_major) {
628 // The information from the minor version are strictly older than
629 // the major version
630 if action == MergeCase::Merged {
631 // If the file was actively merged, its means some non-copy
632 // activity happened on the other branch. It
633 // mean the older copy information are still relevant.
634 //
635 // The major side wins such conflict.
636 (MergePick::Major, true)
637 } else {
638 // No activity on the minor branch, pick the newer one.
639 (MergePick::Major, false)
640 }
641 } else if src_major.is_overwritten_by(src_minor) {
642 if action == MergeCase::Merged {
643 // If the file was actively merged, its means some non-copy
644 // activity happened on the other branch. It
645 // mean the older copy information are still relevant.
646 //
647 // The major side wins such conflict.
648 (MergePick::Major, true)
649 } else {
650 // No activity on the minor branch, pick the newer one.
651 (MergePick::Minor, false)
652 }
653 } else if src_minor.path.is_none() {
654 // the minor side has no relevant information, pick the alive one
655 (MergePick::Major, true)
656 } else if src_major.path.is_none() {
657 // the major side has no relevant information, pick the alive one
658 (MergePick::Minor, true)
659 } else {
660 // by default the major side wins
661 (MergePick::Major, true)
662 }
663 }
664 }