MCPcopy Create free account
hub / github.com/atomicdotdev/atomic / try_lock_file

Function try_lock_file

atomic-repository/src/repository/locks.rs:615–657  ·  view source on GitHub ↗
(
    path: &Path,
    kind: RepositoryLockKind,
    reentrant_owner: bool,
)

Source from the content-addressed store, hash-verified

613}
614
615fn try_lock_file(
616 path: &Path,
617 kind: RepositoryLockKind,
618 reentrant_owner: bool,
619) -> Result<AdvisoryFileLock, RepositoryError> {
620 let path = path.to_path_buf();
621 let reentrant = HELD_LOCKS.with(|held| {
622 let mut held = held.borrow_mut();
623 let (count, file, reentrant) = held.get_mut(&path)?;
624 if !*reentrant {
625 return None;
626 }
627 let file = file.upgrade()?;
628 *count += 1;
629 Some(file)
630 });
631 if let Some(file) = reentrant {
632 return Ok(AdvisoryFileLock { file, path });
633 }
634 if let Some(parent) = path.parent() {
635 std::fs::create_dir_all(parent)?;
636 }
637 let file = OpenOptions::new()
638 .create(true)
639 .truncate(false)
640 .read(true)
641 .write(true)
642 .open(&path)?;
643 match file.try_lock_exclusive() {
644 Ok(()) => {
645 let file = Arc::new(file);
646 HELD_LOCKS.with(|held| {
647 held.borrow_mut()
648 .insert(path.clone(), (1, Arc::downgrade(&file), reentrant_owner));
649 });
650 Ok(AdvisoryFileLock { file, path })
651 }
652 Err(error) if is_lock_contended(&error) => {
653 Err(RepositoryError::LockContended { lock: kind, path })
654 }
655 Err(error) => Err(RepositoryError::Io(error)),
656 }
657}
658
659/// Classify the cross-platform error returned by a contended `fs2` try-lock.
660pub(super) fn is_lock_contended(error: &std::io::Error) -> bool {

Calls 11

withMethod · 0.80
get_mutMethod · 0.80
parentMethod · 0.80
truncateMethod · 0.80
is_lock_contendedFunction · 0.70
openMethod · 0.45
writeMethod · 0.45
readMethod · 0.45
createMethod · 0.45
insertMethod · 0.45
cloneMethod · 0.45

Tested by

no test coverage detected