##// END OF EJS Templates
copies-rust: move the parent token to an enum...
marmoute -
r46675:12192fdb default
parent child Browse files
Show More
@@ -1,567 +1,576 b''
1 use crate::utils::hg_path::HgPath;
1 use crate::utils::hg_path::HgPath;
2 use crate::utils::hg_path::HgPathBuf;
2 use crate::utils::hg_path::HgPathBuf;
3 use crate::Revision;
3 use crate::Revision;
4
4
5 use im_rc::ordmap::DiffItem;
5 use im_rc::ordmap::DiffItem;
6 use im_rc::ordmap::OrdMap;
6 use im_rc::ordmap::OrdMap;
7
7
8 use std::cmp::Ordering;
8 use std::cmp::Ordering;
9 use std::collections::HashMap;
9 use std::collections::HashMap;
10 use std::convert::TryInto;
10 use std::convert::TryInto;
11
11
12 pub type PathCopies = HashMap<HgPathBuf, HgPathBuf>;
12 pub type PathCopies = HashMap<HgPathBuf, HgPathBuf>;
13
13
14 #[derive(Clone, Debug, PartialEq)]
14 #[derive(Clone, Debug, PartialEq)]
15 struct TimeStampedPathCopy {
15 struct TimeStampedPathCopy {
16 /// revision at which the copy information was added
16 /// revision at which the copy information was added
17 rev: Revision,
17 rev: Revision,
18 /// the copy source, (Set to None in case of deletion of the associated
18 /// the copy source, (Set to None in case of deletion of the associated
19 /// key)
19 /// key)
20 path: Option<HgPathBuf>,
20 path: Option<HgPathBuf>,
21 }
21 }
22
22
23 /// maps CopyDestination to Copy Source (+ a "timestamp" for the operation)
23 /// maps CopyDestination to Copy Source (+ a "timestamp" for the operation)
24 type TimeStampedPathCopies = OrdMap<HgPathBuf, TimeStampedPathCopy>;
24 type TimeStampedPathCopies = OrdMap<HgPathBuf, TimeStampedPathCopy>;
25
25
26 /// hold parent 1, parent 2 and relevant files actions.
26 /// hold parent 1, parent 2 and relevant files actions.
27 pub type RevInfo<'a> = (Revision, Revision, ChangedFiles<'a>);
27 pub type RevInfo<'a> = (Revision, Revision, ChangedFiles<'a>);
28
28
29 /// represent the files affected by a changesets
29 /// represent the files affected by a changesets
30 ///
30 ///
31 /// This hold a subset of mercurial.metadata.ChangingFiles as we do not need
31 /// This hold a subset of mercurial.metadata.ChangingFiles as we do not need
32 /// all the data categories tracked by it.
32 /// all the data categories tracked by it.
33 /// This hold a subset of mercurial.metadata.ChangingFiles as we do not need
33 /// This hold a subset of mercurial.metadata.ChangingFiles as we do not need
34 /// all the data categories tracked by it.
34 /// all the data categories tracked by it.
35 pub struct ChangedFiles<'a> {
35 pub struct ChangedFiles<'a> {
36 nb_items: u32,
36 nb_items: u32,
37 index: &'a [u8],
37 index: &'a [u8],
38 data: &'a [u8],
38 data: &'a [u8],
39 }
39 }
40
40
41 /// Represent active changes that affect the copy tracing.
41 /// Represent active changes that affect the copy tracing.
42 enum Action<'a> {
42 enum Action<'a> {
43 /// The parent ? children edge is removing a file
43 /// The parent ? children edge is removing a file
44 ///
44 ///
45 /// (actually, this could be the edge from the other parent, but it does
45 /// (actually, this could be the edge from the other parent, but it does
46 /// not matters)
46 /// not matters)
47 Removed(&'a HgPath),
47 Removed(&'a HgPath),
48 /// The parent ? children edge introduce copy information between (dest,
48 /// The parent ? children edge introduce copy information between (dest,
49 /// source)
49 /// source)
50 Copied(&'a HgPath, &'a HgPath),
50 Copied(&'a HgPath, &'a HgPath),
51 }
51 }
52
52
53 /// This express the possible "special" case we can get in a merge
53 /// This express the possible "special" case we can get in a merge
54 ///
54 ///
55 /// See mercurial/metadata.py for details on these values.
55 /// See mercurial/metadata.py for details on these values.
56 #[derive(PartialEq)]
56 #[derive(PartialEq)]
57 enum MergeCase {
57 enum MergeCase {
58 /// Merged: file had history on both side that needed to be merged
58 /// Merged: file had history on both side that needed to be merged
59 Merged,
59 Merged,
60 /// Salvaged: file was candidate for deletion, but survived the merge
60 /// Salvaged: file was candidate for deletion, but survived the merge
61 Salvaged,
61 Salvaged,
62 /// Normal: Not one of the two cases above
62 /// Normal: Not one of the two cases above
63 Normal,
63 Normal,
64 }
64 }
65
65
66 type FileChange<'a> = (u8, &'a HgPath, &'a HgPath);
66 type FileChange<'a> = (u8, &'a HgPath, &'a HgPath);
67
67
68 const EMPTY: &[u8] = b"";
68 const EMPTY: &[u8] = b"";
69 const COPY_MASK: u8 = 3;
69 const COPY_MASK: u8 = 3;
70 const P1_COPY: u8 = 2;
70 const P1_COPY: u8 = 2;
71 const P2_COPY: u8 = 3;
71 const P2_COPY: u8 = 3;
72 const ACTION_MASK: u8 = 28;
72 const ACTION_MASK: u8 = 28;
73 const REMOVED: u8 = 12;
73 const REMOVED: u8 = 12;
74 const MERGED: u8 = 8;
74 const MERGED: u8 = 8;
75 const SALVAGED: u8 = 16;
75 const SALVAGED: u8 = 16;
76
76
77 impl<'a> ChangedFiles<'a> {
77 impl<'a> ChangedFiles<'a> {
78 const INDEX_START: usize = 4;
78 const INDEX_START: usize = 4;
79 const ENTRY_SIZE: u32 = 9;
79 const ENTRY_SIZE: u32 = 9;
80 const FILENAME_START: u32 = 1;
80 const FILENAME_START: u32 = 1;
81 const COPY_SOURCE_START: u32 = 5;
81 const COPY_SOURCE_START: u32 = 5;
82
82
83 pub fn new(data: &'a [u8]) -> Self {
83 pub fn new(data: &'a [u8]) -> Self {
84 assert!(
84 assert!(
85 data.len() >= 4,
85 data.len() >= 4,
86 "data size ({}) is too small to contain the header (4)",
86 "data size ({}) is too small to contain the header (4)",
87 data.len()
87 data.len()
88 );
88 );
89 let nb_items_raw: [u8; 4] = (&data[0..=3])
89 let nb_items_raw: [u8; 4] = (&data[0..=3])
90 .try_into()
90 .try_into()
91 .expect("failed to turn 4 bytes into 4 bytes");
91 .expect("failed to turn 4 bytes into 4 bytes");
92 let nb_items = u32::from_be_bytes(nb_items_raw);
92 let nb_items = u32::from_be_bytes(nb_items_raw);
93
93
94 let index_size = (nb_items * Self::ENTRY_SIZE) as usize;
94 let index_size = (nb_items * Self::ENTRY_SIZE) as usize;
95 let index_end = Self::INDEX_START + index_size;
95 let index_end = Self::INDEX_START + index_size;
96
96
97 assert!(
97 assert!(
98 data.len() >= index_end,
98 data.len() >= index_end,
99 "data size ({}) is too small to fit the index_data ({})",
99 "data size ({}) is too small to fit the index_data ({})",
100 data.len(),
100 data.len(),
101 index_end
101 index_end
102 );
102 );
103
103
104 let ret = ChangedFiles {
104 let ret = ChangedFiles {
105 nb_items,
105 nb_items,
106 index: &data[Self::INDEX_START..index_end],
106 index: &data[Self::INDEX_START..index_end],
107 data: &data[index_end..],
107 data: &data[index_end..],
108 };
108 };
109 let max_data = ret.filename_end(nb_items - 1) as usize;
109 let max_data = ret.filename_end(nb_items - 1) as usize;
110 assert!(
110 assert!(
111 ret.data.len() >= max_data,
111 ret.data.len() >= max_data,
112 "data size ({}) is too small to fit all data ({})",
112 "data size ({}) is too small to fit all data ({})",
113 data.len(),
113 data.len(),
114 index_end + max_data
114 index_end + max_data
115 );
115 );
116 ret
116 ret
117 }
117 }
118
118
119 pub fn new_empty() -> Self {
119 pub fn new_empty() -> Self {
120 ChangedFiles {
120 ChangedFiles {
121 nb_items: 0,
121 nb_items: 0,
122 index: EMPTY,
122 index: EMPTY,
123 data: EMPTY,
123 data: EMPTY,
124 }
124 }
125 }
125 }
126
126
127 /// internal function to return an individual entry at a given index
127 /// internal function to return an individual entry at a given index
128 fn entry(&'a self, idx: u32) -> FileChange<'a> {
128 fn entry(&'a self, idx: u32) -> FileChange<'a> {
129 if idx >= self.nb_items {
129 if idx >= self.nb_items {
130 panic!(
130 panic!(
131 "index for entry is higher that the number of file {} >= {}",
131 "index for entry is higher that the number of file {} >= {}",
132 idx, self.nb_items
132 idx, self.nb_items
133 )
133 )
134 }
134 }
135 let flags = self.flags(idx);
135 let flags = self.flags(idx);
136 let filename = self.filename(idx);
136 let filename = self.filename(idx);
137 let copy_idx = self.copy_idx(idx);
137 let copy_idx = self.copy_idx(idx);
138 let copy_source = self.filename(copy_idx);
138 let copy_source = self.filename(copy_idx);
139 (flags, filename, copy_source)
139 (flags, filename, copy_source)
140 }
140 }
141
141
142 /// internal function to return the filename of the entry at a given index
142 /// internal function to return the filename of the entry at a given index
143 fn filename(&self, idx: u32) -> &HgPath {
143 fn filename(&self, idx: u32) -> &HgPath {
144 let filename_start;
144 let filename_start;
145 if idx == 0 {
145 if idx == 0 {
146 filename_start = 0;
146 filename_start = 0;
147 } else {
147 } else {
148 filename_start = self.filename_end(idx - 1)
148 filename_start = self.filename_end(idx - 1)
149 }
149 }
150 let filename_end = self.filename_end(idx);
150 let filename_end = self.filename_end(idx);
151 let filename_start = filename_start as usize;
151 let filename_start = filename_start as usize;
152 let filename_end = filename_end as usize;
152 let filename_end = filename_end as usize;
153 HgPath::new(&self.data[filename_start..filename_end])
153 HgPath::new(&self.data[filename_start..filename_end])
154 }
154 }
155
155
156 /// internal function to return the flag field of the entry at a given
156 /// internal function to return the flag field of the entry at a given
157 /// index
157 /// index
158 fn flags(&self, idx: u32) -> u8 {
158 fn flags(&self, idx: u32) -> u8 {
159 let idx = idx as usize;
159 let idx = idx as usize;
160 self.index[idx * (Self::ENTRY_SIZE as usize)]
160 self.index[idx * (Self::ENTRY_SIZE as usize)]
161 }
161 }
162
162
163 /// internal function to return the end of a filename part at a given index
163 /// internal function to return the end of a filename part at a given index
164 fn filename_end(&self, idx: u32) -> u32 {
164 fn filename_end(&self, idx: u32) -> u32 {
165 let start = (idx * Self::ENTRY_SIZE) + Self::FILENAME_START;
165 let start = (idx * Self::ENTRY_SIZE) + Self::FILENAME_START;
166 let end = (idx * Self::ENTRY_SIZE) + Self::COPY_SOURCE_START;
166 let end = (idx * Self::ENTRY_SIZE) + Self::COPY_SOURCE_START;
167 let start = start as usize;
167 let start = start as usize;
168 let end = end as usize;
168 let end = end as usize;
169 let raw = (&self.index[start..end])
169 let raw = (&self.index[start..end])
170 .try_into()
170 .try_into()
171 .expect("failed to turn 4 bytes into 4 bytes");
171 .expect("failed to turn 4 bytes into 4 bytes");
172 u32::from_be_bytes(raw)
172 u32::from_be_bytes(raw)
173 }
173 }
174
174
175 /// internal function to return index of the copy source of the entry at a
175 /// internal function to return index of the copy source of the entry at a
176 /// given index
176 /// given index
177 fn copy_idx(&self, idx: u32) -> u32 {
177 fn copy_idx(&self, idx: u32) -> u32 {
178 let start = (idx * Self::ENTRY_SIZE) + Self::COPY_SOURCE_START;
178 let start = (idx * Self::ENTRY_SIZE) + Self::COPY_SOURCE_START;
179 let end = (idx + 1) * Self::ENTRY_SIZE;
179 let end = (idx + 1) * Self::ENTRY_SIZE;
180 let start = start as usize;
180 let start = start as usize;
181 let end = end as usize;
181 let end = end as usize;
182 let raw = (&self.index[start..end])
182 let raw = (&self.index[start..end])
183 .try_into()
183 .try_into()
184 .expect("failed to turn 4 bytes into 4 bytes");
184 .expect("failed to turn 4 bytes into 4 bytes");
185 u32::from_be_bytes(raw)
185 u32::from_be_bytes(raw)
186 }
186 }
187
187
188 /// Return an iterator over all the `Action` in this instance.
188 /// Return an iterator over all the `Action` in this instance.
189 fn iter_actions(&self, parent: usize) -> ActionsIterator {
189 fn iter_actions(&self, parent: Parent) -> ActionsIterator {
190 ActionsIterator {
190 ActionsIterator {
191 changes: &self,
191 changes: &self,
192 parent: parent,
192 parent: parent,
193 current: 0,
193 current: 0,
194 }
194 }
195 }
195 }
196
196
197 /// return the MergeCase value associated with a filename
197 /// return the MergeCase value associated with a filename
198 fn get_merge_case(&self, path: &HgPath) -> MergeCase {
198 fn get_merge_case(&self, path: &HgPath) -> MergeCase {
199 if self.nb_items == 0 {
199 if self.nb_items == 0 {
200 return MergeCase::Normal;
200 return MergeCase::Normal;
201 }
201 }
202 let mut low_part = 0;
202 let mut low_part = 0;
203 let mut high_part = self.nb_items;
203 let mut high_part = self.nb_items;
204
204
205 while low_part < high_part {
205 while low_part < high_part {
206 let cursor = (low_part + high_part - 1) / 2;
206 let cursor = (low_part + high_part - 1) / 2;
207 let (flags, filename, _source) = self.entry(cursor);
207 let (flags, filename, _source) = self.entry(cursor);
208 match path.cmp(filename) {
208 match path.cmp(filename) {
209 Ordering::Less => low_part = cursor + 1,
209 Ordering::Less => low_part = cursor + 1,
210 Ordering::Greater => high_part = cursor,
210 Ordering::Greater => high_part = cursor,
211 Ordering::Equal => {
211 Ordering::Equal => {
212 return match flags & ACTION_MASK {
212 return match flags & ACTION_MASK {
213 MERGED => MergeCase::Merged,
213 MERGED => MergeCase::Merged,
214 SALVAGED => MergeCase::Salvaged,
214 SALVAGED => MergeCase::Salvaged,
215 _ => MergeCase::Normal,
215 _ => MergeCase::Normal,
216 };
216 };
217 }
217 }
218 }
218 }
219 }
219 }
220 MergeCase::Normal
220 MergeCase::Normal
221 }
221 }
222 }
222 }
223
223
224 /// A struct responsible for answering "is X ancestors of Y" quickly
224 /// A struct responsible for answering "is X ancestors of Y" quickly
225 ///
225 ///
226 /// The structure will delegate ancestors call to a callback, and cache the
226 /// The structure will delegate ancestors call to a callback, and cache the
227 /// result.
227 /// result.
228 #[derive(Debug)]
228 #[derive(Debug)]
229 struct AncestorOracle<'a, A: Fn(Revision, Revision) -> bool> {
229 struct AncestorOracle<'a, A: Fn(Revision, Revision) -> bool> {
230 inner: &'a A,
230 inner: &'a A,
231 pairs: HashMap<(Revision, Revision), bool>,
231 pairs: HashMap<(Revision, Revision), bool>,
232 }
232 }
233
233
234 impl<'a, A: Fn(Revision, Revision) -> bool> AncestorOracle<'a, A> {
234 impl<'a, A: Fn(Revision, Revision) -> bool> AncestorOracle<'a, A> {
235 fn new(func: &'a A) -> Self {
235 fn new(func: &'a A) -> Self {
236 Self {
236 Self {
237 inner: func,
237 inner: func,
238 pairs: HashMap::default(),
238 pairs: HashMap::default(),
239 }
239 }
240 }
240 }
241
241
242 /// returns `true` if `anc` is an ancestors of `desc`, `false` otherwise
242 /// returns `true` if `anc` is an ancestors of `desc`, `false` otherwise
243 fn is_ancestor(&mut self, anc: Revision, desc: Revision) -> bool {
243 fn is_ancestor(&mut self, anc: Revision, desc: Revision) -> bool {
244 if anc > desc {
244 if anc > desc {
245 false
245 false
246 } else if anc == desc {
246 } else if anc == desc {
247 true
247 true
248 } else {
248 } else {
249 if let Some(b) = self.pairs.get(&(anc, desc)) {
249 if let Some(b) = self.pairs.get(&(anc, desc)) {
250 *b
250 *b
251 } else {
251 } else {
252 let b = (self.inner)(anc, desc);
252 let b = (self.inner)(anc, desc);
253 self.pairs.insert((anc, desc), b);
253 self.pairs.insert((anc, desc), b);
254 b
254 b
255 }
255 }
256 }
256 }
257 }
257 }
258 }
258 }
259
259
260 struct ActionsIterator<'a> {
260 struct ActionsIterator<'a> {
261 changes: &'a ChangedFiles<'a>,
261 changes: &'a ChangedFiles<'a>,
262 parent: usize,
262 parent: Parent,
263 current: u32,
263 current: u32,
264 }
264 }
265
265
266 impl<'a> Iterator for ActionsIterator<'a> {
266 impl<'a> Iterator for ActionsIterator<'a> {
267 type Item = Action<'a>;
267 type Item = Action<'a>;
268
268
269 fn next(&mut self) -> Option<Action<'a>> {
269 fn next(&mut self) -> Option<Action<'a>> {
270 let copy_flag = match self.parent {
271 Parent::FirstParent => P1_COPY,
272 Parent::SecondParent => P2_COPY,
273 };
270 while self.current < self.changes.nb_items {
274 while self.current < self.changes.nb_items {
271 let (flags, file, source) = self.changes.entry(self.current);
275 let (flags, file, source) = self.changes.entry(self.current);
272 self.current += 1;
276 self.current += 1;
273 if (flags & ACTION_MASK) == REMOVED {
277 if (flags & ACTION_MASK) == REMOVED {
274 return Some(Action::Removed(file));
278 return Some(Action::Removed(file));
275 }
279 }
276 let copy = flags & COPY_MASK;
280 let copy = flags & COPY_MASK;
277 if self.parent == 1 && copy == P1_COPY {
281 if copy == copy_flag {
278 return Some(Action::Copied(file, source));
279 }
280 if self.parent == 2 && copy == P2_COPY {
281 return Some(Action::Copied(file, source));
282 return Some(Action::Copied(file, source));
282 }
283 }
283 }
284 }
284 return None;
285 return None;
285 }
286 }
286 }
287 }
287
288
288 /// A small struct whose purpose is to ensure lifetime of bytes referenced in
289 /// A small struct whose purpose is to ensure lifetime of bytes referenced in
289 /// ChangedFiles
290 /// ChangedFiles
290 ///
291 ///
291 /// It is passed to the RevInfoMaker callback who can assign any necessary
292 /// It is passed to the RevInfoMaker callback who can assign any necessary
292 /// content to the `data` attribute. The copy tracing code is responsible for
293 /// content to the `data` attribute. The copy tracing code is responsible for
293 /// keeping the DataHolder alive at least as long as the ChangedFiles object.
294 /// keeping the DataHolder alive at least as long as the ChangedFiles object.
294 pub struct DataHolder<D> {
295 pub struct DataHolder<D> {
295 /// RevInfoMaker callback should assign data referenced by the
296 /// RevInfoMaker callback should assign data referenced by the
296 /// ChangedFiles struct it return to this attribute. The DataHolder
297 /// ChangedFiles struct it return to this attribute. The DataHolder
297 /// lifetime will be at least as long as the ChangedFiles one.
298 /// lifetime will be at least as long as the ChangedFiles one.
298 pub data: Option<D>,
299 pub data: Option<D>,
299 }
300 }
300
301
301 pub type RevInfoMaker<'a, D> =
302 pub type RevInfoMaker<'a, D> =
302 Box<dyn for<'r> Fn(Revision, &'r mut DataHolder<D>) -> RevInfo<'r> + 'a>;
303 Box<dyn for<'r> Fn(Revision, &'r mut DataHolder<D>) -> RevInfo<'r> + 'a>;
303
304
305 /// enum used to carry information about the parent β†’ child currently processed
306 #[derive(Copy, Clone, Debug)]
307 enum Parent {
308 /// The `p1(x) β†’ x` edge
309 FirstParent,
310 /// The `p2(x) β†’ x` edge
311 SecondParent,
312 }
313
304 /// Same as mercurial.copies._combine_changeset_copies, but in Rust.
314 /// Same as mercurial.copies._combine_changeset_copies, but in Rust.
305 ///
315 ///
306 /// Arguments are:
316 /// Arguments are:
307 ///
317 ///
308 /// revs: all revisions to be considered
318 /// revs: all revisions to be considered
309 /// children: a {parent ? [childrens]} mapping
319 /// children: a {parent ? [childrens]} mapping
310 /// target_rev: the final revision we are combining copies to
320 /// target_rev: the final revision we are combining copies to
311 /// rev_info(rev): callback to get revision information:
321 /// rev_info(rev): callback to get revision information:
312 /// * first parent
322 /// * first parent
313 /// * second parent
323 /// * second parent
314 /// * ChangedFiles
324 /// * ChangedFiles
315 /// isancestors(low_rev, high_rev): callback to check if a revision is an
325 /// isancestors(low_rev, high_rev): callback to check if a revision is an
316 /// ancestor of another
326 /// ancestor of another
317 pub fn combine_changeset_copies<A: Fn(Revision, Revision) -> bool, D>(
327 pub fn combine_changeset_copies<A: Fn(Revision, Revision) -> bool, D>(
318 revs: Vec<Revision>,
328 revs: Vec<Revision>,
319 children: HashMap<Revision, Vec<Revision>>,
329 children: HashMap<Revision, Vec<Revision>>,
320 target_rev: Revision,
330 target_rev: Revision,
321 rev_info: RevInfoMaker<D>,
331 rev_info: RevInfoMaker<D>,
322 is_ancestor: &A,
332 is_ancestor: &A,
323 ) -> PathCopies {
333 ) -> PathCopies {
324 let mut all_copies = HashMap::new();
334 let mut all_copies = HashMap::new();
325 let mut oracle = AncestorOracle::new(is_ancestor);
335 let mut oracle = AncestorOracle::new(is_ancestor);
326
336
327 for rev in revs {
337 for rev in revs {
328 // Retrieve data computed in a previous iteration
338 // Retrieve data computed in a previous iteration
329 let copies = all_copies.remove(&rev);
339 let copies = all_copies.remove(&rev);
330 let copies = match copies {
340 let copies = match copies {
331 Some(c) => c,
341 Some(c) => c,
332 None => TimeStampedPathCopies::default(), // root of the walked set
342 None => TimeStampedPathCopies::default(), // root of the walked set
333 };
343 };
334
344
335 let current_children = match children.get(&rev) {
345 let current_children = match children.get(&rev) {
336 Some(c) => c,
346 Some(c) => c,
337 None => panic!("inconsistent `revs` and `children`"),
347 None => panic!("inconsistent `revs` and `children`"),
338 };
348 };
339
349
340 for child in current_children {
350 for child in current_children {
341 // We will chain the copies information accumulated for `rev` with
351 // We will chain the copies information accumulated for `rev` with
342 // the individual copies information for each of its children.
352 // the individual copies information for each of its children.
343 // Creating a new PathCopies for each `rev` β†’ `children` vertex.
353 // Creating a new PathCopies for each `rev` β†’ `children` vertex.
344 let mut d: DataHolder<D> = DataHolder { data: None };
354 let mut d: DataHolder<D> = DataHolder { data: None };
345 let (p1, p2, changes) = rev_info(*child, &mut d);
355 let (p1, p2, changes) = rev_info(*child, &mut d);
346
356
347 let parent = if rev == p1 {
357 let parent = if rev == p1 {
348 1
358 Parent::FirstParent
349 } else {
359 } else {
350 assert_eq!(rev, p2);
360 assert_eq!(rev, p2);
351 2
361 Parent::SecondParent
352 };
362 };
353 let mut new_copies = copies.clone();
363 let mut new_copies = copies.clone();
354
364
355 for action in changes.iter_actions(parent) {
365 for action in changes.iter_actions(parent) {
356 match action {
366 match action {
357 Action::Copied(dest, source) => {
367 Action::Copied(dest, source) => {
358 let entry;
368 let entry;
359 if let Some(v) = copies.get(source) {
369 if let Some(v) = copies.get(source) {
360 entry = match &v.path {
370 entry = match &v.path {
361 Some(path) => Some((*(path)).to_owned()),
371 Some(path) => Some((*(path)).to_owned()),
362 None => Some(source.to_owned()),
372 None => Some(source.to_owned()),
363 }
373 }
364 } else {
374 } else {
365 entry = Some(source.to_owned());
375 entry = Some(source.to_owned());
366 }
376 }
367 // Each new entry is introduced by the children, we
377 // Each new entry is introduced by the children, we
368 // record this information as we will need it to take
378 // record this information as we will need it to take
369 // the right decision when merging conflicting copy
379 // the right decision when merging conflicting copy
370 // information. See merge_copies_dict for details.
380 // information. See merge_copies_dict for details.
371 let ttpc = TimeStampedPathCopy {
381 let ttpc = TimeStampedPathCopy {
372 rev: *child,
382 rev: *child,
373 path: entry,
383 path: entry,
374 };
384 };
375 new_copies.insert(dest.to_owned(), ttpc);
385 new_copies.insert(dest.to_owned(), ttpc);
376 }
386 }
377 Action::Removed(f) => {
387 Action::Removed(f) => {
378 // We must drop copy information for removed file.
388 // We must drop copy information for removed file.
379 //
389 //
380 // We need to explicitly record them as dropped to
390 // We need to explicitly record them as dropped to
381 // propagate this information when merging two
391 // propagate this information when merging two
382 // TimeStampedPathCopies object.
392 // TimeStampedPathCopies object.
383 if new_copies.contains_key(f.as_ref()) {
393 if new_copies.contains_key(f.as_ref()) {
384 let ttpc = TimeStampedPathCopy {
394 let ttpc = TimeStampedPathCopy {
385 rev: *child,
395 rev: *child,
386 path: None,
396 path: None,
387 };
397 };
388 new_copies.insert(f.to_owned(), ttpc);
398 new_copies.insert(f.to_owned(), ttpc);
389 }
399 }
390 }
400 }
391 }
401 }
392 }
402 }
393
403
394 // Merge has two parents needs to combines their copy information.
404 // Merge has two parents needs to combines their copy information.
395 //
405 //
396 // If the vertex from the other parent was already processed, we
406 // If the vertex from the other parent was already processed, we
397 // will have a value for the child ready to be used. We need to
407 // will have a value for the child ready to be used. We need to
398 // grab it and combine it with the one we already
408 // grab it and combine it with the one we already
399 // computed. If not we can simply store the newly
409 // computed. If not we can simply store the newly
400 // computed data. The processing happening at
410 // computed data. The processing happening at
401 // the time of the second parent will take care of combining the
411 // the time of the second parent will take care of combining the
402 // two TimeStampedPathCopies instance.
412 // two TimeStampedPathCopies instance.
403 match all_copies.remove(child) {
413 match all_copies.remove(child) {
404 None => {
414 None => {
405 all_copies.insert(child, new_copies);
415 all_copies.insert(child, new_copies);
406 }
416 }
407 Some(other_copies) => {
417 Some(other_copies) => {
408 let (minor, major) = match parent {
418 let (minor, major) = match parent {
409 1 => (other_copies, new_copies),
419 Parent::FirstParent => (other_copies, new_copies),
410 2 => (new_copies, other_copies),
420 Parent::SecondParent => (new_copies, other_copies),
411 _ => unreachable!(),
412 };
421 };
413 let merged_copies =
422 let merged_copies =
414 merge_copies_dict(minor, major, &changes, &mut oracle);
423 merge_copies_dict(minor, major, &changes, &mut oracle);
415 all_copies.insert(child, merged_copies);
424 all_copies.insert(child, merged_copies);
416 }
425 }
417 };
426 };
418 }
427 }
419 }
428 }
420
429
421 // Drop internal information (like the timestamp) and return the final
430 // Drop internal information (like the timestamp) and return the final
422 // mapping.
431 // mapping.
423 let tt_result = all_copies
432 let tt_result = all_copies
424 .remove(&target_rev)
433 .remove(&target_rev)
425 .expect("target revision was not processed");
434 .expect("target revision was not processed");
426 let mut result = PathCopies::default();
435 let mut result = PathCopies::default();
427 for (dest, tt_source) in tt_result {
436 for (dest, tt_source) in tt_result {
428 if let Some(path) = tt_source.path {
437 if let Some(path) = tt_source.path {
429 result.insert(dest, path);
438 result.insert(dest, path);
430 }
439 }
431 }
440 }
432 result
441 result
433 }
442 }
434
443
435 /// merge two copies-mapping together, minor and major
444 /// merge two copies-mapping together, minor and major
436 ///
445 ///
437 /// In case of conflict, value from "major" will be picked, unless in some
446 /// In case of conflict, value from "major" will be picked, unless in some
438 /// cases. See inline documentation for details.
447 /// cases. See inline documentation for details.
439 #[allow(clippy::if_same_then_else)]
448 #[allow(clippy::if_same_then_else)]
440 fn merge_copies_dict<A: Fn(Revision, Revision) -> bool>(
449 fn merge_copies_dict<A: Fn(Revision, Revision) -> bool>(
441 minor: TimeStampedPathCopies,
450 minor: TimeStampedPathCopies,
442 major: TimeStampedPathCopies,
451 major: TimeStampedPathCopies,
443 changes: &ChangedFiles,
452 changes: &ChangedFiles,
444 oracle: &mut AncestorOracle<A>,
453 oracle: &mut AncestorOracle<A>,
445 ) -> TimeStampedPathCopies {
454 ) -> TimeStampedPathCopies {
446 if minor.is_empty() {
455 if minor.is_empty() {
447 return major;
456 return major;
448 } else if major.is_empty() {
457 } else if major.is_empty() {
449 return minor;
458 return minor;
450 }
459 }
451 let mut override_minor = Vec::new();
460 let mut override_minor = Vec::new();
452 let mut override_major = Vec::new();
461 let mut override_major = Vec::new();
453
462
454 let mut to_major = |k: &HgPathBuf, v: &TimeStampedPathCopy| {
463 let mut to_major = |k: &HgPathBuf, v: &TimeStampedPathCopy| {
455 override_major.push((k.clone(), v.clone()))
464 override_major.push((k.clone(), v.clone()))
456 };
465 };
457 let mut to_minor = |k: &HgPathBuf, v: &TimeStampedPathCopy| {
466 let mut to_minor = |k: &HgPathBuf, v: &TimeStampedPathCopy| {
458 override_minor.push((k.clone(), v.clone()))
467 override_minor.push((k.clone(), v.clone()))
459 };
468 };
460
469
461 // The diff function leverage detection of the identical subpart if minor
470 // The diff function leverage detection of the identical subpart if minor
462 // and major has some common ancestors. This make it very fast is most
471 // and major has some common ancestors. This make it very fast is most
463 // case.
472 // case.
464 //
473 //
465 // In case where the two map are vastly different in size, the current
474 // In case where the two map are vastly different in size, the current
466 // approach is still slowish because the iteration will iterate over
475 // approach is still slowish because the iteration will iterate over
467 // all the "exclusive" content of the larger on. This situation can be
476 // all the "exclusive" content of the larger on. This situation can be
468 // frequent when the subgraph of revision we are processing has a lot
477 // frequent when the subgraph of revision we are processing has a lot
469 // of roots. Each roots adding they own fully new map to the mix (and
478 // of roots. Each roots adding they own fully new map to the mix (and
470 // likely a small map, if the path from the root to the "main path" is
479 // likely a small map, if the path from the root to the "main path" is
471 // small.
480 // small.
472 //
481 //
473 // We could do better by detecting such situation and processing them
482 // We could do better by detecting such situation and processing them
474 // differently.
483 // differently.
475 for d in minor.diff(&major) {
484 for d in minor.diff(&major) {
476 match d {
485 match d {
477 DiffItem::Add(k, v) => to_minor(k, v),
486 DiffItem::Add(k, v) => to_minor(k, v),
478 DiffItem::Remove(k, v) => to_major(k, v),
487 DiffItem::Remove(k, v) => to_major(k, v),
479 DiffItem::Update { old, new } => {
488 DiffItem::Update { old, new } => {
480 let (dest, src_major) = new;
489 let (dest, src_major) = new;
481 let (_, src_minor) = old;
490 let (_, src_minor) = old;
482 let mut pick_minor = || (to_major(dest, src_minor));
491 let mut pick_minor = || (to_major(dest, src_minor));
483 let mut pick_major = || (to_minor(dest, src_major));
492 let mut pick_major = || (to_minor(dest, src_major));
484 if src_major.path == src_minor.path {
493 if src_major.path == src_minor.path {
485 // we have the same value, but from other source;
494 // we have the same value, but from other source;
486 if src_major.rev == src_minor.rev {
495 if src_major.rev == src_minor.rev {
487 // If the two entry are identical, no need to do
496 // If the two entry are identical, no need to do
488 // anything (but diff should not have yield them)
497 // anything (but diff should not have yield them)
489 unreachable!();
498 unreachable!();
490 } else if oracle.is_ancestor(src_major.rev, src_minor.rev)
499 } else if oracle.is_ancestor(src_major.rev, src_minor.rev)
491 {
500 {
492 pick_minor();
501 pick_minor();
493 } else {
502 } else {
494 pick_major();
503 pick_major();
495 }
504 }
496 } else if src_major.rev == src_minor.rev {
505 } else if src_major.rev == src_minor.rev {
497 // We cannot get copy information for both p1 and p2 in the
506 // We cannot get copy information for both p1 and p2 in the
498 // same rev. So this is the same value.
507 // same rev. So this is the same value.
499 unreachable!();
508 unreachable!();
500 } else {
509 } else {
501 let action = changes.get_merge_case(&dest);
510 let action = changes.get_merge_case(&dest);
502 if src_major.path.is_none()
511 if src_major.path.is_none()
503 && action == MergeCase::Salvaged
512 && action == MergeCase::Salvaged
504 {
513 {
505 // If the file is "deleted" in the major side but was
514 // If the file is "deleted" in the major side but was
506 // salvaged by the merge, we keep the minor side alive
515 // salvaged by the merge, we keep the minor side alive
507 pick_minor();
516 pick_minor();
508 } else if src_minor.path.is_none()
517 } else if src_minor.path.is_none()
509 && action == MergeCase::Salvaged
518 && action == MergeCase::Salvaged
510 {
519 {
511 // If the file is "deleted" in the minor side but was
520 // If the file is "deleted" in the minor side but was
512 // salvaged by the merge, unconditionnaly preserve the
521 // salvaged by the merge, unconditionnaly preserve the
513 // major side.
522 // major side.
514 pick_major();
523 pick_major();
515 } else if action == MergeCase::Merged {
524 } else if action == MergeCase::Merged {
516 // If the file was actively merged, copy information
525 // If the file was actively merged, copy information
517 // from each side might conflict. The major side will
526 // from each side might conflict. The major side will
518 // win such conflict.
527 // win such conflict.
519 pick_major();
528 pick_major();
520 } else if oracle.is_ancestor(src_major.rev, src_minor.rev)
529 } else if oracle.is_ancestor(src_major.rev, src_minor.rev)
521 {
530 {
522 // If the minor side is strictly newer than the major
531 // If the minor side is strictly newer than the major
523 // side, it should be kept.
532 // side, it should be kept.
524 pick_minor();
533 pick_minor();
525 } else if src_major.path.is_some() {
534 } else if src_major.path.is_some() {
526 // without any special case, the "major" value win
535 // without any special case, the "major" value win
527 // other the "minor" one.
536 // other the "minor" one.
528 pick_major();
537 pick_major();
529 } else if oracle.is_ancestor(src_minor.rev, src_major.rev)
538 } else if oracle.is_ancestor(src_minor.rev, src_major.rev)
530 {
539 {
531 // the "major" rev is a direct ancestors of "minor",
540 // the "major" rev is a direct ancestors of "minor",
532 // any different value should
541 // any different value should
533 // overwrite
542 // overwrite
534 pick_major();
543 pick_major();
535 } else {
544 } else {
536 // major version is None (so the file was deleted on
545 // major version is None (so the file was deleted on
537 // that branch) and that branch is independant (neither
546 // that branch) and that branch is independant (neither
538 // minor nor major is an ancestors of the other one.)
547 // minor nor major is an ancestors of the other one.)
539 // We preserve the new
548 // We preserve the new
540 // information about the new file.
549 // information about the new file.
541 pick_minor();
550 pick_minor();
542 }
551 }
543 }
552 }
544 }
553 }
545 };
554 };
546 }
555 }
547
556
548 let updates;
557 let updates;
549 let mut result;
558 let mut result;
550 if override_major.is_empty() {
559 if override_major.is_empty() {
551 result = major
560 result = major
552 } else if override_minor.is_empty() {
561 } else if override_minor.is_empty() {
553 result = minor
562 result = minor
554 } else {
563 } else {
555 if override_minor.len() < override_major.len() {
564 if override_minor.len() < override_major.len() {
556 updates = override_minor;
565 updates = override_minor;
557 result = minor;
566 result = minor;
558 } else {
567 } else {
559 updates = override_major;
568 updates = override_major;
560 result = major;
569 result = major;
561 }
570 }
562 for (k, v) in updates {
571 for (k, v) in updates {
563 result.insert(k, v);
572 result.insert(k, v);
564 }
573 }
565 }
574 }
566 result
575 result
567 }
576 }
General Comments 0
You need to be logged in to leave comments. Login now