Debian Codegraph @

rust/hg-core/src/dirstate/on_disk.rs

raw
1 //! The "version 2" disk representation of the dirstate
2 //!
3 //! See `mercurial/helptext/internals/dirstate-v2.txt`
4
5 use std::borrow::Cow;
6 use std::fmt::Display;
7 use std::fmt::Write;
8
9 use bitflags::bitflags;
10 use bytes_cast::unaligned::U16Be;
11 use bytes_cast::unaligned::U32Be;
12 use bytes_cast::BytesCast;
13 use format_bytes::format_bytes;
14 use rand::Rng;
15 use uuid::Uuid;
16
17 use super::dirstate_map::DirstateIdentity;
18 use super::DirstateError;
19 use crate::dirstate::dirstate_map::DirstateMap;
20 use crate::dirstate::dirstate_map::DirstateMapWriteMode;
21 use crate::dirstate::dirstate_map::DirstateVersion;
22 use crate::dirstate::dirstate_map::NodeRef;
23 use crate::dirstate::dirstate_map::{self};
24 use crate::dirstate::entry::DirstateEntry;
25 use crate::dirstate::entry::DirstateV2Data;
26 use crate::dirstate::entry::TruncatedTimestamp;
27 use crate::dirstate::path_with_basename::WithBasename;
28 use crate::errors::HgBacktrace;
29 use crate::errors::HgError;
30 use crate::errors::IoResultExt;
31 use crate::repo::Repo;
32 use crate::requirements::DIRSTATE_TRACKED_HINT_V1;
33 use crate::utils::hg_path::HgPath;
34 use crate::DirstateParents;
35
36 /// Added at the start of `.hg/dirstate` when the "v2" format is used.
37 /// This a redundant sanity check more than an actual "magic number" since
38 /// `.hg/requires` already governs which format should be used.
39 pub const V2_FORMAT_MARKER: &[u8; 12] = b"dirstate-v2\n";
40
41 /// Keep space for 256-bit hashes
42 const STORED_NODE_ID_BYTES: usize = 32;
43
44 /// … even though only 160 bits are used for now, with SHA-1
45 const USED_NODE_ID_BYTES: usize = 20;
46
47 pub(super) const IGNORE_PATTERNS_HASH_LEN: usize = 20;
48 pub(super) type IgnorePatternsHash = [u8; IGNORE_PATTERNS_HASH_LEN];
49
50 /// Must match constants of the same names in `mercurial/dirstateutils/v2.py`
51 const TREE_METADATA_SIZE: usize = 44;
52 const NODE_SIZE: usize = 44;
53
54 /// Make sure that size-affecting changes are made knowingly
55 #[allow(unused)]
56 fn static_assert_size_of() {
57 let _ = std::mem::transmute::<TreeMetadata, [u8; TREE_METADATA_SIZE]>;
58 let _ = std::mem::transmute::<DocketHeader, [u8; TREE_METADATA_SIZE + 81]>;
59 let _ = std::mem::transmute::<Node, [u8; NODE_SIZE]>;
60 }
61
62 // Must match `HEADER` in `mercurial/dirstateutils/docket.py`
63 #[derive(BytesCast)]
64 #[repr(C)]
65 struct DocketHeader {
66 marker: [u8; V2_FORMAT_MARKER.len()],
67 parent_1: [u8; STORED_NODE_ID_BYTES],
68 parent_2: [u8; STORED_NODE_ID_BYTES],
69
70 metadata: TreeMetadata,
71
72 /// Counted in bytes
73 data_size: Size,
74
75 uuid_size: u8,
76 }
77
78 pub struct Docket<'on_disk> {
79 header: &'on_disk DocketHeader,
80 pub uuid: &'on_disk [u8],
81 }
82
83 /// Fields are documented in the *Tree metadata in the docket file*
84 /// section of `mercurial/helptext/internals/dirstate-v2.txt`
85 #[derive(BytesCast)]
86 #[repr(C)]
87 pub struct TreeMetadata {
88 root_nodes: ChildNodes,
89 nodes_with_entry_count: Size,
90 nodes_with_copy_source_count: Size,
91 unreachable_bytes: Size,
92 unused: [u8; 4],
93
94 /// See *Optional hash of ignore patterns* section of
95 /// `mercurial/helptext/internals/dirstate-v2.txt`
96 ignore_patterns_hash: IgnorePatternsHash,
97 }
98
99 /// Fields are documented in the *The data file format*
100 /// section of `mercurial/helptext/internals/dirstate-v2.txt`
101 #[derive(BytesCast, Debug)]
102 #[repr(C)]
103 pub(super) struct Node {
104 full_path: PathSlice,
105
106 /// In bytes from `self.full_path.start`
107 base_name_start: PathSize,
108
109 copy_source: OptPathSlice,
110 children: ChildNodes,
111 pub(super) descendants_with_entry_count: Size,
112 pub(super) tracked_descendants_count: Size,
113 flags: U16Be,
114 size: U32Be,
115 mtime: PackedTruncatedTimestamp,
116 }
117
118 bitflags! {
119 #[repr(C)]
120 struct Flags: u16 {
121 const WDIR_TRACKED = 1 << 0;
122 const P1_TRACKED = 1 << 1;
123 const P2_INFO = 1 << 2;
124 const MODE_EXEC_PERM = 1 << 3;
125 const MODE_IS_SYMLINK = 1 << 4;
126 const HAS_FALLBACK_EXEC = 1 << 5;
127 const FALLBACK_EXEC = 1 << 6;
128 const HAS_FALLBACK_SYMLINK = 1 << 7;
129 const FALLBACK_SYMLINK = 1 << 8;
130 const EXPECTED_STATE_IS_MODIFIED = 1 << 9;
131 const HAS_MODE_AND_SIZE = 1 <<10;
132 const HAS_MTIME = 1 <<11;
133 const MTIME_SECOND_AMBIGUOUS = 1 << 12;
134 const DIRECTORY = 1 <<13;
135 const ALL_UNKNOWN_RECORDED = 1 <<14;
136 const ALL_IGNORED_RECORDED = 1 <<15;
137 }
138 }
139
140 /// Duration since the Unix epoch
141 #[derive(BytesCast, Copy, Clone, Debug)]
142 #[repr(C)]
143 struct PackedTruncatedTimestamp {
144 truncated_seconds: U32Be,
145 nanoseconds: U32Be,
146 }
147
148 /// Counted in bytes from the start of the file
149 ///
150 /// NOTE: not supporting `.hg/dirstate` files larger than 4 GiB.
151 type Offset = U32Be;
152
153 /// Counted in number of items
154 ///
155 /// NOTE: we choose not to support counting more than 4 billion nodes anywhere.
156 type Size = U32Be;
157
158 /// Counted in bytes
159 ///
160 /// NOTE: we choose not to support file names/paths longer than 64 KiB.
161 type PathSize = U16Be;
162
163 /// A contiguous sequence of `len` times `Node`, representing the child nodes
164 /// of either some other node or of the repository root.
165 ///
166 /// Always sorted by ascending `full_path`, to allow binary search.
167 /// Since nodes with the same parent nodes also have the same parent path,
168 /// only the `base_name`s need to be compared during binary search.
169 #[derive(BytesCast, Copy, Clone, Debug)]
170 #[repr(C)]
171 struct ChildNodes {
172 start: Offset,
173 len: Size,
174 }
175
176 /// A `HgPath` of `len` bytes
177 #[derive(BytesCast, Copy, Clone, Debug)]
178 #[repr(C)]
179 struct PathSlice {
180 start: Offset,
181 len: PathSize,
182 }
183
184 /// Either nothing if `start == 0`, or a `HgPath` of `len` bytes
185 type OptPathSlice = PathSlice;
186
187 /// Unexpected file format found in `.hg/dirstate` with the "v2" format.
188 ///
189 /// This should only happen if Mercurial is buggy or a repository is corrupted.
190 #[derive(Debug)]
191 pub struct DirstateV2ParseError {
192 message: String,
193 backtrace: HgBacktrace,
194 }
195
196 impl DirstateV2ParseError {
197 pub fn new<S: Into<String>>(message: S) -> Self {
198 Self { message: message.into(), backtrace: HgBacktrace::capture() }
199 }
200 }
201
202 impl From<DirstateV2ParseError> for HgError {
203 fn from(e: DirstateV2ParseError) -> Self {
204 HgError::CorruptedRepository(
205 format!("dirstate-v2 parse error: {}", e.message),
206 e.backtrace,
207 )
208 }
209 }
210
211 impl Display for DirstateV2ParseError {
212 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213 write!(f, "{}dirstate-v2 parse error: {}", self.backtrace, self.message)
214 }
215 }
216
217 impl From<DirstateV2ParseError> for DirstateError {
218 fn from(error: DirstateV2ParseError) -> Self {
219 HgError::from(error).into()
220 }
221 }
222
223 impl TreeMetadata {
224 pub fn as_bytes(&self) -> &[u8] {
225 BytesCast::as_bytes(self)
226 }
227 }
228
229 impl Docket<'_> {
230 /// Generate the identifier for a new data file
231 ///
232 /// TODO: support the `HGTEST_UUIDFILE` environment variable.
233 /// See `mercurial/revlogutils/docket.py`
234 pub fn new_uid() -> String {
235 const ID_LENGTH: usize = 8;
236 let mut id = String::with_capacity(ID_LENGTH);
237 let mut rng = rand::rng();
238 for _ in 0..ID_LENGTH {
239 // One random hexadecimal digit.
240 // `unwrap` never panics because `impl Write for String`
241 // never returns an error.
242 write!(&mut id, "{:x}", rng.random_range(0..16)).unwrap();
243 }
244 id
245 }
246
247 pub fn serialize(
248 parents: DirstateParents,
249 tree_metadata: TreeMetadata,
250 data_size: u64,
251 uuid: &[u8],
252 ) -> Result<Vec<u8>, std::num::TryFromIntError> {
253 let header = DocketHeader {
254 marker: *V2_FORMAT_MARKER,
255 parent_1: parents.p1.pad_to_256_bits(),
256 parent_2: parents.p2.pad_to_256_bits(),
257 metadata: tree_metadata,
258 data_size: u32::try_from(data_size)?.into(),
259 uuid_size: uuid.len().try_into()?,
260 };
261 let header = header.as_bytes();
262 let mut docket = Vec::with_capacity(header.len() + uuid.len());
263 docket.extend_from_slice(header);
264 docket.extend_from_slice(uuid);
265 Ok(docket)
266 }
267
268 pub fn parents(&self) -> DirstateParents {
269 use crate::Node;
270 let p1 = Node::try_from(&self.header.parent_1[..USED_NODE_ID_BYTES])
271 .unwrap();
272 let p2 = Node::try_from(&self.header.parent_2[..USED_NODE_ID_BYTES])
273 .unwrap();
274 DirstateParents { p1, p2 }
275 }
276
277 pub fn tree_metadata(&self) -> &[u8] {
278 self.header.metadata.as_bytes()
279 }
280
281 pub fn data_size(&self) -> usize {
282 // This `unwrap` could only panic on a 16-bit CPU
283 self.header.data_size.get().try_into().unwrap()
284 }
285
286 pub fn data_filename(&self) -> String {
287 String::from_utf8(format_bytes!(b"dirstate.{}", self.uuid)).unwrap()
288 }
289 }
290
291 pub fn read_docket(on_disk: &[u8]) -> Result<Docket<'_>, DirstateV2ParseError> {
292 let (header, uuid) = DocketHeader::from_bytes(on_disk).map_err(|e| {
293 DirstateV2ParseError::new(format!("when reading docket, {}", e))
294 })?;
295 let uuid_size = header.uuid_size as usize;
296 if header.marker == *V2_FORMAT_MARKER && uuid.len() == uuid_size {
297 Ok(Docket { header, uuid })
298 } else {
299 Err(DirstateV2ParseError::new("invalid format marker or uuid size"))
300 }
301 }
302
303 pub(super) fn read<'on_disk>(
304 on_disk: &'on_disk [u8],
305 metadata: &[u8],
306 uuid: Vec<u8>,
307 identity: Option<DirstateIdentity>,
308 ) -> Result<DirstateMap<'on_disk>, DirstateV2ParseError> {
309 if on_disk.is_empty() {
310 let mut map = DirstateMap::empty(on_disk);
311 map.identity = identity;
312 map.old_uuid = Some(uuid);
313 map.dirstate_version = DirstateVersion::V2;
314 return Ok(map);
315 }
316 let (meta, _) = TreeMetadata::from_bytes(metadata).map_err(|e| {
317 DirstateV2ParseError::new(format!("when parsing tree metadata, {}", e))
318 })?;
319 let dirstate_map = DirstateMap {
320 on_disk,
321 root: dirstate_map::ChildNodes::OnDisk(
322 read_nodes(on_disk, meta.root_nodes).map_err(|mut e| {
323 e.message = format!("{}, when reading root notes", e.message);
324 e
325 })?,
326 ),
327 nodes_with_entry_count: meta.nodes_with_entry_count.get(),
328 nodes_with_copy_source_count: meta.nodes_with_copy_source_count.get(),
329 ignore_patterns_hash: meta.ignore_patterns_hash,
330 unreachable_bytes: meta.unreachable_bytes.get(),
331 old_data_size: on_disk.len(),
332 old_uuid: Some(uuid),
333 identity,
334 dirstate_version: DirstateVersion::V2,
335 write_mode: DirstateMapWriteMode::Auto,
336 use_tracked_hint: false,
337 };
338 Ok(dirstate_map)
339 }
340
341 impl Node {
342 pub(super) fn full_path<'on_disk>(
343 &self,
344 on_disk: &'on_disk [u8],
345 ) -> Result<&'on_disk HgPath, DirstateV2ParseError> {
346 read_hg_path(on_disk, self.full_path)
347 }
348
349 pub(super) fn base_name_start(
350 &self,
351 ) -> Result<usize, DirstateV2ParseError> {
352 let start = self.base_name_start.get();
353 if start < self.full_path.len.get() {
354 let start = usize::from(start);
355 Ok(start)
356 } else {
357 Err(DirstateV2ParseError::new("not enough bytes for base name"))
358 }
359 }
360
361 pub(super) fn base_name<'on_disk>(
362 &self,
363 on_disk: &'on_disk [u8],
364 ) -> Result<&'on_disk HgPath, DirstateV2ParseError> {
365 let full_path = self.full_path(on_disk)?;
366 let base_name_start = self.base_name_start()?;
367 Ok(HgPath::new(&full_path.as_bytes()[base_name_start..]))
368 }
369
370 pub(super) fn path<'on_disk>(
371 &self,
372 on_disk: &'on_disk [u8],
373 ) -> Result<dirstate_map::NodeKey<'on_disk>, DirstateV2ParseError> {
374 Ok(WithBasename::from_raw_parts(
375 Cow::Borrowed(self.full_path(on_disk)?),
376 self.base_name_start()?,
377 ))
378 }
379
380 pub(super) fn has_copy_source(&self) -> bool {
381 self.copy_source.start.get() != 0
382 }
383
384 pub(super) fn copy_source<'on_disk>(
385 &self,
386 on_disk: &'on_disk [u8],
387 ) -> Result<Option<&'on_disk HgPath>, DirstateV2ParseError> {
388 Ok(if self.has_copy_source() {
389 Some(read_hg_path(on_disk, self.copy_source)?)
390 } else {
391 None
392 })
393 }
394
395 fn flags(&self) -> Flags {
396 Flags::from_bits_truncate(self.flags.get())
397 }
398
399 fn has_entry(&self) -> bool {
400 self.flags().intersects(
401 Flags::WDIR_TRACKED | Flags::P1_TRACKED | Flags::P2_INFO,
402 )
403 }
404
405 pub(super) fn node_data(
406 &self,
407 ) -> Result<dirstate_map::NodeData, DirstateV2ParseError> {
408 if self.has_entry() {
409 Ok(dirstate_map::NodeData::Entry(self.assume_entry()?))
410 } else if let Some(mtime) = self.cached_directory_mtime()? {
411 Ok(dirstate_map::NodeData::CachedDirectory { mtime })
412 } else {
413 Ok(dirstate_map::NodeData::None)
414 }
415 }
416
417 pub(super) fn cached_directory_mtime(
418 &self,
419 ) -> Result<Option<TruncatedTimestamp>, DirstateV2ParseError> {
420 // For now we do not have code to handle the absence of
421 // ALL_UNKNOWN_RECORDED, so we ignore the mtime if the flag is
422 // unset.
423 if self.flags().contains(Flags::DIRECTORY)
424 && self.flags().contains(Flags::HAS_MTIME)
425 && self.flags().contains(Flags::ALL_UNKNOWN_RECORDED)
426 {
427 Ok(Some(self.mtime()?))
428 } else {
429 Ok(None)
430 }
431 }
432
433 fn synthesize_unix_mode(&self) -> u32 {
434 // Some platforms' libc don't have the same type (MacOS uses i32 here)
435 #[allow(clippy::unnecessary_cast)]
436 let file_type = if self.flags().contains(Flags::MODE_IS_SYMLINK) {
437 libc::S_IFLNK as u32
438 } else {
439 libc::S_IFREG as u32
440 };
441 let permissions = if self.flags().contains(Flags::MODE_EXEC_PERM) {
442 0o755
443 } else {
444 0o644
445 };
446 file_type | permissions
447 }
448
449 fn mtime(&self) -> Result<TruncatedTimestamp, DirstateV2ParseError> {
450 let mut m: TruncatedTimestamp = self.mtime.try_into()?;
451 if self.flags().contains(Flags::MTIME_SECOND_AMBIGUOUS) {
452 m.second_ambiguous = true;
453 }
454 Ok(m)
455 }
456
457 fn assume_entry(&self) -> Result<DirstateEntry, DirstateV2ParseError> {
458 // TODO: convert through raw bits instead?
459 let wc_tracked = self.flags().contains(Flags::WDIR_TRACKED);
460 let p1_tracked = self.flags().contains(Flags::P1_TRACKED);
461 let p2_info = self.flags().contains(Flags::P2_INFO);
462 let mode_size = if self.flags().contains(Flags::HAS_MODE_AND_SIZE)
463 && !self.flags().contains(Flags::EXPECTED_STATE_IS_MODIFIED)
464 {
465 Some((self.synthesize_unix_mode(), self.size.into()))
466 } else {
467 None
468 };
469 let mtime = if self.flags().contains(Flags::HAS_MTIME)
470 && !self.flags().contains(Flags::DIRECTORY)
471 && !self.flags().contains(Flags::EXPECTED_STATE_IS_MODIFIED)
472 {
473 Some(self.mtime()?)
474 } else {
475 None
476 };
477 let fallback_exec = if self.flags().contains(Flags::HAS_FALLBACK_EXEC) {
478 Some(self.flags().contains(Flags::FALLBACK_EXEC))
479 } else {
480 None
481 };
482 let fallback_symlink =
483 if self.flags().contains(Flags::HAS_FALLBACK_SYMLINK) {
484 Some(self.flags().contains(Flags::FALLBACK_SYMLINK))
485 } else {
486 None
487 };
488 Ok(DirstateEntry::from_v2_data(DirstateV2Data {
489 wc_tracked,
490 p1_tracked,
491 p2_info,
492 mode_size,
493 mtime,
494 fallback_exec,
495 fallback_symlink,
496 }))
497 }
498
499 pub(super) fn entry(
500 &self,
501 ) -> Result<Option<DirstateEntry>, DirstateV2ParseError> {
502 if self.has_entry() {
503 Ok(Some(self.assume_entry()?))
504 } else {
505 Ok(None)
506 }
507 }
508
509 pub(super) fn children<'on_disk>(
510 &self,
511 on_disk: &'on_disk [u8],
512 ) -> Result<&'on_disk [Node], DirstateV2ParseError> {
513 read_nodes(on_disk, self.children)
514 }
515
516 pub(super) fn to_in_memory_node<'on_disk>(
517 &self,
518 on_disk: &'on_disk [u8],
519 ) -> Result<dirstate_map::Node<'on_disk>, DirstateV2ParseError> {
520 Ok(dirstate_map::Node {
521 children: dirstate_map::ChildNodes::OnDisk(self.children(on_disk)?),
522 copy_source: self.copy_source(on_disk)?.map(Cow::Borrowed),
523 data: self.node_data()?,
524 descendants_with_entry_count: self
525 .descendants_with_entry_count
526 .get(),
527 tracked_descendants_count: self.tracked_descendants_count.get(),
528 })
529 }
530
531 fn from_dirstate_entry(
532 entry: &DirstateEntry,
533 ) -> (Flags, U32Be, PackedTruncatedTimestamp) {
534 let DirstateV2Data {
535 wc_tracked,
536 p1_tracked,
537 p2_info,
538 mode_size: mode_size_opt,
539 mtime: mtime_opt,
540 fallback_exec,
541 fallback_symlink,
542 } = entry.v2_data();
543 // TODO: convert through raw flag bits instead?
544 let mut flags = Flags::empty();
545 flags.set(Flags::WDIR_TRACKED, wc_tracked);
546 flags.set(Flags::P1_TRACKED, p1_tracked);
547 flags.set(Flags::P2_INFO, p2_info);
548 // Some platforms' libc don't have the same type (MacOS uses i32 here)
549 #[allow(clippy::unnecessary_cast)]
550 let size = if let Some((m, s)) = mode_size_opt {
551 let exec_perm = m & (libc::S_IXUSR as u32) != 0;
552 let is_symlink = m & (libc::S_IFMT as u32) == libc::S_IFLNK as u32;
553 flags.set(Flags::MODE_EXEC_PERM, exec_perm);
554 flags.set(Flags::MODE_IS_SYMLINK, is_symlink);
555 flags.insert(Flags::HAS_MODE_AND_SIZE);
556 s.into()
557 } else {
558 0.into()
559 };
560 let mtime = if let Some(m) = mtime_opt {
561 flags.insert(Flags::HAS_MTIME);
562 if m.second_ambiguous {
563 flags.insert(Flags::MTIME_SECOND_AMBIGUOUS);
564 };
565 m.into()
566 } else {
567 PackedTruncatedTimestamp::null()
568 };
569 if let Some(f_exec) = fallback_exec {
570 flags.insert(Flags::HAS_FALLBACK_EXEC);
571 if f_exec {
572 flags.insert(Flags::FALLBACK_EXEC);
573 }
574 }
575 if let Some(f_symlink) = fallback_symlink {
576 flags.insert(Flags::HAS_FALLBACK_SYMLINK);
577 if f_symlink {
578 flags.insert(Flags::FALLBACK_SYMLINK);
579 }
580 }
581 (flags, size, mtime)
582 }
583 }
584
585 fn read_hg_path(
586 on_disk: &[u8],
587 slice: PathSlice,
588 ) -> Result<&HgPath, DirstateV2ParseError> {
589 read_slice(on_disk, slice.start, slice.len.get()).map(HgPath::new)
590 }
591
592 fn read_nodes(
593 on_disk: &[u8],
594 slice: ChildNodes,
595 ) -> Result<&[Node], DirstateV2ParseError> {
596 read_slice(on_disk, slice.start, slice.len.get())
597 }
598
599 fn read_slice<T, Len>(
600 on_disk: &[u8],
601 start: Offset,
602 len: Len,
603 ) -> Result<&[T], DirstateV2ParseError>
604 where
605 T: BytesCast,
606 Len: TryInto<usize>,
607 {
608 // Either `usize::MAX` would result in "out of bounds" error since a single
609 // `&[u8]` cannot occupy the entire addess space.
610 let start = start.get().try_into().unwrap_or(usize::MAX);
611 let len = len.try_into().unwrap_or(usize::MAX);
612 let bytes = match on_disk.get(start..) {
613 Some(bytes) => bytes,
614 None => {
615 return Err(DirstateV2ParseError::new("not enough bytes from disk"))
616 }
617 };
618 T::slice_from_bytes(bytes, len)
619 .map_err(|e| {
620 DirstateV2ParseError::new(format!("when reading a slice, {}", e))
621 })
622 .map(|(slice, _rest)| slice)
623 }
624
625 /// Returns new data and metadata, together with whether that data should be
626 /// appended to the existing data file whose content is at
627 /// `dirstate_map.on_disk` (true), instead of written to a new data file
628 /// (false), and the previous size of data on disk.
629 pub(super) fn write(
630 dirstate_map: &DirstateMap,
631 write_mode: DirstateMapWriteMode,
632 ) -> Result<(Vec<u8>, TreeMetadata, bool, usize), DirstateError> {
633 let append = match write_mode {
634 DirstateMapWriteMode::Auto => dirstate_map.write_should_append(),
635 DirstateMapWriteMode::ForceNewDataFile => false,
636 DirstateMapWriteMode::ForceAppend => true,
637 };
638 if append {
639 tracing::debug!("appending to the dirstate data file");
640 } else {
641 tracing::debug!("creating new dirstate data file");
642 }
643
644 // This ignores the space for paths, and for nodes without an entry.
645 // TODO: better estimate? Skip the `Vec` and write to a file directly?
646 let size_guess = std::mem::size_of::<Node>()
647 * dirstate_map.nodes_with_entry_count as usize;
648
649 let mut writer =
650 Writer { dirstate_map, append, out: Vec::with_capacity(size_guess) };
651
652 let root_nodes = dirstate_map.root.as_ref();
653 for node in root_nodes.iter() {
654 // Catch some corruptions before we write to disk
655 let full_path = node.full_path(dirstate_map.on_disk)?;
656 let base_name = node.base_name(dirstate_map.on_disk)?;
657 if full_path != base_name {
658 let explanation = format!(
659 "Dirstate root node '{}' is not at the root",
660 full_path
661 );
662 return Err(HgError::corrupted(explanation).into());
663 }
664 }
665 let root_nodes = writer.write_nodes(root_nodes)?;
666
667 let unreachable_bytes = if append {
668 dirstate_map.unreachable_bytes
669 } else {
670 0
671 };
672 let meta = TreeMetadata {
673 root_nodes,
674 nodes_with_entry_count: dirstate_map.nodes_with_entry_count.into(),
675 nodes_with_copy_source_count: dirstate_map
676 .nodes_with_copy_source_count
677 .into(),
678 unreachable_bytes: unreachable_bytes.into(),
679 unused: [0; 4],
680 ignore_patterns_hash: dirstate_map.ignore_patterns_hash,
681 };
682 Ok((writer.out, meta, append, dirstate_map.old_data_size))
683 }
684
685 struct Writer<'dmap, 'on_disk> {
686 dirstate_map: &'dmap DirstateMap<'on_disk>,
687 append: bool,
688 out: Vec<u8>,
689 }
690
691 impl Writer<'_, '_> {
692 fn write_nodes(
693 &mut self,
694 nodes: dirstate_map::ChildNodesRef,
695 ) -> Result<ChildNodes, DirstateError> {
696 // Reuse already-written nodes if possible
697 if self.append {
698 if let dirstate_map::ChildNodesRef::OnDisk(nodes_slice) = nodes {
699 let start = self.on_disk_offset_of(nodes_slice).expect(
700 "dirstate-v2 OnDisk nodes not found within on_disk",
701 );
702 let len = child_nodes_len_from_usize(nodes_slice.len());
703 return Ok(ChildNodes { start, len });
704 }
705 }
706
707 // `dirstate_map::ChildNodes::InMemory` contains a `HashMap` which has
708 // undefined iteration order. Sort to enable binary search in the
709 // written file.
710 let nodes = nodes.sorted();
711 let nodes_len = nodes.len();
712
713 // First accumulate serialized nodes in a `Vec`
714 let mut on_disk_nodes = Vec::with_capacity(nodes_len);
715 for node in nodes {
716 let children = node.children(self.dirstate_map.on_disk)?;
717 let full_path = node.full_path(self.dirstate_map.on_disk)?;
718 self.check_children(&children, full_path)?;
719
720 let children = self.write_nodes(children)?;
721 let full_path = self.write_path(full_path.as_bytes());
722 let copy_source = if let Some(source) =
723 node.copy_source(self.dirstate_map.on_disk)?
724 {
725 self.write_path(source.as_bytes())
726 } else {
727 PathSlice { start: 0.into(), len: 0.into() }
728 };
729 on_disk_nodes.push(match node {
730 NodeRef::InMemory(path, node) => {
731 let (flags, size, mtime) = match &node.data {
732 dirstate_map::NodeData::Entry(entry) => {
733 Node::from_dirstate_entry(entry)
734 }
735 dirstate_map::NodeData::CachedDirectory { mtime } => {
736 // we currently never set a mtime if unknown file
737 // are present.
738 // So if we have a mtime for a directory, we know
739 // they are no unknown
740 // files and we
741 // blindly set ALL_UNKNOWN_RECORDED.
742 //
743 // We never set ALL_IGNORED_RECORDED since we
744 // don't track that case
745 // currently.
746 let mut flags = Flags::DIRECTORY
747 | Flags::HAS_MTIME
748 | Flags::ALL_UNKNOWN_RECORDED;
749 if mtime.second_ambiguous {
750 flags.insert(Flags::MTIME_SECOND_AMBIGUOUS)
751 }
752 (flags, 0.into(), (*mtime).into())
753 }
754 dirstate_map::NodeData::None => (
755 Flags::DIRECTORY,
756 0.into(),
757 PackedTruncatedTimestamp::null(),
758 ),
759 };
760 Node {
761 children,
762 copy_source,
763 full_path,
764 base_name_start: u16::try_from(path.base_name_start())
765 // Could only panic for paths over 64 KiB
766 .expect("dirstate-v2 path length overflow")
767 .into(),
768 descendants_with_entry_count: node
769 .descendants_with_entry_count
770 .into(),
771 tracked_descendants_count: node
772 .tracked_descendants_count
773 .into(),
774 flags: flags.bits().into(),
775 size,
776 mtime,
777 }
778 }
779 NodeRef::OnDisk(node) => {
780 Node { children, copy_source, full_path, ..*node }
781 }
782 })
783 }
784 // … so we can write them contiguously, after writing everything else
785 // they refer to.
786 let start = self.current_offset();
787 let len = child_nodes_len_from_usize(nodes_len);
788 self.out.extend(on_disk_nodes.as_bytes());
789 Ok(ChildNodes { start, len })
790 }
791
792 /// Catch some dirstate corruptions before writing them to disk
793 fn check_children(
794 &mut self,
795 children: &dirstate_map::ChildNodesRef,
796 full_path: &HgPath,
797 ) -> Result<(), DirstateError> {
798 for child in children.iter() {
799 let child_full_path = child.full_path(self.dirstate_map.on_disk)?;
800
801 let prefix_length = child_full_path.len()
802 // remove the filename
803 - child.base_name(self.dirstate_map.on_disk)?.len();
804
805 let child_prefix = &child_full_path.as_bytes()[..prefix_length];
806 if child_prefix.last() != Some(&b'/')
807 || &child_prefix[0..child_prefix.len() - 1]
808 != full_path.as_bytes()
809 {
810 let explanation = format!(
811 "dirstate child node's path '{}' \
812 does not start with its parent's path '{}'",
813 child_full_path, full_path,
814 );
815
816 return Err(HgError::corrupted(explanation).into());
817 }
818 }
819 Ok(())
820 }
821
822 /// If the given slice of items is within `on_disk`, returns its offset
823 /// from the start of `on_disk`.
824 fn on_disk_offset_of<T>(&self, slice: &[T]) -> Option<Offset>
825 where
826 T: BytesCast,
827 {
828 fn address_range(slice: &[u8]) -> std::ops::RangeInclusive<usize> {
829 let start = slice.as_ptr() as usize;
830 let end = start + slice.len();
831 start..=end
832 }
833 let slice_addresses = address_range(slice.as_bytes());
834 let on_disk_addresses = address_range(self.dirstate_map.on_disk);
835 if on_disk_addresses.contains(slice_addresses.start())
836 && on_disk_addresses.contains(slice_addresses.end())
837 {
838 let offset = slice_addresses.start() - on_disk_addresses.start();
839 Some(offset_from_usize(offset))
840 } else {
841 None
842 }
843 }
844
845 fn current_offset(&mut self) -> Offset {
846 let mut offset = self.out.len();
847 if self.append {
848 offset += self.dirstate_map.on_disk.len()
849 }
850 offset_from_usize(offset)
851 }
852
853 fn write_path(&mut self, slice: &[u8]) -> PathSlice {
854 let len = path_len_from_usize(slice.len());
855 // Reuse an already-written path if possible
856 if self.append {
857 if let Some(start) = self.on_disk_offset_of(slice) {
858 return PathSlice { start, len };
859 }
860 }
861 let start = self.current_offset();
862 self.out.extend(slice.as_bytes());
863 PathSlice { start, len }
864 }
865 }
866
867 fn offset_from_usize(x: usize) -> Offset {
868 u32::try_from(x)
869 // Could only panic for a dirstate file larger than 4 GiB
870 .expect("dirstate-v2 offset overflow")
871 .into()
872 }
873
874 fn child_nodes_len_from_usize(x: usize) -> Size {
875 u32::try_from(x)
876 // Could only panic with over 4 billion nodes
877 .expect("dirstate-v2 slice length overflow")
878 .into()
879 }
880
881 fn path_len_from_usize(x: usize) -> PathSize {
882 u16::try_from(x)
883 // Could only panic for paths over 64 KiB
884 .expect("dirstate-v2 path length overflow")
885 .into()
886 }
887
888 impl From<TruncatedTimestamp> for PackedTruncatedTimestamp {
889 fn from(timestamp: TruncatedTimestamp) -> Self {
890 Self {
891 truncated_seconds: timestamp.truncated_seconds().into(),
892 nanoseconds: timestamp.nanoseconds().into(),
893 }
894 }
895 }
896
897 impl TryFrom<PackedTruncatedTimestamp> for TruncatedTimestamp {
898 type Error = DirstateV2ParseError;
899
900 fn try_from(
901 timestamp: PackedTruncatedTimestamp,
902 ) -> Result<Self, Self::Error> {
903 Self::from_already_truncated(
904 timestamp.truncated_seconds.get(),
905 timestamp.nanoseconds.get(),
906 false,
907 )
908 }
909 }
910 impl PackedTruncatedTimestamp {
911 fn null() -> Self {
912 Self { truncated_seconds: 0.into(), nanoseconds: 0.into() }
913 }
914 }
915
916 /// Write a new tracked key to disk.
917 /// See `format.use-dirstate-tracked-hint` config help for more details.
918 pub fn write_tracked_key(repo: &Repo) -> Result<(), HgError> {
919 // TODO move this to the dirstate itself once it grows a `dirty` flag and
920 // can reason about which context it needs to write this in.
921 // For now, only this fast-path needs to think about the tracked hint.
922 // Use [`crate::dirstate::dirstate_map::DirstateMap::
923 // use_tracked_hint`] instead of looking at the requirements once
924 // refactored.
925 if !repo.requirements().contains(DIRSTATE_TRACKED_HINT_V1) {
926 return Ok(());
927 }
928 // TODO use `hg_vfs` once the `InnerRevlog` is in.
929 let path = repo.working_directory_path().join(".hg/dirstate-tracked-hint");
930 std::fs::write(&path, Uuid::new_v4().as_bytes()).when_writing_file(&path)
931 }