Debian Codegraph @

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

raw
1 use std::path::PathBuf;
2
3 use super::manifest::Manifest;
4 use super::options::RevlogOpenOptions;
5 use super::path_encode::PathEncoding;
6 use crate::dirstate::entry::has_exec_bit;
7 use crate::errors::HgError;
8 use crate::repo::Repo;
9 use crate::revlog::inner_revlog::InnerRevlog;
10 use crate::revlog::manifest::ManifestFlags;
11 use crate::revlog::path_encode::path_encode;
12 use crate::revlog::NodePrefix;
13 use crate::revlog::Revision;
14 use crate::revlog::Revlog;
15 use crate::revlog::RevlogEntry;
16 use crate::revlog::RevlogError;
17 use crate::revlog::RevlogType;
18 use crate::revlog::REVISION_FLAG_HASMETA;
19 use crate::utils::files::get_bytes_from_os_string;
20 use crate::utils::files::get_path_from_bytes;
21 use crate::utils::hg_path::hg_path_to_path_buf;
22 use crate::utils::hg_path::HgPath;
23 use crate::utils::strings::SliceExt;
24 use crate::utils::RawData;
25 use crate::vfs::VfsImpl;
26 use crate::Graph;
27 use crate::GraphError;
28 use crate::Node;
29 use crate::UncheckedRevision;
30
31 /// A specialized `Revlog` to work with file data logs.
32 pub struct Filelog {
33 /// The generic `revlog` format.
34 pub(crate) revlog: Revlog,
35 }
36
37 impl Graph for Filelog {
38 fn parents(&self, rev: Revision) -> Result<[Revision; 2], GraphError> {
39 self.revlog.parents(rev)
40 }
41 }
42
43 impl Filelog {
44 pub fn open_vfs(
45 store_vfs: &crate::vfs::VfsImpl,
46 file_path: &HgPath,
47 options: RevlogOpenOptions,
48 ) -> Result<Self, HgError> {
49 let index_path = store_path(file_path, b".i", store_vfs.encoding);
50 let data_path = store_path(file_path, b".d", store_vfs.encoding);
51 let revlog = Revlog::open(
52 store_vfs,
53 index_path,
54 Some(&data_path),
55 options,
56 RevlogType::Filelog,
57 )?;
58 Ok(Self { revlog })
59 }
60
61 pub fn open(
62 repo: &Repo,
63 file_path: &HgPath,
64 options: RevlogOpenOptions,
65 ) -> Result<Self, HgError> {
66 Self::open_vfs(&repo.store_vfs(), file_path, options)
67 }
68
69 /// The given node ID is that of the file as found in a filelog, not of a
70 /// changeset.
71 pub fn data_for_node(
72 &self,
73 file_node: impl Into<NodePrefix>,
74 ) -> Result<FilelogRevisionData, RevlogError> {
75 let file_rev = self.revlog.rev_from_node(file_node.into())?;
76 Ok(self.entry(file_rev)?.data()?)
77 }
78
79 /// The given revision is that of the file as found in a filelog, not of a
80 /// changeset.
81 pub fn data_for_unchecked_rev(
82 &self,
83 file_rev: UncheckedRevision,
84 ) -> Result<FilelogRevisionData, RevlogError> {
85 let data = self.revlog.get_data_for_unchecked_rev(file_rev);
86 maybe_ignore_censored_revision(&self.revlog.inner, data)
87 }
88
89 /// The given node ID is that of the file as found in a filelog, not of a
90 /// changeset.
91 pub fn entry_for_node(
92 &self,
93 file_node: impl Into<NodePrefix>,
94 ) -> Result<FilelogEntry, RevlogError> {
95 let file_rev = self.revlog.rev_from_node(file_node.into())?;
96 self.entry(file_rev)
97 }
98
99 /// The given revision is that of the file as found in a filelog, not of a
100 /// changeset.
101 pub fn entry_for_unchecked_rev(
102 &self,
103 file_rev: UncheckedRevision,
104 ) -> Result<FilelogEntry, RevlogError> {
105 Ok(FilelogEntry(self.revlog.get_entry_for_unchecked_rev(file_rev)?))
106 }
107
108 /// Same as [`Self::entry_for_unchecked_rev`] for a checked revision.
109 pub fn entry(
110 &self,
111 file_rev: Revision,
112 ) -> Result<FilelogEntry, RevlogError> {
113 Ok(FilelogEntry(self.revlog.get_entry(file_rev)?))
114 }
115 }
116
117 /// Given a [`Result`] of fetching filelog revision data, catch the eventual
118 /// censored node error and either forward it or ignore it according to config.
119 fn maybe_ignore_censored_revision(
120 irl: &InnerRevlog,
121 data_result: Result<RawData, RevlogError>,
122 ) -> Result<FilelogRevisionData, RevlogError> {
123 match data_result {
124 Ok(data) => Ok(FilelogRevisionData(data)),
125 // Errors other than `HgError` should not happen at this point
126 Err(e) => match &e {
127 RevlogError::Other(hg_error) => match hg_error {
128 HgError::CensoredNodeError(_, _)
129 if irl.ignore_filelog_censored_revisions() =>
130 {
131 Ok(FilelogRevisionData(RawData::empty()))
132 }
133 _ => Err(e),
134 },
135 _ => Err(e),
136 },
137 }
138 }
139
140 fn store_path(
141 hg_path: &HgPath,
142 suffix: &[u8],
143 encoding: PathEncoding,
144 ) -> PathBuf {
145 let encoded_bytes =
146 path_encode(&[b"data/", hg_path.as_bytes(), suffix].concat(), encoding);
147 get_path_from_bytes(&encoded_bytes).into()
148 }
149
150 pub struct FilelogEntry<'a>(pub(crate) RevlogEntry<'a>);
151
152 impl FilelogEntry<'_> {
153 /// `self.data()` can be expensive, with decompression and delta
154 /// resolution.
155 ///
156 /// *Without* paying this cost, based on revlog index information
157 /// including `RevlogEntry::uncompressed_len`:
158 ///
159 /// * Returns `true` if the length that `self.data().file_data().len()`
160 /// would return is definitely **not equal** to `other_len`.
161 /// * Returns `false` if available information is inconclusive.
162 pub fn file_data_len_not_equal_to(&self, other_len: u64) -> bool {
163 // Relevant code that implement this behavior in Python code:
164 // basefilectx.cmp, filelog.size, filelog.renamed,
165 // revlog.size, revlog.rawsize
166
167 // Let’s call `file_data_len` what would be returned by
168 // `self.data().file_data().len()`.
169
170 if self.0.is_censored() {
171 let file_data_len = 0;
172 return other_len != file_data_len;
173 }
174
175 if self.0.has_length_affecting_flag_processor() {
176 // We can’t conclude anything about `file_data_len`.
177 return false;
178 }
179
180 // Revlog revisions (usually) have metadata for the size of
181 // their data after decompression and delta resolution
182 // as would be returned by `Revlog::get_rev_data`.
183 //
184 // For filelogs this is the file’s contents preceded by an optional
185 // metadata block.
186 let uncompressed_len = if let Some(l) = self.0.uncompressed_len() {
187 l as u64
188 } else {
189 // The field was set to -1, the actual uncompressed len is unknown.
190 // We need to decompress to say more.
191 return false;
192 };
193 // `uncompressed_len = file_data_len + optional_metadata_len`,
194 // so `file_data_len <= uncompressed_len`.
195 if uncompressed_len < other_len {
196 // Transitively, `file_data_len < other_len`.
197 // So `other_len != file_data_len` definitely.
198 return true;
199 }
200
201 if self.0.revlog.index.uses_filelog_meta() {
202 if (self.0.flags & REVISION_FLAG_HASMETA) != 0 {
203 return false;
204 }
205 } else {
206 if uncompressed_len == other_len + 4 {
207 // It’s possible that `file_data_len == other_len` with an empty
208 // metadata block (2 start marker bytes + 2 end marker bytes).
209 // This happens when there wouldn’t otherwise be metadata, but
210 // the first 2 bytes of file data happen to match a start marker
211 // and would be ambiguous.
212 return false;
213 }
214
215 if !self.0.has_p1() {
216 // There may or may not be copy metadata, so we can’t deduce
217 // more about `file_data_len` without computing
218 // file data.
219 return false;
220 }
221 }
222
223 // Filelog ancestry is not meaningful in the way changelog ancestry is.
224 // It only provides hints to delta generation.
225 // p1 and p2 are set to null when making a copy or rename since
226 // contents are likely unrelatedto what might have previously existed
227 // at the destination path.
228 //
229 // Conversely, since here p1 is non-null, there is no copy metadata.
230 // Note that this reasoning may be invalidated in the presence of
231 // merges made by some previous versions of Mercurial that
232 // swapped p1 and p2. See <https://bz.mercurial-scm.org/show_bug.cgi?id=6528>
233 // and `tests/test-issue6528.t`.
234 //
235 // Since copy metadata is currently the only kind of metadata
236 // kept in revlog data of filelogs,
237 // this `FilelogEntry` does not have such metadata:
238 let file_data_len = uncompressed_len;
239
240 file_data_len != other_len
241 }
242
243 pub fn data(&self) -> Result<FilelogRevisionData, HgError> {
244 let data = self.0.data();
245 maybe_ignore_censored_revision(self.0.revlog, data).map_err(|e| match e
246 {
247 RevlogError::Other(hg_error) => hg_error,
248 revlog_error => HgError::abort_simple(revlog_error.to_string()),
249 })
250 }
251 }
252
253 /// The data for one revision in a filelog, uncompressed and delta-resolved.
254 pub struct FilelogRevisionData(RawData);
255
256 impl FilelogRevisionData {
257 /// Split into metadata and data
258 pub fn split(
259 &self,
260 ) -> Result<(FilelogRevisionMetadata<'_>, &[u8]), HgError> {
261 const DELIMITER: &[u8; 2] = b"\x01\n";
262
263 if let Some(rest) = self.0.drop_prefix(DELIMITER) {
264 if let Some((metadata, data)) = rest.split_2_by_slice(DELIMITER) {
265 Ok((FilelogRevisionMetadata(Some(metadata)), data))
266 } else {
267 Err(HgError::corrupted(
268 "Missing metadata end delimiter in filelog entry",
269 ))
270 }
271 } else {
272 Ok((FilelogRevisionMetadata(None), &self.0))
273 }
274 }
275
276 /// Returns the metadata header.
277 pub fn metadata(&self) -> Result<FilelogRevisionMetadata<'_>, HgError> {
278 let (metadata, _data) = self.split()?;
279 Ok(metadata)
280 }
281
282 /// Returns the file contents at this revision, stripped of any metadata
283 pub fn file_data(&self) -> Result<&[u8], HgError> {
284 let (_metadata, data) = self.split()?;
285 Ok(data)
286 }
287
288 /// Consume the entry, and convert it into data, discarding any metadata,
289 /// if present.
290 pub fn into_file_data(self) -> Result<RawData, HgError> {
291 if let (FilelogRevisionMetadata(Some(_)), data) = self.split()? {
292 Ok(RawData::from(data)) // XXX consider the Bytes crate
293 } else {
294 Ok(self.0)
295 }
296 }
297 }
298
299 /// The optional metadata header included in [`FilelogRevisionData`].
300 pub struct FilelogRevisionMetadata<'a>(Option<&'a [u8]>);
301
302 /// Fields parsed from [`FilelogRevisionMetadata`].
303 #[derive(Debug, PartialEq, Default)]
304 pub struct FilelogRevisionMetadataFields<'a> {
305 /// True if the file revision data is censored.
306 pub censored: bool,
307 /// Path of the copy source.
308 pub copy: Option<&'a HgPath>,
309 /// Filelog node ID of the copy source.
310 pub copyrev: Option<Node>,
311 }
312
313 impl<'a> FilelogRevisionMetadata<'a> {
314 /// Parses the metadata fields.
315 pub fn parse(self) -> Result<FilelogRevisionMetadataFields<'a>, HgError> {
316 let mut fields = FilelogRevisionMetadataFields::default();
317 if let Some(metadata) = self.0 {
318 let mut rest = metadata;
319 while !rest.is_empty() {
320 let Some(colon_idx) = memchr::memchr(b':', rest) else {
321 return Err(HgError::corrupted(
322 "File metadata header line missing colon",
323 ));
324 };
325 if rest.get(colon_idx + 1) != Some(&b' ') {
326 return Err(HgError::corrupted(
327 "File metadata header line missing space",
328 ));
329 }
330 let key = &rest[..colon_idx];
331 rest = &rest[colon_idx + 2..];
332 let Some(newline_idx) = memchr::memchr(b'\n', rest) else {
333 return Err(HgError::corrupted(
334 "File metadata header line missing newline",
335 ));
336 };
337 let value = &rest[..newline_idx];
338 match key {
339 b"censored" => {
340 match value {
341 b"" => fields.censored = true,
342 _ => return Err(HgError::corrupted(
343 "File metadata header 'censored' field has nonempty value",
344 )),
345 }
346 }
347 b"copy" => fields.copy = Some(HgPath::new(value)),
348 b"copyrev" => {
349 fields.copyrev = Some(Node::from_hex_for_repo(value)?)
350 }
351 _ => {
352 return Err(HgError::corrupted(
353 format!(
354 "File metadata header has unrecognized key '{}'",
355 String::from_utf8_lossy(key),
356 ),
357 ))
358 }
359 }
360 rest = &rest[newline_idx + 1..];
361 }
362 }
363 Ok(fields)
364 }
365 }
366
367 /// Outcome of checking if a file has changed since the last commit
368 #[derive(Debug, PartialEq, Eq)]
369 pub enum FileCompOutcome {
370 /// The file is actually clean
371 Clean,
372 /// The file has been modified
373 Modified,
374 /// The file was deleted on disk (or became another type of fs entry)
375 Deleted,
376 }
377
378 /// Check if a file is modified by comparing actual repo store and file system.
379 pub fn is_file_modified(
380 working_directory_vfs: &VfsImpl,
381 store_vfs: &VfsImpl,
382 check_exec: bool,
383 manifest: &Manifest,
384 hg_path: &HgPath,
385 revlog_open_options: RevlogOpenOptions,
386 ) -> Result<FileCompOutcome, HgError> {
387 let vfs = working_directory_vfs;
388 let fs_path = hg_path_to_path_buf(hg_path).expect("HgPath conversion");
389 let fs_metadata = if let Ok(it) = vfs.symlink_metadata(&fs_path) {
390 it
391 } else {
392 return Ok(FileCompOutcome::Deleted);
393 };
394 let is_symlink = fs_metadata.file_type().is_symlink();
395
396 let entry =
397 manifest.find_by_path(hg_path)?.expect("ambgious file not in p1");
398
399 // TODO: Also account for `FALLBACK_SYMLINK` and `FALLBACK_EXEC` from the
400 // dirstate
401 let fs_flags = if is_symlink {
402 ManifestFlags::new_link()
403 } else if check_exec && has_exec_bit(&fs_metadata) {
404 ManifestFlags::new_exec()
405 } else {
406 ManifestFlags::new_empty()
407 };
408
409 let entry_flags = if check_exec {
410 entry.flags
411 } else if entry.flags.is_exec() {
412 ManifestFlags::new_empty()
413 } else {
414 entry.flags
415 };
416
417 if entry_flags != fs_flags {
418 return Ok(FileCompOutcome::Modified);
419 }
420 let filelog = Filelog::open_vfs(store_vfs, hg_path, revlog_open_options)?;
421 let fs_len = fs_metadata.len();
422 let file_node = entry.node_id()?;
423 let filelog_entry = filelog.entry_for_node(file_node).map_err(|_| {
424 HgError::corrupted(format!(
425 "filelog {:?} missing node {:?} from manifest",
426 hg_path, file_node
427 ))
428 })?;
429 if filelog_entry.file_data_len_not_equal_to(fs_len) {
430 // No need to read file contents:
431 // it cannot be equal if it has a different length.
432 return Ok(FileCompOutcome::Modified);
433 }
434
435 let p1_filelog_data = filelog_entry.data()?;
436 let p1_contents = p1_filelog_data.file_data()?;
437 if p1_contents.len() as u64 != fs_len {
438 // No need to read file contents:
439 // it cannot be equal if it has a different length.
440 return Ok(FileCompOutcome::Modified);
441 }
442
443 let fs_contents = if is_symlink {
444 get_bytes_from_os_string(vfs.read_link(fs_path)?.into_os_string())
445 } else {
446 vfs.read(fs_path)?
447 };
448
449 Ok(if p1_contents != &*fs_contents {
450 FileCompOutcome::Modified
451 } else {
452 FileCompOutcome::Clean
453 })
454 }
455
456 #[cfg(test)]
457 mod tests {
458 use format_bytes::format_bytes;
459
460 use super::*;
461
462 #[test]
463 fn test_parse_no_metadata() {
464 let data = FilelogRevisionData(RawData::from(b"data".to_vec()));
465 let fields = data.metadata().unwrap().parse().unwrap();
466 assert_eq!(fields, Default::default());
467 }
468
469 #[test]
470 fn test_parse_empty_metadata() {
471 let data =
472 FilelogRevisionData(RawData::from(b"\x01\n\x01\ndata".to_vec()));
473 let fields = data.metadata().unwrap().parse().unwrap();
474 assert_eq!(fields, Default::default());
475 }
476
477 #[test]
478 fn test_parse_one_field() {
479 let data = FilelogRevisionData(RawData::from(
480 b"\x01\ncopy: foo\n\x01\ndata".to_vec(),
481 ));
482 let fields = data.metadata().unwrap().parse().unwrap();
483 assert_eq!(
484 fields,
485 FilelogRevisionMetadataFields {
486 copy: Some(HgPath::new("foo")),
487 ..Default::default()
488 }
489 );
490 }
491
492 #[test]
493 fn test_parse_all_fields() {
494 let sha = b"215d5d1546f82a79481eb2df513a7bc341bdf17f";
495 let data = FilelogRevisionData(RawData::from(format_bytes!(
496 b"\x01\ncensored: \ncopy: foo\ncopyrev: {}\n\x01\ndata",
497 sha
498 )));
499 let fields = data.metadata().unwrap().parse().unwrap();
500 assert_eq!(
501 fields,
502 FilelogRevisionMetadataFields {
503 censored: true,
504 copy: Some(HgPath::new("foo")),
505 copyrev: Some(Node::from_hex(sha).unwrap()),
506 }
507 );
508 }
509
510 #[test]
511 fn test_parse_invalid_metadata() {
512 let data = FilelogRevisionData(RawData::from(
513 b"\x01\nbad: value\n\x01\ndata".to_vec(),
514 ));
515 let err = data.metadata().unwrap().parse().unwrap_err();
516 assert!(err.to_string().contains("unrecognized key 'bad'"));
517 }
518 }