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