##// END OF EJS Templates
rust: format with rustfmt...
Raphaël Gomès -
r46162:c35db907 default
parent child Browse files
Show More
@@ -1,467 +1,505 b''
1 // dirstate_map.rs
1 // dirstate_map.rs
2 //
2 //
3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
3 // Copyright 2019 Raphaël Gomès <rgomes@octobus.net>
4 //
4 //
5 // This software may be used and distributed according to the terms of the
5 // This software may be used and distributed according to the terms of the
6 // GNU General Public License version 2 or any later version.
6 // GNU General Public License version 2 or any later version.
7
7
8 use crate::revlog::node::NULL_NODE_ID;
8 use crate::revlog::node::NULL_NODE_ID;
9 use crate::{
9 use crate::{
10 dirstate::{parsers::PARENT_SIZE, EntryState, SIZE_FROM_OTHER_PARENT},
10 dirstate::{parsers::PARENT_SIZE, EntryState, SIZE_FROM_OTHER_PARENT},
11 pack_dirstate, parse_dirstate,
11 pack_dirstate, parse_dirstate,
12 utils::{
12 utils::{
13 files::normalize_case,
13 files::normalize_case,
14 hg_path::{HgPath, HgPathBuf},
14 hg_path::{HgPath, HgPathBuf},
15 },
15 },
16 CopyMap, DirsMultiset, DirstateEntry, DirstateError, DirstateMapError, DirstateParents,
16 CopyMap, DirsMultiset, DirstateEntry, DirstateError, DirstateMapError,
17 DirstateParseError, FastHashMap, StateMap,
17 DirstateParents, DirstateParseError, FastHashMap, StateMap,
18 };
18 };
19 use core::borrow::Borrow;
19 use core::borrow::Borrow;
20 use micro_timer::timed;
20 use micro_timer::timed;
21 use std::collections::HashSet;
21 use std::collections::HashSet;
22 use std::convert::TryInto;
22 use std::convert::TryInto;
23 use std::iter::FromIterator;
23 use std::iter::FromIterator;
24 use std::ops::Deref;
24 use std::ops::Deref;
25 use std::time::Duration;
25 use std::time::Duration;
26
26
27 pub type FileFoldMap = FastHashMap<HgPathBuf, HgPathBuf>;
27 pub type FileFoldMap = FastHashMap<HgPathBuf, HgPathBuf>;
28
28
29 const MTIME_UNSET: i32 = -1;
29 const MTIME_UNSET: i32 = -1;
30
30
31 #[derive(Default)]
31 #[derive(Default)]
32 pub struct DirstateMap {
32 pub struct DirstateMap {
33 state_map: StateMap,
33 state_map: StateMap,
34 pub copy_map: CopyMap,
34 pub copy_map: CopyMap,
35 file_fold_map: Option<FileFoldMap>,
35 file_fold_map: Option<FileFoldMap>,
36 pub dirs: Option<DirsMultiset>,
36 pub dirs: Option<DirsMultiset>,
37 pub all_dirs: Option<DirsMultiset>,
37 pub all_dirs: Option<DirsMultiset>,
38 non_normal_set: Option<HashSet<HgPathBuf>>,
38 non_normal_set: Option<HashSet<HgPathBuf>>,
39 other_parent_set: Option<HashSet<HgPathBuf>>,
39 other_parent_set: Option<HashSet<HgPathBuf>>,
40 parents: Option<DirstateParents>,
40 parents: Option<DirstateParents>,
41 dirty_parents: bool,
41 dirty_parents: bool,
42 }
42 }
43
43
44 /// Should only really be used in python interface code, for clarity
44 /// Should only really be used in python interface code, for clarity
45 impl Deref for DirstateMap {
45 impl Deref for DirstateMap {
46 type Target = StateMap;
46 type Target = StateMap;
47
47
48 fn deref(&self) -> &Self::Target {
48 fn deref(&self) -> &Self::Target {
49 &self.state_map
49 &self.state_map
50 }
50 }
51 }
51 }
52
52
53 impl FromIterator<(HgPathBuf, DirstateEntry)> for DirstateMap {
53 impl FromIterator<(HgPathBuf, DirstateEntry)> for DirstateMap {
54 fn from_iter<I: IntoIterator<Item = (HgPathBuf, DirstateEntry)>>(iter: I) -> Self {
54 fn from_iter<I: IntoIterator<Item = (HgPathBuf, DirstateEntry)>>(
55 iter: I,
56 ) -> Self {
55 Self {
57 Self {
56 state_map: iter.into_iter().collect(),
58 state_map: iter.into_iter().collect(),
57 ..Self::default()
59 ..Self::default()
58 }
60 }
59 }
61 }
60 }
62 }
61
63
62 impl DirstateMap {
64 impl DirstateMap {
63 pub fn new() -> Self {
65 pub fn new() -> Self {
64 Self::default()
66 Self::default()
65 }
67 }
66
68
67 pub fn clear(&mut self) {
69 pub fn clear(&mut self) {
68 self.state_map.clear();
70 self.state_map.clear();
69 self.copy_map.clear();
71 self.copy_map.clear();
70 self.file_fold_map = None;
72 self.file_fold_map = None;
71 self.non_normal_set = None;
73 self.non_normal_set = None;
72 self.other_parent_set = None;
74 self.other_parent_set = None;
73 self.set_parents(&DirstateParents {
75 self.set_parents(&DirstateParents {
74 p1: NULL_NODE_ID,
76 p1: NULL_NODE_ID,
75 p2: NULL_NODE_ID,
77 p2: NULL_NODE_ID,
76 })
78 })
77 }
79 }
78
80
79 /// Add a tracked file to the dirstate
81 /// Add a tracked file to the dirstate
80 pub fn add_file(
82 pub fn add_file(
81 &mut self,
83 &mut self,
82 filename: &HgPath,
84 filename: &HgPath,
83 old_state: EntryState,
85 old_state: EntryState,
84 entry: DirstateEntry,
86 entry: DirstateEntry,
85 ) -> Result<(), DirstateMapError> {
87 ) -> Result<(), DirstateMapError> {
86 if old_state == EntryState::Unknown || old_state == EntryState::Removed {
88 if old_state == EntryState::Unknown || old_state == EntryState::Removed
89 {
87 if let Some(ref mut dirs) = self.dirs {
90 if let Some(ref mut dirs) = self.dirs {
88 dirs.add_path(filename)?;
91 dirs.add_path(filename)?;
89 }
92 }
90 }
93 }
91 if old_state == EntryState::Unknown {
94 if old_state == EntryState::Unknown {
92 if let Some(ref mut all_dirs) = self.all_dirs {
95 if let Some(ref mut all_dirs) = self.all_dirs {
93 all_dirs.add_path(filename)?;
96 all_dirs.add_path(filename)?;
94 }
97 }
95 }
98 }
96 self.state_map.insert(filename.to_owned(), entry.to_owned());
99 self.state_map.insert(filename.to_owned(), entry.to_owned());
97
100
98 if entry.state != EntryState::Normal || entry.mtime == MTIME_UNSET {
101 if entry.state != EntryState::Normal || entry.mtime == MTIME_UNSET {
99 self.get_non_normal_other_parent_entries()
102 self.get_non_normal_other_parent_entries()
100 .0
103 .0
101 .insert(filename.to_owned());
104 .insert(filename.to_owned());
102 }
105 }
103
106
104 if entry.size == SIZE_FROM_OTHER_PARENT {
107 if entry.size == SIZE_FROM_OTHER_PARENT {
105 self.get_non_normal_other_parent_entries()
108 self.get_non_normal_other_parent_entries()
106 .1
109 .1
107 .insert(filename.to_owned());
110 .insert(filename.to_owned());
108 }
111 }
109 Ok(())
112 Ok(())
110 }
113 }
111
114
112 /// Mark a file as removed in the dirstate.
115 /// Mark a file as removed in the dirstate.
113 ///
116 ///
114 /// The `size` parameter is used to store sentinel values that indicate
117 /// The `size` parameter is used to store sentinel values that indicate
115 /// the file's previous state. In the future, we should refactor this
118 /// the file's previous state. In the future, we should refactor this
116 /// to be more explicit about what that state is.
119 /// to be more explicit about what that state is.
117 pub fn remove_file(
120 pub fn remove_file(
118 &mut self,
121 &mut self,
119 filename: &HgPath,
122 filename: &HgPath,
120 old_state: EntryState,
123 old_state: EntryState,
121 size: i32,
124 size: i32,
122 ) -> Result<(), DirstateMapError> {
125 ) -> Result<(), DirstateMapError> {
123 if old_state != EntryState::Unknown && old_state != EntryState::Removed {
126 if old_state != EntryState::Unknown && old_state != EntryState::Removed
127 {
124 if let Some(ref mut dirs) = self.dirs {
128 if let Some(ref mut dirs) = self.dirs {
125 dirs.delete_path(filename)?;
129 dirs.delete_path(filename)?;
126 }
130 }
127 }
131 }
128 if old_state == EntryState::Unknown {
132 if old_state == EntryState::Unknown {
129 if let Some(ref mut all_dirs) = self.all_dirs {
133 if let Some(ref mut all_dirs) = self.all_dirs {
130 all_dirs.add_path(filename)?;
134 all_dirs.add_path(filename)?;
131 }
135 }
132 }
136 }
133
137
134 if let Some(ref mut file_fold_map) = self.file_fold_map {
138 if let Some(ref mut file_fold_map) = self.file_fold_map {
135 file_fold_map.remove(&normalize_case(filename));
139 file_fold_map.remove(&normalize_case(filename));
136 }
140 }
137 self.state_map.insert(
141 self.state_map.insert(
138 filename.to_owned(),
142 filename.to_owned(),
139 DirstateEntry {
143 DirstateEntry {
140 state: EntryState::Removed,
144 state: EntryState::Removed,
141 mode: 0,
145 mode: 0,
142 size,
146 size,
143 mtime: 0,
147 mtime: 0,
144 },
148 },
145 );
149 );
146 self.get_non_normal_other_parent_entries()
150 self.get_non_normal_other_parent_entries()
147 .0
151 .0
148 .insert(filename.to_owned());
152 .insert(filename.to_owned());
149 Ok(())
153 Ok(())
150 }
154 }
151
155
152 /// Remove a file from the dirstate.
156 /// Remove a file from the dirstate.
153 /// Returns `true` if the file was previously recorded.
157 /// Returns `true` if the file was previously recorded.
154 pub fn drop_file(
158 pub fn drop_file(
155 &mut self,
159 &mut self,
156 filename: &HgPath,
160 filename: &HgPath,
157 old_state: EntryState,
161 old_state: EntryState,
158 ) -> Result<bool, DirstateMapError> {
162 ) -> Result<bool, DirstateMapError> {
159 let exists = self.state_map.remove(filename).is_some();
163 let exists = self.state_map.remove(filename).is_some();
160
164
161 if exists {
165 if exists {
162 if old_state != EntryState::Removed {
166 if old_state != EntryState::Removed {
163 if let Some(ref mut dirs) = self.dirs {
167 if let Some(ref mut dirs) = self.dirs {
164 dirs.delete_path(filename)?;
168 dirs.delete_path(filename)?;
165 }
169 }
166 }
170 }
167 if let Some(ref mut all_dirs) = self.all_dirs {
171 if let Some(ref mut all_dirs) = self.all_dirs {
168 all_dirs.delete_path(filename)?;
172 all_dirs.delete_path(filename)?;
169 }
173 }
170 }
174 }
171 if let Some(ref mut file_fold_map) = self.file_fold_map {
175 if let Some(ref mut file_fold_map) = self.file_fold_map {
172 file_fold_map.remove(&normalize_case(filename));
176 file_fold_map.remove(&normalize_case(filename));
173 }
177 }
174 self.get_non_normal_other_parent_entries()
178 self.get_non_normal_other_parent_entries()
175 .0
179 .0
176 .remove(filename);
180 .remove(filename);
177
181
178 Ok(exists)
182 Ok(exists)
179 }
183 }
180
184
181 pub fn clear_ambiguous_times(&mut self, filenames: Vec<HgPathBuf>, now: i32) {
185 pub fn clear_ambiguous_times(
186 &mut self,
187 filenames: Vec<HgPathBuf>,
188 now: i32,
189 ) {
182 for filename in filenames {
190 for filename in filenames {
183 let mut changed = false;
191 let mut changed = false;
184 self.state_map
192 self.state_map
185 .entry(filename.to_owned())
193 .entry(filename.to_owned())
186 .and_modify(|entry| {
194 .and_modify(|entry| {
187 if entry.state == EntryState::Normal && entry.mtime == now {
195 if entry.state == EntryState::Normal && entry.mtime == now
196 {
188 changed = true;
197 changed = true;
189 *entry = DirstateEntry {
198 *entry = DirstateEntry {
190 mtime: MTIME_UNSET,
199 mtime: MTIME_UNSET,
191 ..*entry
200 ..*entry
192 };
201 };
193 }
202 }
194 });
203 });
195 if changed {
204 if changed {
196 self.get_non_normal_other_parent_entries()
205 self.get_non_normal_other_parent_entries()
197 .0
206 .0
198 .insert(filename.to_owned());
207 .insert(filename.to_owned());
199 }
208 }
200 }
209 }
201 }
210 }
202
211
203 pub fn non_normal_entries_remove(&mut self, key: impl AsRef<HgPath>) -> bool {
212 pub fn non_normal_entries_remove(
213 &mut self,
214 key: impl AsRef<HgPath>,
215 ) -> bool {
204 self.get_non_normal_other_parent_entries()
216 self.get_non_normal_other_parent_entries()
205 .0
217 .0
206 .remove(key.as_ref())
218 .remove(key.as_ref())
207 }
219 }
208 pub fn non_normal_entries_union(&mut self, other: HashSet<HgPathBuf>) -> Vec<HgPathBuf> {
220 pub fn non_normal_entries_union(
221 &mut self,
222 other: HashSet<HgPathBuf>,
223 ) -> Vec<HgPathBuf> {
209 self.get_non_normal_other_parent_entries()
224 self.get_non_normal_other_parent_entries()
210 .0
225 .0
211 .union(&other)
226 .union(&other)
212 .map(ToOwned::to_owned)
227 .map(ToOwned::to_owned)
213 .collect()
228 .collect()
214 }
229 }
215
230
216 pub fn get_non_normal_other_parent_entries(
231 pub fn get_non_normal_other_parent_entries(
217 &mut self,
232 &mut self,
218 ) -> (&mut HashSet<HgPathBuf>, &mut HashSet<HgPathBuf>) {
233 ) -> (&mut HashSet<HgPathBuf>, &mut HashSet<HgPathBuf>) {
219 self.set_non_normal_other_parent_entries(false);
234 self.set_non_normal_other_parent_entries(false);
220 (
235 (
221 self.non_normal_set.as_mut().unwrap(),
236 self.non_normal_set.as_mut().unwrap(),
222 self.other_parent_set.as_mut().unwrap(),
237 self.other_parent_set.as_mut().unwrap(),
223 )
238 )
224 }
239 }
225
240
226 /// Useful to get immutable references to those sets in contexts where
241 /// Useful to get immutable references to those sets in contexts where
227 /// you only have an immutable reference to the `DirstateMap`, like when
242 /// you only have an immutable reference to the `DirstateMap`, like when
228 /// sharing references with Python.
243 /// sharing references with Python.
229 ///
244 ///
230 /// TODO, get rid of this along with the other "setter/getter" stuff when
245 /// TODO, get rid of this along with the other "setter/getter" stuff when
231 /// a nice typestate plan is defined.
246 /// a nice typestate plan is defined.
232 ///
247 ///
233 /// # Panics
248 /// # Panics
234 ///
249 ///
235 /// Will panic if either set is `None`.
250 /// Will panic if either set is `None`.
236 pub fn get_non_normal_other_parent_entries_panic(
251 pub fn get_non_normal_other_parent_entries_panic(
237 &self,
252 &self,
238 ) -> (&HashSet<HgPathBuf>, &HashSet<HgPathBuf>) {
253 ) -> (&HashSet<HgPathBuf>, &HashSet<HgPathBuf>) {
239 (
254 (
240 self.non_normal_set.as_ref().unwrap(),
255 self.non_normal_set.as_ref().unwrap(),
241 self.other_parent_set.as_ref().unwrap(),
256 self.other_parent_set.as_ref().unwrap(),
242 )
257 )
243 }
258 }
244
259
245 pub fn set_non_normal_other_parent_entries(&mut self, force: bool) {
260 pub fn set_non_normal_other_parent_entries(&mut self, force: bool) {
246 if !force && self.non_normal_set.is_some() && self.other_parent_set.is_some() {
261 if !force
262 && self.non_normal_set.is_some()
263 && self.other_parent_set.is_some()
264 {
247 return;
265 return;
248 }
266 }
249 let mut non_normal = HashSet::new();
267 let mut non_normal = HashSet::new();
250 let mut other_parent = HashSet::new();
268 let mut other_parent = HashSet::new();
251
269
252 for (
270 for (
253 filename,
271 filename,
254 DirstateEntry {
272 DirstateEntry {
255 state, size, mtime, ..
273 state, size, mtime, ..
256 },
274 },
257 ) in self.state_map.iter()
275 ) in self.state_map.iter()
258 {
276 {
259 if *state != EntryState::Normal || *mtime == MTIME_UNSET {
277 if *state != EntryState::Normal || *mtime == MTIME_UNSET {
260 non_normal.insert(filename.to_owned());
278 non_normal.insert(filename.to_owned());
261 }
279 }
262 if *state == EntryState::Normal && *size == SIZE_FROM_OTHER_PARENT {
280 if *state == EntryState::Normal && *size == SIZE_FROM_OTHER_PARENT
281 {
263 other_parent.insert(filename.to_owned());
282 other_parent.insert(filename.to_owned());
264 }
283 }
265 }
284 }
266 self.non_normal_set = Some(non_normal);
285 self.non_normal_set = Some(non_normal);
267 self.other_parent_set = Some(other_parent);
286 self.other_parent_set = Some(other_parent);
268 }
287 }
269
288
270 /// Both of these setters and their uses appear to be the simplest way to
289 /// Both of these setters and their uses appear to be the simplest way to
271 /// emulate a Python lazy property, but it is ugly and unidiomatic.
290 /// emulate a Python lazy property, but it is ugly and unidiomatic.
272 /// TODO One day, rewriting this struct using the typestate might be a
291 /// TODO One day, rewriting this struct using the typestate might be a
273 /// good idea.
292 /// good idea.
274 pub fn set_all_dirs(&mut self) -> Result<(), DirstateMapError> {
293 pub fn set_all_dirs(&mut self) -> Result<(), DirstateMapError> {
275 if self.all_dirs.is_none() {
294 if self.all_dirs.is_none() {
276 self.all_dirs = Some(DirsMultiset::from_dirstate(&self.state_map, None)?);
295 self.all_dirs =
296 Some(DirsMultiset::from_dirstate(&self.state_map, None)?);
277 }
297 }
278 Ok(())
298 Ok(())
279 }
299 }
280
300
281 pub fn set_dirs(&mut self) -> Result<(), DirstateMapError> {
301 pub fn set_dirs(&mut self) -> Result<(), DirstateMapError> {
282 if self.dirs.is_none() {
302 if self.dirs.is_none() {
283 self.dirs = Some(DirsMultiset::from_dirstate(
303 self.dirs = Some(DirsMultiset::from_dirstate(
284 &self.state_map,
304 &self.state_map,
285 Some(EntryState::Removed),
305 Some(EntryState::Removed),
286 )?);
306 )?);
287 }
307 }
288 Ok(())
308 Ok(())
289 }
309 }
290
310
291 pub fn has_tracked_dir(&mut self, directory: &HgPath) -> Result<bool, DirstateMapError> {
311 pub fn has_tracked_dir(
312 &mut self,
313 directory: &HgPath,
314 ) -> Result<bool, DirstateMapError> {
292 self.set_dirs()?;
315 self.set_dirs()?;
293 Ok(self.dirs.as_ref().unwrap().contains(directory))
316 Ok(self.dirs.as_ref().unwrap().contains(directory))
294 }
317 }
295
318
296 pub fn has_dir(&mut self, directory: &HgPath) -> Result<bool, DirstateMapError> {
319 pub fn has_dir(
320 &mut self,
321 directory: &HgPath,
322 ) -> Result<bool, DirstateMapError> {
297 self.set_all_dirs()?;
323 self.set_all_dirs()?;
298 Ok(self.all_dirs.as_ref().unwrap().contains(directory))
324 Ok(self.all_dirs.as_ref().unwrap().contains(directory))
299 }
325 }
300
326
301 pub fn parents(&mut self, file_contents: &[u8]) -> Result<&DirstateParents, DirstateError> {
327 pub fn parents(
328 &mut self,
329 file_contents: &[u8],
330 ) -> Result<&DirstateParents, DirstateError> {
302 if let Some(ref parents) = self.parents {
331 if let Some(ref parents) = self.parents {
303 return Ok(parents);
332 return Ok(parents);
304 }
333 }
305 let parents;
334 let parents;
306 if file_contents.len() == PARENT_SIZE * 2 {
335 if file_contents.len() == PARENT_SIZE * 2 {
307 parents = DirstateParents {
336 parents = DirstateParents {
308 p1: file_contents[..PARENT_SIZE].try_into().unwrap(),
337 p1: file_contents[..PARENT_SIZE].try_into().unwrap(),
309 p2: file_contents[PARENT_SIZE..PARENT_SIZE * 2]
338 p2: file_contents[PARENT_SIZE..PARENT_SIZE * 2]
310 .try_into()
339 .try_into()
311 .unwrap(),
340 .unwrap(),
312 };
341 };
313 } else if file_contents.is_empty() {
342 } else if file_contents.is_empty() {
314 parents = DirstateParents {
343 parents = DirstateParents {
315 p1: NULL_NODE_ID,
344 p1: NULL_NODE_ID,
316 p2: NULL_NODE_ID,
345 p2: NULL_NODE_ID,
317 };
346 };
318 } else {
347 } else {
319 return Err(DirstateError::Parse(DirstateParseError::Damaged));
348 return Err(DirstateError::Parse(DirstateParseError::Damaged));
320 }
349 }
321
350
322 self.parents = Some(parents);
351 self.parents = Some(parents);
323 Ok(self.parents.as_ref().unwrap())
352 Ok(self.parents.as_ref().unwrap())
324 }
353 }
325
354
326 pub fn set_parents(&mut self, parents: &DirstateParents) {
355 pub fn set_parents(&mut self, parents: &DirstateParents) {
327 self.parents = Some(parents.clone());
356 self.parents = Some(parents.clone());
328 self.dirty_parents = true;
357 self.dirty_parents = true;
329 }
358 }
330
359
331 #[timed]
360 #[timed]
332 pub fn read(&mut self, file_contents: &[u8]) -> Result<Option<DirstateParents>, DirstateError> {
361 pub fn read(
362 &mut self,
363 file_contents: &[u8],
364 ) -> Result<Option<DirstateParents>, DirstateError> {
333 if file_contents.is_empty() {
365 if file_contents.is_empty() {
334 return Ok(None);
366 return Ok(None);
335 }
367 }
336
368
337 let (parents, entries, copies) = parse_dirstate(file_contents)?;
369 let (parents, entries, copies) = parse_dirstate(file_contents)?;
338 self.state_map.extend(
370 self.state_map.extend(
339 entries
371 entries
340 .into_iter()
372 .into_iter()
341 .map(|(path, entry)| (path.to_owned(), entry)),
373 .map(|(path, entry)| (path.to_owned(), entry)),
342 );
374 );
343 self.copy_map.extend(
375 self.copy_map.extend(
344 copies
376 copies
345 .into_iter()
377 .into_iter()
346 .map(|(path, copy)| (path.to_owned(), copy.to_owned())),
378 .map(|(path, copy)| (path.to_owned(), copy.to_owned())),
347 );
379 );
348
380
349 if !self.dirty_parents {
381 if !self.dirty_parents {
350 self.set_parents(&parents);
382 self.set_parents(&parents);
351 }
383 }
352
384
353 Ok(Some(parents))
385 Ok(Some(parents))
354 }
386 }
355
387
356 pub fn pack(
388 pub fn pack(
357 &mut self,
389 &mut self,
358 parents: DirstateParents,
390 parents: DirstateParents,
359 now: Duration,
391 now: Duration,
360 ) -> Result<Vec<u8>, DirstateError> {
392 ) -> Result<Vec<u8>, DirstateError> {
361 let packed = pack_dirstate(&mut self.state_map, &self.copy_map, parents, now)?;
393 let packed =
394 pack_dirstate(&mut self.state_map, &self.copy_map, parents, now)?;
362
395
363 self.dirty_parents = false;
396 self.dirty_parents = false;
364
397
365 self.set_non_normal_other_parent_entries(true);
398 self.set_non_normal_other_parent_entries(true);
366 Ok(packed)
399 Ok(packed)
367 }
400 }
368
401
369 pub fn build_file_fold_map(&mut self) -> &FileFoldMap {
402 pub fn build_file_fold_map(&mut self) -> &FileFoldMap {
370 if let Some(ref file_fold_map) = self.file_fold_map {
403 if let Some(ref file_fold_map) = self.file_fold_map {
371 return file_fold_map;
404 return file_fold_map;
372 }
405 }
373 let mut new_file_fold_map = FileFoldMap::default();
406 let mut new_file_fold_map = FileFoldMap::default();
374 for (filename, DirstateEntry { state, .. }) in self.state_map.borrow() {
407 for (filename, DirstateEntry { state, .. }) in self.state_map.borrow()
408 {
375 if *state == EntryState::Removed {
409 if *state == EntryState::Removed {
376 new_file_fold_map.insert(normalize_case(filename), filename.to_owned());
410 new_file_fold_map
411 .insert(normalize_case(filename), filename.to_owned());
377 }
412 }
378 }
413 }
379 self.file_fold_map = Some(new_file_fold_map);
414 self.file_fold_map = Some(new_file_fold_map);
380 self.file_fold_map.as_ref().unwrap()
415 self.file_fold_map.as_ref().unwrap()
381 }
416 }
382 }
417 }
383
418
384 #[cfg(test)]
419 #[cfg(test)]
385 mod tests {
420 mod tests {
386 use super::*;
421 use super::*;
387
422
388 #[test]
423 #[test]
389 fn test_dirs_multiset() {
424 fn test_dirs_multiset() {
390 let mut map = DirstateMap::new();
425 let mut map = DirstateMap::new();
391 assert!(map.dirs.is_none());
426 assert!(map.dirs.is_none());
392 assert!(map.all_dirs.is_none());
427 assert!(map.all_dirs.is_none());
393
428
394 assert_eq!(map.has_dir(HgPath::new(b"nope")).unwrap(), false);
429 assert_eq!(map.has_dir(HgPath::new(b"nope")).unwrap(), false);
395 assert!(map.all_dirs.is_some());
430 assert!(map.all_dirs.is_some());
396 assert!(map.dirs.is_none());
431 assert!(map.dirs.is_none());
397
432
398 assert_eq!(map.has_tracked_dir(HgPath::new(b"nope")).unwrap(), false);
433 assert_eq!(map.has_tracked_dir(HgPath::new(b"nope")).unwrap(), false);
399 assert!(map.dirs.is_some());
434 assert!(map.dirs.is_some());
400 }
435 }
401
436
402 #[test]
437 #[test]
403 fn test_add_file() {
438 fn test_add_file() {
404 let mut map = DirstateMap::new();
439 let mut map = DirstateMap::new();
405
440
406 assert_eq!(0, map.len());
441 assert_eq!(0, map.len());
407
442
408 map.add_file(
443 map.add_file(
409 HgPath::new(b"meh"),
444 HgPath::new(b"meh"),
410 EntryState::Normal,
445 EntryState::Normal,
411 DirstateEntry {
446 DirstateEntry {
412 state: EntryState::Normal,
447 state: EntryState::Normal,
413 mode: 1337,
448 mode: 1337,
414 mtime: 1337,
449 mtime: 1337,
415 size: 1337,
450 size: 1337,
416 },
451 },
417 )
452 )
418 .unwrap();
453 .unwrap();
419
454
420 assert_eq!(1, map.len());
455 assert_eq!(1, map.len());
421 assert_eq!(0, map.get_non_normal_other_parent_entries().0.len());
456 assert_eq!(0, map.get_non_normal_other_parent_entries().0.len());
422 assert_eq!(0, map.get_non_normal_other_parent_entries().1.len());
457 assert_eq!(0, map.get_non_normal_other_parent_entries().1.len());
423 }
458 }
424
459
425 #[test]
460 #[test]
426 fn test_non_normal_other_parent_entries() {
461 fn test_non_normal_other_parent_entries() {
427 let mut map: DirstateMap = [
462 let mut map: DirstateMap = [
428 (b"f1", (EntryState::Removed, 1337, 1337, 1337)),
463 (b"f1", (EntryState::Removed, 1337, 1337, 1337)),
429 (b"f2", (EntryState::Normal, 1337, 1337, -1)),
464 (b"f2", (EntryState::Normal, 1337, 1337, -1)),
430 (b"f3", (EntryState::Normal, 1337, 1337, 1337)),
465 (b"f3", (EntryState::Normal, 1337, 1337, 1337)),
431 (b"f4", (EntryState::Normal, 1337, -2, 1337)),
466 (b"f4", (EntryState::Normal, 1337, -2, 1337)),
432 (b"f5", (EntryState::Added, 1337, 1337, 1337)),
467 (b"f5", (EntryState::Added, 1337, 1337, 1337)),
433 (b"f6", (EntryState::Added, 1337, 1337, -1)),
468 (b"f6", (EntryState::Added, 1337, 1337, -1)),
434 (b"f7", (EntryState::Merged, 1337, 1337, -1)),
469 (b"f7", (EntryState::Merged, 1337, 1337, -1)),
435 (b"f8", (EntryState::Merged, 1337, 1337, 1337)),
470 (b"f8", (EntryState::Merged, 1337, 1337, 1337)),
436 (b"f9", (EntryState::Merged, 1337, -2, 1337)),
471 (b"f9", (EntryState::Merged, 1337, -2, 1337)),
437 (b"fa", (EntryState::Added, 1337, -2, 1337)),
472 (b"fa", (EntryState::Added, 1337, -2, 1337)),
438 (b"fb", (EntryState::Removed, 1337, -2, 1337)),
473 (b"fb", (EntryState::Removed, 1337, -2, 1337)),
439 ]
474 ]
440 .iter()
475 .iter()
441 .map(|(fname, (state, mode, size, mtime))| {
476 .map(|(fname, (state, mode, size, mtime))| {
442 (
477 (
443 HgPathBuf::from_bytes(fname.as_ref()),
478 HgPathBuf::from_bytes(fname.as_ref()),
444 DirstateEntry {
479 DirstateEntry {
445 state: *state,
480 state: *state,
446 mode: *mode,
481 mode: *mode,
447 size: *size,
482 size: *size,
448 mtime: *mtime,
483 mtime: *mtime,
449 },
484 },
450 )
485 )
451 })
486 })
452 .collect();
487 .collect();
453
488
454 let mut non_normal = [
489 let mut non_normal = [
455 b"f1", b"f2", b"f5", b"f6", b"f7", b"f8", b"f9", b"fa", b"fb",
490 b"f1", b"f2", b"f5", b"f6", b"f7", b"f8", b"f9", b"fa", b"fb",
456 ]
491 ]
457 .iter()
492 .iter()
458 .map(|x| HgPathBuf::from_bytes(x.as_ref()))
493 .map(|x| HgPathBuf::from_bytes(x.as_ref()))
459 .collect();
494 .collect();
460
495
461 let mut other_parent = HashSet::new();
496 let mut other_parent = HashSet::new();
462 other_parent.insert(HgPathBuf::from_bytes(b"f4"));
497 other_parent.insert(HgPathBuf::from_bytes(b"f4"));
463 let entries = map.get_non_normal_other_parent_entries();
498 let entries = map.get_non_normal_other_parent_entries();
464
499
465 assert_eq!((&mut non_normal, &mut other_parent), (entries.0, entries.1));
500 assert_eq!(
501 (&mut non_normal, &mut other_parent),
502 (entries.0, entries.1)
503 );
466 }
504 }
467 }
505 }
@@ -1,358 +1,392 b''
1 // iter.rs
1 // iter.rs
2 //
2 //
3 // Copyright 2020, Raphaël Gomès <rgomes@octobus.net>
3 // Copyright 2020, Raphaël Gomès <rgomes@octobus.net>
4 //
4 //
5 // This software may be used and distributed according to the terms of the
5 // This software may be used and distributed according to the terms of the
6 // GNU General Public License version 2 or any later version.
6 // GNU General Public License version 2 or any later version.
7
7
8 use super::node::{Node, NodeKind};
8 use super::node::{Node, NodeKind};
9 use super::tree::Tree;
9 use super::tree::Tree;
10 use crate::dirstate::dirstate_tree::node::Directory;
10 use crate::dirstate::dirstate_tree::node::Directory;
11 use crate::dirstate::status::Dispatch;
11 use crate::dirstate::status::Dispatch;
12 use crate::utils::hg_path::{hg_path_to_path_buf, HgPath, HgPathBuf};
12 use crate::utils::hg_path::{hg_path_to_path_buf, HgPath, HgPathBuf};
13 use crate::DirstateEntry;
13 use crate::DirstateEntry;
14 use std::borrow::Cow;
14 use std::borrow::Cow;
15 use std::collections::VecDeque;
15 use std::collections::VecDeque;
16 use std::iter::{FromIterator, FusedIterator};
16 use std::iter::{FromIterator, FusedIterator};
17 use std::path::PathBuf;
17 use std::path::PathBuf;
18
18
19 impl FromIterator<(HgPathBuf, DirstateEntry)> for Tree {
19 impl FromIterator<(HgPathBuf, DirstateEntry)> for Tree {
20 fn from_iter<T: IntoIterator<Item = (HgPathBuf, DirstateEntry)>>(iter: T) -> Self {
20 fn from_iter<T: IntoIterator<Item = (HgPathBuf, DirstateEntry)>>(
21 iter: T,
22 ) -> Self {
21 let mut tree = Self::new();
23 let mut tree = Self::new();
22 for (path, entry) in iter {
24 for (path, entry) in iter {
23 tree.insert(path, entry);
25 tree.insert(path, entry);
24 }
26 }
25 tree
27 tree
26 }
28 }
27 }
29 }
28
30
29 /// Iterator of all entries in the dirstate tree.
31 /// Iterator of all entries in the dirstate tree.
30 ///
32 ///
31 /// It has no particular ordering.
33 /// It has no particular ordering.
32 pub struct Iter<'a> {
34 pub struct Iter<'a> {
33 to_visit: VecDeque<(Cow<'a, [u8]>, &'a Node)>,
35 to_visit: VecDeque<(Cow<'a, [u8]>, &'a Node)>,
34 }
36 }
35
37
36 impl<'a> Iter<'a> {
38 impl<'a> Iter<'a> {
37 pub fn new(node: &'a Node) -> Iter<'a> {
39 pub fn new(node: &'a Node) -> Iter<'a> {
38 let mut to_visit = VecDeque::new();
40 let mut to_visit = VecDeque::new();
39 to_visit.push_back((Cow::Borrowed(&b""[..]), node));
41 to_visit.push_back((Cow::Borrowed(&b""[..]), node));
40 Self { to_visit }
42 Self { to_visit }
41 }
43 }
42 }
44 }
43
45
44 impl<'a> Iterator for Iter<'a> {
46 impl<'a> Iterator for Iter<'a> {
45 type Item = (HgPathBuf, DirstateEntry);
47 type Item = (HgPathBuf, DirstateEntry);
46
48
47 fn next(&mut self) -> Option<Self::Item> {
49 fn next(&mut self) -> Option<Self::Item> {
48 while let Some((base_path, node)) = self.to_visit.pop_front() {
50 while let Some((base_path, node)) = self.to_visit.pop_front() {
49 match &node.kind {
51 match &node.kind {
50 NodeKind::Directory(dir) => {
52 NodeKind::Directory(dir) => {
51 add_children_to_visit(&mut self.to_visit, &base_path, &dir);
53 add_children_to_visit(
54 &mut self.to_visit,
55 &base_path,
56 &dir,
57 );
52 if let Some(file) = &dir.was_file {
58 if let Some(file) = &dir.was_file {
53 return Some((HgPathBuf::from_bytes(&base_path), file.entry));
59 return Some((
60 HgPathBuf::from_bytes(&base_path),
61 file.entry,
62 ));
54 }
63 }
55 }
64 }
56 NodeKind::File(file) => {
65 NodeKind::File(file) => {
57 if let Some(dir) = &file.was_directory {
66 if let Some(dir) = &file.was_directory {
58 add_children_to_visit(&mut self.to_visit, &base_path, &dir);
67 add_children_to_visit(
68 &mut self.to_visit,
69 &base_path,
70 &dir,
71 );
59 }
72 }
60 return Some((HgPathBuf::from_bytes(&base_path), file.entry));
73 return Some((
74 HgPathBuf::from_bytes(&base_path),
75 file.entry,
76 ));
61 }
77 }
62 }
78 }
63 }
79 }
64 None
80 None
65 }
81 }
66 }
82 }
67
83
68 impl<'a> FusedIterator for Iter<'a> {}
84 impl<'a> FusedIterator for Iter<'a> {}
69
85
70 /// Iterator of all entries in the dirstate tree, with a special filesystem
86 /// Iterator of all entries in the dirstate tree, with a special filesystem
71 /// handling for the directories containing said entries.
87 /// handling for the directories containing said entries.
72 ///
88 ///
73 /// It checks every directory on-disk to see if it has become a symlink, to
89 /// It checks every directory on-disk to see if it has become a symlink, to
74 /// prevent a potential security issue.
90 /// prevent a potential security issue.
75 /// Using this information, it may dispatch `status` information early: it
91 /// Using this information, it may dispatch `status` information early: it
76 /// returns canonical paths along with `Shortcut`s, which are either a
92 /// returns canonical paths along with `Shortcut`s, which are either a
77 /// `DirstateEntry` or a `Dispatch`, if the fate of said path has already been
93 /// `DirstateEntry` or a `Dispatch`, if the fate of said path has already been
78 /// determined.
94 /// determined.
79 ///
95 ///
80 /// Like `Iter`, it has no particular ordering.
96 /// Like `Iter`, it has no particular ordering.
81 pub struct FsIter<'a> {
97 pub struct FsIter<'a> {
82 root_dir: PathBuf,
98 root_dir: PathBuf,
83 to_visit: VecDeque<(Cow<'a, [u8]>, &'a Node)>,
99 to_visit: VecDeque<(Cow<'a, [u8]>, &'a Node)>,
84 shortcuts: VecDeque<(HgPathBuf, StatusShortcut)>,
100 shortcuts: VecDeque<(HgPathBuf, StatusShortcut)>,
85 }
101 }
86
102
87 impl<'a> FsIter<'a> {
103 impl<'a> FsIter<'a> {
88 pub fn new(node: &'a Node, root_dir: PathBuf) -> FsIter<'a> {
104 pub fn new(node: &'a Node, root_dir: PathBuf) -> FsIter<'a> {
89 let mut to_visit = VecDeque::new();
105 let mut to_visit = VecDeque::new();
90 to_visit.push_back((Cow::Borrowed(&b""[..]), node));
106 to_visit.push_back((Cow::Borrowed(&b""[..]), node));
91 Self {
107 Self {
92 root_dir,
108 root_dir,
93 to_visit,
109 to_visit,
94 shortcuts: Default::default(),
110 shortcuts: Default::default(),
95 }
111 }
96 }
112 }
97
113
98 /// Mercurial tracks symlinks but *not* what they point to.
114 /// Mercurial tracks symlinks but *not* what they point to.
99 /// If a directory is moved and symlinked:
115 /// If a directory is moved and symlinked:
100 ///
116 ///
101 /// ```bash
117 /// ```bash
102 /// $ mkdir foo
118 /// $ mkdir foo
103 /// $ touch foo/a
119 /// $ touch foo/a
104 /// $ # commit...
120 /// $ # commit...
105 /// $ mv foo bar
121 /// $ mv foo bar
106 /// $ ln -s bar foo
122 /// $ ln -s bar foo
107 /// ```
123 /// ```
108 /// We need to dispatch the new symlink as `Unknown` and all the
124 /// We need to dispatch the new symlink as `Unknown` and all the
109 /// descendents of the directory it replace as `Deleted`.
125 /// descendents of the directory it replace as `Deleted`.
110 fn dispatch_symlinked_directory(&mut self, path: impl AsRef<HgPath>, node: &Node) {
126 fn dispatch_symlinked_directory(
127 &mut self,
128 path: impl AsRef<HgPath>,
129 node: &Node,
130 ) {
111 let path = path.as_ref();
131 let path = path.as_ref();
112 self.shortcuts
132 self.shortcuts.push_back((
113 .push_back((path.to_owned(), StatusShortcut::Dispatch(Dispatch::Unknown)));
133 path.to_owned(),
134 StatusShortcut::Dispatch(Dispatch::Unknown),
135 ));
114 for (file, _) in node.iter() {
136 for (file, _) in node.iter() {
115 self.shortcuts.push_back((
137 self.shortcuts.push_back((
116 path.join(&file),
138 path.join(&file),
117 StatusShortcut::Dispatch(Dispatch::Deleted),
139 StatusShortcut::Dispatch(Dispatch::Deleted),
118 ));
140 ));
119 }
141 }
120 }
142 }
121
143
122 /// Returns `true` if the canonical `path` of a directory corresponds to a
144 /// Returns `true` if the canonical `path` of a directory corresponds to a
123 /// symlink on disk. It means it was moved and symlinked after the last
145 /// symlink on disk. It means it was moved and symlinked after the last
124 /// dirstate update.
146 /// dirstate update.
125 ///
147 ///
126 /// # Special cases
148 /// # Special cases
127 ///
149 ///
128 /// Returns `false` for the repository root.
150 /// Returns `false` for the repository root.
129 /// Returns `false` on io error, error handling is outside of the iterator.
151 /// Returns `false` on io error, error handling is outside of the iterator.
130 fn directory_became_symlink(&mut self, path: &HgPath) -> bool {
152 fn directory_became_symlink(&mut self, path: &HgPath) -> bool {
131 if path.is_empty() {
153 if path.is_empty() {
132 return false;
154 return false;
133 }
155 }
134 let filename_as_path = match hg_path_to_path_buf(&path) {
156 let filename_as_path = match hg_path_to_path_buf(&path) {
135 Ok(p) => p,
157 Ok(p) => p,
136 _ => return false,
158 _ => return false,
137 };
159 };
138 let meta = self.root_dir.join(filename_as_path).symlink_metadata();
160 let meta = self.root_dir.join(filename_as_path).symlink_metadata();
139 match meta {
161 match meta {
140 Ok(ref m) if m.file_type().is_symlink() => true,
162 Ok(ref m) if m.file_type().is_symlink() => true,
141 _ => return false,
163 _ => return false,
142 }
164 }
143 }
165 }
144 }
166 }
145
167
146 /// Returned by `FsIter`, since the `Dispatch` of any given entry may already
168 /// Returned by `FsIter`, since the `Dispatch` of any given entry may already
147 /// be determined during the iteration. This is necessary for performance
169 /// be determined during the iteration. This is necessary for performance
148 /// reasons, since hierarchical information is needed to `Dispatch` an entire
170 /// reasons, since hierarchical information is needed to `Dispatch` an entire
149 /// subtree efficiently.
171 /// subtree efficiently.
150 #[derive(Debug, Copy, Clone)]
172 #[derive(Debug, Copy, Clone)]
151 pub enum StatusShortcut {
173 pub enum StatusShortcut {
152 /// A entry in the dirstate for further inspection
174 /// A entry in the dirstate for further inspection
153 Entry(DirstateEntry),
175 Entry(DirstateEntry),
154 /// The result of the status of the corresponding file
176 /// The result of the status of the corresponding file
155 Dispatch(Dispatch),
177 Dispatch(Dispatch),
156 }
178 }
157
179
158 impl<'a> Iterator for FsIter<'a> {
180 impl<'a> Iterator for FsIter<'a> {
159 type Item = (HgPathBuf, StatusShortcut);
181 type Item = (HgPathBuf, StatusShortcut);
160
182
161 fn next(&mut self) -> Option<Self::Item> {
183 fn next(&mut self) -> Option<Self::Item> {
162 // If any paths have already been `Dispatch`-ed, return them
184 // If any paths have already been `Dispatch`-ed, return them
163 while let Some(res) = self.shortcuts.pop_front() {
185 while let Some(res) = self.shortcuts.pop_front() {
164 return Some(res);
186 return Some(res);
165 }
187 }
166
188
167 while let Some((base_path, node)) = self.to_visit.pop_front() {
189 while let Some((base_path, node)) = self.to_visit.pop_front() {
168 match &node.kind {
190 match &node.kind {
169 NodeKind::Directory(dir) => {
191 NodeKind::Directory(dir) => {
170 let canonical_path = HgPath::new(&base_path);
192 let canonical_path = HgPath::new(&base_path);
171 if self.directory_became_symlink(canonical_path) {
193 if self.directory_became_symlink(canonical_path) {
172 // Potential security issue, don't do a normal
194 // Potential security issue, don't do a normal
173 // traversal, force the results.
195 // traversal, force the results.
174 self.dispatch_symlinked_directory(canonical_path, &node);
196 self.dispatch_symlinked_directory(
197 canonical_path,
198 &node,
199 );
175 continue;
200 continue;
176 }
201 }
177 add_children_to_visit(&mut self.to_visit, &base_path, &dir);
202 add_children_to_visit(
203 &mut self.to_visit,
204 &base_path,
205 &dir,
206 );
178 if let Some(file) = &dir.was_file {
207 if let Some(file) = &dir.was_file {
179 return Some((
208 return Some((
180 HgPathBuf::from_bytes(&base_path),
209 HgPathBuf::from_bytes(&base_path),
181 StatusShortcut::Entry(file.entry),
210 StatusShortcut::Entry(file.entry),
182 ));
211 ));
183 }
212 }
184 }
213 }
185 NodeKind::File(file) => {
214 NodeKind::File(file) => {
186 if let Some(dir) = &file.was_directory {
215 if let Some(dir) = &file.was_directory {
187 add_children_to_visit(&mut self.to_visit, &base_path, &dir);
216 add_children_to_visit(
217 &mut self.to_visit,
218 &base_path,
219 &dir,
220 );
188 }
221 }
189 return Some((
222 return Some((
190 HgPathBuf::from_bytes(&base_path),
223 HgPathBuf::from_bytes(&base_path),
191 StatusShortcut::Entry(file.entry),
224 StatusShortcut::Entry(file.entry),
192 ));
225 ));
193 }
226 }
194 }
227 }
195 }
228 }
196
229
197 None
230 None
198 }
231 }
199 }
232 }
200
233
201 impl<'a> FusedIterator for FsIter<'a> {}
234 impl<'a> FusedIterator for FsIter<'a> {}
202
235
203 fn join_path<'a, 'b>(path: &'a [u8], other: &'b [u8]) -> Cow<'b, [u8]> {
236 fn join_path<'a, 'b>(path: &'a [u8], other: &'b [u8]) -> Cow<'b, [u8]> {
204 if path.is_empty() {
237 if path.is_empty() {
205 other.into()
238 other.into()
206 } else {
239 } else {
207 [path, &b"/"[..], other].concat().into()
240 [path, &b"/"[..], other].concat().into()
208 }
241 }
209 }
242 }
210
243
211 /// Adds all children of a given directory `dir` to the visit queue `to_visit`
244 /// Adds all children of a given directory `dir` to the visit queue `to_visit`
212 /// prefixed by a `base_path`.
245 /// prefixed by a `base_path`.
213 fn add_children_to_visit<'a>(
246 fn add_children_to_visit<'a>(
214 to_visit: &mut VecDeque<(Cow<'a, [u8]>, &'a Node)>,
247 to_visit: &mut VecDeque<(Cow<'a, [u8]>, &'a Node)>,
215 base_path: &[u8],
248 base_path: &[u8],
216 dir: &'a Directory,
249 dir: &'a Directory,
217 ) {
250 ) {
218 to_visit.extend(dir.children.iter().map(|(path, child)| {
251 to_visit.extend(dir.children.iter().map(|(path, child)| {
219 let full_path = join_path(&base_path, &path);
252 let full_path = join_path(&base_path, &path);
220 (Cow::from(full_path), child)
253 (Cow::from(full_path), child)
221 }));
254 }));
222 }
255 }
223
256
224 #[cfg(test)]
257 #[cfg(test)]
225 mod tests {
258 mod tests {
226 use super::*;
259 use super::*;
227 use crate::utils::hg_path::HgPath;
260 use crate::utils::hg_path::HgPath;
228 use crate::{EntryState, FastHashMap};
261 use crate::{EntryState, FastHashMap};
229 use std::collections::HashSet;
262 use std::collections::HashSet;
230
263
231 #[test]
264 #[test]
232 fn test_iteration() {
265 fn test_iteration() {
233 let mut tree = Tree::new();
266 let mut tree = Tree::new();
234
267
235 assert_eq!(
268 assert_eq!(
236 tree.insert(
269 tree.insert(
237 HgPathBuf::from_bytes(b"foo/bar"),
270 HgPathBuf::from_bytes(b"foo/bar"),
238 DirstateEntry {
271 DirstateEntry {
239 state: EntryState::Merged,
272 state: EntryState::Merged,
240 mode: 41,
273 mode: 41,
241 mtime: 42,
274 mtime: 42,
242 size: 43,
275 size: 43,
243 }
276 }
244 ),
277 ),
245 None
278 None
246 );
279 );
247
280
248 assert_eq!(
281 assert_eq!(
249 tree.insert(
282 tree.insert(
250 HgPathBuf::from_bytes(b"foo2"),
283 HgPathBuf::from_bytes(b"foo2"),
251 DirstateEntry {
284 DirstateEntry {
252 state: EntryState::Merged,
285 state: EntryState::Merged,
253 mode: 40,
286 mode: 40,
254 mtime: 41,
287 mtime: 41,
255 size: 42,
288 size: 42,
256 }
289 }
257 ),
290 ),
258 None
291 None
259 );
292 );
260
293
261 assert_eq!(
294 assert_eq!(
262 tree.insert(
295 tree.insert(
263 HgPathBuf::from_bytes(b"foo/baz"),
296 HgPathBuf::from_bytes(b"foo/baz"),
264 DirstateEntry {
297 DirstateEntry {
265 state: EntryState::Normal,
298 state: EntryState::Normal,
266 mode: 0,
299 mode: 0,
267 mtime: 0,
300 mtime: 0,
268 size: 0,
301 size: 0,
269 }
302 }
270 ),
303 ),
271 None
304 None
272 );
305 );
273
306
274 assert_eq!(
307 assert_eq!(
275 tree.insert(
308 tree.insert(
276 HgPathBuf::from_bytes(b"foo/bap/nested"),
309 HgPathBuf::from_bytes(b"foo/bap/nested"),
277 DirstateEntry {
310 DirstateEntry {
278 state: EntryState::Normal,
311 state: EntryState::Normal,
279 mode: 0,
312 mode: 0,
280 mtime: 0,
313 mtime: 0,
281 size: 0,
314 size: 0,
282 }
315 }
283 ),
316 ),
284 None
317 None
285 );
318 );
286
319
287 assert_eq!(tree.len(), 4);
320 assert_eq!(tree.len(), 4);
288
321
289 let results: HashSet<_> = tree.iter().map(|(c, _)| c.to_owned()).collect();
322 let results: HashSet<_> =
323 tree.iter().map(|(c, _)| c.to_owned()).collect();
290 dbg!(&results);
324 dbg!(&results);
291 assert!(results.contains(HgPath::new(b"foo2")));
325 assert!(results.contains(HgPath::new(b"foo2")));
292 assert!(results.contains(HgPath::new(b"foo/bar")));
326 assert!(results.contains(HgPath::new(b"foo/bar")));
293 assert!(results.contains(HgPath::new(b"foo/baz")));
327 assert!(results.contains(HgPath::new(b"foo/baz")));
294 assert!(results.contains(HgPath::new(b"foo/bap/nested")));
328 assert!(results.contains(HgPath::new(b"foo/bap/nested")));
295
329
296 let mut iter = tree.iter();
330 let mut iter = tree.iter();
297 assert!(iter.next().is_some());
331 assert!(iter.next().is_some());
298 assert!(iter.next().is_some());
332 assert!(iter.next().is_some());
299 assert!(iter.next().is_some());
333 assert!(iter.next().is_some());
300 assert!(iter.next().is_some());
334 assert!(iter.next().is_some());
301 assert_eq!(None, iter.next());
335 assert_eq!(None, iter.next());
302 assert_eq!(None, iter.next());
336 assert_eq!(None, iter.next());
303 drop(iter);
337 drop(iter);
304
338
305 assert_eq!(
339 assert_eq!(
306 tree.insert(
340 tree.insert(
307 HgPathBuf::from_bytes(b"foo/bap/nested/a"),
341 HgPathBuf::from_bytes(b"foo/bap/nested/a"),
308 DirstateEntry {
342 DirstateEntry {
309 state: EntryState::Normal,
343 state: EntryState::Normal,
310 mode: 0,
344 mode: 0,
311 mtime: 0,
345 mtime: 0,
312 size: 0,
346 size: 0,
313 }
347 }
314 ),
348 ),
315 None
349 None
316 );
350 );
317
351
318 let results: FastHashMap<_, _> = tree.iter().collect();
352 let results: FastHashMap<_, _> = tree.iter().collect();
319 assert!(results.contains_key(HgPath::new(b"foo2")));
353 assert!(results.contains_key(HgPath::new(b"foo2")));
320 assert!(results.contains_key(HgPath::new(b"foo/bar")));
354 assert!(results.contains_key(HgPath::new(b"foo/bar")));
321 assert!(results.contains_key(HgPath::new(b"foo/baz")));
355 assert!(results.contains_key(HgPath::new(b"foo/baz")));
322 // Is a dir but `was_file`, so it's listed as a removed file
356 // Is a dir but `was_file`, so it's listed as a removed file
323 assert!(results.contains_key(HgPath::new(b"foo/bap/nested")));
357 assert!(results.contains_key(HgPath::new(b"foo/bap/nested")));
324 assert!(results.contains_key(HgPath::new(b"foo/bap/nested/a")));
358 assert!(results.contains_key(HgPath::new(b"foo/bap/nested/a")));
325
359
326 // insert removed file (now directory) after nested file
360 // insert removed file (now directory) after nested file
327 assert_eq!(
361 assert_eq!(
328 tree.insert(
362 tree.insert(
329 HgPathBuf::from_bytes(b"a/a"),
363 HgPathBuf::from_bytes(b"a/a"),
330 DirstateEntry {
364 DirstateEntry {
331 state: EntryState::Normal,
365 state: EntryState::Normal,
332 mode: 0,
366 mode: 0,
333 mtime: 0,
367 mtime: 0,
334 size: 0,
368 size: 0,
335 }
369 }
336 ),
370 ),
337 None
371 None
338 );
372 );
339
373
340 // `insert` returns `None` for a directory
374 // `insert` returns `None` for a directory
341 assert_eq!(
375 assert_eq!(
342 tree.insert(
376 tree.insert(
343 HgPathBuf::from_bytes(b"a"),
377 HgPathBuf::from_bytes(b"a"),
344 DirstateEntry {
378 DirstateEntry {
345 state: EntryState::Removed,
379 state: EntryState::Removed,
346 mode: 0,
380 mode: 0,
347 mtime: 0,
381 mtime: 0,
348 size: 0,
382 size: 0,
349 }
383 }
350 ),
384 ),
351 None
385 None
352 );
386 );
353
387
354 let results: FastHashMap<_, _> = tree.iter().collect();
388 let results: FastHashMap<_, _> = tree.iter().collect();
355 assert!(results.contains_key(HgPath::new(b"a")));
389 assert!(results.contains_key(HgPath::new(b"a")));
356 assert!(results.contains_key(HgPath::new(b"a/a")));
390 assert!(results.contains_key(HgPath::new(b"a/a")));
357 }
391 }
358 }
392 }
@@ -1,377 +1,395 b''
1 // node.rs
1 // node.rs
2 //
2 //
3 // Copyright 2020, Raphaël Gomès <rgomes@octobus.net>
3 // Copyright 2020, Raphaël Gomès <rgomes@octobus.net>
4 //
4 //
5 // This software may be used and distributed according to the terms of the
5 // This software may be used and distributed according to the terms of the
6 // GNU General Public License version 2 or any later version.
6 // GNU General Public License version 2 or any later version.
7
7
8 use super::iter::Iter;
8 use super::iter::Iter;
9 use crate::utils::hg_path::HgPathBuf;
9 use crate::utils::hg_path::HgPathBuf;
10 use crate::{DirstateEntry, EntryState, FastHashMap};
10 use crate::{DirstateEntry, EntryState, FastHashMap};
11
11
12 /// Represents a filesystem directory in the dirstate tree
12 /// Represents a filesystem directory in the dirstate tree
13 #[derive(Debug, Default, Clone, PartialEq)]
13 #[derive(Debug, Default, Clone, PartialEq)]
14 pub struct Directory {
14 pub struct Directory {
15 /// Contains the old file information if it existed between changesets.
15 /// Contains the old file information if it existed between changesets.
16 /// Happens if a file `foo` is marked as removed, removed from the
16 /// Happens if a file `foo` is marked as removed, removed from the
17 /// filesystem then a directory `foo` is created and at least one of its
17 /// filesystem then a directory `foo` is created and at least one of its
18 /// descendents is added to Mercurial.
18 /// descendents is added to Mercurial.
19 pub(super) was_file: Option<Box<File>>,
19 pub(super) was_file: Option<Box<File>>,
20 pub(super) children: FastHashMap<Vec<u8>, Node>,
20 pub(super) children: FastHashMap<Vec<u8>, Node>,
21 }
21 }
22
22
23 /// Represents a filesystem file (or symlink) in the dirstate tree
23 /// Represents a filesystem file (or symlink) in the dirstate tree
24 #[derive(Debug, Clone, PartialEq)]
24 #[derive(Debug, Clone, PartialEq)]
25 pub struct File {
25 pub struct File {
26 /// Contains the old structure if it existed between changesets.
26 /// Contains the old structure if it existed between changesets.
27 /// Happens all descendents of `foo` marked as removed and removed from
27 /// Happens all descendents of `foo` marked as removed and removed from
28 /// the filesystem, then a file `foo` is created and added to Mercurial.
28 /// the filesystem, then a file `foo` is created and added to Mercurial.
29 pub(super) was_directory: Option<Box<Directory>>,
29 pub(super) was_directory: Option<Box<Directory>>,
30 pub(super) entry: DirstateEntry,
30 pub(super) entry: DirstateEntry,
31 }
31 }
32
32
33 #[derive(Debug, Clone, PartialEq)]
33 #[derive(Debug, Clone, PartialEq)]
34 pub enum NodeKind {
34 pub enum NodeKind {
35 Directory(Directory),
35 Directory(Directory),
36 File(File),
36 File(File),
37 }
37 }
38
38
39 #[derive(Debug, Default, Clone, PartialEq)]
39 #[derive(Debug, Default, Clone, PartialEq)]
40 pub struct Node {
40 pub struct Node {
41 pub kind: NodeKind,
41 pub kind: NodeKind,
42 }
42 }
43
43
44 impl Default for NodeKind {
44 impl Default for NodeKind {
45 fn default() -> Self {
45 fn default() -> Self {
46 NodeKind::Directory(Default::default())
46 NodeKind::Directory(Default::default())
47 }
47 }
48 }
48 }
49
49
50 impl Node {
50 impl Node {
51 pub fn insert(&mut self, path: &[u8], new_entry: DirstateEntry) -> InsertResult {
51 pub fn insert(
52 &mut self,
53 path: &[u8],
54 new_entry: DirstateEntry,
55 ) -> InsertResult {
52 let mut split = path.splitn(2, |&c| c == b'/');
56 let mut split = path.splitn(2, |&c| c == b'/');
53 let head = split.next().unwrap_or(b"");
57 let head = split.next().unwrap_or(b"");
54 let tail = split.next().unwrap_or(b"");
58 let tail = split.next().unwrap_or(b"");
55
59
56 if let NodeKind::File(file) = &mut self.kind {
60 if let NodeKind::File(file) = &mut self.kind {
57 if tail.is_empty() && head.is_empty() {
61 if tail.is_empty() && head.is_empty() {
58 // We're modifying the current file
62 // We're modifying the current file
59 let new = Self {
63 let new = Self {
60 kind: NodeKind::File(File {
64 kind: NodeKind::File(File {
61 entry: new_entry,
65 entry: new_entry,
62 ..file.clone()
66 ..file.clone()
63 }),
67 }),
64 };
68 };
65 return InsertResult {
69 return InsertResult {
66 did_insert: false,
70 did_insert: false,
67 old_entry: Some(std::mem::replace(self, new)),
71 old_entry: Some(std::mem::replace(self, new)),
68 };
72 };
69 } else {
73 } else {
70 match file.entry.state {
74 match file.entry.state {
71 // Only replace the current file with a directory if it's
75 // Only replace the current file with a directory if it's
72 // marked as `Removed`
76 // marked as `Removed`
73 EntryState::Removed => {
77 EntryState::Removed => {
74 self.kind = NodeKind::Directory(Directory {
78 self.kind = NodeKind::Directory(Directory {
75 was_file: Some(Box::from(file.clone())),
79 was_file: Some(Box::from(file.clone())),
76 children: Default::default(),
80 children: Default::default(),
77 })
81 })
78 }
82 }
79 _ => return Node::insert_in_file(file, new_entry, head, tail),
83 _ => {
84 return Node::insert_in_file(
85 file, new_entry, head, tail,
86 )
87 }
80 }
88 }
81 }
89 }
82 }
90 }
83
91
84 match &mut self.kind {
92 match &mut self.kind {
85 NodeKind::Directory(directory) => {
93 NodeKind::Directory(directory) => {
86 return Node::insert_in_directory(directory, new_entry, head, tail);
94 return Node::insert_in_directory(
95 directory, new_entry, head, tail,
96 );
87 }
97 }
88 NodeKind::File(_) => unreachable!("The file case has already been handled"),
98 NodeKind::File(_) => {
99 unreachable!("The file case has already been handled")
100 }
89 }
101 }
90 }
102 }
91
103
92 /// The current file still exists and is not marked as `Removed`.
104 /// The current file still exists and is not marked as `Removed`.
93 /// Insert the entry in its `was_directory`.
105 /// Insert the entry in its `was_directory`.
94 fn insert_in_file(
106 fn insert_in_file(
95 file: &mut File,
107 file: &mut File,
96 new_entry: DirstateEntry,
108 new_entry: DirstateEntry,
97 head: &[u8],
109 head: &[u8],
98 tail: &[u8],
110 tail: &[u8],
99 ) -> InsertResult {
111 ) -> InsertResult {
100 if let Some(d) = &mut file.was_directory {
112 if let Some(d) = &mut file.was_directory {
101 Node::insert_in_directory(d, new_entry, head, tail)
113 Node::insert_in_directory(d, new_entry, head, tail)
102 } else {
114 } else {
103 let mut dir = Directory {
115 let mut dir = Directory {
104 was_file: None,
116 was_file: None,
105 children: FastHashMap::default(),
117 children: FastHashMap::default(),
106 };
118 };
107 let res = Node::insert_in_directory(&mut dir, new_entry, head, tail);
119 let res =
120 Node::insert_in_directory(&mut dir, new_entry, head, tail);
108 file.was_directory = Some(Box::new(dir));
121 file.was_directory = Some(Box::new(dir));
109 res
122 res
110 }
123 }
111 }
124 }
112
125
113 /// Insert an entry in the subtree of `directory`
126 /// Insert an entry in the subtree of `directory`
114 fn insert_in_directory(
127 fn insert_in_directory(
115 directory: &mut Directory,
128 directory: &mut Directory,
116 new_entry: DirstateEntry,
129 new_entry: DirstateEntry,
117 head: &[u8],
130 head: &[u8],
118 tail: &[u8],
131 tail: &[u8],
119 ) -> InsertResult {
132 ) -> InsertResult {
120 let mut res = InsertResult::default();
133 let mut res = InsertResult::default();
121
134
122 if let Some(node) = directory.children.get_mut(head) {
135 if let Some(node) = directory.children.get_mut(head) {
123 // Node exists
136 // Node exists
124 match &mut node.kind {
137 match &mut node.kind {
125 NodeKind::Directory(subdir) => {
138 NodeKind::Directory(subdir) => {
126 if tail.is_empty() {
139 if tail.is_empty() {
127 let becomes_file = Self {
140 let becomes_file = Self {
128 kind: NodeKind::File(File {
141 kind: NodeKind::File(File {
129 was_directory: Some(Box::from(subdir.clone())),
142 was_directory: Some(Box::from(subdir.clone())),
130 entry: new_entry,
143 entry: new_entry,
131 }),
144 }),
132 };
145 };
133 let old_entry = directory.children.insert(head.to_owned(), becomes_file);
146 let old_entry = directory
147 .children
148 .insert(head.to_owned(), becomes_file);
134 return InsertResult {
149 return InsertResult {
135 did_insert: true,
150 did_insert: true,
136 old_entry,
151 old_entry,
137 };
152 };
138 } else {
153 } else {
139 res = node.insert(tail, new_entry);
154 res = node.insert(tail, new_entry);
140 }
155 }
141 }
156 }
142 NodeKind::File(_) => {
157 NodeKind::File(_) => {
143 res = node.insert(tail, new_entry);
158 res = node.insert(tail, new_entry);
144 }
159 }
145 }
160 }
146 } else if tail.is_empty() {
161 } else if tail.is_empty() {
147 // File does not already exist
162 // File does not already exist
148 directory.children.insert(
163 directory.children.insert(
149 head.to_owned(),
164 head.to_owned(),
150 Self {
165 Self {
151 kind: NodeKind::File(File {
166 kind: NodeKind::File(File {
152 was_directory: None,
167 was_directory: None,
153 entry: new_entry,
168 entry: new_entry,
154 }),
169 }),
155 },
170 },
156 );
171 );
157 res.did_insert = true;
172 res.did_insert = true;
158 } else {
173 } else {
159 // Directory does not already exist
174 // Directory does not already exist
160 let mut nested = Self {
175 let mut nested = Self {
161 kind: NodeKind::Directory(Directory {
176 kind: NodeKind::Directory(Directory {
162 was_file: None,
177 was_file: None,
163 children: Default::default(),
178 children: Default::default(),
164 }),
179 }),
165 };
180 };
166 res = nested.insert(tail, new_entry);
181 res = nested.insert(tail, new_entry);
167 directory.children.insert(head.to_owned(), nested);
182 directory.children.insert(head.to_owned(), nested);
168 }
183 }
169 res
184 res
170 }
185 }
171
186
172 /// Removes an entry from the tree, returns a `RemoveResult`.
187 /// Removes an entry from the tree, returns a `RemoveResult`.
173 pub fn remove(&mut self, path: &[u8]) -> RemoveResult {
188 pub fn remove(&mut self, path: &[u8]) -> RemoveResult {
174 let empty_result = RemoveResult::default();
189 let empty_result = RemoveResult::default();
175 if path.is_empty() {
190 if path.is_empty() {
176 return empty_result;
191 return empty_result;
177 }
192 }
178 let mut split = path.splitn(2, |&c| c == b'/');
193 let mut split = path.splitn(2, |&c| c == b'/');
179 let head = split.next();
194 let head = split.next();
180 let tail = split.next().unwrap_or(b"");
195 let tail = split.next().unwrap_or(b"");
181
196
182 let head = match head {
197 let head = match head {
183 None => {
198 None => {
184 return empty_result;
199 return empty_result;
185 }
200 }
186 Some(h) => h,
201 Some(h) => h,
187 };
202 };
188 if head == path {
203 if head == path {
189 match &mut self.kind {
204 match &mut self.kind {
190 NodeKind::Directory(d) => {
205 NodeKind::Directory(d) => {
191 return Node::remove_from_directory(head, d);
206 return Node::remove_from_directory(head, d);
192 }
207 }
193 NodeKind::File(f) => {
208 NodeKind::File(f) => {
194 if let Some(d) = &mut f.was_directory {
209 if let Some(d) = &mut f.was_directory {
195 let RemoveResult { old_entry, .. } = Node::remove_from_directory(head, d);
210 let RemoveResult { old_entry, .. } =
211 Node::remove_from_directory(head, d);
196 return RemoveResult {
212 return RemoveResult {
197 cleanup: false,
213 cleanup: false,
198 old_entry,
214 old_entry,
199 };
215 };
200 }
216 }
201 }
217 }
202 }
218 }
203 empty_result
219 empty_result
204 } else {
220 } else {
205 // Look into the dirs
221 // Look into the dirs
206 match &mut self.kind {
222 match &mut self.kind {
207 NodeKind::Directory(d) => {
223 NodeKind::Directory(d) => {
208 if let Some(child) = d.children.get_mut(head) {
224 if let Some(child) = d.children.get_mut(head) {
209 let mut res = child.remove(tail);
225 let mut res = child.remove(tail);
210 if res.cleanup {
226 if res.cleanup {
211 d.children.remove(head);
227 d.children.remove(head);
212 }
228 }
213 res.cleanup = d.children.len() == 0 && d.was_file.is_none();
229 res.cleanup =
230 d.children.len() == 0 && d.was_file.is_none();
214 res
231 res
215 } else {
232 } else {
216 empty_result
233 empty_result
217 }
234 }
218 }
235 }
219 NodeKind::File(f) => {
236 NodeKind::File(f) => {
220 if let Some(d) = &mut f.was_directory {
237 if let Some(d) = &mut f.was_directory {
221 if let Some(child) = d.children.get_mut(head) {
238 if let Some(child) = d.children.get_mut(head) {
222 let RemoveResult { cleanup, old_entry } = child.remove(tail);
239 let RemoveResult { cleanup, old_entry } =
240 child.remove(tail);
223 if cleanup {
241 if cleanup {
224 d.children.remove(head);
242 d.children.remove(head);
225 }
243 }
226 if d.children.len() == 0 && d.was_file.is_none() {
244 if d.children.len() == 0 && d.was_file.is_none() {
227 f.was_directory = None;
245 f.was_directory = None;
228 }
246 }
229
247
230 return RemoveResult {
248 return RemoveResult {
231 cleanup: false,
249 cleanup: false,
232 old_entry,
250 old_entry,
233 };
251 };
234 }
252 }
235 }
253 }
236 empty_result
254 empty_result
237 }
255 }
238 }
256 }
239 }
257 }
240 }
258 }
241
259
242 fn remove_from_directory(head: &[u8], d: &mut Directory) -> RemoveResult {
260 fn remove_from_directory(head: &[u8], d: &mut Directory) -> RemoveResult {
243 if let Some(node) = d.children.get_mut(head) {
261 if let Some(node) = d.children.get_mut(head) {
244 return match &mut node.kind {
262 return match &mut node.kind {
245 NodeKind::Directory(d) => {
263 NodeKind::Directory(d) => {
246 if let Some(f) = &mut d.was_file {
264 if let Some(f) = &mut d.was_file {
247 let entry = f.entry;
265 let entry = f.entry;
248 d.was_file = None;
266 d.was_file = None;
249 RemoveResult {
267 RemoveResult {
250 cleanup: false,
268 cleanup: false,
251 old_entry: Some(entry),
269 old_entry: Some(entry),
252 }
270 }
253 } else {
271 } else {
254 RemoveResult::default()
272 RemoveResult::default()
255 }
273 }
256 }
274 }
257 NodeKind::File(f) => {
275 NodeKind::File(f) => {
258 let entry = f.entry;
276 let entry = f.entry;
259 let mut cleanup = false;
277 let mut cleanup = false;
260 match &f.was_directory {
278 match &f.was_directory {
261 None => {
279 None => {
262 if d.children.len() == 1 {
280 if d.children.len() == 1 {
263 cleanup = true;
281 cleanup = true;
264 }
282 }
265 d.children.remove(head);
283 d.children.remove(head);
266 }
284 }
267 Some(dir) => {
285 Some(dir) => {
268 node.kind = NodeKind::Directory(*dir.clone());
286 node.kind = NodeKind::Directory(*dir.clone());
269 }
287 }
270 }
288 }
271
289
272 RemoveResult {
290 RemoveResult {
273 cleanup: cleanup,
291 cleanup: cleanup,
274 old_entry: Some(entry),
292 old_entry: Some(entry),
275 }
293 }
276 }
294 }
277 };
295 };
278 }
296 }
279 RemoveResult::default()
297 RemoveResult::default()
280 }
298 }
281
299
282 pub fn get(&self, path: &[u8]) -> Option<&Node> {
300 pub fn get(&self, path: &[u8]) -> Option<&Node> {
283 if path.is_empty() {
301 if path.is_empty() {
284 return Some(&self);
302 return Some(&self);
285 }
303 }
286 let mut split = path.splitn(2, |&c| c == b'/');
304 let mut split = path.splitn(2, |&c| c == b'/');
287 let head = split.next();
305 let head = split.next();
288 let tail = split.next().unwrap_or(b"");
306 let tail = split.next().unwrap_or(b"");
289
307
290 let head = match head {
308 let head = match head {
291 None => {
309 None => {
292 return Some(&self);
310 return Some(&self);
293 }
311 }
294 Some(h) => h,
312 Some(h) => h,
295 };
313 };
296 match &self.kind {
314 match &self.kind {
297 NodeKind::Directory(d) => {
315 NodeKind::Directory(d) => {
298 if let Some(child) = d.children.get(head) {
316 if let Some(child) = d.children.get(head) {
299 return child.get(tail);
317 return child.get(tail);
300 }
318 }
301 }
319 }
302 NodeKind::File(f) => {
320 NodeKind::File(f) => {
303 if let Some(d) = &f.was_directory {
321 if let Some(d) = &f.was_directory {
304 if let Some(child) = d.children.get(head) {
322 if let Some(child) = d.children.get(head) {
305 return child.get(tail);
323 return child.get(tail);
306 }
324 }
307 }
325 }
308 }
326 }
309 }
327 }
310
328
311 None
329 None
312 }
330 }
313
331
314 pub fn get_mut(&mut self, path: &[u8]) -> Option<&mut NodeKind> {
332 pub fn get_mut(&mut self, path: &[u8]) -> Option<&mut NodeKind> {
315 if path.is_empty() {
333 if path.is_empty() {
316 return Some(&mut self.kind);
334 return Some(&mut self.kind);
317 }
335 }
318 let mut split = path.splitn(2, |&c| c == b'/');
336 let mut split = path.splitn(2, |&c| c == b'/');
319 let head = split.next();
337 let head = split.next();
320 let tail = split.next().unwrap_or(b"");
338 let tail = split.next().unwrap_or(b"");
321
339
322 let head = match head {
340 let head = match head {
323 None => {
341 None => {
324 return Some(&mut self.kind);
342 return Some(&mut self.kind);
325 }
343 }
326 Some(h) => h,
344 Some(h) => h,
327 };
345 };
328 match &mut self.kind {
346 match &mut self.kind {
329 NodeKind::Directory(d) => {
347 NodeKind::Directory(d) => {
330 if let Some(child) = d.children.get_mut(head) {
348 if let Some(child) = d.children.get_mut(head) {
331 return child.get_mut(tail);
349 return child.get_mut(tail);
332 }
350 }
333 }
351 }
334 NodeKind::File(f) => {
352 NodeKind::File(f) => {
335 if let Some(d) = &mut f.was_directory {
353 if let Some(d) = &mut f.was_directory {
336 if let Some(child) = d.children.get_mut(head) {
354 if let Some(child) = d.children.get_mut(head) {
337 return child.get_mut(tail);
355 return child.get_mut(tail);
338 }
356 }
339 }
357 }
340 }
358 }
341 }
359 }
342
360
343 None
361 None
344 }
362 }
345
363
346 pub fn iter(&self) -> Iter {
364 pub fn iter(&self) -> Iter {
347 Iter::new(self)
365 Iter::new(self)
348 }
366 }
349 }
367 }
350
368
351 /// Information returned to the caller of an `insert` operation for integrity.
369 /// Information returned to the caller of an `insert` operation for integrity.
352 #[derive(Debug, Default)]
370 #[derive(Debug, Default)]
353 pub struct InsertResult {
371 pub struct InsertResult {
354 /// Whether the insertion resulted in an actual insertion and not an
372 /// Whether the insertion resulted in an actual insertion and not an
355 /// update
373 /// update
356 pub(super) did_insert: bool,
374 pub(super) did_insert: bool,
357 /// The entry that was replaced, if it exists
375 /// The entry that was replaced, if it exists
358 pub(super) old_entry: Option<Node>,
376 pub(super) old_entry: Option<Node>,
359 }
377 }
360
378
361 /// Information returned to the caller of a `remove` operation integrity.
379 /// Information returned to the caller of a `remove` operation integrity.
362 #[derive(Debug, Default)]
380 #[derive(Debug, Default)]
363 pub struct RemoveResult {
381 pub struct RemoveResult {
364 /// If the caller needs to remove the current node
382 /// If the caller needs to remove the current node
365 pub(super) cleanup: bool,
383 pub(super) cleanup: bool,
366 /// The entry that was replaced, if it exists
384 /// The entry that was replaced, if it exists
367 pub(super) old_entry: Option<DirstateEntry>,
385 pub(super) old_entry: Option<DirstateEntry>,
368 }
386 }
369
387
370 impl<'a> IntoIterator for &'a Node {
388 impl<'a> IntoIterator for &'a Node {
371 type Item = (HgPathBuf, DirstateEntry);
389 type Item = (HgPathBuf, DirstateEntry);
372 type IntoIter = Iter<'a>;
390 type IntoIter = Iter<'a>;
373
391
374 fn into_iter(self) -> Self::IntoIter {
392 fn into_iter(self) -> Self::IntoIter {
375 self.iter()
393 self.iter()
376 }
394 }
377 }
395 }
@@ -1,661 +1,682 b''
1 // tree.rs
1 // tree.rs
2 //
2 //
3 // Copyright 2020, Raphaël Gomès <rgomes@octobus.net>
3 // Copyright 2020, Raphaël Gomès <rgomes@octobus.net>
4 //
4 //
5 // This software may be used and distributed according to the terms of the
5 // This software may be used and distributed according to the terms of the
6 // GNU General Public License version 2 or any later version.
6 // GNU General Public License version 2 or any later version.
7
7
8 use super::iter::Iter;
8 use super::iter::Iter;
9 use super::node::{Directory, Node, NodeKind};
9 use super::node::{Directory, Node, NodeKind};
10 use crate::dirstate::dirstate_tree::iter::FsIter;
10 use crate::dirstate::dirstate_tree::iter::FsIter;
11 use crate::dirstate::dirstate_tree::node::{InsertResult, RemoveResult};
11 use crate::dirstate::dirstate_tree::node::{InsertResult, RemoveResult};
12 use crate::utils::hg_path::{HgPath, HgPathBuf};
12 use crate::utils::hg_path::{HgPath, HgPathBuf};
13 use crate::DirstateEntry;
13 use crate::DirstateEntry;
14 use std::path::PathBuf;
14 use std::path::PathBuf;
15
15
16 /// A specialized tree to represent the Mercurial dirstate.
16 /// A specialized tree to represent the Mercurial dirstate.
17 ///
17 ///
18 /// # Advantages over a flat structure
18 /// # Advantages over a flat structure
19 ///
19 ///
20 /// The dirstate is inherently hierarchical, since it's a representation of the
20 /// The dirstate is inherently hierarchical, since it's a representation of the
21 /// file structure of the project. The current dirstate format is flat, and
21 /// file structure of the project. The current dirstate format is flat, and
22 /// while that affords us potentially great (unordered) iteration speeds, the
22 /// while that affords us potentially great (unordered) iteration speeds, the
23 /// need to retrieve a given path is great enough that you need some kind of
23 /// need to retrieve a given path is great enough that you need some kind of
24 /// hashmap or tree in a lot of cases anyway.
24 /// hashmap or tree in a lot of cases anyway.
25 ///
25 ///
26 /// Going with a tree allows us to be smarter:
26 /// Going with a tree allows us to be smarter:
27 /// - Skipping an ignored directory means we don't visit its entire subtree
27 /// - Skipping an ignored directory means we don't visit its entire subtree
28 /// - Security auditing does not need to reconstruct paths backwards to check
28 /// - Security auditing does not need to reconstruct paths backwards to check
29 /// for symlinked directories, this can be done during the iteration in a
29 /// for symlinked directories, this can be done during the iteration in a
30 /// very efficient fashion
30 /// very efficient fashion
31 /// - We don't need to build the directory information in another struct,
31 /// - We don't need to build the directory information in another struct,
32 /// simplifying the code a lot, reducing the memory footprint and
32 /// simplifying the code a lot, reducing the memory footprint and
33 /// potentially going faster depending on the implementation.
33 /// potentially going faster depending on the implementation.
34 /// - We can use it to store a (platform-dependent) caching mechanism [1]
34 /// - We can use it to store a (platform-dependent) caching mechanism [1]
35 /// - And probably other types of optimizations.
35 /// - And probably other types of optimizations.
36 ///
36 ///
37 /// Only the first two items in this list are implemented as of this commit.
37 /// Only the first two items in this list are implemented as of this commit.
38 ///
38 ///
39 /// [1]: https://www.mercurial-scm.org/wiki/DirsCachePlan
39 /// [1]: https://www.mercurial-scm.org/wiki/DirsCachePlan
40 ///
40 ///
41 ///
41 ///
42 /// # Structure
42 /// # Structure
43 ///
43 ///
44 /// It's a prefix (radix) tree with no fixed arity, with a granularity of a
44 /// It's a prefix (radix) tree with no fixed arity, with a granularity of a
45 /// folder, allowing it to mimic a filesystem hierarchy:
45 /// folder, allowing it to mimic a filesystem hierarchy:
46 ///
46 ///
47 /// ```text
47 /// ```text
48 /// foo/bar
48 /// foo/bar
49 /// foo/baz
49 /// foo/baz
50 /// test
50 /// test
51 /// ```
51 /// ```
52 /// Will be represented (simplified) by:
52 /// Will be represented (simplified) by:
53 ///
53 ///
54 /// ```text
54 /// ```text
55 /// Directory(root):
55 /// Directory(root):
56 /// - File("test")
56 /// - File("test")
57 /// - Directory("foo"):
57 /// - Directory("foo"):
58 /// - File("bar")
58 /// - File("bar")
59 /// - File("baz")
59 /// - File("baz")
60 /// ```
60 /// ```
61 ///
61 ///
62 /// Moreover, it is special-cased for storing the dirstate and as such handles
62 /// Moreover, it is special-cased for storing the dirstate and as such handles
63 /// cases that a simple `HashMap` would handle, but while preserving the
63 /// cases that a simple `HashMap` would handle, but while preserving the
64 /// hierarchy.
64 /// hierarchy.
65 /// For example:
65 /// For example:
66 ///
66 ///
67 /// ```shell
67 /// ```shell
68 /// $ touch foo
68 /// $ touch foo
69 /// $ hg add foo
69 /// $ hg add foo
70 /// $ hg commit -m "foo"
70 /// $ hg commit -m "foo"
71 /// $ hg remove foo
71 /// $ hg remove foo
72 /// $ rm foo
72 /// $ rm foo
73 /// $ mkdir foo
73 /// $ mkdir foo
74 /// $ touch foo/a
74 /// $ touch foo/a
75 /// $ hg add foo/a
75 /// $ hg add foo/a
76 /// $ hg status
76 /// $ hg status
77 /// R foo
77 /// R foo
78 /// A foo/a
78 /// A foo/a
79 /// ```
79 /// ```
80 /// To represent this in a tree, one needs to keep track of whether any given
80 /// To represent this in a tree, one needs to keep track of whether any given
81 /// file was a directory and whether any given directory was a file at the last
81 /// file was a directory and whether any given directory was a file at the last
82 /// dirstate update. This tree stores that information, but only in the right
82 /// dirstate update. This tree stores that information, but only in the right
83 /// circumstances by respecting the high-level rules that prevent nonsensical
83 /// circumstances by respecting the high-level rules that prevent nonsensical
84 /// structures to exist:
84 /// structures to exist:
85 /// - a file can only be added as a child of another file if the latter is
85 /// - a file can only be added as a child of another file if the latter is
86 /// marked as `Removed`
86 /// marked as `Removed`
87 /// - a file cannot replace a folder unless all its descendents are removed
87 /// - a file cannot replace a folder unless all its descendents are removed
88 ///
88 ///
89 /// This second rule is not checked by the tree for performance reasons, and
89 /// This second rule is not checked by the tree for performance reasons, and
90 /// because high-level logic already prevents that state from happening.
90 /// because high-level logic already prevents that state from happening.
91 ///
91 ///
92 /// # Ordering
92 /// # Ordering
93 ///
93 ///
94 /// It makes no guarantee of ordering for now.
94 /// It makes no guarantee of ordering for now.
95 #[derive(Debug, Default, Clone, PartialEq)]
95 #[derive(Debug, Default, Clone, PartialEq)]
96 pub struct Tree {
96 pub struct Tree {
97 pub root: Node,
97 pub root: Node,
98 files_count: usize,
98 files_count: usize,
99 }
99 }
100
100
101 impl Tree {
101 impl Tree {
102 pub fn new() -> Self {
102 pub fn new() -> Self {
103 Self {
103 Self {
104 root: Node {
104 root: Node {
105 kind: NodeKind::Directory(Directory {
105 kind: NodeKind::Directory(Directory {
106 was_file: None,
106 was_file: None,
107 children: Default::default(),
107 children: Default::default(),
108 }),
108 }),
109 },
109 },
110 files_count: 0,
110 files_count: 0,
111 }
111 }
112 }
112 }
113
113
114 /// How many files (not directories) are stored in the tree, including ones
114 /// How many files (not directories) are stored in the tree, including ones
115 /// marked as `Removed`.
115 /// marked as `Removed`.
116 pub fn len(&self) -> usize {
116 pub fn len(&self) -> usize {
117 self.files_count
117 self.files_count
118 }
118 }
119
119
120 pub fn is_empty(&self) -> bool {
120 pub fn is_empty(&self) -> bool {
121 self.len() == 0
121 self.len() == 0
122 }
122 }
123
123
124 /// Inserts a file in the tree and returns the previous entry if any.
124 /// Inserts a file in the tree and returns the previous entry if any.
125 pub fn insert(
125 pub fn insert(
126 &mut self,
126 &mut self,
127 path: impl AsRef<HgPath>,
127 path: impl AsRef<HgPath>,
128 kind: DirstateEntry,
128 kind: DirstateEntry,
129 ) -> Option<DirstateEntry> {
129 ) -> Option<DirstateEntry> {
130 let old = self.insert_node(path, kind);
130 let old = self.insert_node(path, kind);
131 match old?.kind {
131 match old?.kind {
132 NodeKind::Directory(_) => None,
132 NodeKind::Directory(_) => None,
133 NodeKind::File(f) => Some(f.entry),
133 NodeKind::File(f) => Some(f.entry),
134 }
134 }
135 }
135 }
136
136
137 /// Low-level insertion method that returns the previous node (directories
137 /// Low-level insertion method that returns the previous node (directories
138 /// included).
138 /// included).
139 fn insert_node(&mut self, path: impl AsRef<HgPath>, kind: DirstateEntry) -> Option<Node> {
139 fn insert_node(
140 &mut self,
141 path: impl AsRef<HgPath>,
142 kind: DirstateEntry,
143 ) -> Option<Node> {
140 let InsertResult {
144 let InsertResult {
141 did_insert,
145 did_insert,
142 old_entry,
146 old_entry,
143 } = self.root.insert(path.as_ref().as_bytes(), kind);
147 } = self.root.insert(path.as_ref().as_bytes(), kind);
144 self.files_count += if did_insert { 1 } else { 0 };
148 self.files_count += if did_insert { 1 } else { 0 };
145 old_entry
149 old_entry
146 }
150 }
147
151
148 /// Returns a reference to a node if it exists.
152 /// Returns a reference to a node if it exists.
149 pub fn get_node(&self, path: impl AsRef<HgPath>) -> Option<&Node> {
153 pub fn get_node(&self, path: impl AsRef<HgPath>) -> Option<&Node> {
150 self.root.get(path.as_ref().as_bytes())
154 self.root.get(path.as_ref().as_bytes())
151 }
155 }
152
156
153 /// Returns a reference to the entry corresponding to `path` if it exists.
157 /// Returns a reference to the entry corresponding to `path` if it exists.
154 pub fn get(&self, path: impl AsRef<HgPath>) -> Option<&DirstateEntry> {
158 pub fn get(&self, path: impl AsRef<HgPath>) -> Option<&DirstateEntry> {
155 if let Some(node) = self.get_node(&path) {
159 if let Some(node) = self.get_node(&path) {
156 return match &node.kind {
160 return match &node.kind {
157 NodeKind::Directory(d) => d.was_file.as_ref().map(|f| &f.entry),
161 NodeKind::Directory(d) => {
162 d.was_file.as_ref().map(|f| &f.entry)
163 }
158 NodeKind::File(f) => Some(&f.entry),
164 NodeKind::File(f) => Some(&f.entry),
159 };
165 };
160 }
166 }
161 None
167 None
162 }
168 }
163
169
164 /// Returns `true` if an entry is found for the given `path`.
170 /// Returns `true` if an entry is found for the given `path`.
165 pub fn contains_key(&self, path: impl AsRef<HgPath>) -> bool {
171 pub fn contains_key(&self, path: impl AsRef<HgPath>) -> bool {
166 self.get(path).is_some()
172 self.get(path).is_some()
167 }
173 }
168
174
169 /// Returns a mutable reference to the entry corresponding to `path` if it
175 /// Returns a mutable reference to the entry corresponding to `path` if it
170 /// exists.
176 /// exists.
171 pub fn get_mut(&mut self, path: impl AsRef<HgPath>) -> Option<&mut DirstateEntry> {
177 pub fn get_mut(
178 &mut self,
179 path: impl AsRef<HgPath>,
180 ) -> Option<&mut DirstateEntry> {
172 if let Some(kind) = self.root.get_mut(path.as_ref().as_bytes()) {
181 if let Some(kind) = self.root.get_mut(path.as_ref().as_bytes()) {
173 return match kind {
182 return match kind {
174 NodeKind::Directory(d) => d.was_file.as_mut().map(|f| &mut f.entry),
183 NodeKind::Directory(d) => {
184 d.was_file.as_mut().map(|f| &mut f.entry)
185 }
175 NodeKind::File(f) => Some(&mut f.entry),
186 NodeKind::File(f) => Some(&mut f.entry),
176 };
187 };
177 }
188 }
178 None
189 None
179 }
190 }
180
191
181 /// Returns an iterator over the paths and corresponding entries in the
192 /// Returns an iterator over the paths and corresponding entries in the
182 /// tree.
193 /// tree.
183 pub fn iter(&self) -> Iter {
194 pub fn iter(&self) -> Iter {
184 Iter::new(&self.root)
195 Iter::new(&self.root)
185 }
196 }
186
197
187 /// Returns an iterator of all entries in the tree, with a special
198 /// Returns an iterator of all entries in the tree, with a special
188 /// filesystem handling for the directories containing said entries. See
199 /// filesystem handling for the directories containing said entries. See
189 /// the documentation of `FsIter` for more.
200 /// the documentation of `FsIter` for more.
190 pub fn fs_iter(&self, root_dir: PathBuf) -> FsIter {
201 pub fn fs_iter(&self, root_dir: PathBuf) -> FsIter {
191 FsIter::new(&self.root, root_dir)
202 FsIter::new(&self.root, root_dir)
192 }
203 }
193
204
194 /// Remove the entry at `path` and returns it, if it exists.
205 /// Remove the entry at `path` and returns it, if it exists.
195 pub fn remove(&mut self, path: impl AsRef<HgPath>) -> Option<DirstateEntry> {
206 pub fn remove(
196 let RemoveResult { old_entry, .. } = self.root.remove(path.as_ref().as_bytes());
207 &mut self,
208 path: impl AsRef<HgPath>,
209 ) -> Option<DirstateEntry> {
210 let RemoveResult { old_entry, .. } =
211 self.root.remove(path.as_ref().as_bytes());
197 self.files_count = self
212 self.files_count = self
198 .files_count
213 .files_count
199 .checked_sub(if old_entry.is_some() { 1 } else { 0 })
214 .checked_sub(if old_entry.is_some() { 1 } else { 0 })
200 .expect("removed too many files");
215 .expect("removed too many files");
201 old_entry
216 old_entry
202 }
217 }
203 }
218 }
204
219
205 impl<P: AsRef<HgPath>> Extend<(P, DirstateEntry)> for Tree {
220 impl<P: AsRef<HgPath>> Extend<(P, DirstateEntry)> for Tree {
206 fn extend<T: IntoIterator<Item = (P, DirstateEntry)>>(&mut self, iter: T) {
221 fn extend<T: IntoIterator<Item = (P, DirstateEntry)>>(&mut self, iter: T) {
207 for (path, entry) in iter {
222 for (path, entry) in iter {
208 self.insert(path, entry);
223 self.insert(path, entry);
209 }
224 }
210 }
225 }
211 }
226 }
212
227
213 impl<'a> IntoIterator for &'a Tree {
228 impl<'a> IntoIterator for &'a Tree {
214 type Item = (HgPathBuf, DirstateEntry);
229 type Item = (HgPathBuf, DirstateEntry);
215 type IntoIter = Iter<'a>;
230 type IntoIter = Iter<'a>;
216
231
217 fn into_iter(self) -> Self::IntoIter {
232 fn into_iter(self) -> Self::IntoIter {
218 self.iter()
233 self.iter()
219 }
234 }
220 }
235 }
221
236
222 #[cfg(test)]
237 #[cfg(test)]
223 mod tests {
238 mod tests {
224 use super::*;
239 use super::*;
225 use crate::dirstate::dirstate_tree::node::File;
240 use crate::dirstate::dirstate_tree::node::File;
226 use crate::{EntryState, FastHashMap};
241 use crate::{EntryState, FastHashMap};
227 use pretty_assertions::assert_eq;
242 use pretty_assertions::assert_eq;
228
243
229 impl Node {
244 impl Node {
230 /// Shortcut for getting children of a node in tests.
245 /// Shortcut for getting children of a node in tests.
231 fn children(&self) -> Option<&FastHashMap<Vec<u8>, Node>> {
246 fn children(&self) -> Option<&FastHashMap<Vec<u8>, Node>> {
232 match &self.kind {
247 match &self.kind {
233 NodeKind::Directory(d) => Some(&d.children),
248 NodeKind::Directory(d) => Some(&d.children),
234 NodeKind::File(_) => None,
249 NodeKind::File(_) => None,
235 }
250 }
236 }
251 }
237 }
252 }
238
253
239 #[test]
254 #[test]
240 fn test_dirstate_tree() {
255 fn test_dirstate_tree() {
241 let mut tree = Tree::new();
256 let mut tree = Tree::new();
242
257
243 assert_eq!(
258 assert_eq!(
244 tree.insert_node(
259 tree.insert_node(
245 HgPath::new(b"we/p"),
260 HgPath::new(b"we/p"),
246 DirstateEntry {
261 DirstateEntry {
247 state: EntryState::Normal,
262 state: EntryState::Normal,
248 mode: 0,
263 mode: 0,
249 mtime: 0,
264 mtime: 0,
250 size: 0
265 size: 0
251 }
266 }
252 ),
267 ),
253 None
268 None
254 );
269 );
255 dbg!(&tree);
270 dbg!(&tree);
256 assert!(tree.get_node(HgPath::new(b"we")).is_some());
271 assert!(tree.get_node(HgPath::new(b"we")).is_some());
257 let entry = DirstateEntry {
272 let entry = DirstateEntry {
258 state: EntryState::Merged,
273 state: EntryState::Merged,
259 mode: 41,
274 mode: 41,
260 mtime: 42,
275 mtime: 42,
261 size: 43,
276 size: 43,
262 };
277 };
263 assert_eq!(tree.insert_node(HgPath::new(b"foo/bar"), entry), None);
278 assert_eq!(tree.insert_node(HgPath::new(b"foo/bar"), entry), None);
264 assert_eq!(
279 assert_eq!(
265 tree.get_node(HgPath::new(b"foo/bar")),
280 tree.get_node(HgPath::new(b"foo/bar")),
266 Some(&Node {
281 Some(&Node {
267 kind: NodeKind::File(File {
282 kind: NodeKind::File(File {
268 was_directory: None,
283 was_directory: None,
269 entry
284 entry
270 })
285 })
271 })
286 })
272 );
287 );
273 // We didn't override the first entry we made
288 // We didn't override the first entry we made
274 assert!(tree.get_node(HgPath::new(b"we")).is_some(),);
289 assert!(tree.get_node(HgPath::new(b"we")).is_some(),);
275 // Inserting the same key again
290 // Inserting the same key again
276 assert_eq!(
291 assert_eq!(
277 tree.insert_node(HgPath::new(b"foo/bar"), entry),
292 tree.insert_node(HgPath::new(b"foo/bar"), entry),
278 Some(Node {
293 Some(Node {
279 kind: NodeKind::File(File {
294 kind: NodeKind::File(File {
280 was_directory: None,
295 was_directory: None,
281 entry
296 entry
282 }),
297 }),
283 })
298 })
284 );
299 );
285 // Inserting the two levels deep
300 // Inserting the two levels deep
286 assert_eq!(tree.insert_node(HgPath::new(b"foo/bar/baz"), entry), None);
301 assert_eq!(tree.insert_node(HgPath::new(b"foo/bar/baz"), entry), None);
287 // Getting a file "inside a file" should return `None`
302 // Getting a file "inside a file" should return `None`
288 assert_eq!(tree.get_node(HgPath::new(b"foo/bar/baz/bap"),), None);
303 assert_eq!(tree.get_node(HgPath::new(b"foo/bar/baz/bap"),), None);
289
304
290 assert_eq!(
305 assert_eq!(
291 tree.insert_node(HgPath::new(b"wasdir/subfile"), entry),
306 tree.insert_node(HgPath::new(b"wasdir/subfile"), entry),
292 None,
307 None,
293 );
308 );
294 let removed_entry = DirstateEntry {
309 let removed_entry = DirstateEntry {
295 state: EntryState::Removed,
310 state: EntryState::Removed,
296 mode: 0,
311 mode: 0,
297 mtime: 0,
312 mtime: 0,
298 size: 0,
313 size: 0,
299 };
314 };
300 assert!(tree
315 assert!(tree
301 .insert_node(HgPath::new(b"wasdir"), removed_entry)
316 .insert_node(HgPath::new(b"wasdir"), removed_entry)
302 .is_some());
317 .is_some());
303
318
304 assert_eq!(
319 assert_eq!(
305 tree.get_node(HgPath::new(b"wasdir")),
320 tree.get_node(HgPath::new(b"wasdir")),
306 Some(&Node {
321 Some(&Node {
307 kind: NodeKind::File(File {
322 kind: NodeKind::File(File {
308 was_directory: Some(Box::new(Directory {
323 was_directory: Some(Box::new(Directory {
309 was_file: None,
324 was_file: None,
310 children: [(
325 children: [(
311 b"subfile".to_vec(),
326 b"subfile".to_vec(),
312 Node {
327 Node {
313 kind: NodeKind::File(File {
328 kind: NodeKind::File(File {
314 was_directory: None,
329 was_directory: None,
315 entry,
330 entry,
316 })
331 })
317 }
332 }
318 )]
333 )]
319 .to_vec()
334 .to_vec()
320 .into_iter()
335 .into_iter()
321 .collect()
336 .collect()
322 })),
337 })),
323 entry: removed_entry
338 entry: removed_entry
324 })
339 })
325 })
340 })
326 );
341 );
327
342
328 assert!(tree.get(HgPath::new(b"wasdir/subfile")).is_some())
343 assert!(tree.get(HgPath::new(b"wasdir/subfile")).is_some())
329 }
344 }
330
345
331 #[test]
346 #[test]
332 fn test_insert_removed() {
347 fn test_insert_removed() {
333 let mut tree = Tree::new();
348 let mut tree = Tree::new();
334 let entry = DirstateEntry {
349 let entry = DirstateEntry {
335 state: EntryState::Merged,
350 state: EntryState::Merged,
336 mode: 1,
351 mode: 1,
337 mtime: 2,
352 mtime: 2,
338 size: 3,
353 size: 3,
339 };
354 };
340 let removed_entry = DirstateEntry {
355 let removed_entry = DirstateEntry {
341 state: EntryState::Removed,
356 state: EntryState::Removed,
342 mode: 10,
357 mode: 10,
343 mtime: 20,
358 mtime: 20,
344 size: 30,
359 size: 30,
345 };
360 };
346 assert_eq!(tree.insert_node(HgPath::new(b"foo"), entry), None);
361 assert_eq!(tree.insert_node(HgPath::new(b"foo"), entry), None);
347 assert_eq!(tree.insert_node(HgPath::new(b"foo/a"), removed_entry), None);
362 assert_eq!(
363 tree.insert_node(HgPath::new(b"foo/a"), removed_entry),
364 None
365 );
348 // The insert should not turn `foo` into a directory as `foo` is not
366 // The insert should not turn `foo` into a directory as `foo` is not
349 // `Removed`.
367 // `Removed`.
350 match tree.get_node(HgPath::new(b"foo")).unwrap().kind {
368 match tree.get_node(HgPath::new(b"foo")).unwrap().kind {
351 NodeKind::Directory(_) => panic!("should be a file"),
369 NodeKind::Directory(_) => panic!("should be a file"),
352 NodeKind::File(_) => {}
370 NodeKind::File(_) => {}
353 }
371 }
354
372
355 let mut tree = Tree::new();
373 let mut tree = Tree::new();
356 let entry = DirstateEntry {
374 let entry = DirstateEntry {
357 state: EntryState::Merged,
375 state: EntryState::Merged,
358 mode: 1,
376 mode: 1,
359 mtime: 2,
377 mtime: 2,
360 size: 3,
378 size: 3,
361 };
379 };
362 let removed_entry = DirstateEntry {
380 let removed_entry = DirstateEntry {
363 state: EntryState::Removed,
381 state: EntryState::Removed,
364 mode: 10,
382 mode: 10,
365 mtime: 20,
383 mtime: 20,
366 size: 30,
384 size: 30,
367 };
385 };
368 // The insert *should* turn `foo` into a directory as it is `Removed`.
386 // The insert *should* turn `foo` into a directory as it is `Removed`.
369 assert_eq!(tree.insert_node(HgPath::new(b"foo"), removed_entry), None);
387 assert_eq!(tree.insert_node(HgPath::new(b"foo"), removed_entry), None);
370 assert_eq!(tree.insert_node(HgPath::new(b"foo/a"), entry), None);
388 assert_eq!(tree.insert_node(HgPath::new(b"foo/a"), entry), None);
371 match tree.get_node(HgPath::new(b"foo")).unwrap().kind {
389 match tree.get_node(HgPath::new(b"foo")).unwrap().kind {
372 NodeKind::Directory(_) => {}
390 NodeKind::Directory(_) => {}
373 NodeKind::File(_) => panic!("should be a directory"),
391 NodeKind::File(_) => panic!("should be a directory"),
374 }
392 }
375 }
393 }
376
394
377 #[test]
395 #[test]
378 fn test_get() {
396 fn test_get() {
379 let mut tree = Tree::new();
397 let mut tree = Tree::new();
380 let entry = DirstateEntry {
398 let entry = DirstateEntry {
381 state: EntryState::Merged,
399 state: EntryState::Merged,
382 mode: 1,
400 mode: 1,
383 mtime: 2,
401 mtime: 2,
384 size: 3,
402 size: 3,
385 };
403 };
386 assert_eq!(tree.insert_node(HgPath::new(b"a/b/c"), entry), None);
404 assert_eq!(tree.insert_node(HgPath::new(b"a/b/c"), entry), None);
387 assert_eq!(tree.files_count, 1);
405 assert_eq!(tree.files_count, 1);
388 assert_eq!(tree.get(HgPath::new(b"a/b/c")), Some(&entry));
406 assert_eq!(tree.get(HgPath::new(b"a/b/c")), Some(&entry));
389 assert_eq!(tree.get(HgPath::new(b"a/b")), None);
407 assert_eq!(tree.get(HgPath::new(b"a/b")), None);
390 assert_eq!(tree.get(HgPath::new(b"a")), None);
408 assert_eq!(tree.get(HgPath::new(b"a")), None);
391 assert_eq!(tree.get(HgPath::new(b"a/b/c/d")), None);
409 assert_eq!(tree.get(HgPath::new(b"a/b/c/d")), None);
392 let entry2 = DirstateEntry {
410 let entry2 = DirstateEntry {
393 state: EntryState::Removed,
411 state: EntryState::Removed,
394 mode: 0,
412 mode: 0,
395 mtime: 5,
413 mtime: 5,
396 size: 1,
414 size: 1,
397 };
415 };
398 // was_directory
416 // was_directory
399 assert_eq!(tree.insert(HgPath::new(b"a/b"), entry2), None);
417 assert_eq!(tree.insert(HgPath::new(b"a/b"), entry2), None);
400 assert_eq!(tree.files_count, 2);
418 assert_eq!(tree.files_count, 2);
401 assert_eq!(tree.get(HgPath::new(b"a/b")), Some(&entry2));
419 assert_eq!(tree.get(HgPath::new(b"a/b")), Some(&entry2));
402 assert_eq!(tree.get(HgPath::new(b"a/b/c")), Some(&entry));
420 assert_eq!(tree.get(HgPath::new(b"a/b/c")), Some(&entry));
403
421
404 let mut tree = Tree::new();
422 let mut tree = Tree::new();
405
423
406 // was_file
424 // was_file
407 assert_eq!(tree.insert_node(HgPath::new(b"a"), entry), None);
425 assert_eq!(tree.insert_node(HgPath::new(b"a"), entry), None);
408 assert_eq!(tree.files_count, 1);
426 assert_eq!(tree.files_count, 1);
409 assert_eq!(tree.insert_node(HgPath::new(b"a/b"), entry2), None);
427 assert_eq!(tree.insert_node(HgPath::new(b"a/b"), entry2), None);
410 assert_eq!(tree.files_count, 2);
428 assert_eq!(tree.files_count, 2);
411 assert_eq!(tree.get(HgPath::new(b"a/b")), Some(&entry2));
429 assert_eq!(tree.get(HgPath::new(b"a/b")), Some(&entry2));
412 }
430 }
413
431
414 #[test]
432 #[test]
415 fn test_get_mut() {
433 fn test_get_mut() {
416 let mut tree = Tree::new();
434 let mut tree = Tree::new();
417 let mut entry = DirstateEntry {
435 let mut entry = DirstateEntry {
418 state: EntryState::Merged,
436 state: EntryState::Merged,
419 mode: 1,
437 mode: 1,
420 mtime: 2,
438 mtime: 2,
421 size: 3,
439 size: 3,
422 };
440 };
423 assert_eq!(tree.insert_node(HgPath::new(b"a/b/c"), entry), None);
441 assert_eq!(tree.insert_node(HgPath::new(b"a/b/c"), entry), None);
424 assert_eq!(tree.files_count, 1);
442 assert_eq!(tree.files_count, 1);
425 assert_eq!(tree.get_mut(HgPath::new(b"a/b/c")), Some(&mut entry));
443 assert_eq!(tree.get_mut(HgPath::new(b"a/b/c")), Some(&mut entry));
426 assert_eq!(tree.get_mut(HgPath::new(b"a/b")), None);
444 assert_eq!(tree.get_mut(HgPath::new(b"a/b")), None);
427 assert_eq!(tree.get_mut(HgPath::new(b"a")), None);
445 assert_eq!(tree.get_mut(HgPath::new(b"a")), None);
428 assert_eq!(tree.get_mut(HgPath::new(b"a/b/c/d")), None);
446 assert_eq!(tree.get_mut(HgPath::new(b"a/b/c/d")), None);
429 let mut entry2 = DirstateEntry {
447 let mut entry2 = DirstateEntry {
430 state: EntryState::Removed,
448 state: EntryState::Removed,
431 mode: 0,
449 mode: 0,
432 mtime: 5,
450 mtime: 5,
433 size: 1,
451 size: 1,
434 };
452 };
435 // was_directory
453 // was_directory
436 assert_eq!(tree.insert(HgPath::new(b"a/b"), entry2), None);
454 assert_eq!(tree.insert(HgPath::new(b"a/b"), entry2), None);
437 assert_eq!(tree.files_count, 2);
455 assert_eq!(tree.files_count, 2);
438 assert_eq!(tree.get_mut(HgPath::new(b"a/b")), Some(&mut entry2));
456 assert_eq!(tree.get_mut(HgPath::new(b"a/b")), Some(&mut entry2));
439 assert_eq!(tree.get_mut(HgPath::new(b"a/b/c")), Some(&mut entry));
457 assert_eq!(tree.get_mut(HgPath::new(b"a/b/c")), Some(&mut entry));
440
458
441 let mut tree = Tree::new();
459 let mut tree = Tree::new();
442
460
443 // was_file
461 // was_file
444 assert_eq!(tree.insert_node(HgPath::new(b"a"), entry), None);
462 assert_eq!(tree.insert_node(HgPath::new(b"a"), entry), None);
445 assert_eq!(tree.files_count, 1);
463 assert_eq!(tree.files_count, 1);
446 assert_eq!(tree.insert_node(HgPath::new(b"a/b"), entry2), None);
464 assert_eq!(tree.insert_node(HgPath::new(b"a/b"), entry2), None);
447 assert_eq!(tree.files_count, 2);
465 assert_eq!(tree.files_count, 2);
448 assert_eq!(tree.get_mut(HgPath::new(b"a/b")), Some(&mut entry2));
466 assert_eq!(tree.get_mut(HgPath::new(b"a/b")), Some(&mut entry2));
449 }
467 }
450
468
451 #[test]
469 #[test]
452 fn test_remove() {
470 fn test_remove() {
453 let mut tree = Tree::new();
471 let mut tree = Tree::new();
454 assert_eq!(tree.files_count, 0);
472 assert_eq!(tree.files_count, 0);
455 assert_eq!(tree.remove(HgPath::new(b"foo")), None);
473 assert_eq!(tree.remove(HgPath::new(b"foo")), None);
456 assert_eq!(tree.files_count, 0);
474 assert_eq!(tree.files_count, 0);
457
475
458 let entry = DirstateEntry {
476 let entry = DirstateEntry {
459 state: EntryState::Normal,
477 state: EntryState::Normal,
460 mode: 0,
478 mode: 0,
461 mtime: 0,
479 mtime: 0,
462 size: 0,
480 size: 0,
463 };
481 };
464 assert_eq!(tree.insert_node(HgPath::new(b"a/b/c"), entry), None);
482 assert_eq!(tree.insert_node(HgPath::new(b"a/b/c"), entry), None);
465 assert_eq!(tree.files_count, 1);
483 assert_eq!(tree.files_count, 1);
466
484
467 assert_eq!(tree.remove(HgPath::new(b"a/b/c")), Some(entry));
485 assert_eq!(tree.remove(HgPath::new(b"a/b/c")), Some(entry));
468 assert_eq!(tree.files_count, 0);
486 assert_eq!(tree.files_count, 0);
469
487
470 assert_eq!(tree.insert_node(HgPath::new(b"a/b/x"), entry), None);
488 assert_eq!(tree.insert_node(HgPath::new(b"a/b/x"), entry), None);
471 assert_eq!(tree.insert_node(HgPath::new(b"a/b/y"), entry), None);
489 assert_eq!(tree.insert_node(HgPath::new(b"a/b/y"), entry), None);
472 assert_eq!(tree.insert_node(HgPath::new(b"a/b/z"), entry), None);
490 assert_eq!(tree.insert_node(HgPath::new(b"a/b/z"), entry), None);
473 assert_eq!(tree.insert_node(HgPath::new(b"x"), entry), None);
491 assert_eq!(tree.insert_node(HgPath::new(b"x"), entry), None);
474 assert_eq!(tree.insert_node(HgPath::new(b"y"), entry), None);
492 assert_eq!(tree.insert_node(HgPath::new(b"y"), entry), None);
475 assert_eq!(tree.files_count, 5);
493 assert_eq!(tree.files_count, 5);
476
494
477 assert_eq!(tree.remove(HgPath::new(b"a/b/x")), Some(entry));
495 assert_eq!(tree.remove(HgPath::new(b"a/b/x")), Some(entry));
478 assert_eq!(tree.files_count, 4);
496 assert_eq!(tree.files_count, 4);
479 assert_eq!(tree.remove(HgPath::new(b"a/b/x")), None);
497 assert_eq!(tree.remove(HgPath::new(b"a/b/x")), None);
480 assert_eq!(tree.files_count, 4);
498 assert_eq!(tree.files_count, 4);
481 assert_eq!(tree.remove(HgPath::new(b"a/b/y")), Some(entry));
499 assert_eq!(tree.remove(HgPath::new(b"a/b/y")), Some(entry));
482 assert_eq!(tree.files_count, 3);
500 assert_eq!(tree.files_count, 3);
483 assert_eq!(tree.remove(HgPath::new(b"a/b/z")), Some(entry));
501 assert_eq!(tree.remove(HgPath::new(b"a/b/z")), Some(entry));
484 assert_eq!(tree.files_count, 2);
502 assert_eq!(tree.files_count, 2);
485
503
486 assert_eq!(tree.remove(HgPath::new(b"x")), Some(entry));
504 assert_eq!(tree.remove(HgPath::new(b"x")), Some(entry));
487 assert_eq!(tree.files_count, 1);
505 assert_eq!(tree.files_count, 1);
488 assert_eq!(tree.remove(HgPath::new(b"y")), Some(entry));
506 assert_eq!(tree.remove(HgPath::new(b"y")), Some(entry));
489 assert_eq!(tree.files_count, 0);
507 assert_eq!(tree.files_count, 0);
490
508
491 // `a` should have been cleaned up, no more files anywhere in its
509 // `a` should have been cleaned up, no more files anywhere in its
492 // descendents
510 // descendents
493 assert_eq!(tree.get_node(HgPath::new(b"a")), None);
511 assert_eq!(tree.get_node(HgPath::new(b"a")), None);
494 assert_eq!(tree.root.children().unwrap().len(), 0);
512 assert_eq!(tree.root.children().unwrap().len(), 0);
495
513
496 let removed_entry = DirstateEntry {
514 let removed_entry = DirstateEntry {
497 state: EntryState::Removed,
515 state: EntryState::Removed,
498 ..entry
516 ..entry
499 };
517 };
500 assert_eq!(tree.insert(HgPath::new(b"a"), removed_entry), None);
518 assert_eq!(tree.insert(HgPath::new(b"a"), removed_entry), None);
501 assert_eq!(tree.insert_node(HgPath::new(b"a/b/x"), entry), None);
519 assert_eq!(tree.insert_node(HgPath::new(b"a/b/x"), entry), None);
502 assert_eq!(tree.files_count, 2);
520 assert_eq!(tree.files_count, 2);
503 dbg!(&tree);
521 dbg!(&tree);
504 assert_eq!(tree.remove(HgPath::new(b"a")), Some(removed_entry));
522 assert_eq!(tree.remove(HgPath::new(b"a")), Some(removed_entry));
505 assert_eq!(tree.files_count, 1);
523 assert_eq!(tree.files_count, 1);
506 dbg!(&tree);
524 dbg!(&tree);
507 assert_eq!(tree.remove(HgPath::new(b"a/b/x")), Some(entry));
525 assert_eq!(tree.remove(HgPath::new(b"a/b/x")), Some(entry));
508 assert_eq!(tree.files_count, 0);
526 assert_eq!(tree.files_count, 0);
509
527
510 // The entire tree should have been cleaned up, no more files anywhere
528 // The entire tree should have been cleaned up, no more files anywhere
511 // in its descendents
529 // in its descendents
512 assert_eq!(tree.root.children().unwrap().len(), 0);
530 assert_eq!(tree.root.children().unwrap().len(), 0);
513
531
514 let removed_entry = DirstateEntry {
532 let removed_entry = DirstateEntry {
515 state: EntryState::Removed,
533 state: EntryState::Removed,
516 ..entry
534 ..entry
517 };
535 };
518 assert_eq!(tree.insert(HgPath::new(b"a"), entry), None);
536 assert_eq!(tree.insert(HgPath::new(b"a"), entry), None);
519 assert_eq!(tree.insert_node(HgPath::new(b"a/b/x"), removed_entry), None);
537 assert_eq!(
538 tree.insert_node(HgPath::new(b"a/b/x"), removed_entry),
539 None
540 );
520 assert_eq!(tree.files_count, 2);
541 assert_eq!(tree.files_count, 2);
521 dbg!(&tree);
542 dbg!(&tree);
522 assert_eq!(tree.remove(HgPath::new(b"a")), Some(entry));
543 assert_eq!(tree.remove(HgPath::new(b"a")), Some(entry));
523 assert_eq!(tree.files_count, 1);
544 assert_eq!(tree.files_count, 1);
524 dbg!(&tree);
545 dbg!(&tree);
525 assert_eq!(tree.remove(HgPath::new(b"a/b/x")), Some(removed_entry));
546 assert_eq!(tree.remove(HgPath::new(b"a/b/x")), Some(removed_entry));
526 assert_eq!(tree.files_count, 0);
547 assert_eq!(tree.files_count, 0);
527
548
528 dbg!(&tree);
549 dbg!(&tree);
529 // The entire tree should have been cleaned up, no more files anywhere
550 // The entire tree should have been cleaned up, no more files anywhere
530 // in its descendents
551 // in its descendents
531 assert_eq!(tree.root.children().unwrap().len(), 0);
552 assert_eq!(tree.root.children().unwrap().len(), 0);
532
553
533 assert_eq!(tree.insert(HgPath::new(b"d"), entry), None);
554 assert_eq!(tree.insert(HgPath::new(b"d"), entry), None);
534 assert_eq!(tree.insert(HgPath::new(b"d/d/d"), entry), None);
555 assert_eq!(tree.insert(HgPath::new(b"d/d/d"), entry), None);
535 assert_eq!(tree.files_count, 2);
556 assert_eq!(tree.files_count, 2);
536
557
537 // Deleting the nested file should not delete the top directory as it
558 // Deleting the nested file should not delete the top directory as it
538 // used to be a file
559 // used to be a file
539 assert_eq!(tree.remove(HgPath::new(b"d/d/d")), Some(entry));
560 assert_eq!(tree.remove(HgPath::new(b"d/d/d")), Some(entry));
540 assert_eq!(tree.files_count, 1);
561 assert_eq!(tree.files_count, 1);
541 assert!(tree.get_node(HgPath::new(b"d")).is_some());
562 assert!(tree.get_node(HgPath::new(b"d")).is_some());
542 assert!(tree.remove(HgPath::new(b"d")).is_some());
563 assert!(tree.remove(HgPath::new(b"d")).is_some());
543 assert_eq!(tree.files_count, 0);
564 assert_eq!(tree.files_count, 0);
544
565
545 // Deleting the nested file should not delete the top file (other way
566 // Deleting the nested file should not delete the top file (other way
546 // around from the last case)
567 // around from the last case)
547 assert_eq!(tree.insert(HgPath::new(b"a/a"), entry), None);
568 assert_eq!(tree.insert(HgPath::new(b"a/a"), entry), None);
548 assert_eq!(tree.files_count, 1);
569 assert_eq!(tree.files_count, 1);
549 assert_eq!(tree.insert(HgPath::new(b"a"), entry), None);
570 assert_eq!(tree.insert(HgPath::new(b"a"), entry), None);
550 assert_eq!(tree.files_count, 2);
571 assert_eq!(tree.files_count, 2);
551 dbg!(&tree);
572 dbg!(&tree);
552 assert_eq!(tree.remove(HgPath::new(b"a/a")), Some(entry));
573 assert_eq!(tree.remove(HgPath::new(b"a/a")), Some(entry));
553 assert_eq!(tree.files_count, 1);
574 assert_eq!(tree.files_count, 1);
554 dbg!(&tree);
575 dbg!(&tree);
555 assert!(tree.get_node(HgPath::new(b"a")).is_some());
576 assert!(tree.get_node(HgPath::new(b"a")).is_some());
556 assert!(tree.get_node(HgPath::new(b"a/a")).is_none());
577 assert!(tree.get_node(HgPath::new(b"a/a")).is_none());
557 }
578 }
558
579
559 #[test]
580 #[test]
560 fn test_was_directory() {
581 fn test_was_directory() {
561 let mut tree = Tree::new();
582 let mut tree = Tree::new();
562
583
563 let entry = DirstateEntry {
584 let entry = DirstateEntry {
564 state: EntryState::Removed,
585 state: EntryState::Removed,
565 mode: 0,
586 mode: 0,
566 mtime: 0,
587 mtime: 0,
567 size: 0,
588 size: 0,
568 };
589 };
569 assert_eq!(tree.insert_node(HgPath::new(b"a/b/c"), entry), None);
590 assert_eq!(tree.insert_node(HgPath::new(b"a/b/c"), entry), None);
570 assert_eq!(tree.files_count, 1);
591 assert_eq!(tree.files_count, 1);
571
592
572 assert!(tree.insert_node(HgPath::new(b"a"), entry).is_some());
593 assert!(tree.insert_node(HgPath::new(b"a"), entry).is_some());
573 let new_a = tree.root.children().unwrap().get(&b"a".to_vec()).unwrap();
594 let new_a = tree.root.children().unwrap().get(&b"a".to_vec()).unwrap();
574
595
575 match &new_a.kind {
596 match &new_a.kind {
576 NodeKind::Directory(_) => panic!(),
597 NodeKind::Directory(_) => panic!(),
577 NodeKind::File(f) => {
598 NodeKind::File(f) => {
578 let dir = f.was_directory.clone().unwrap();
599 let dir = f.was_directory.clone().unwrap();
579 let c = dir
600 let c = dir
580 .children
601 .children
581 .get(&b"b".to_vec())
602 .get(&b"b".to_vec())
582 .unwrap()
603 .unwrap()
583 .children()
604 .children()
584 .unwrap()
605 .unwrap()
585 .get(&b"c".to_vec())
606 .get(&b"c".to_vec())
586 .unwrap();
607 .unwrap();
587
608
588 assert_eq!(
609 assert_eq!(
589 match &c.kind {
610 match &c.kind {
590 NodeKind::Directory(_) => panic!(),
611 NodeKind::Directory(_) => panic!(),
591 NodeKind::File(f) => f.entry,
612 NodeKind::File(f) => f.entry,
592 },
613 },
593 entry
614 entry
594 );
615 );
595 }
616 }
596 }
617 }
597 assert_eq!(tree.files_count, 2);
618 assert_eq!(tree.files_count, 2);
598 dbg!(&tree);
619 dbg!(&tree);
599 assert_eq!(tree.remove(HgPath::new(b"a/b/c")), Some(entry));
620 assert_eq!(tree.remove(HgPath::new(b"a/b/c")), Some(entry));
600 assert_eq!(tree.files_count, 1);
621 assert_eq!(tree.files_count, 1);
601 dbg!(&tree);
622 dbg!(&tree);
602 let a = tree.get_node(HgPath::new(b"a")).unwrap();
623 let a = tree.get_node(HgPath::new(b"a")).unwrap();
603 match &a.kind {
624 match &a.kind {
604 NodeKind::Directory(_) => panic!(),
625 NodeKind::Directory(_) => panic!(),
605 NodeKind::File(f) => {
626 NodeKind::File(f) => {
606 // Directory in `was_directory` was emptied, should be removed
627 // Directory in `was_directory` was emptied, should be removed
607 assert_eq!(f.was_directory, None);
628 assert_eq!(f.was_directory, None);
608 }
629 }
609 }
630 }
610 }
631 }
611 #[test]
632 #[test]
612 fn test_extend() {
633 fn test_extend() {
613 let insertions = [
634 let insertions = [
614 (
635 (
615 HgPathBuf::from_bytes(b"d"),
636 HgPathBuf::from_bytes(b"d"),
616 DirstateEntry {
637 DirstateEntry {
617 state: EntryState::Added,
638 state: EntryState::Added,
618 mode: 0,
639 mode: 0,
619 mtime: -1,
640 mtime: -1,
620 size: -1,
641 size: -1,
621 },
642 },
622 ),
643 ),
623 (
644 (
624 HgPathBuf::from_bytes(b"b"),
645 HgPathBuf::from_bytes(b"b"),
625 DirstateEntry {
646 DirstateEntry {
626 state: EntryState::Normal,
647 state: EntryState::Normal,
627 mode: 33188,
648 mode: 33188,
628 mtime: 1599647984,
649 mtime: 1599647984,
629 size: 2,
650 size: 2,
630 },
651 },
631 ),
652 ),
632 (
653 (
633 HgPathBuf::from_bytes(b"a/a"),
654 HgPathBuf::from_bytes(b"a/a"),
634 DirstateEntry {
655 DirstateEntry {
635 state: EntryState::Normal,
656 state: EntryState::Normal,
636 mode: 33188,
657 mode: 33188,
637 mtime: 1599647984,
658 mtime: 1599647984,
638 size: 2,
659 size: 2,
639 },
660 },
640 ),
661 ),
641 (
662 (
642 HgPathBuf::from_bytes(b"d/d/d"),
663 HgPathBuf::from_bytes(b"d/d/d"),
643 DirstateEntry {
664 DirstateEntry {
644 state: EntryState::Removed,
665 state: EntryState::Removed,
645 mode: 0,
666 mode: 0,
646 mtime: 0,
667 mtime: 0,
647 size: 0,
668 size: 0,
648 },
669 },
649 ),
670 ),
650 ]
671 ]
651 .to_vec();
672 .to_vec();
652 let mut tree = Tree::new();
673 let mut tree = Tree::new();
653
674
654 tree.extend(insertions.clone().into_iter());
675 tree.extend(insertions.clone().into_iter());
655
676
656 for (path, _) in &insertions {
677 for (path, _) in &insertions {
657 assert!(tree.contains_key(path), true);
678 assert!(tree.contains_key(path), true);
658 }
679 }
659 assert_eq!(tree.files_count, 4);
680 assert_eq!(tree.files_count, 4);
660 }
681 }
661 }
682 }
General Comments 0
You need to be logged in to leave comments. Login now