Debian Codegraph @

rust/hg-core/src/revlog/mod.rs

raw
1 // Copyright 2018-2023 Georges Racinet <[email protected]>
2 // and Mercurial contributors
3 //
4 // This software may be used and distributed according to the terms of the
5 // GNU General Public License version 2 or any later version.
6 //! Mercurial concepts for handling revision history
7
8 pub mod deltas;
9 pub mod diff;
10 pub mod node;
11 pub mod nodemap;
12 mod nodemap_docket;
13 pub mod path_encode;
14 use inner_revlog::CoreRevisionBuffer;
15 use inner_revlog::InnerRevlog;
16 use inner_revlog::RevisionBuffer;
17 use memmap2::MmapOptions;
18 pub use node::FromHexError;
19 pub use node::Node;
20 pub use node::NodePrefix;
21 pub use node::NULL_NODE;
22 pub use node::NULL_NODE_ID;
23 use nodemap::read_persistent_nodemap;
24 use options::RevlogOpenOptions;
25 pub mod changelog;
26 pub mod compression;
27 pub mod file_io;
28 pub mod filelog;
29 pub mod index;
30 pub mod inner_revlog;
31 pub mod manifest;
32 pub mod options;
33 pub mod patch;
34
35 use std::io::ErrorKind;
36 use std::io::Read;
37 use std::path::Path;
38
39 use self::nodemap_docket::NodeMapDocket;
40 use crate::dyn_bytes::DynBytes;
41 use crate::errors::HgBacktrace;
42 use crate::errors::HgError;
43 use crate::errors::IoResultExt;
44 use crate::exit_codes;
45 use crate::revlog::index::Index;
46 use crate::revlog::nodemap::NodeMapError;
47 use crate::utils::u32_u;
48 use crate::utils::RawData;
49 use crate::vfs::Vfs;
50 use crate::vfs::VfsImpl;
51
52 /// As noted in revlog.c, revision numbers are actually encoded in
53 /// 4 bytes, and are liberally converted to ints, whence the i32
54 pub type BaseRevision = i32;
55
56 /// Mercurial revision numbers
57 /// In contrast to the more general [`UncheckedRevision`], these are "checked"
58 /// in the sense that they should only be used for revisions that are
59 /// valid for a given index (i.e. in bounds).
60 #[derive(
61 Debug,
62 derive_more::Display,
63 Clone,
64 Copy,
65 Hash,
66 PartialEq,
67 Eq,
68 PartialOrd,
69 Ord,
70 )]
71 pub struct Revision(pub BaseRevision);
72
73 impl format_bytes::DisplayBytes for Revision {
74 fn display_bytes(
75 &self,
76 output: &mut dyn std::io::Write,
77 ) -> std::io::Result<()> {
78 self.0.display_bytes(output)
79 }
80 }
81
82 /// Unchecked Mercurial revision numbers.
83 ///
84 /// Values of this type have no guarantee of being a valid revision number
85 /// in any context. Use method `check_revision` to get a valid revision within
86 /// the appropriate index object.
87 #[derive(
88 Debug,
89 derive_more::Display,
90 Clone,
91 Copy,
92 Hash,
93 PartialEq,
94 Eq,
95 PartialOrd,
96 Ord,
97 )]
98 pub struct UncheckedRevision(pub BaseRevision);
99
100 impl UncheckedRevision {
101 pub fn is_nullrev(&self) -> bool {
102 self.0 == -1
103 }
104 }
105
106 impl format_bytes::DisplayBytes for UncheckedRevision {
107 fn display_bytes(
108 &self,
109 output: &mut dyn std::io::Write,
110 ) -> std::io::Result<()> {
111 self.0.display_bytes(output)
112 }
113 }
114
115 impl From<Revision> for UncheckedRevision {
116 fn from(value: Revision) -> Self {
117 Self(value.0)
118 }
119 }
120
121 impl From<BaseRevision> for UncheckedRevision {
122 fn from(value: BaseRevision) -> Self {
123 Self(value)
124 }
125 }
126
127 /// Marker expressing the absence of a parent
128 ///
129 /// Independently of the actual representation, `NULL_REVISION` is guaranteed
130 /// to be smaller than all existing revisions.
131 pub const NULL_REVISION: Revision = Revision(-1);
132
133 /// Same as `mercurial.node.wdirrev`
134 ///
135 /// This is also equal to `i32::max_value()`, but it's better to spell
136 /// it out explicitely, same as in `mercurial.node`
137 #[allow(clippy::unreadable_literal)]
138 pub const WORKING_DIRECTORY_REVISION: UncheckedRevision =
139 UncheckedRevision(0x7fffffff);
140
141 pub const WORKING_DIRECTORY_HEX: &str =
142 "ffffffffffffffffffffffffffffffffffffffff";
143
144 /// Either a checked revision or the working directory.
145 /// Note that [`Revision`] will never hold [`WORKING_DIRECTORY_REVISION`]
146 /// because that is not a valid revision in any revlog.
147 #[derive(Copy, Clone, Hash, Debug, Eq, PartialEq, Ord, PartialOrd)]
148 pub struct RevisionOrWdir(BaseRevision);
149
150 impl From<Revision> for RevisionOrWdir {
151 fn from(value: Revision) -> Self {
152 RevisionOrWdir(value.0)
153 }
154 }
155
156 impl RevisionOrWdir {
157 /// Creates a [`RevisionOrWdir`] representing the working directory.
158 pub fn wdir() -> Self {
159 RevisionOrWdir(WORKING_DIRECTORY_REVISION.0)
160 }
161
162 /// Returns the revision, or `None` if this is the working directory.
163 pub fn exclude_wdir(self) -> Option<Revision> {
164 if self.0 == WORKING_DIRECTORY_REVISION.0 {
165 None
166 } else {
167 Some(Revision(self.0))
168 }
169 }
170
171 /// Returns true if this is the working directory.
172 pub fn is_wdir(&self) -> bool {
173 *self == Self::wdir()
174 }
175 }
176
177 /// The simplest expression of what we need of Mercurial DAGs.
178 pub trait Graph {
179 /// Return the two parents of the given `Revision`.
180 ///
181 /// Each of the parents can be independently `NULL_REVISION`
182 fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError>;
183 }
184
185 #[derive(Clone, Debug, PartialEq)]
186 pub enum GraphError {
187 /// Parent revision does not exist, i.e. below 0 or above max revision.
188 ParentOutOfRange(Revision),
189 /// Parent revision number is greater than one of its descendants.
190 ParentOutOfOrder(Revision),
191 }
192
193 impl std::fmt::Display for GraphError {
194 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195 match self {
196 GraphError::ParentOutOfRange(revision) => {
197 write!(f, "parent out of range ({})", revision)
198 }
199 GraphError::ParentOutOfOrder(revision) => {
200 write!(f, "parent out of order ({})", revision)
201 }
202 }
203 }
204 }
205
206 impl<T: Graph> Graph for &T {
207 fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError> {
208 (*self).parents(rev)
209 }
210 }
211
212 /// The Mercurial Revlog Index
213 ///
214 /// This is currently limited to the minimal interface that is needed for
215 /// the [`nodemap`](nodemap/index.html) module
216 pub trait RevlogIndex {
217 /// Total number of Revisions referenced in this index
218 fn len(&self) -> usize;
219
220 fn is_empty(&self) -> bool {
221 self.len() == 0
222 }
223
224 /// Return a reference to the Node
225 fn node(&self, rev: Revision) -> &Node;
226
227 /// Return a [`Revision`] if `rev` is a valid revision number for this
228 /// index.
229 ///
230 /// [`NULL_REVISION`] is considered to be valid.
231 #[inline(always)]
232 fn check_revision(&self, rev: UncheckedRevision) -> Option<Revision> {
233 let rev = rev.0;
234
235 if rev == NULL_REVISION.0 || (rev >= 0 && (rev as usize) < self.len()) {
236 Some(Revision(rev))
237 } else {
238 None
239 }
240 }
241 }
242
243 /// Internal trait used by [`InnerRevlog`], **should not be called directly**.
244 pub trait RevlogIndexNodeLookup: RevlogIndex {
245 /// This is used internally by the [`InnerRevlog`] nodemap and **should not
246 /// be called directly**.
247 ///
248 /// Finds a [`Revision`] from a given [`NodePrefix`] directly in the index.
249 ///
250 /// - `visit` is a function that is called on each revision we visit during
251 /// the lookup with the ([`Node`], [`Revision`]) pair.
252 /// - `from_rev_down` is the (potential) revision from which to start
253 /// iterating backwards into the index, used for optimizing multiple calls
254 /// that have already checked the top-most revisions. Using this parameter
255 /// in a context where the top-most revisions have not been checked yet
256 /// can yield false negatives.
257 /// - `prefix_match` is the (potential) revision that may have been found in
258 /// the existing (incomplete) nodemap, to return if there is no ambiguous
259 /// node that also matches `prefix`. Not giving this revision if it exists
260 /// and is higher than `from_rev_down` (if provided) will result in a
261 /// false negative or a wrong match in the case of an ambiguity.
262 fn rev_from_prefix(
263 &self,
264 prefix: NodePrefix,
265 mut visit: impl FnMut(Node, Revision),
266 from_rev_down: Option<Revision>,
267 prefix_match: Option<Revision>,
268 ) -> Result<Option<(Node, Revision)>, NodeMapError> {
269 let mut found_by_prefix =
270 prefix_match.map(|rev| (*self.node(rev), rev));
271 let from_rev_down = from_rev_down
272 .map(|r| r.0)
273 .unwrap_or_else(|| self.len() as BaseRevision);
274 // Linear scan of the revlog
275 for rev in (-1..from_rev_down).rev() {
276 let rev = Revision(rev as BaseRevision);
277 let candidate_node = if rev == Revision(-1) {
278 NULL_NODE
279 } else {
280 *self.node(rev)
281 };
282 visit(candidate_node, rev);
283 if prefix.is_prefix_of(&candidate_node) {
284 if let Some((found_prefix, found_rev)) = found_by_prefix {
285 if candidate_node != found_prefix || rev != found_rev {
286 return Err(NodeMapError::MultipleResults);
287 }
288 }
289 if prefix.nybbles_len() == candidate_node.nybbles_len() {
290 // Exact match, no need to keep looking
291 return Ok(Some((candidate_node, rev)));
292 }
293 // Only a prefix match, we need to keep traversing to make sure
294 // there is no ambiguity.
295 found_by_prefix = Some((candidate_node, rev))
296 }
297 }
298 Ok(found_by_prefix)
299 }
300 }
301
302 impl<T> RevlogIndexNodeLookup for T where T: RevlogIndex {}
303
304 const REVISION_FLAG_CENSORED: u16 = 1 << 15;
305 const REVISION_FLAG_ELLIPSIS: u16 = 1 << 14;
306 const REVISION_FLAG_EXTSTORED: u16 = 1 << 13;
307 const REVISION_FLAG_HASCOPIESINFO: u16 = 1 << 12;
308 const REVISION_FLAG_HASMETA: u16 = 1 << 11;
309 const REVISION_FLAG_DELTA_IS_SNAPSHOT: u16 = 1 << 10;
310 const REVISION_FLAG_DELTA_HAS_QUALITY: u16 = 1 << 9;
311 const REVISION_FLAG_DELTA_IS_GOOD: u16 = 1 << 8;
312 const REVISION_FLAG_DELTA_P1_IS_SMALL: u16 = 1 << 7;
313 const REVISION_FLAG_DELTA_P2_IS_SMALL: u16 = 1 << 6;
314
315 // Keep this in sync with REVIDX_KNOWN_FLAGS in
316 // mercurial/revlogutils/flagutil.py
317 const REVIDX_KNOWN_FLAGS: u16 = REVISION_FLAG_CENSORED
318 | REVISION_FLAG_ELLIPSIS
319 | REVISION_FLAG_EXTSTORED
320 | REVISION_FLAG_HASCOPIESINFO
321 | REVISION_FLAG_HASMETA
322 | REVISION_FLAG_DELTA_IS_SNAPSHOT
323 | REVISION_FLAG_DELTA_HAS_QUALITY
324 | REVISION_FLAG_DELTA_IS_GOOD
325 | REVISION_FLAG_DELTA_P1_IS_SMALL
326 | REVISION_FLAG_DELTA_P2_IS_SMALL;
327
328 const NULL_REVLOG_ENTRY_FLAGS: u16 = 0;
329
330 #[derive(Debug, derive_more::From, derive_more::Display)]
331 pub enum RevlogError {
332 #[display("invalid revision identifier: {}", "_0")]
333 InvalidRevision(String),
334 /// Working directory is not supported
335 WDirUnsupported,
336 /// Found more than one entry whose ID match the requested prefix
337 AmbiguousPrefix(String),
338 #[from]
339 Other(HgError),
340 }
341
342 impl From<(NodeMapError, String)> for RevlogError {
343 fn from((error, rev): (NodeMapError, String)) -> Self {
344 match error {
345 NodeMapError::MultipleResults => RevlogError::AmbiguousPrefix(rev),
346 NodeMapError::RevisionNotInIndex(rev) => RevlogError::corrupted(
347 format!("nodemap point to revision {} not in index", rev),
348 ),
349 }
350 }
351 }
352
353 fn corrupted<S: AsRef<str>>(context: S) -> HgError {
354 HgError::corrupted(format!("corrupted revlog, {}", context.as_ref()))
355 }
356
357 impl RevlogError {
358 fn corrupted<S: AsRef<str>>(context: S) -> Self {
359 RevlogError::Other(corrupted(context))
360 }
361 }
362
363 #[derive(derive_more::Display, Debug, Copy, Clone, PartialEq, Eq)]
364 pub enum RevlogType {
365 Changelog,
366 Manifestlog,
367 Filelog,
368 /// unknown destination, used by debug command looking at arbitrary file
369 Other,
370 }
371
372 impl TryFrom<usize> for RevlogType {
373 type Error = HgError;
374
375 fn try_from(value: usize) -> Result<Self, Self::Error> {
376 match value {
377 1001 => Ok(Self::Changelog),
378 1002 => Ok(Self::Manifestlog),
379 1003 => Ok(Self::Filelog),
380 1004 => Ok(Self::Other),
381 t => Err(HgError::abort(
382 format!("Unknown revlog type {}", t),
383 exit_codes::ABORT,
384 None,
385 )),
386 }
387 }
388 }
389
390 pub struct Revlog {
391 inner: InnerRevlog,
392 }
393
394 impl Graph for Revlog {
395 fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError> {
396 self.index().parents(rev)
397 }
398 }
399 impl Revlog {
400 /// Open a revlog index file.
401 ///
402 /// It will also open the associated data file if index and data are not
403 /// interleaved.
404 pub fn open(
405 // Todo use the `Vfs` trait here once we create a function for mmap
406 store_vfs: &VfsImpl,
407 index_path: impl AsRef<Path>,
408 data_path: Option<&Path>,
409 options: RevlogOpenOptions,
410 revlog_type: RevlogType,
411 ) -> Result<Self, HgError> {
412 Self::open_gen(
413 store_vfs,
414 index_path,
415 data_path,
416 options,
417 None,
418 revlog_type,
419 )
420 }
421
422 fn index(&self) -> &Index {
423 &self.inner.index
424 }
425
426 fn open_gen(
427 // Todo use the `Vfs` trait here once we create a function for mmap
428 store_vfs: &VfsImpl,
429 index_path: impl AsRef<Path>,
430 data_path: Option<&Path>,
431 options: RevlogOpenOptions,
432 nodemap_for_test: Option<nodemap::NodeTree>,
433 revlog_type: RevlogType,
434 ) -> Result<Self, HgError> {
435 let index_path = index_path.as_ref();
436 let index = open_index(store_vfs, index_path, options)?;
437
438 let default_data_path = index_path.with_extension("d");
439 let data_path = data_path.unwrap_or(&default_data_path);
440
441 let nodemap = if index.is_inline() || !options.use_nodemap {
442 None
443 } else {
444 read_persistent_nodemap(store_vfs, index_path, &index)?
445 };
446
447 let nodemap = nodemap_for_test.or(nodemap);
448
449 Ok(Revlog {
450 inner: InnerRevlog::new(
451 Box::new(store_vfs.clone()),
452 index,
453 index_path.to_path_buf(),
454 data_path.to_path_buf(),
455 options.data_config,
456 options.delta_config,
457 options.feature_config,
458 revlog_type,
459 nodemap,
460 ),
461 })
462 }
463
464 /// Return number of entries of the `Revlog`.
465 pub fn len(&self) -> usize {
466 self.index().len()
467 }
468
469 /// Returns `true` if the `Revlog` has zero `entries`.
470 pub fn is_empty(&self) -> bool {
471 self.index().is_empty()
472 }
473
474 /// Returns the node ID for the given revision number, if it exists in this
475 /// revlog
476 pub fn node_from_rev(&self, rev: Revision) -> &Node {
477 self.index().get_entry(rev).hash()
478 }
479
480 /// Like [`Self::node_from_rev`] but checks `rev` first.
481 pub fn node_from_unchecked_rev(
482 &self,
483 rev: UncheckedRevision,
484 ) -> Option<&Node> {
485 Some(self.node_from_rev(self.index().check_revision(rev)?))
486 }
487
488 /// Return the revision number for the given node ID, if it exists in this
489 /// revlog
490 pub fn rev_from_node(
491 &self,
492 node: NodePrefix,
493 ) -> Result<Revision, RevlogError> {
494 self.inner
495 .rev_from_node_prefix(node)?
496 .ok_or_else(|| RevlogError::InvalidRevision(format!("{:x}", node)))
497 }
498
499 /// Returns whether the given revision exists in this revlog.
500 pub fn has_rev(&self, rev: UncheckedRevision) -> bool {
501 self.index().check_revision(rev).is_some()
502 }
503
504 pub fn get_entry(&self, rev: Revision) -> Result<RevlogEntry, RevlogError> {
505 self.inner.get_entry(rev)
506 }
507
508 pub fn get_entry_for_unchecked_rev(
509 &self,
510 rev: UncheckedRevision,
511 ) -> Result<RevlogEntry, RevlogError> {
512 self.inner.get_entry_for_unchecked_rev(rev)
513 }
514
515 /// Returns the delta parent of the given revision.
516 pub fn delta_parent(&self, rev: Revision) -> Revision {
517 if rev == NULL_REVISION {
518 NULL_REVISION
519 } else {
520 self.inner.delta_parent(rev)
521 }
522 }
523
524 /// Returns the link revision (a.k.a. "linkrev") of the given revision.
525 /// Returns an error if the linkrev does not exist in `linked_revlog`.
526 pub fn link_revision(
527 &self,
528 rev: Revision,
529 linked_revlog: &Self,
530 ) -> Result<Revision, RevlogError> {
531 let entry = self.index().get_entry(rev);
532 linked_revlog.index().check_revision(entry.link_revision()).ok_or_else(
533 || {
534 RevlogError::corrupted(format!(
535 "linkrev for rev {} is invalid",
536 rev
537 ))
538 },
539 )
540 }
541
542 /// Return the full data associated to a revision.
543 ///
544 /// All entries required to build the final data out of deltas will be
545 /// retrieved as needed, and the deltas will be applied to the initial
546 /// snapshot to rebuild the final data.
547 pub fn get_data_for_unchecked_rev(
548 &self,
549 rev: UncheckedRevision,
550 ) -> Result<RawData, RevlogError> {
551 if rev == NULL_REVISION.into() {
552 return Ok(RawData::empty());
553 };
554 self.get_entry_for_unchecked_rev(rev)?.data()
555 }
556
557 /// [`Self::get_data_for_unchecked_rev`] for a checked [`Revision`].
558 pub fn get_data(&self, rev: Revision) -> Result<RawData, RevlogError> {
559 if rev == NULL_REVISION {
560 return Ok(RawData::empty());
561 };
562 self.get_entry(rev)?.data()
563 }
564
565 /// Gets the raw uncompressed data stored for a revision, which is either
566 /// the full text or a delta. Panics if `rev` is null.
567 pub fn get_data_incr(
568 &self,
569 rev: Revision,
570 ) -> Result<RawdataBuf, RevlogError> {
571 let index = self.index();
572 let entry = index.get_entry(rev);
573 let delta_base = entry.base_revision_or_base_of_delta_chain();
574 let base = if UncheckedRevision::from(rev) == delta_base {
575 None
576 } else if index.uses_generaldelta() {
577 Some(delta_base)
578 } else {
579 Some(UncheckedRevision(rev.0 - 1))
580 };
581 let data = self.inner.chunk_for_rev(rev)?;
582 Ok(RawdataBuf { base, data })
583 }
584
585 /// Check the hash of some given data against the recorded hash.
586 pub fn check_hash(
587 &self,
588 p1: Revision,
589 p2: Revision,
590 expected: &[u8],
591 data: &[u8],
592 ) -> bool {
593 self.inner.check_hash(p1, p2, expected, data)
594 }
595 }
596
597 pub struct RawdataBuf {
598 // If `Some`, data is a delta.
599 base: Option<UncheckedRevision>,
600 data: RawData,
601 }
602
603 impl<'a> RawdataBuf {
604 fn as_delta(
605 &'a self,
606 ) -> Result<patch::Delta<'a, patch::PlainDeltaPiece<'a>>, RevlogError> {
607 match self.base {
608 None => Ok(patch::Delta::full_snapshot(&self.data)),
609 Some(_) => patch::Delta::new(&self.data),
610 }
611 }
612 }
613
614 /// TODO We should check for version 5.14+ at runtime, but we either should
615 /// add the `nix` dependency to get it efficiently, or vendor the code to read
616 /// both of which are overkill for such a feature. If we need this dependency
617 /// for more things later, we'll use it here too.
618 #[cfg(target_os = "linux")]
619 fn can_advise_populate_read() -> bool {
620 true
621 }
622
623 #[cfg(not(target_os = "linux"))]
624 fn can_advise_populate_read() -> bool {
625 false
626 }
627
628 /// Call `madvise` on the mmap with `MADV_POPULATE_READ` in a separate thread
629 /// to populate the mmap in the background for a small perf improvement.
630 #[cfg(target_os = "linux")]
631 fn advise_populate_read_mmap(mmap: &memmap2::Mmap) {
632 const MADV_POPULATE_READ: i32 = 22;
633
634 // This is fine because the mmap is still referenced for at least
635 // the duration of this function, and the kernel will reject any wrong
636 // address.
637 let ptr = mmap.as_ptr() as u64;
638 let len = mmap.len();
639
640 // Fire and forget. The `JoinHandle` returned by `spawn` is dropped right
641 // after the call, the thread is thus detached. We don't care about success
642 // or failure here.
643 std::thread::spawn(move || unsafe {
644 // mmap's pointer is always page-aligned on Linux. In the case of
645 // file-based mmap (which is our use-case), the length should be
646 // correct. If not, it's not a safety concern as the kernel will just
647 // ignore unmapped pages and return ENOMEM, which we will promptly
648 // ignore, because we don't care about any errors.
649 libc::madvise(ptr as *mut libc::c_void, len, MADV_POPULATE_READ);
650 });
651 }
652
653 #[cfg(not(target_os = "linux"))]
654 fn advise_populate_read_mmap(mmap: &memmap2::Mmap) {}
655
656 /// Open the revlog [`Index`] at `index_path`, through the `store_vfs` and the
657 /// given `options`. This controls whether (and how) we `mmap` the index file,
658 /// and returns an empty buffer if the index does not exist on disk.
659 /// This is only used when doing pure-Rust work, in Python contexts this is
660 /// unused at the time of writing.
661 pub fn open_index(
662 store_vfs: &impl Vfs,
663 index_path: &Path,
664 options: RevlogOpenOptions,
665 ) -> Result<Index, HgError> {
666 let buf: DynBytes = match store_vfs.open(index_path) {
667 Ok(mut file) => {
668 let mut buf = if let Some(threshold) =
669 options.data_config.mmap_index_threshold
670 {
671 let size = store_vfs.file_size(&file)?;
672 if size >= threshold {
673 // TODO madvise populate read in a background thread
674 let mut mmap_options = MmapOptions::new();
675 if !can_advise_populate_read() {
676 // Fall back to populating in the main thread if
677 // post-creation advice is not supported.
678 // Does nothing on platforms where it's not defined.
679 mmap_options.populate();
680 }
681 // Safety is "enforced" by locks and assuming other
682 // processes are well-behaved. If any misbehaving or
683 // malicious process does touch the index, it could lead
684 // to corruption. This is somewhat inherent to file-based
685 // `mmap`, though some platforms have some ways of
686 // mitigating.
687 // TODO linux: set the immutable flag with `chattr(1)`?
688 let mmap = unsafe { mmap_options.map(&file) }
689 .when_reading_file(index_path)?;
690
691 if can_advise_populate_read() {
692 advise_populate_read_mmap(&mmap);
693 }
694
695 Some(DynBytes::new(Box::new(mmap)))
696 } else {
697 None
698 }
699 } else {
700 None
701 };
702
703 if buf.is_none() {
704 let mut data = vec![];
705 file.read_to_end(&mut data).when_reading_file(index_path)?;
706 buf = Some(DynBytes::new(Box::new(data)));
707 }
708 buf.unwrap()
709 }
710 Err(err) => match err {
711 HgError::IoError { error, context, backtrace } => {
712 match error.kind() {
713 ErrorKind::NotFound => DynBytes::default(),
714 _ => {
715 return Err(HgError::IoError {
716 error,
717 context,
718 backtrace,
719 })
720 }
721 }
722 }
723 e => return Err(e),
724 },
725 };
726
727 let index = Index::new(buf, options.index_header())?;
728 Ok(index)
729 }
730
731 /// The revlog entry's bytes and the necessary informations to extract
732 /// the entry's data.
733 #[derive(Clone)]
734 pub struct RevlogEntry<'revlog> {
735 revlog: &'revlog InnerRevlog,
736 rev: Revision,
737 uncompressed_len: i32,
738 p1: Revision,
739 p2: Revision,
740 flags: u16,
741 hash: Node,
742 }
743
744 impl<'revlog> RevlogEntry<'revlog> {
745 pub fn revision(&self) -> Revision {
746 self.rev
747 }
748
749 pub fn node(&self) -> &Node {
750 &self.hash
751 }
752
753 pub fn uncompressed_len(&self) -> Option<u32> {
754 u32::try_from(self.uncompressed_len).ok()
755 }
756
757 pub fn has_p1(&self) -> bool {
758 self.p1 != NULL_REVISION
759 }
760
761 pub fn p1_entry(
762 &self,
763 ) -> Result<Option<RevlogEntry<'revlog>>, RevlogError> {
764 if self.p1 == NULL_REVISION {
765 Ok(None)
766 } else {
767 Ok(Some(self.revlog.get_entry(self.p1)?))
768 }
769 }
770
771 pub fn p2_entry(
772 &self,
773 ) -> Result<Option<RevlogEntry<'revlog>>, RevlogError> {
774 if self.p2 == NULL_REVISION {
775 Ok(None)
776 } else {
777 Ok(Some(self.revlog.get_entry(self.p2)?))
778 }
779 }
780
781 pub fn p1(&self) -> Option<Revision> {
782 if self.p1 == NULL_REVISION {
783 None
784 } else {
785 Some(self.p1)
786 }
787 }
788
789 pub fn p2(&self) -> Option<Revision> {
790 if self.p2 == NULL_REVISION {
791 None
792 } else {
793 Some(self.p2)
794 }
795 }
796
797 pub fn is_censored(&self) -> bool {
798 (self.flags & REVISION_FLAG_CENSORED) != 0
799 }
800
801 pub fn has_length_affecting_flag_processor(&self) -> bool {
802 // Relevant Python code: revlog.size()
803 // note: ELLIPSIS is known to not change the content
804 (self.flags & (REVIDX_KNOWN_FLAGS ^ REVISION_FLAG_ELLIPSIS)) != 0
805 }
806
807 fn check_data(&self, data: RawData) -> Result<RawData, RevlogError> {
808 if self.revlog.check_hash(self.p1, self.p2, self.hash.as_bytes(), &data)
809 {
810 Ok(data)
811 } else {
812 if (self.flags & REVISION_FLAG_ELLIPSIS) != 0 {
813 return Err(HgError::unsupported(
814 "support for ellipsis nodes is missing",
815 )
816 .into());
817 }
818 Err(corrupted(format!(
819 "hash check failed for revision {}",
820 self.rev
821 ))
822 .into())
823 }
824 }
825
826 /// Get the revision data, without checking it integrity
827 fn data_unchecked(&self) -> Result<RawData, RevlogError> {
828 if self.rev == NULL_REVISION {
829 return Ok(RawData::empty());
830 }
831 if self.is_censored() {
832 return Err(HgError::CensoredNodeError(
833 *self.node(),
834 HgBacktrace::capture(),
835 )
836 .into());
837 }
838 let raw_size = self.uncompressed_len();
839 if let Some(size) = raw_size {
840 if size == 0 {
841 return Ok(RawData::empty());
842 }
843 self.revlog.seen_file_size(u32_u(size));
844 }
845 let cached_rev = self.revlog.get_rev_cache();
846 if let Some(ref cached) = cached_rev {
847 if cached.rev == self.rev {
848 let raw_text = cached.as_data();
849 self.revlog.set_rev_cache_native(self.rev, &raw_text);
850 return Ok(raw_text);
851 }
852 }
853 let cache = cached_rev.as_ref().map(|c| c.as_delta_base());
854 let stop_rev = cache.map(|(r, _)| r);
855 let (chunks, stopped) =
856 self.revlog.chunks_for_chain(self.revision(), stop_rev)?;
857 let (base_text, deltas) = if stopped {
858 if chunks.is_empty() {
859 // The revision is equivalent to another one, just return the
860 // equivalent one.
861 let cache_value =
862 cached_rev.expect("cannot stop without a cache");
863 let raw_text = cache_value.as_data();
864 self.revlog.set_rev_cache_native(self.rev, &raw_text);
865 return Ok(raw_text);
866 }
867 let cache_value = cache.expect("cannot stop without a cache");
868 let base_text = cache_value.1;
869 (base_text, &chunks[..])
870 } else {
871 let base_text = &chunks[0];
872 let deltas = &chunks[1..];
873 if deltas.is_empty() {
874 // The revision is equivalent to another one, just return the
875 // equivalent one.
876 return Ok(chunks
877 .into_iter()
878 .next()
879 .expect("the base must exists"));
880 }
881 (base_text.as_ref(), deltas)
882 };
883 let size = raw_size.map(|l| l as usize).unwrap_or(base_text.len());
884
885 let mut data = CoreRevisionBuffer::new();
886 data.resize(size);
887 patch::build_data_from_deltas(&mut data, base_text, deltas)?;
888 let raw_text: RawData = data.finish().into();
889 self.revlog.set_rev_cache_native(self.rev, &raw_text);
890 Ok(raw_text)
891 }
892
893 /// Get the revision data, checking its integrity in the process
894 pub fn data(&self) -> Result<RawData, RevlogError> {
895 if self.rev == NULL_REVISION {
896 return Ok(RawData::empty());
897 }
898 self.check_data(self.data_unchecked()?)
899 }
900 }
901
902 #[cfg(test)]
903 mod tests {
904 use itertools::Itertools;
905
906 use super::*;
907 use crate::revlog::index::IndexEntryBuilder;
908 use crate::revlog::path_encode::PathEncoding;
909
910 #[test]
911 fn test_empty() {
912 let temp = tempfile::tempdir().unwrap();
913 let vfs = VfsImpl::new(
914 temp.path().to_owned(),
915 false,
916 PathEncoding::DotEncode,
917 );
918 std::fs::write(temp.path().join("foo.i"), b"").unwrap();
919 std::fs::write(temp.path().join("foo.d"), b"").unwrap();
920 let revlog = Revlog::open(
921 &vfs,
922 "foo.i",
923 None,
924 RevlogOpenOptions::default(),
925 RevlogType::Changelog,
926 )
927 .unwrap();
928 assert!(revlog.is_empty());
929 assert_eq!(revlog.len(), 0);
930 assert!(revlog.get_entry_for_unchecked_rev(0.into()).is_err());
931 assert!(!revlog.has_rev(0.into()));
932 assert_eq!(
933 revlog.rev_from_node(NULL_NODE.into()).unwrap(),
934 NULL_REVISION
935 );
936 let null_entry = revlog
937 .get_entry_for_unchecked_rev(NULL_REVISION.into())
938 .ok()
939 .unwrap();
940 assert_eq!(null_entry.revision(), NULL_REVISION);
941 assert!(null_entry.data().unwrap().is_empty());
942 }
943
944 #[test]
945 fn test_inline() {
946 let temp = tempfile::tempdir().unwrap();
947 let vfs = VfsImpl::new(
948 temp.path().to_owned(),
949 false,
950 PathEncoding::DotEncode,
951 );
952 let node0 =
953 Node::from_hex("2ed2a3912a0b24502043eae84ee4b279c18b90dd").unwrap();
954 let node1 =
955 Node::from_hex("b004912a8510032a0350a74daa2803dadfb00e12").unwrap();
956 let node2 =
957 Node::from_hex("dd6ad206e907be60927b5a3117b97dffb2590582").unwrap();
958 let entry0_bytes = IndexEntryBuilder::new()
959 .is_first(true)
960 .with_version(1)
961 .with_inline(true)
962 .with_node(node0)
963 .build();
964 let entry1_bytes = IndexEntryBuilder::new().with_node(node1).build();
965 let entry2_bytes = IndexEntryBuilder::new()
966 .with_p1(Revision(0))
967 .with_p2(Revision(1))
968 .with_node(node2)
969 .build();
970 let contents = vec![entry0_bytes, entry1_bytes, entry2_bytes]
971 .into_iter()
972 .flatten()
973 .collect_vec();
974 std::fs::write(temp.path().join("foo.i"), contents).unwrap();
975 let revlog = Revlog::open(
976 &vfs,
977 "foo.i",
978 None,
979 RevlogOpenOptions::default(),
980 RevlogType::Changelog,
981 )
982 .unwrap();
983
984 let entry0 = revlog.get_entry_for_unchecked_rev(0.into()).ok().unwrap();
985 assert_eq!(entry0.revision(), Revision(0));
986 assert_eq!(*entry0.node(), node0);
987 assert!(!entry0.has_p1());
988 assert_eq!(entry0.p1(), None);
989 assert_eq!(entry0.p2(), None);
990 let p1_entry = entry0.p1_entry().unwrap();
991 assert!(p1_entry.is_none());
992 let p2_entry = entry0.p2_entry().unwrap();
993 assert!(p2_entry.is_none());
994
995 let entry1 = revlog.get_entry_for_unchecked_rev(1.into()).ok().unwrap();
996 assert_eq!(entry1.revision(), Revision(1));
997 assert_eq!(*entry1.node(), node1);
998 assert!(!entry1.has_p1());
999 assert_eq!(entry1.p1(), None);
1000 assert_eq!(entry1.p2(), None);
1001 let p1_entry = entry1.p1_entry().unwrap();
1002 assert!(p1_entry.is_none());
1003 let p2_entry = entry1.p2_entry().unwrap();
1004 assert!(p2_entry.is_none());
1005
1006 let entry2 = revlog.get_entry_for_unchecked_rev(2.into()).ok().unwrap();
1007 assert_eq!(entry2.revision(), Revision(2));
1008 assert_eq!(*entry2.node(), node2);
1009 assert!(entry2.has_p1());
1010 assert_eq!(entry2.p1(), Some(Revision(0)));
1011 assert_eq!(entry2.p2(), Some(Revision(1)));
1012 let p1_entry = entry2.p1_entry().unwrap();
1013 assert!(p1_entry.is_some());
1014 assert_eq!(p1_entry.unwrap().revision(), Revision(0));
1015 let p2_entry = entry2.p2_entry().unwrap();
1016 assert!(p2_entry.is_some());
1017 assert_eq!(p2_entry.unwrap().revision(), Revision(1));
1018 }
1019
1020 #[test]
1021 fn test_nodemap() {
1022 let temp = tempfile::tempdir().unwrap();
1023 let vfs = VfsImpl::new(
1024 temp.path().to_owned(),
1025 false,
1026 PathEncoding::DotEncode,
1027 );
1028
1029 // building a revlog with a forced Node starting with zeros
1030 // This is a corruption, but it does not preclude using the nodemap
1031 // if we don't try and access the data
1032 let node0 =
1033 Node::from_hex("00d2a3912a0b24502043eae84ee4b279c18b90dd").unwrap();
1034 let node1 =
1035 Node::from_hex("b004912a8510032a0350a74daa2803dadfb00e12").unwrap();
1036 let entry0_bytes = IndexEntryBuilder::new()
1037 .is_first(true)
1038 .with_version(1)
1039 .with_inline(true)
1040 .with_node(node0)
1041 .build();
1042 let entry1_bytes = IndexEntryBuilder::new().with_node(node1).build();
1043 let contents = vec![entry0_bytes, entry1_bytes]
1044 .into_iter()
1045 .flatten()
1046 .collect_vec();
1047 std::fs::write(temp.path().join("foo.i"), contents).unwrap();
1048
1049 let mut idx = nodemap::tests::TestNtIndex::new();
1050 idx.insert_node(Revision(0), node0).unwrap();
1051 idx.insert_node(Revision(1), node1).unwrap();
1052
1053 let revlog = Revlog::open_gen(
1054 &vfs,
1055 "foo.i",
1056 None,
1057 RevlogOpenOptions::default(),
1058 Some(idx.nt),
1059 RevlogType::Changelog,
1060 )
1061 .unwrap();
1062
1063 // accessing the data shows the corruption
1064 revlog
1065 .get_entry_for_unchecked_rev(0.into())
1066 .unwrap()
1067 .data()
1068 .unwrap_err();
1069
1070 assert_eq!(
1071 revlog.rev_from_node(NULL_NODE.into()).unwrap(),
1072 Revision(-1)
1073 );
1074 assert_eq!(revlog.rev_from_node(node0.into()).unwrap(), Revision(0));
1075 assert_eq!(revlog.rev_from_node(node1.into()).unwrap(), Revision(1));
1076 assert_eq!(
1077 revlog.rev_from_node(NodePrefix::from_hex("000").unwrap()).unwrap(),
1078 Revision(-1)
1079 );
1080 assert_eq!(
1081 revlog.rev_from_node(NodePrefix::from_hex("b00").unwrap()).unwrap(),
1082 Revision(1)
1083 );
1084 // RevlogError does not implement PartialEq
1085 // (ultimately because io::Error does not)
1086 match revlog
1087 .rev_from_node(NodePrefix::from_hex("00").unwrap())
1088 .expect_err("Expected to give AmbiguousPrefix error")
1089 {
1090 RevlogError::AmbiguousPrefix(_) => (),
1091 e => {
1092 panic!("Got another error than AmbiguousPrefix: {:?}", e);
1093 }
1094 };
1095 }
1096
1097 #[test]
1098 fn test_revision_or_wdir_ord() {
1099 let highest: RevisionOrWdir = Revision(i32::MAX - 1).into();
1100 assert!(highest < RevisionOrWdir::wdir());
1101 }
1102 }