(
path: &Path,
kind: RepositoryLockKind,
reentrant_owner: bool,
)
| 588 | } |
| 589 | |
| 590 | fn try_lock_file( |
| 591 | path: &Path, |
| 592 | kind: RepositoryLockKind, |
| 593 | reentrant_owner: bool, |
| 594 | ) -> Result<AdvisoryFileLock, RepositoryError> { |
| 595 | let path = path.to_path_buf(); |
| 596 | let reentrant = HELD_LOCKS.with(|held| { |
| 597 | let mut held = held.borrow_mut(); |
| 598 | let (count, file, reentrant) = held.get_mut(&path)?; |
| 599 | if !*reentrant { |
| 600 | return None; |
| 601 | } |
| 602 | let file = file.upgrade()?; |
| 603 | *count += 1; |
| 604 | Some(file) |
| 605 | }); |
| 606 | if let Some(file) = reentrant { |
| 607 | return Ok(AdvisoryFileLock { file, path }); |
| 608 | } |
| 609 | if let Some(parent) = path.parent() { |
| 610 | std::fs::create_dir_all(parent)?; |
| 611 | } |
| 612 | let file = OpenOptions::new() |
| 613 | .create(true) |
| 614 | .truncate(false) |
| 615 | .read(true) |
| 616 | .write(true) |
| 617 | .open(&path)?; |
| 618 | match file.try_lock_exclusive() { |
| 619 | Ok(()) => { |
| 620 | let file = Arc::new(file); |
| 621 | HELD_LOCKS.with(|held| { |
| 622 | held.borrow_mut() |
| 623 | .insert(path.clone(), (1, Arc::downgrade(&file), reentrant_owner)); |
| 624 | }); |
| 625 | Ok(AdvisoryFileLock { file, path }) |
| 626 | } |
| 627 | Err(error) if is_lock_contended(&error) => { |
| 628 | Err(RepositoryError::LockContended { lock: kind, path }) |
| 629 | } |
| 630 | Err(error) => Err(RepositoryError::Io(error)), |
| 631 | } |
| 632 | } |
| 633 | |
| 634 | /// Classify the cross-platform error returned by a contended `fs2` try-lock. |
| 635 | pub(super) fn is_lock_contended(error: &std::io::Error) -> bool { |
no test coverage detected