Debian Codegraph @

rust/hg-core/src/update.rs

raw
1 //! Tools for moving the repository to a given revision
2
3 use std::collections::HashSet;
4 use std::fs::Metadata;
5 use std::fs::Permissions;
6 use std::io::Write;
7 use std::ops::Deref;
8 use std::os::unix::fs::MetadataExt;
9 use std::os::unix::fs::OpenOptionsExt;
10 use std::os::unix::fs::PermissionsExt;
11 use std::path::Path;
12 use std::path::PathBuf;
13 use std::sync::atomic::Ordering;
14 use std::time::Duration;
15
16 use crossbeam_channel::Receiver;
17 use crossbeam_channel::Sender;
18 use rayon::prelude::*;
19
20 use crate::checkexec::check_exec;
21 use crate::checkexec::is_executable;
22 use crate::dirstate::dirstate_map::DirstateEntryReset;
23 use crate::dirstate::dirstate_map::DirstateMap;
24 use crate::dirstate::entry::ParentFileData;
25 use crate::dirstate::entry::TruncatedTimestamp;
26 use crate::dirstate::owning::OwningDirstateMap;
27 use crate::errors::HgError;
28 use crate::errors::HgResultExt;
29 use crate::errors::IoResultExt;
30 use crate::exit_codes;
31 use crate::matchers::Matcher;
32 use crate::narrow;
33 use crate::operations::list_rev_tracked_files;
34 use crate::operations::ExpandedManifestEntry;
35 use crate::operations::FilesForRevBorrowed;
36 use crate::progress::Progress;
37 use crate::repo::Repo;
38 use crate::revlog::filelog::is_file_modified;
39 use crate::revlog::filelog::FileCompOutcome;
40 use crate::revlog::filelog::Filelog;
41 use crate::revlog::manifest::Manifest;
42 use crate::revlog::manifest::ManifestFlags;
43 use crate::revlog::options::default_revlog_options;
44 use crate::revlog::options::RevlogOpenOptions;
45 use crate::revlog::path_encode::PathEncoding;
46 use crate::revlog::RevlogType;
47 use crate::sparse;
48 use crate::utils::cap_default_rayon_threads;
49 use crate::utils::files::filesystem_now;
50 use crate::utils::files::find_dirs_recursive_no_root;
51 use crate::utils::files::get_bytes_from_path;
52 use crate::utils::files::get_path_from_bytes;
53 use crate::utils::hg_path::hg_path_to_path_buf;
54 use crate::utils::hg_path::HgPath;
55 use crate::utils::hg_path::HgPathBuf;
56 use crate::utils::hg_path::HgPathErrorKind;
57 use crate::utils::path_auditor::check_filesystem_single;
58 use crate::utils::path_auditor::PathAuditor;
59 use crate::vfs::get_umask;
60 use crate::vfs::is_on_nfs_mount;
61 use crate::vfs::Vfs;
62 use crate::vfs::VfsImpl;
63 use crate::warnings::HgWarningSender;
64 use crate::DirstateParents;
65 use crate::Revision;
66 use crate::UncheckedRevision;
67 use crate::INTERRUPT_RECEIVED;
68 use crate::NULL_NODE;
69
70 /// What kind of update we're doing
71 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
72 enum UpdateKind {
73 /// All tracked files are clean, but there can be unknown/ignored files
74 FromClean,
75 /// We're starting from the null revision and the working copy is empty
76 /// save for the `.hg` folder.
77 FromNull,
78 }
79
80 /// A clutch to be used to pass down relevant config items from Python that
81 /// may have been set through the CLI and thus be inaccessible from Rust.
82 ///
83 /// TODO remove this once the Python config object is backed by Rust code.
84 #[derive(Debug)]
85 pub struct UpdateConfig {
86 /// `worker.numcpus` if `worker.enabled`
87 pub workers: Option<usize>,
88 /// `experimental.removeemptydirs`
89 pub remove_empty_dirs: bool,
90 /// `devel.update.abort-on-dirstate-change`
91 pub devel_abort_dirstate: bool,
92 /// `ui.origbackuppath`
93 pub orig_backup_path: Option<Vec<u8>>,
94 /// `experimental.update.atomic-file`
95 pub atomic_file: bool,
96 pub ignored_conflict: FileConflictConfig,
97 pub unknown_conflict: FileConflictConfig,
98 }
99
100 /// Update the current working copy of `repo` to the given revision `to`, from
101 /// the null revision and update the dirstate without writing it to disk.
102 ///
103 /// Do not call this outside of a Python context. This does *not* handle any
104 /// of the checks, hooks, lock taking needed to setup and get out of this
105 /// update from the null revision.
106 #[tracing::instrument(level = "debug", skip_all)]
107 pub fn update_from_null(
108 repo: &Repo,
109 to: UncheckedRevision,
110 dirstate: &mut OwningDirstateMap,
111 progress: &dyn Progress,
112 update_config: &UpdateConfig,
113 warnings: &HgWarningSender,
114 ) -> Result<UpdateStats, HgError> {
115 let narrow_matcher = narrow::matcher(repo, warnings)?;
116
117 let files_for_rev = list_rev_tracked_files(repo, to, narrow_matcher)?;
118 repo.manually_set_parents(DirstateParents {
119 p1: repo.node(to).expect("update target should exist"),
120 p2: NULL_NODE,
121 })?;
122
123 // Filter the working copy according to the sparse spec
124 let tracked_files: Result<Vec<_>, HgError> = if !repo.has_sparse() {
125 files_for_rev
126 .iter()
127 .map(|e| {
128 Ok(WorkingCopyFileUpdate {
129 entry: e?,
130 backup: false,
131 flags_differ: false,
132 })
133 })
134 .collect()
135 } else {
136 let sparse_matcher = sparse::matcher(repo, None, warnings)?;
137 files_for_rev
138 .iter()
139 .filter(|f| {
140 match f {
141 Ok(f) => sparse_matcher.matches(f.0),
142 Err(_) => true, // Errors stop the update, include them
143 }
144 })
145 .map(|e| {
146 Ok(WorkingCopyFileUpdate {
147 entry: e?,
148 backup: false,
149 flags_differ: false,
150 })
151 })
152 .collect()
153 };
154 let tracked_files = tracked_files?;
155
156 if tracked_files.is_empty() {
157 return Ok(UpdateStats::default());
158 }
159 let store_vfs = &repo.store_vfs();
160 let options = default_revlog_options(
161 repo.config(),
162 repo.requirements(),
163 crate::revlog::RevlogType::Filelog,
164 )?;
165 let (files_sender, files_receiver) = crossbeam_channel::unbounded();
166
167 let files_count = tracked_files.len();
168 let (symlinks, chunks) = chunk_tracked_files(tracked_files, true);
169 progress.update(0, Some(files_count as u64));
170
171 // TODO find a way (with `nix` or `signal-hook`?) of resetting the
172 // previous signal handler directly after. Currently, this is Python's
173 // job, but:
174 // - it introduces a (small) race between catching and resetting
175 // - it would break signal handlers in other contexts like `rhg``
176 let _ = ctrlc::set_handler(|| {
177 INTERRUPT_RECEIVED.store(true, Ordering::Relaxed)
178 });
179
180 create_working_copy(
181 chunks,
182 symlinks,
183 &repo.working_directory_vfs(),
184 store_vfs,
185 options,
186 &files_sender,
187 progress,
188 update_config,
189 )?;
190 drop(files_sender);
191
192 // Reset the global interrupt now that we're done
193 if INTERRUPT_RECEIVED.swap(false, Ordering::Relaxed) {
194 tracing::warn!("Interrupt received, aborting the update");
195 // The threads have all exited early, let's re-raise
196 return Err(HgError::InterruptReceived);
197 }
198
199 // TODO try to run this concurrently to update the dirstate while we're
200 // still writing out the working copy to see if that improves performance.
201 let total = update_dirstate(
202 repo,
203 dirstate,
204 files_receiver,
205 None,
206 update_config.devel_abort_dirstate,
207 UpdateKind::FromNull,
208 )?;
209
210 Ok(total)
211 }
212
213 /// Update the current working copy of `repo` to the given revision `to`, from
214 /// an arbitrary revision with clean tracked files, and update the dirstate
215 /// without writing it to disk.
216 ///
217 /// Do not call this outside of a Python context. This does *not* handle any
218 /// of the checks, hooks, lock taking needed to setup and get out of this
219 /// update.
220 #[allow(clippy::too_many_arguments)]
221 #[tracing::instrument(level = "debug", skip_all)]
222 pub fn update_from_clean(
223 repo: &Repo,
224 dirstate: &mut OwningDirstateMap,
225 wc_manifest_bytes: Box<dyn Deref<Target = [u8]> + Send + Sync>,
226 target_rev: Revision,
227 target_manifest_bytes: Box<dyn Deref<Target = [u8]> + Send + Sync>,
228 progress: &dyn Progress,
229 update_config: &UpdateConfig,
230 warnings: &HgWarningSender,
231 ) -> Result<UpdateStats, HgError> {
232 let wc_manifest = Manifest::from_bytes(wc_manifest_bytes);
233 let target_manifest = Manifest::from_bytes(target_manifest_bytes);
234
235 let narrow_matcher = narrow::matcher(repo, warnings)?;
236 let sparse_matcher =
237 sparse::matcher(repo, Some(vec![target_rev]), warnings)?;
238
239 let narrow_matcher = narrow_matcher.as_ref();
240 let actions = compute_actions(
241 repo,
242 dirstate.get_map(),
243 &wc_manifest,
244 &target_manifest,
245 &narrow_matcher,
246 &sparse_matcher.as_ref(),
247 warnings,
248 update_config,
249 )?;
250
251 progress.update(0, Some(actions.len() as u64));
252 repo.manually_set_parents(DirstateParents {
253 p1: repo.node(target_rev.into()).expect("target node should exist"),
254 p2: NULL_NODE,
255 })?;
256
257 let (file_updates_sender, file_updates_receiver) =
258 crossbeam_channel::unbounded();
259 let (removals_sender, removals_receiver) = crossbeam_channel::unbounded();
260
261 apply_actions(
262 repo,
263 actions,
264 progress,
265 file_updates_sender,
266 removals_sender,
267 warnings,
268 update_config,
269 )?;
270
271 // TODO try to run this concurrently to update the dirstate while we're
272 // still writing out the working copy to see if that improves performance.
273 let stats = update_dirstate(
274 repo,
275 dirstate,
276 file_updates_receiver,
277 Some(removals_receiver),
278 update_config.devel_abort_dirstate,
279 UpdateKind::FromClean,
280 )?;
281
282 Ok(stats)
283 }
284
285 /// Statistics about the update we've just done
286 #[derive(Debug, Default)]
287 pub struct UpdateStats {
288 /// The number of files that were added
289 pub added: usize,
290 /// The number of files that were updated without merge
291 pub updated: usize,
292 /// The number of files that were merged
293 pub merged: usize,
294 /// The number of files that were removed
295 pub removed: usize,
296 /// The number of files that were left unresolved
297 pub unresolved: usize,
298 }
299
300 /// Represents an update to be applied to the working copy
301 #[derive(Debug, PartialEq)]
302 pub struct WorkingCopyFileUpdate<'a> {
303 /// The manifest entry metadata from which to get the file information
304 entry: ExpandedManifestEntry<'a>,
305 /// Whether to backup this path before trying to update it
306 backup: bool,
307 /// Whether the flags for this pre-existing file have changed. `false` if
308 /// the file doesn't exist in source.
309 flags_differ: bool,
310 }
311
312 /// Represents the actions to take on the working copy for an update
313 #[derive(Debug)]
314 pub struct MergeActions<'a> {
315 /// Files whose only flags have changed (exec or link toggled either way)
316 pub flags: Vec<(&'a HgPath, ManifestFlags)>,
317 /// Files that need to be updated
318 pub get: Vec<WorkingCopyFileUpdate<'a>>,
319 /// Files that need to be created
320 pub create: Vec<ExpandedManifestEntry<'a>>,
321 /// Files that need to be removed
322 pub remove: Vec<&'a HgPath>,
323 }
324
325 impl<'paths> MergeActions<'paths> {
326 fn new() -> Self {
327 Self {
328 flags: vec![],
329 get: vec![],
330 create: vec![],
331 remove: vec![],
332 // Adjust [`Self::len`] and [`Self::files`] when changing fields!
333 }
334 }
335 pub fn len(&self) -> usize {
336 self.flags.len()
337 + self.get.len()
338 + self.create.len()
339 + self.remove.len()
340 }
341
342 pub fn is_empty(&self) -> bool {
343 self.len() == 0
344 }
345
346 /// Retains files for which `retain_fn` returns `true`
347 pub fn retain_files(
348 &mut self,
349 mut retain_fn: impl FnMut(&'paths HgPath) -> bool,
350 ) {
351 self.flags.retain(|item| retain_fn(item.0));
352 self.get.retain(|item| retain_fn(item.path()));
353 self.create.retain(|item| retain_fn(item.0));
354 self.remove.retain(|item| retain_fn(item));
355 }
356 }
357
358 /// A change to the dirstate required after a workspace update done
359 /// by hg itself
360 pub struct DirstateUpdate<'a> {
361 pub path: &'a HgPath,
362 pub mode: u32,
363 pub size: usize,
364 pub timestamp: TruncatedTimestamp,
365 }
366
367 impl<'a> DirstateUpdate<'a> {
368 fn from_metadata(
369 path: &'a HgPath,
370 full_path: &Path,
371 meta: Metadata,
372 ) -> Result<Self, HgError> {
373 let truncated_timestamp = TruncatedTimestamp::for_mtime_of(&meta)
374 .when_reading_file(full_path)?;
375 Ok(Self {
376 path,
377 mode: meta.mode(),
378 size: meta.len().try_into().expect("file too large"),
379 timestamp: truncated_timestamp,
380 })
381 }
382 }
383
384 struct IsExec(bool);
385
386 fn mode_for_create_syscall(IsExec(is_exec): IsExec) -> u32 {
387 if is_exec {
388 0o777
389 } else {
390 0o666
391 }
392 }
393
394 /// Change the file to a symlink or set executable permissions, if any flag
395 /// information asks for it. Return the new mode, size and mtime to put
396 /// into dirstate, if any change was made.
397 pub fn apply_flags_to_file<'a>(
398 path_in_repo: &'a HgPath,
399 path: &Path,
400 flags: ManifestFlags,
401 ) -> Result<Option<DirstateUpdate<'a>>, HgError> {
402 let meta = path.symlink_metadata().when_reading_file(path)?;
403 let flags_link = flags.is_link();
404 let disk_link = meta.is_symlink();
405 let flags_exec = flags.is_exec();
406
407 if flags_link && !disk_link {
408 // Switch file to link
409 let contents = std::fs::read(path).when_reading_file(path)?;
410 std::fs::remove_file(path).when_writing_file(path)?;
411 let target = get_path_from_bytes(&contents);
412 if std::os::unix::fs::symlink(target, path)
413 .when_writing_file(path)
414 .is_err()
415 {
416 // failed to create the link, rewrite the file
417 std::fs::write(path, &contents).when_writing_file(path)?;
418 }
419 let meta = path.symlink_metadata().when_reading_file(path)?;
420 return Ok(Some(DirstateUpdate::from_metadata(
421 path_in_repo,
422 path,
423 meta,
424 )?));
425 }
426 if !flags_link && disk_link {
427 // Switch link to file: write the link target as the file contents
428 let target = std::fs::read_link(path).when_reading_file(path)?;
429 let target_bytes = get_bytes_from_path(target);
430 std::fs::remove_file(path).when_writing_file(path)?;
431 let mode = mode_for_create_syscall(IsExec(flags_exec));
432 let mut f = std::fs::OpenOptions::new()
433 .write(true)
434 .create_new(true)
435 .mode(mode)
436 .open(path)
437 .when_writing_file(path)?;
438 f.write_all(&target_bytes).when_writing_file(path)?;
439 let meta = f.metadata().when_reading_file(path)?;
440 return Ok(Some(DirstateUpdate::from_metadata(
441 path_in_repo,
442 path,
443 meta,
444 )?));
445 }
446 let disk_exec = is_executable(&meta);
447 if meta.nlink() > 1 && flags_exec != disk_exec {
448 // The file is a hardlink, break it
449 let contents = std::fs::read(path).when_reading_file(path)?;
450 std::fs::remove_file(path).when_writing_file(path)?;
451 std::fs::write(path, contents).when_writing_file(path)?;
452 }
453
454 let mode = meta.mode();
455
456 let mode = if flags_exec && !disk_exec {
457 // Turn on +x for every +r bit when making a file executable
458 // and obey umask.
459 let mode = mode | ((mode & 0o444) >> 2) & !get_umask();
460 std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))
461 .when_writing_file(path)?;
462 Some(mode)
463 } else if !flags_exec && disk_exec {
464 // Turn off all +x bits
465 let mode = mode & 0o666;
466 std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))
467 .when_writing_file(path)?;
468 Some(mode)
469 } else {
470 None
471 };
472 match mode {
473 None => Ok(None),
474 Some(mode) => {
475 let mut update =
476 DirstateUpdate::from_metadata(path_in_repo, path, meta)?;
477 update.mode = mode;
478 Ok(Some(update))
479 }
480 }
481 }
482
483 fn working_copy_remove(
484 path: impl AsRef<Path>,
485 vfs: &impl Vfs,
486 remove_empty_dirs: bool,
487 ) -> Result<(), HgError> {
488 vfs.unlink(path.as_ref())?;
489 if remove_empty_dirs {
490 let path = vfs.base().join(path.as_ref());
491
492 let mut current = path;
493 while let Some(Ok(parent)) = current.parent().map(|p| p.canonicalize())
494 {
495 if vfs.base() == parent {
496 break;
497 }
498 if std::fs::remove_dir(&parent).is_err() {
499 break;
500 }
501 current = parent;
502 }
503 }
504 Ok(())
505 }
506
507 /// Apply the computed `actions` to the working copy.
508 #[allow(clippy::too_many_arguments)]
509 #[tracing::instrument(level = "debug", skip_all)]
510 fn apply_actions<'a: 'b, 'b>(
511 repo: &Repo,
512 actions: MergeActions<'a>,
513 progress: &dyn Progress,
514 file_updates: Sender<DirstateUpdate<'b>>,
515 file_removals: Sender<&'b HgPath>,
516 warnings: &HgWarningSender,
517 update_config: &UpdateConfig,
518 ) -> Result<(), HgError> {
519 let options = default_revlog_options(
520 repo.config(),
521 repo.requirements(),
522 crate::revlog::RevlogType::Filelog,
523 )?;
524 let working_copy_vfs = repo.working_directory_vfs();
525 let auditor = PathAuditor::new(working_copy_vfs.base());
526
527 let work_closure =
528 |(_dir, chunk): (&HgPath, Vec<&'a HgPath>)| -> Result<(), HgError> {
529 let chunk_size = chunk.len();
530 for hg_path in chunk {
531 auditor.audit_path(hg_path)?;
532 let path = hg_path_to_path_buf(hg_path)?;
533 if let Err(e) = working_copy_remove(
534 &path,
535 &working_copy_vfs,
536 update_config.remove_empty_dirs,
537 )
538 .io_not_found_as_none()
539 {
540 warnings.send(UpdateWarning::UnlinkFailure(path, e));
541 }
542 file_removals.send(hg_path).expect("channel should be open");
543 }
544 progress.increment(chunk_size as u64, None);
545 Ok(())
546 };
547
548 let cwd_exists = std::env::current_dir().is_ok();
549
550 let removing_span =
551 tracing::span!(tracing::Level::TRACE, "removing files").entered();
552 maybe_parallel(
553 "update",
554 chunk_tracked_files(actions.remove, false).1,
555 work_closure,
556 update_config.workers,
557 )?;
558 removing_span.exit();
559
560 if cwd_exists && std::env::current_dir().is_err() {
561 // cwd was removed in the course of removing files; print a helpful
562 // warning.
563 warnings.send(UpdateWarning::CwdRemoved);
564 }
565
566 let (symlinks, chunks) = chunk_tracked_files(actions.get, true);
567 create_working_copy(
568 chunks,
569 symlinks,
570 &repo.working_directory_vfs(),
571 &repo.store_vfs(),
572 options,
573 &file_updates,
574 progress,
575 update_config,
576 )?;
577
578 // Change flags on any files that only need their flags changed
579 for (path, flags) in actions.flags {
580 progress.increment(1, None);
581 let full_path =
582 repo.working_directory_vfs().join(hg_path_to_path_buf(path)?);
583 if let Some(distate_update) =
584 apply_flags_to_file(path, &full_path, flags)?
585 {
586 file_updates.send(distate_update).expect("channel must be open");
587 }
588 }
589
590 Ok(())
591 }
592
593 /// Warnings that can occur during the update process
594 #[derive(Debug)]
595 pub enum UpdateWarning {
596 /// We've failed to remove a file
597 UnlinkFailure(PathBuf, HgError),
598 /// Current directory was removed
599 CwdRemoved,
600 /// We have a conflict with an untracked file
601 UntrackedConflict(HgPathBuf),
602 /// We are replacing a conflicting untracked file
603 ReplacingUntracked(HgPathBuf),
604 }
605
606 /// What to do when encountering a file conflict on disk. There is a different
607 /// config for unknown and ignored files.
608 #[derive(Copy, Clone, Debug)]
609 pub enum FileConflictConfig {
610 /// Abort the update process entirely
611 Abort,
612 /// Warn about each file
613 Warn,
614 /// Ignore all conflicts
615 Ignore,
616 }
617
618 impl FileConflictConfig {
619 pub fn new(config: &str, value: Option<&str>) -> Result<Self, HgError> {
620 match value {
621 Some("abort") => Ok(Self::Abort),
622 Some("warn") => Ok(Self::Warn),
623 Some("ignore") => Ok(Self::Ignore),
624 _ => Err(HgError::abort(
625 format!(
626 "{} not valid, expected 'abort', 'ignore' or 'warn'",
627 config
628 ),
629 exit_codes::CONFIG_ERROR_ABORT,
630 None,
631 )),
632 }
633 }
634 }
635
636 /// Compute what actions need to be taken to update the working copy to the
637 /// target revision.
638 #[tracing::instrument(level = "debug", skip_all)]
639 #[allow(clippy::too_many_arguments)]
640 pub fn compute_actions<
641 'manifests,
642 'm1: 'manifests,
643 'm2: 'manifests,
644 'ma: 'manifests,
645 >(
646 repo: &Repo,
647 dirstate: &DirstateMap,
648 wc_manifest: &'m1 Manifest,
649 target_manifest: &'m2 Manifest,
650 narrow_matcher: &'m1 impl Matcher,
651 sparse_matcher: &impl Matcher,
652 warnings: &HgWarningSender,
653 update_config: &UpdateConfig,
654 ) -> Result<MergeActions<'manifests>, HgError> {
655 let mut actions =
656 manifest_actions(wc_manifest, target_manifest, narrow_matcher)?;
657 if !actions.create.is_empty() {
658 let mut old_gets = std::mem::take(&mut actions.get);
659 let file_conflicts = check_unknown_files(
660 repo,
661 dirstate,
662 &actions,
663 target_manifest,
664 warnings,
665 update_config,
666 )?;
667
668 if file_conflicts.len() >= 100 {
669 // There will be few conflicts most of the time, and they are
670 // sorted,so only create and use a HashSet if we need to match
671 // against many paths.
672 let file_conflicts: HashSet<_> =
673 file_conflicts.into_iter().collect();
674 let new_gets = actions.create.iter().copied().map(|c| {
675 let backup = file_conflicts.contains(&c.0);
676 WorkingCopyFileUpdate { entry: c, backup, flags_differ: false }
677 });
678 old_gets.extend(new_gets);
679 } else {
680 // This is the same as the other arm, it's just not worth the
681 // complexity to build a macro for this, so just copy.
682 let new_gets = actions.create.iter().copied().map(|c| {
683 let backup = file_conflicts.contains(&c.0);
684 WorkingCopyFileUpdate { entry: c, backup, flags_differ: false }
685 });
686 old_gets.extend(new_gets);
687 }
688 actions.get = old_gets;
689 // Don't `sort_unstable` since we're in the special case of
690 // concatenating two sorted sequences.
691 actions.get.sort_by_key(|e| e.entry.0);
692 // All creates have been transformed into gets, free some memory and
693 // make the total correct again.
694 std::mem::take(&mut actions.create);
695 }
696 if repo.has_sparse() {
697 filter_sparse_actions(
698 repo,
699 sparse_matcher,
700 narrow_matcher,
701 target_manifest,
702 &mut actions,
703 warnings,
704 )?;
705 }
706 Ok(actions)
707 }
708
709 /// Filter actions that would fall outside of the sparse profile
710 fn filter_sparse_actions<'a>(
711 repo: &Repo,
712 sparse_matcher: &impl Matcher,
713 narrow_matcher: &'a impl Matcher,
714 target_manifest: &'a Manifest,
715 actions: &mut MergeActions<'a>,
716 warnings: &HgWarningSender,
717 ) -> Result<(), HgError> {
718 let old_sparse_matcher = sparse::matcher(repo, None, warnings)?;
719 if old_sparse_matcher.matches_everything() {
720 return Ok(());
721 }
722
723 let mut to_remove = vec![];
724 let profiles = sparse::active_profiles(repo, warnings)?;
725 let mut profile_changed = false;
726 actions.retain_files(|path| {
727 if !profile_changed && profiles.contains(path.as_bytes()) {
728 profile_changed = true
729 }
730 let matches = sparse_matcher.matches(path);
731 if !matches {
732 to_remove.push(path);
733 }
734 matches
735 });
736 actions.remove.extend(to_remove);
737 if profile_changed {
738 let mut to_remove = vec![];
739 let mut to_get = vec![];
740 let files = FilesForRevBorrowed::new(target_manifest, narrow_matcher);
741 // If an active profile changed during the update, refresh the checkout
742 for entry in files.iter() {
743 let (path, node, flags) = entry?;
744 let old = old_sparse_matcher.matches(path);
745 let new = sparse_matcher.matches(path);
746 if !old && new {
747 to_get.push(WorkingCopyFileUpdate {
748 entry: (path, node, flags),
749 backup: false,
750 flags_differ: false,
751 });
752 } else if old && !new {
753 to_remove.push(path);
754 }
755 }
756 actions.get.extend(to_get);
757 actions.remove.extend(to_remove);
758 }
759 Ok(())
760 }
761
762 /// Gathers a list of all unknown (potentially ignored) files and either abort,
763 /// warn or ignore them depending on the config, and returns that list.
764 fn check_unknown_files<'a>(
765 repo: &Repo,
766 dirstate: &DirstateMap,
767 merge_result: &'a MergeActions,
768 p2_manifest: &Manifest,
769 warnings: &HgWarningSender,
770 update_config: &UpdateConfig,
771 ) -> Result<Vec<&'a HgPath>, HgError> {
772 let check_exec = check_exec(repo.working_directory_path());
773 let filelog_options = default_revlog_options(
774 repo.config(),
775 repo.requirements(),
776 RevlogType::Filelog,
777 )?;
778 let (unknown_sender, unknown_receiver) = crossbeam_channel::unbounded();
779 let (ignored_sender, ignored_receiver) = crossbeam_channel::unbounded();
780 let ignore_func = repo.get_ignore_function(warnings)?;
781 let working_directory_vfs = repo.working_directory_vfs();
782 let store_vfs = repo.store_vfs();
783 merge_result.create.par_iter().try_for_each(
784 |(path, _, _)| -> Result<(), HgError> {
785 if is_conflicting_unknown_file(
786 path,
787 dirstate,
788 p2_manifest,
789 check_exec,
790 filelog_options,
791 &working_directory_vfs,
792 &store_vfs,
793 )? {
794 if ignore_func(path) {
795 ignored_sender.send(*path).expect("channel must be open");
796 } else {
797 unknown_sender.send(*path).expect("channel must be open");
798 }
799 }
800 Ok(())
801 },
802 )?;
803 drop(ignored_sender);
804 drop(unknown_sender);
805 let mut ignored_conflicts: Vec<&HgPath> =
806 ignored_receiver.into_iter().collect();
807 let unknown_conflicts: Vec<&HgPath> =
808 unknown_receiver.into_iter().collect();
809
810 let (mut abort_conflicts, mut warn_conflicts): (
811 Vec<&HgPath>,
812 Vec<&HgPath>,
813 ) = match (update_config.ignored_conflict, update_config.unknown_conflict) {
814 (FileConflictConfig::Abort, FileConflictConfig::Abort) => (
815 ignored_conflicts
816 .iter()
817 .chain(unknown_conflicts.iter())
818 .copied()
819 .collect(),
820 vec![],
821 ),
822 (FileConflictConfig::Abort, FileConflictConfig::Warn) => {
823 (ignored_conflicts.to_owned(), unknown_conflicts.to_owned())
824 }
825 (FileConflictConfig::Abort, FileConflictConfig::Ignore) => {
826 (ignored_conflicts.to_owned(), vec![])
827 }
828 (FileConflictConfig::Warn, FileConflictConfig::Abort) => {
829 (unknown_conflicts.to_owned(), ignored_conflicts.to_owned())
830 }
831 (FileConflictConfig::Warn, FileConflictConfig::Warn) => (
832 vec![],
833 ignored_conflicts
834 .iter()
835 .chain(unknown_conflicts.iter())
836 .copied()
837 .collect(),
838 ),
839 (FileConflictConfig::Warn, FileConflictConfig::Ignore) => {
840 (vec![], ignored_conflicts.to_owned())
841 }
842 (FileConflictConfig::Ignore, FileConflictConfig::Abort) => {
843 (unknown_conflicts.to_owned(), vec![])
844 }
845 (FileConflictConfig::Ignore, FileConflictConfig::Warn) => {
846 (vec![], unknown_conflicts.to_owned())
847 }
848 (FileConflictConfig::Ignore, FileConflictConfig::Ignore) => {
849 (vec![], vec![])
850 }
851 };
852
853 if !abort_conflicts.is_empty() {
854 abort_conflicts.sort_unstable();
855 for conflict in abort_conflicts {
856 let warn = UpdateWarning::UntrackedConflict(conflict.to_owned());
857 warnings.send(warn);
858 }
859 return Err(HgError::abort(
860 "untracked files in working directory differ \
861 from files in requested revision",
862 exit_codes::STATE_ERROR,
863 None,
864 ));
865 }
866 if !warn_conflicts.is_empty() {
867 warn_conflicts.sort_unstable();
868 for conflict in warn_conflicts {
869 let warn = UpdateWarning::ReplacingUntracked(conflict.to_owned());
870 warnings.send(warn);
871 }
872 }
873 ignored_conflicts.extend(unknown_conflicts);
874 // The two vecs are sorted, then concatenated, so use stable sorting.
875 ignored_conflicts.sort();
876 Ok(ignored_conflicts)
877 }
878
879 /// Whether this path is unknown (or ignored) and conflicts with the update
880 fn is_conflicting_unknown_file(
881 path: &HgPath,
882 dirstate: &DirstateMap,
883 p2_manifest: &Manifest,
884 check_exec: bool,
885 filelog_open_options: RevlogOpenOptions,
886 wc_vfs: &VfsImpl,
887 store_vfs: &VfsImpl,
888 ) -> Result<bool, HgError> {
889 Ok(!dirstate.has_node(path)?
890 && is_file_or_link_check_dirs(path, wc_vfs).unwrap_or(false)
891 // TODO write is_entry_modified to re-use the entry we've already
892 // resolved during the diff
893 && !matches!(is_file_modified(
894 wc_vfs,
895 store_vfs,
896 check_exec,
897 p2_manifest,
898 path,
899 filelog_open_options,
900 )?, FileCompOutcome::Clean | FileCompOutcome::Deleted))
901 }
902
903 /// Whether this path if a file or a symlink, taking care of not traversing
904 /// symlinks.
905 fn is_file_or_link_check_dirs(
906 path: &HgPath,
907 working_directory_vfs: &impl Vfs,
908 ) -> Result<bool, HgError> {
909 for dir in find_dirs_recursive_no_root(path) {
910 check_filesystem_single(
911 working_directory_vfs.base().join(hg_path_to_path_buf(path)?),
912 dir,
913 path,
914 )?;
915 }
916 let path = working_directory_vfs.base().join(hg_path_to_path_buf(path)?);
917 Ok(path.is_file() || path.is_symlink())
918 }
919
920 /// Return the actions to be taken to get from the current manifest to the
921 /// target manifest.
922 #[tracing::instrument(level = "debug", skip_all)]
923 fn manifest_actions<'manifests, 'm1: 'manifests, 'm2: 'manifests>(
924 wc_manifest: &'m1 Manifest,
925 target_manifest: &'m2 Manifest,
926 narrow_matcher: &impl Matcher,
927 ) -> Result<MergeActions<'manifests>, HgError> {
928 let diff = wc_manifest.diff(target_manifest)?;
929
930 let mut actions = MergeActions::new();
931
932 for (wc_entry, p2_entry) in diff.into_iter() {
933 match (wc_entry, p2_entry) {
934 (Some(wc_entry), Some(p2_entry)) => {
935 let filename = wc_entry.path;
936 let p2_node_id = p2_entry.node_id()?;
937 let nodes_equal = wc_entry.node_id()? == p2_node_id;
938 let flags_differ = wc_entry.flags != p2_entry.flags;
939 if nodes_equal && flags_differ {
940 actions.flags.push((filename, p2_entry.flags));
941 } else {
942 actions.get.push(WorkingCopyFileUpdate {
943 entry: (filename, p2_node_id, p2_entry.flags),
944 backup: false,
945 flags_differ,
946 });
947 }
948 }
949 (Some(wc_entry), None) => {
950 let filename = wc_entry.path;
951 actions.remove.push(filename);
952 }
953 (None, Some(p2_entry)) => {
954 actions.create.push((
955 p2_entry.path,
956 p2_entry.node_id()?,
957 p2_entry.flags,
958 ));
959 }
960 (None, None) => unreachable!("diff missing from both sides"),
961 }
962 }
963 if !narrow_matcher.matches_everything() {
964 filter_narrow_actions(narrow_matcher, &mut actions)
965 }
966 Ok(actions)
967 }
968
969 /// Filters actions that would touch files outside of the narrowspec
970 fn filter_narrow_actions(matcher: &impl Matcher, actions: &mut MergeActions) {
971 actions.retain_files(|file| matcher.matches(file));
972 }
973
974 /// Preallocated size of Vec holding directory contents. This aims at
975 /// preventing the need for re-allocating the Vec in most cases.
976 ///
977 /// The value is arbitrarily picked as a little over an average number of files
978 /// per directory done by looking at a few larger open-source repos.
979 /// Most of the runtime is IO anyway, so this doesn't matter too much.
980 const FILES_PER_DIRECTORY: usize = 16;
981
982 /// Abstraction over types of path information to help with parallel chunking
983 pub trait ChunkableItem<'a> {
984 /// Returns the path of this item
985 fn path(&self) -> &'a HgPath;
986 /// Whether this path is a symlink
987 fn is_link(&self) -> bool;
988 }
989
990 impl<'a> ChunkableItem<'a> for WorkingCopyFileUpdate<'a> {
991 fn path(&self) -> &'a HgPath {
992 self.entry.0
993 }
994
995 fn is_link(&self) -> bool {
996 self.entry.2.is_link()
997 }
998 }
999
1000 impl<'a> ChunkableItem<'a> for &'a HgPath {
1001 fn path(&self) -> &'a HgPath {
1002 self
1003 }
1004
1005 fn is_link(&self) -> bool {
1006 // This impl is made for simpler paths, which don't concern themselves
1007 // with whether this is a link (file removals and tests).
1008 false
1009 }
1010 }
1011
1012 /// Represents a directory with its direct descendants
1013 type DirectoryChunk<'a, T> = (&'a HgPath, Vec<T>);
1014
1015 /// Chunk files per directory prefix, so almost every directory is handled
1016 /// in a separate thread, which works around the FS inode mutex.
1017 /// Chunking less (and doing approximately `files_count`/`threads`) actually
1018 /// ends up being less performant: my hypothesis is `rayon`'s work stealing
1019 /// being more efficient with tasks of varying lengths.
1020 ///
1021 /// If `separate_symlinks` is true, the first item of the returned tuple will
1022 /// be the same chunked structure, but only for the symlinks, separate from
1023 /// the normal files. See [`create_working_copy`] for why.
1024 #[tracing::instrument(level = "debug", skip_all)]
1025 fn chunk_tracked_files<'a, T: ChunkableItem<'a>>(
1026 tracked_files: Vec<T>,
1027 separate_symlinks: bool,
1028 ) -> (Vec<DirectoryChunk<'a, T>>, Vec<DirectoryChunk<'a, T>>) {
1029 if tracked_files.is_empty() {
1030 return (vec![], vec![]);
1031 }
1032 let files_count = tracked_files.len();
1033 // TODO don't chunk if we know we'll end up doing it sequentially?
1034 // Refactor the heuristic for parallelism somewhere
1035
1036 let mut chunks = Vec::with_capacity(files_count / FILES_PER_DIRECTORY);
1037 let mut symlinks = vec![];
1038
1039 let mut current_chunk = Vec::with_capacity(FILES_PER_DIRECTORY);
1040 let mut current_symlinks = vec![];
1041 let mut tracked_files = tracked_files.into_iter().peekable();
1042 let mut last_directory =
1043 tracked_files.peek().expect("empty tracked files").path().parent();
1044
1045 for file_info in tracked_files {
1046 let current_directory = file_info.path().parent();
1047 let different_directory = current_directory != last_directory;
1048 if different_directory {
1049 if separate_symlinks && !current_symlinks.is_empty() {
1050 symlinks.push((last_directory, current_symlinks));
1051 current_symlinks = vec![];
1052 }
1053 if !current_chunk.is_empty() {
1054 chunks.push((last_directory, current_chunk));
1055 current_chunk = Vec::with_capacity(FILES_PER_DIRECTORY);
1056 }
1057 }
1058 if separate_symlinks && file_info.is_link() {
1059 current_symlinks.push(file_info);
1060 } else {
1061 current_chunk.push(file_info);
1062 }
1063 last_directory = current_directory;
1064 }
1065 symlinks.push((last_directory, current_symlinks));
1066 chunks.push((last_directory, current_chunk));
1067 (symlinks, chunks)
1068 }
1069
1070 /// Run `work_closure` either serially or in parallel depending on its
1071 /// `work_arg`, and the `workers` config.
1072 ///
1073 /// Allows the `work_closure` to abort, but does not do anything with the
1074 /// output, the closure should communicate through something like channels.
1075 pub fn maybe_parallel<T: Send>(
1076 topic: &str,
1077 work_arg: Vec<T>,
1078 work_closure: impl Fn(T) -> Result<(), HgError> + Sync + Send,
1079 mut workers: Option<usize>,
1080 ) -> Result<(), HgError> {
1081 if work_arg.len() < 10 {
1082 workers = Some(1);
1083 }
1084 if let Some(workers) = workers {
1085 if workers > 1 {
1086 // Work in parallel, potentially restricting the number of threads
1087 match rayon::ThreadPoolBuilder::new().num_threads(workers).build() {
1088 Err(error) => Err(HgError::abort(
1089 error.to_string(),
1090 exit_codes::ABORT,
1091 None,
1092 )),
1093 Ok(pool) => {
1094 tracing::debug!(
1095 "restricting {} to {} threads",
1096 topic,
1097 workers
1098 );
1099 pool.install(|| {
1100 work_arg.into_par_iter().try_for_each(work_closure)
1101 })
1102 }
1103 }
1104 } else {
1105 // Work sequentially, don't even invoke rayon
1106 work_arg.into_iter().try_for_each(work_closure)
1107 }
1108 } else {
1109 // Work in parallel by default in the global threadpool
1110 let _ = cap_default_rayon_threads();
1111 work_arg.into_par_iter().with_min_len(10).try_for_each(work_closure)
1112 }
1113 }
1114
1115 /// Contains the information for all files or all symlinks, chunked by directory
1116 type ChunkedFileInfo<'a> = Vec<DirectoryChunk<'a, WorkingCopyFileUpdate<'a>>>;
1117
1118 /// Take both chunked file information and update the working copy, possibly
1119 /// in parallel.
1120 #[tracing::instrument(level = "debug", skip_all)]
1121 #[allow(clippy::too_many_arguments)]
1122 fn create_working_copy<'a: 'b, 'b>(
1123 chunks: ChunkedFileInfo<'a>,
1124 symlinks: ChunkedFileInfo<'a>,
1125 working_copy_vfs: &VfsImpl,
1126 store_vfs: &VfsImpl,
1127 options: RevlogOpenOptions,
1128 files_sender: &Sender<DirstateUpdate<'b>>,
1129 progress: &dyn Progress,
1130 update_config: &UpdateConfig,
1131 ) -> Result<(), HgError> {
1132 let auditor = PathAuditor::new(working_copy_vfs.base());
1133
1134 let work_closure = |(dir_path, chunk): (_, Vec<_>)| -> Result<(), HgError> {
1135 let progress_incr = chunk.len() as u64;
1136 working_copy_worker(
1137 dir_path,
1138 chunk,
1139 working_copy_vfs,
1140 store_vfs,
1141 options,
1142 files_sender,
1143 &auditor,
1144 update_config,
1145 )?;
1146 progress.increment(progress_incr, None);
1147 Ok(())
1148 };
1149
1150 // First, create all the symlinks sequentially.
1151 // We need to make sure that no two threads will race:
1152 // - A: successfully audit file a/b
1153 // - B: correctly delete empty `a` folder
1154 // - B: correctly create `a` symlink
1155 // - A: incorrectly create `a/b`, traversing the symlink `a`
1156 // This can only happen because Mercurial can store an invalid commit:
1157 //
1158 // $ mkdir update-symlink-out
1159 // $ hg init update-symlink
1160 // $ cd update-symlink
1161 // $ ln -s ../update-symlink-out a
1162 // $ hg commit -qAm 'symlink a -> ../update-symlink-out'
1163 // $ hg rm a
1164 // $ mkdir a && touch a/b
1165 // $ hg commit -qAm 'file a/b' a/b
1166 //
1167 // The crucial detail is in the last line: committing *only* `a/b` succeeds,
1168 // but `hg` should either refuse or also commit the removal of `a`.
1169 //
1170 // This needs to be fixed in `commit`, but regardless will always exist in
1171 // the wild, so catch it here.
1172
1173 let symlinks_span =
1174 tracing::span!(tracing::Level::TRACE, "adding symlinks").entered();
1175 maybe_parallel("update", symlinks, work_closure, update_config.workers)?;
1176 symlinks_span.exit();
1177
1178 let files_span =
1179 tracing::span!(tracing::Level::TRACE, "adding files").entered();
1180 // Then take care of the normal files
1181 let res =
1182 maybe_parallel("update", chunks, work_closure, update_config.workers);
1183 files_span.exit();
1184 res
1185 }
1186
1187 /// Returns the backup path for `path`, relative to the `working_copy_vfs`'s
1188 /// base. The backup root can be overridden by the config.
1189 pub fn backup_path(
1190 orig_backup_path: Option<&[u8]>,
1191 working_copy_vfs: &VfsImpl,
1192 path: &Path,
1193 ) -> Result<PathBuf, HgError> {
1194 // TODO improve the VFS trait and use it everywhere:
1195 // - makedirs
1196 // - is_dir, is_symlink
1197 // - join from hg_path
1198 // - etc.
1199 let vfs = if let Some(orig_path) = orig_backup_path {
1200 if orig_path.is_empty() {
1201 return Ok(working_copy_vfs.join(path.with_extension("orig")));
1202 }
1203 VfsImpl::new(
1204 working_copy_vfs.join(get_path_from_bytes(orig_path)),
1205 false,
1206 PathEncoding::None,
1207 )
1208 } else {
1209 return Ok(working_copy_vfs.join(path.with_extension("orig")));
1210 };
1211
1212 let full_path = vfs.join(path);
1213 let backup_dir = full_path.parent().expect("file at root");
1214 let backup_meta = backup_dir.symlink_metadata().ok();
1215 if backup_meta.map(|m| !m.is_dir() || m.is_symlink()).unwrap_or(true) {
1216 // Remove any files that conflict with the backup file's path
1217 for ancestor in full_path.ancestors() {
1218 if ancestor.is_file() || ancestor.is_symlink() {
1219 tracing::debug!(
1220 "removing conflicting file {}",
1221 backup_dir.display()
1222 );
1223 vfs.unlink(ancestor)?;
1224 break;
1225 }
1226 if ancestor == vfs.base() {
1227 break;
1228 }
1229 }
1230 tracing::debug!("creating {}", backup_dir.display());
1231 std::fs::create_dir_all(backup_dir).when_writing_file(backup_dir)?;
1232 }
1233 let full_path_meta = full_path.symlink_metadata().ok();
1234 if full_path_meta.map(|m| m.is_dir() && !m.is_symlink()).unwrap_or(false) {
1235 tracing::debug!(
1236 "removing conflicting directory {}",
1237 full_path.display()
1238 );
1239 std::fs::remove_dir_all(&full_path).with_context(|| {
1240 crate::errors::IoErrorContext::RemovingFile(full_path.to_owned())
1241 })?;
1242 }
1243 Ok(full_path
1244 .strip_prefix(working_copy_vfs.base())
1245 .expect("backup path should be relative to the working copy vfs")
1246 .to_owned())
1247 }
1248
1249 /// Represents a work unit for a single thread, responsible for this set of
1250 /// files and restoring them to the working copy.
1251 #[allow(clippy::too_many_arguments)]
1252 fn working_copy_worker<'a: 'b, 'b>(
1253 dir_path: &HgPath,
1254 chunk: Vec<WorkingCopyFileUpdate<'a>>,
1255 working_copy_vfs: &VfsImpl,
1256 store_vfs: &VfsImpl,
1257 options: RevlogOpenOptions,
1258 files_sender: &Sender<DirstateUpdate<'b>>,
1259 auditor: &PathAuditor,
1260 update_config: &UpdateConfig,
1261 ) -> Result<(), HgError> {
1262 let dir_path =
1263 hg_path_to_path_buf(dir_path).expect("invalid path in manifest");
1264 let dir_path = working_copy_vfs.join(dir_path);
1265 std::fs::create_dir_all(&dir_path).when_writing_file(&dir_path)?;
1266
1267 if INTERRUPT_RECEIVED.load(Ordering::Relaxed) {
1268 // Stop working, the user has requested that we stop
1269 return Err(HgError::InterruptReceived);
1270 }
1271
1272 for WorkingCopyFileUpdate { entry, backup, flags_differ } in chunk {
1273 let (file, file_node, flags) = entry;
1274 if backup {
1275 // If a file or directory exists with the same name, back that
1276 // up. Otherwise, look to see if there is a file that conflicts
1277 // with a directory this file is in, and if so, back that up.
1278 let file_path = hg_path_to_path_buf(file)?;
1279 let mut conflicting = working_copy_vfs.base().join(&file_path);
1280 let conflict_exists = match conflicting.symlink_metadata() {
1281 Ok(_) => true,
1282 Err(_) => {
1283 for ancestor in find_dirs_recursive_no_root(file) {
1284 let ancestor = hg_path_to_path_buf(ancestor)?;
1285 let ancestor = working_copy_vfs.base().join(ancestor);
1286 if ancestor.is_file() || ancestor.is_symlink() {
1287 conflicting = ancestor;
1288 }
1289 }
1290 conflicting.symlink_metadata().is_ok()
1291 }
1292 };
1293
1294 if conflict_exists {
1295 let orig = backup_path(
1296 update_config.orig_backup_path.as_deref(),
1297 working_copy_vfs,
1298 &file_path,
1299 )?;
1300 working_copy_vfs.rename(&conflicting, &orig, false)?;
1301 }
1302 }
1303 auditor.audit_path(file)?;
1304 let relative_path = hg_path_to_path_buf(file)?;
1305 let path = working_copy_vfs.join(&relative_path);
1306 // This handles the edge case of a previous unknown directory
1307 // conflicting with this creation. We've backed up anything relevant
1308 // by this point.
1309 if path.is_dir() && !path.is_symlink() {
1310 let dir_removal = std::fs::remove_dir(&path).with_context(|| {
1311 crate::errors::IoErrorContext::RemovingFile(path.to_owned())
1312 });
1313 if let Err(err) = dir_removal {
1314 // Give an error message instead of a traceback in the case
1315 // where the conflicting unknown directory is not empty
1316 match &err {
1317 HgError::IoError { error, .. }
1318 if error.kind()
1319 == std::io::ErrorKind::DirectoryNotEmpty =>
1320 {
1321 let msg = format!(
1322 "conflicting unknown directory '{}' is not empty",
1323 path.display()
1324 );
1325 return Err(HgError::abort_simple(msg));
1326 }
1327 _ => return Err(err),
1328 }
1329 }
1330 }
1331
1332 // Treemanifest is not supported
1333 assert!(!flags.is_tree());
1334
1335 let filelog = Filelog::open_vfs(store_vfs, file, options)?;
1336 let filelog_revision_data = &filelog.data_for_node(file_node)?;
1337 let file_data = filelog_revision_data.file_data()?;
1338
1339 if flags.is_link() {
1340 let target = get_path_from_bytes(file_data);
1341 let _ = working_copy_vfs.unlink(&path);
1342 if let Err(e) = std::os::unix::fs::symlink(target, &path) {
1343 // If the path already exists either:
1344 // - this symlink points to a different directory in this new
1345 // revision
1346 // - another process created this file while ignoring the lock
1347 // => error
1348 // - our check for the fast path is incorrect => error
1349 // - this is a malicious repo/bundle and this is symlink that
1350 // tries to write things where it shouldn't be able to.
1351 match e.kind() {
1352 std::io::ErrorKind::AlreadyExists => {
1353 let metadata = std::fs::symlink_metadata(&path)
1354 .when_reading_file(&path)?;
1355 if metadata.is_dir() {
1356 return Err(HgError::Path(
1357 HgPathErrorKind::TraversesSymbolicLink {
1358 // Technically it should be one of the
1359 // children, but good enough
1360 path: file
1361 .join(HgPath::new(b"*"))
1362 .to_owned(),
1363 symlink: file.to_owned(),
1364 }
1365 .into(),
1366 ));
1367 } else if metadata.is_symlink() {
1368 let _ = working_copy_vfs.unlink(&path);
1369 std::os::unix::fs::symlink(target, &path)
1370 .when_writing_file(&path)?;
1371 } else {
1372 return Err(e).when_writing_file(&path);
1373 }
1374 }
1375 _ => return Err(e).when_writing_file(&path),
1376 }
1377 }
1378 } else if update_config.atomic_file {
1379 working_copy_vfs.atomic_write(relative_path, file_data)?;
1380 } else {
1381 let mut f = working_copy_vfs.create_working_copy(&relative_path)?;
1382 f.write_all(file_data).when_writing_file(&path)?;
1383 }
1384
1385 if !flags.is_link() && (flags_differ || flags.is_exec()) {
1386 // Respect umask since this is an after-creation update
1387 let mode =
1388 mode_for_create_syscall(IsExec(flags.is_exec())) & !get_umask();
1389 std::fs::set_permissions(&path, Permissions::from_mode(mode))
1390 .when_writing_file(&path)?;
1391 }
1392
1393 let metadata =
1394 std::fs::symlink_metadata(&path).when_reading_file(&path)?;
1395
1396 let mode = metadata.mode();
1397
1398 files_sender
1399 .send(DirstateUpdate {
1400 path: file,
1401 mode,
1402 size: file_data.len(),
1403 timestamp: TruncatedTimestamp::for_mtime_of(&metadata)
1404 .when_reading_file(&path)?,
1405 })
1406 .expect("channel should not be closed");
1407 }
1408 Ok(())
1409 }
1410
1411 /// Update the dirstate to reflect the changes we've made to the working copy
1412 #[tracing::instrument(level = "debug", skip_all)]
1413 fn update_dirstate(
1414 repo: &Repo,
1415 dirstate: &mut OwningDirstateMap,
1416 files_receiver: Receiver<DirstateUpdate>,
1417 removals_receiver: Option<Receiver<&HgPath>>,
1418 devel_abort: bool,
1419 update_kind: UpdateKind,
1420 ) -> Result<UpdateStats, HgError> {
1421 if devel_abort {
1422 let msg = "simulated error while recording dirstate updates";
1423 return Err(HgError::abort_simple(msg));
1424 }
1425 let mut removed = 0;
1426
1427 if let Some(removals) = removals_receiver {
1428 for filename in removals.into_iter() {
1429 removed += 1;
1430 dirstate.drop_entry_and_copy_source(filename).map_err(|e| {
1431 HgError::abort(e.to_string(), exit_codes::ABORT, None)
1432 })?;
1433 }
1434 }
1435
1436 // (see the comments in `filter_ambiguous_files` in `merge.py` for more)
1437 // It turns out that (on Linux at least) the filesystem resolution time
1438 // for most filesystems is based on the HZ kernel config. Their internal
1439 // clocks do return nanoseconds if the hardware clock is precise enough,
1440 // which should be the case on most recent computers but are only updated
1441 // every few milliseconds at best (every "jiffy").
1442 //
1443 // We are still not concerned with fixing the race with other
1444 // processes that might modify the working copy right after it was created
1445 // within the same tick, because it is impossible to catch.
1446 // However, we might as well not race with operations that could run right
1447 // after this one, especially other Mercurial operations that could be
1448 // waiting for the wlock to change file contents and the dirstate.
1449 //
1450 // Thus: wait until the filesystem clock has ticked to filter ambiguous
1451 // entries and write the dirstate, but only for dirstate-v2, since v1 only
1452 // has second-level granularity and waiting for a whole second is too much
1453 // of a penalty in the general case.
1454 // Although we're assuming that people running dirstate-v2 on Linux
1455 // don't have a second-granularity FS (with the exclusion of NFS), users
1456 // can be surprising, and at some point in the future dirstate-v2 will
1457 // become the default. To that end, we limit the wait time to 100ms and
1458 // fall back to the filter method in case of a timeout.
1459 //
1460 // +------------+------+--------------+
1461 // | version | wait | filter level |
1462 // +------------+------+--------------+
1463 // | V1 | No | Second |
1464 // | V2 | Yes | Nanosecond |
1465 // | V2-slow-fs | No | Second |
1466 // +------------+------+--------------+
1467 let dirstate_v2 = repo.use_dirstate_v2();
1468
1469 // Let's ignore NFS right off the bat
1470 let mut fast_enough_fs = !is_on_nfs_mount(repo.working_directory_path());
1471 let fs_time_now = if dirstate_v2 && fast_enough_fs {
1472 match wait_until_fs_tick(repo.working_directory_path()) {
1473 None => None,
1474 Some(Ok(time)) => Some(time),
1475 Some(Err(time)) => {
1476 fast_enough_fs = false;
1477 Some(time)
1478 }
1479 }
1480 } else {
1481 filesystem_now(repo.working_directory_path())
1482 .ok()
1483 .map(TruncatedTimestamp::from)
1484 };
1485
1486 let mut updated = 0;
1487 let mut added = 0;
1488 for DirstateUpdate { path: filename, mode, size, timestamp: mtime } in
1489 files_receiver.into_iter()
1490 {
1491 updated += 1;
1492 // When using dirstate-v2 on a filesystem with reasonable performance
1493 // this is basically always true unless you get a mtime from the
1494 // far future.
1495 let has_meaningful_mtime = if let Some(fs_time) = fs_time_now {
1496 mtime.for_reliable_mtime_of_self(&fs_time).is_some_and(|t| {
1497 // Dirstate-v1 only has second-level information
1498 !t.second_ambiguous || dirstate_v2 && fast_enough_fs
1499 })
1500 } else {
1501 // We somehow failed to write to the filesystem, so don't store
1502 // the cache information.
1503 false
1504 };
1505
1506 let reset = DirstateEntryReset {
1507 filename,
1508 wc_tracked: true,
1509 p1_tracked: true,
1510 p2_info: false,
1511 has_meaningful_mtime,
1512 parent_file_data_opt: Some(ParentFileData {
1513 mode_size: Some((
1514 mode,
1515 size.try_into().expect("invalid file size in manifest"),
1516 )),
1517 mtime: Some(mtime),
1518 }),
1519 // We are only certain that there isn't a previous entry in the
1520 // case of update from null
1521 from_empty: update_kind == UpdateKind::FromNull,
1522 };
1523 let new_entry = dirstate.reset_state(reset).map_err(|e| {
1524 HgError::abort(e.to_string(), exit_codes::ABORT, None)
1525 })?;
1526 if new_entry {
1527 added += 1
1528 }
1529 }
1530
1531 Ok(UpdateStats { updated, added, merged: 0, removed, unresolved: 0 })
1532 }
1533
1534 /// Wait until the next update from the filesystem time by writing in a loop
1535 /// a new temporary file inside the working directory and checking if its time
1536 /// differs from the first one observed.
1537 ///
1538 /// Returns `None` if we are unable to get the filesystem time,
1539 /// `Some(Err(timestamp))` if we've timed out waiting for the filesystem clock
1540 /// to tick, and `Some(Ok(timestamp))` if we've waited successfully.
1541 ///
1542 /// On Linux, your average tick is going to be a "jiffy", or 1/HZ.
1543 /// HZ is your kernel's tick rate (if it has one configured) and the value
1544 /// is the one returned by `grep 'CONFIG_HZ=' /boot/config-$(uname -r)`,
1545 /// again assuming a normal setup.
1546 ///
1547 /// In my case (Alphare) at the time of writing, I get `CONFIG_HZ=250`,
1548 /// which equates to 4ms.
1549 ///
1550 /// This might change with a series that could make it to Linux 6.12:
1551 /// https://lore.kernel.org/all/[email protected]
1552 fn wait_until_fs_tick(
1553 working_directory_path: &Path,
1554 ) -> Option<Result<TruncatedTimestamp, TruncatedTimestamp>> {
1555 let start = std::time::Instant::now();
1556 let old_fs_time = filesystem_now(working_directory_path).ok()?;
1557 let mut fs_time = filesystem_now(working_directory_path).ok()?;
1558
1559 const FS_TICK_WAIT_TIMEOUT: Duration = Duration::from_millis(100);
1560
1561 while fs_time == old_fs_time {
1562 if std::time::Instant::now() - start > FS_TICK_WAIT_TIMEOUT {
1563 tracing::debug!(
1564 "timed out waiting for the fs clock to tick after {:?}",
1565 FS_TICK_WAIT_TIMEOUT
1566 );
1567 return Some(Err(TruncatedTimestamp::from(old_fs_time)));
1568 }
1569 fs_time = filesystem_now(working_directory_path).ok()?;
1570 }
1571 tracing::debug!(
1572 "waited for {:?} before writing the dirstate",
1573 fs_time.duration_since(old_fs_time)
1574 );
1575 Some(Ok(TruncatedTimestamp::from(fs_time)))
1576 }
1577
1578 #[cfg(test)]
1579 mod test {
1580 use pretty_assertions::assert_eq;
1581
1582 use super::*;
1583 use crate::revlog::manifest::ManifestFlags;
1584
1585 // Test `apply_flags` converting a symlink to a file (not executable).
1586 // The file contents should be the symlink's target, mode should be 666.
1587 #[test]
1588 fn test_apply_flags_link_to_file_regular() {
1589 let dir = tempfile::tempdir().unwrap();
1590 let path_in_repo = HgPathBuf::from_bytes(b"f");
1591 let path = dir.path().join("f");
1592 let target = b"some-other-file.txt";
1593 std::os::unix::fs::symlink(get_path_from_bytes(target), &path).unwrap();
1594
1595 let DirstateUpdate {
1596 path: _,
1597 mode: reported_mode,
1598 size: reported_size,
1599 timestamp: _,
1600 } = apply_flags_to_file(
1601 &path_in_repo,
1602 &path,
1603 ManifestFlags::new_empty(),
1604 )
1605 .unwrap()
1606 .expect("should report change");
1607
1608 let meta = path.symlink_metadata().unwrap();
1609 assert!(meta.is_file());
1610 assert_eq!(std::fs::read(&path).unwrap(), target);
1611 let expected_mode = 0o666 & !get_umask();
1612 assert_eq!(meta.mode() & 0o777, expected_mode);
1613 assert_eq!(reported_mode, meta.mode());
1614 assert_eq!(reported_size, target.len());
1615 }
1616
1617 // Test `apply_flags` converting a symlink to a file (executable).
1618 // The file contents should be the symlink's target, mode should be 777.
1619 #[test]
1620 fn test_apply_flags_link_to_file_executable() {
1621 let dir = tempfile::tempdir().unwrap();
1622 let path_in_repo = HgPathBuf::from_bytes(b"f");
1623 let path = dir.path().join("f");
1624 let target = b"some-other-file.txt";
1625 std::os::unix::fs::symlink(get_path_from_bytes(target), &path).unwrap();
1626
1627 let DirstateUpdate {
1628 path: _,
1629 mode: reported_mode,
1630 size: reported_size,
1631 timestamp: _,
1632 } = apply_flags_to_file(
1633 &path_in_repo,
1634 &path,
1635 ManifestFlags::new_exec(),
1636 )
1637 .unwrap()
1638 .expect("should report change");
1639
1640 let meta = path.symlink_metadata().unwrap();
1641 assert!(meta.is_file());
1642 assert_eq!(std::fs::read(&path).unwrap(), target);
1643 let expected_mode = 0o777 & !get_umask();
1644 assert_eq!(meta.mode() & 0o777, expected_mode);
1645 assert_eq!(reported_mode, meta.mode());
1646 assert_eq!(reported_size, target.len());
1647 }
1648
1649 // Test `apply_flags` converting a file to a symlink.
1650 // The symlink target should be the file's contents.
1651 #[test]
1652 fn test_apply_flags_file_to_link() {
1653 let dir = tempfile::tempdir().unwrap();
1654 let path_in_repo = HgPathBuf::from_bytes(b"f");
1655 let path = dir.path().join("f");
1656 let content = b"some-other-file.txt";
1657 std::fs::write(&path, content).unwrap();
1658
1659 let DirstateUpdate {
1660 path: _,
1661 mode: reported_mode,
1662 size: reported_size,
1663 timestamp: _,
1664 } = apply_flags_to_file(
1665 &path_in_repo,
1666 &path,
1667 ManifestFlags::new_link(),
1668 )
1669 .unwrap()
1670 .expect("should report change");
1671
1672 let meta = path.symlink_metadata().unwrap();
1673 assert!(meta.is_symlink());
1674 let target = get_bytes_from_path(std::fs::read_link(&path).unwrap());
1675 assert_eq!(target, content);
1676 assert_eq!(reported_mode, meta.mode());
1677 assert_eq!(reported_size, content.len());
1678 }
1679
1680 #[test]
1681 fn test_chunk_tracked_files() {
1682 fn chunk(v: Vec<&'static str>) -> Vec<WorkingCopyFileUpdate<'static>> {
1683 v.into_iter()
1684 .map(|f| WorkingCopyFileUpdate {
1685 entry: (
1686 HgPath::new(f.as_bytes()),
1687 NULL_NODE,
1688 ManifestFlags::new_empty(),
1689 ),
1690 backup: false,
1691 flags_differ: false,
1692 })
1693 .collect()
1694 }
1695 let p = HgPath::new;
1696
1697 let files = chunk(vec!["a"]);
1698 let expected = vec![(p(""), chunk(vec!["a"]))];
1699 assert_eq!(chunk_tracked_files(files, false).1, expected);
1700
1701 let files = chunk(vec!["a", "b", "c"]);
1702 let expected = vec![(p(""), chunk(vec!["a", "b", "c"]))];
1703 assert_eq!(chunk_tracked_files(files, false).1, expected);
1704
1705 let files = chunk(vec![
1706 "dir/a-new",
1707 "dir/a/mut",
1708 "dir/a/mut-mut",
1709 "dir/albert",
1710 "dir/b",
1711 "dir/subdir/c",
1712 "dir/subdir/d",
1713 "file",
1714 ]);
1715 let expected = vec![
1716 (p("dir"), chunk(vec!["dir/a-new"])),
1717 (p("dir/a"), chunk(vec!["dir/a/mut", "dir/a/mut-mut"])),
1718 (p("dir"), chunk(vec!["dir/albert", "dir/b"])),
1719 (p("dir/subdir"), chunk(vec!["dir/subdir/c", "dir/subdir/d"])),
1720 (p(""), chunk(vec!["file"])),
1721 ];
1722 assert_eq!(chunk_tracked_files(files, false).1, expected);
1723
1724 // Doesn't get split
1725 let large_dir = vec![
1726 "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
1727 "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23",
1728 ];
1729 let files = chunk(large_dir.clone());
1730 let expected = vec![(p(""), chunk(large_dir))];
1731 assert_eq!(chunk_tracked_files(files, false).1, expected);
1732 }
1733 }