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 uncompressed_len == other_len + 4 {
202 // It’s possible that `file_data_len == other_len` with an empty
203 // metadata block (2 start marker bytes + 2 end marker bytes).
204 // This happens when there wouldn’t otherwise be metadata, but
205 // the first 2 bytes of file data happen to match a start marker
206 // and would be ambiguous.
207 return false;
208 }
209
210 if self.0.revlog.index.uses_filelog_meta() {
211 return (self.0.flags & REVISION_FLAG_HASMETA) != 0;
212 } else if !self.0.has_p1() {
213 // There may or may not be copy metadata, so we can’t deduce more
214 // about `file_data_len` without computing file data.
215 return false;
216 }
217
218 // Filelog ancestry is not meaningful in the way changelog ancestry is.
219 // It only provides hints to delta generation.
220 // p1 and p2 are set to null when making a copy or rename since
221 // contents are likely unrelatedto what might have previously existed
222 // at the destination path.
223 //
224 // Conversely, since here p1 is non-null, there is no copy metadata.
225 // Note that this reasoning may be invalidated in the presence of
226 // merges made by some previous versions of Mercurial that
227 // swapped p1 and p2. See <https://bz.mercurial-scm.org/show_bug.cgi?id=6528>
228 // and `tests/test-issue6528.t`.
229 //
230 // Since copy metadata is currently the only kind of metadata
231 // kept in revlog data of filelogs,
232 // this `FilelogEntry` does not have such metadata:
233 let file_data_len = uncompressed_len;
234
235 file_data_len != other_len
236 }
237
238 pub fn data(&self) -> Result<FilelogRevisionData, HgError> {
239 let data = self.0.data();
240 maybe_ignore_censored_revision(self.0.revlog, data).map_err(|e| match e
241 {
242 RevlogError::Other(hg_error) => hg_error,
243 revlog_error => HgError::abort_simple(revlog_error.to_string()),
244 })
245 }
246 }
247
248 /// The data for one revision in a filelog, uncompressed and delta-resolved.
249 pub struct FilelogRevisionData(RawData);
250
251 impl FilelogRevisionData {
252 /// Split into metadata and data
253 pub fn split(
254 &self,
255 ) -> Result<(FilelogRevisionMetadata<'_>, &[u8]), HgError> {
256 const DELIMITER: &[u8; 2] = b"\x01\n";
257
258 if let Some(rest) = self.0.drop_prefix(DELIMITER) {
259 if let Some((metadata, data)) = rest.split_2_by_slice(DELIMITER) {
260 Ok((FilelogRevisionMetadata(Some(metadata)), data))
261 } else {
262 Err(HgError::corrupted(
263 "Missing metadata end delimiter in filelog entry",
264 ))
265 }
266 } else {
267 Ok((FilelogRevisionMetadata(None), &self.0))
268 }
269 }
270
271 /// Returns the metadata header.
272 pub fn metadata(&self) -> Result<FilelogRevisionMetadata<'_>, HgError> {
273 let (metadata, _data) = self.split()?;
274 Ok(metadata)
275 }
276
277 /// Returns the file contents at this revision, stripped of any metadata
278 pub fn file_data(&self) -> Result<&[u8], HgError> {
279 let (_metadata, data) = self.split()?;
280 Ok(data)
281 }
282
283 /// Consume the entry, and convert it into data, discarding any metadata,
284 /// if present.
285 pub fn into_file_data(self) -> Result<RawData, HgError> {
286 if let (FilelogRevisionMetadata(Some(_)), data) = self.split()? {
287 Ok(RawData::from(data)) // XXX consider the Bytes crate
288 } else {
289 Ok(self.0)
290 }
291 }
292 }
293
294 /// The optional metadata header included in [`FilelogRevisionData`].
295 pub struct FilelogRevisionMetadata<'a>(Option<&'a [u8]>);
296
297 /// Fields parsed from [`FilelogRevisionMetadata`].
298 #[derive(Debug, PartialEq, Default)]
299 pub struct FilelogRevisionMetadataFields<'a> {
300 /// True if the file revision data is censored.
301 pub censored: bool,
302 /// Path of the copy source.
303 pub copy: Option<&'a HgPath>,
304 /// Filelog node ID of the copy source.
305 pub copyrev: Option<Node>,
306 }
307
308 impl<'a> FilelogRevisionMetadata<'a> {
309 /// Parses the metadata fields.
310 pub fn parse(self) -> Result<FilelogRevisionMetadataFields<'a>, HgError> {
311 let mut fields = FilelogRevisionMetadataFields::default();
312 if let Some(metadata) = self.0 {
313 let mut rest = metadata;
314 while !rest.is_empty() {
315 let Some(colon_idx) = memchr::memchr(b':', rest) else {
316 return Err(HgError::corrupted(
317 "File metadata header line missing colon",
318 ));
319 };
320 if rest.get(colon_idx + 1) != Some(&b' ') {
321 return Err(HgError::corrupted(
322 "File metadata header line missing space",
323 ));
324 }
325 let key = &rest[..colon_idx];
326 rest = &rest[colon_idx + 2..];
327 let Some(newline_idx) = memchr::memchr(b'\n', rest) else {
328 return Err(HgError::corrupted(
329 "File metadata header line missing newline",
330 ));
331 };
332 let value = &rest[..newline_idx];
333 match key {
334 b"censored" => {
335 match value {
336 b"" => fields.censored = true,
337 _ => return Err(HgError::corrupted(
338 "File metadata header 'censored' field has nonempty value",
339 )),
340 }
341 }
342 b"copy" => fields.copy = Some(HgPath::new(value)),
343 b"copyrev" => {
344 fields.copyrev = Some(Node::from_hex_for_repo(value)?)
345 }
346 _ => {
347 return Err(HgError::corrupted(
348 format!(
349 "File metadata header has unrecognized key '{}'",
350 String::from_utf8_lossy(key),
351 ),
352 ))
353 }
354 }
355 rest = &rest[newline_idx + 1..];
356 }
357 }
358 Ok(fields)
359 }
360 }
361
362 /// Outcome of checking if a file has changed since the last commit
363 #[derive(Debug, PartialEq, Eq)]
364 pub enum FileCompOutcome {
365 /// The file is actually clean
366 Clean,
367 /// The file has been modified
368 Modified,
369 /// The file was deleted on disk (or became another type of fs entry)
370 Deleted,
371 }
372
373 /// Check if a file is modified by comparing actual repo store and file system.
374 pub fn is_file_modified(
375 working_directory_vfs: &VfsImpl,
376 store_vfs: &VfsImpl,
377 check_exec: bool,
378 manifest: &Manifest,
379 hg_path: &HgPath,
380 revlog_open_options: RevlogOpenOptions,
381 ) -> Result<FileCompOutcome, HgError> {
382 let vfs = working_directory_vfs;
383 let fs_path = hg_path_to_path_buf(hg_path).expect("HgPath conversion");
384 let fs_metadata = if let Ok(it) = vfs.symlink_metadata(&fs_path) {
385 it
386 } else {
387 return Ok(FileCompOutcome::Deleted);
388 };
389 let is_symlink = fs_metadata.file_type().is_symlink();
390
391 let entry =
392 manifest.find_by_path(hg_path)?.expect("ambgious file not in p1");
393
394 // TODO: Also account for `FALLBACK_SYMLINK` and `FALLBACK_EXEC` from the
395 // dirstate
396 let fs_flags = if is_symlink {
397 ManifestFlags::new_link()
398 } else if check_exec && has_exec_bit(&fs_metadata) {
399 ManifestFlags::new_exec()
400 } else {
401 ManifestFlags::new_empty()
402 };
403
404 let entry_flags = if check_exec {
405 entry.flags
406 } else if entry.flags.is_exec() {
407 ManifestFlags::new_empty()
408 } else {
409 entry.flags
410 };
411
412 if entry_flags != fs_flags {
413 return Ok(FileCompOutcome::Modified);
414 }
415 let filelog = Filelog::open_vfs(store_vfs, hg_path, revlog_open_options)?;
416 let fs_len = fs_metadata.len();
417 let file_node = entry.node_id()?;
418 let filelog_entry = filelog.entry_for_node(file_node).map_err(|_| {
419 HgError::corrupted(format!(
420 "filelog {:?} missing node {:?} from manifest",
421 hg_path, file_node
422 ))
423 })?;
424 if filelog_entry.file_data_len_not_equal_to(fs_len) {
425 // No need to read file contents:
426 // it cannot be equal if it has a different length.
427 return Ok(FileCompOutcome::Modified);
428 }
429
430 let p1_filelog_data = filelog_entry.data()?;
431 let p1_contents = p1_filelog_data.file_data()?;
432 if p1_contents.len() as u64 != fs_len {
433 // No need to read file contents:
434 // it cannot be equal if it has a different length.
435 return Ok(FileCompOutcome::Modified);
436 }
437
438 let fs_contents = if is_symlink {
439 get_bytes_from_os_string(vfs.read_link(fs_path)?.into_os_string())
440 } else {
441 vfs.read(fs_path)?
442 };
443
444 Ok(if p1_contents != &*fs_contents {
445 FileCompOutcome::Modified
446 } else {
447 FileCompOutcome::Clean
448 })
449 }
450
451 #[cfg(test)]
452 mod tests {
453 use format_bytes::format_bytes;
454
455 use super::*;
456
457 #[test]
458 fn test_parse_no_metadata() {
459 let data = FilelogRevisionData(RawData::from(b"data".to_vec()));
460 let fields = data.metadata().unwrap().parse().unwrap();
461 assert_eq!(fields, Default::default());
462 }
463
464 #[test]
465 fn test_parse_empty_metadata() {
466 let data =
467 FilelogRevisionData(RawData::from(b"\x01\n\x01\ndata".to_vec()));
468 let fields = data.metadata().unwrap().parse().unwrap();
469 assert_eq!(fields, Default::default());
470 }
471
472 #[test]
473 fn test_parse_one_field() {
474 let data = FilelogRevisionData(RawData::from(
475 b"\x01\ncopy: foo\n\x01\ndata".to_vec(),
476 ));
477 let fields = data.metadata().unwrap().parse().unwrap();
478 assert_eq!(
479 fields,
480 FilelogRevisionMetadataFields {
481 copy: Some(HgPath::new("foo")),
482 ..Default::default()
483 }
484 );
485 }
486
487 #[test]
488 fn test_parse_all_fields() {
489 let sha = b"215d5d1546f82a79481eb2df513a7bc341bdf17f";
490 let data = FilelogRevisionData(RawData::from(format_bytes!(
491 b"\x01\ncensored: \ncopy: foo\ncopyrev: {}\n\x01\ndata",
492 sha
493 )));
494 let fields = data.metadata().unwrap().parse().unwrap();
495 assert_eq!(
496 fields,
497 FilelogRevisionMetadataFields {
498 censored: true,
499 copy: Some(HgPath::new("foo")),
500 copyrev: Some(Node::from_hex(sha).unwrap()),
501 }
502 );
503 }
504
505 #[test]
506 fn test_parse_invalid_metadata() {
507 let data = FilelogRevisionData(RawData::from(
508 b"\x01\nbad: value\n\x01\ndata".to_vec(),
509 ));
510 let err = data.metadata().unwrap().parse().unwrap_err();
511 assert!(err.to_string().contains("unrecognized key 'bad'"));
512 }
513 }