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