use std::fs::File;
use std::path::{Path, PathBuf};
use crate::error::{Error, Result};
const LOCK_FILE: &str = ".cargo-lock";
pub struct BuildLocks {
held: Vec<(PathBuf, File)>,
}
impl BuildLocks {
pub fn held(&self) -> impl ExactSizeIterator<Item = &Path> {
self.held.iter().map(|(path, _)| path.as_path())
}
}
pub fn acquire(src: &Path) -> Result<BuildLocks> {
let mut held = Vec::new();
for path in lock_files(src)? {
if let Some(file) = lock_shared(&path)? {
held.push((path, file));
}
}
Ok(BuildLocks { held })
}
fn lock_files(src: &Path) -> Result<Vec<PathBuf>> {
let mut found = Vec::new();
for candidate in directories_in(src)? {
let direct = candidate.join(LOCK_FILE);
if direct.is_file() {
found.push(direct);
continue;
}
for nested in directories_in(&candidate)? {
let deeper = nested.join(LOCK_FILE);
if deeper.is_file() {
found.push(deeper);
}
}
}
Ok(found)
}
fn directories_in(path: &Path) -> Result<Vec<PathBuf>> {
let entries = std::fs::read_dir(path).map_err(Error::io("reading", path))?;
let mut directories = Vec::new();
for entry in entries {
let entry = entry.map_err(Error::io("reading", path))?;
if entry.path().is_dir() {
directories.push(entry.path());
}
}
Ok(directories)
}
#[cfg(unix)]
fn lock_shared(path: &Path) -> Result<Option<File>> {
use rustix::fs::{FlockOperation, flock};
let file = File::open(path).map_err(Error::io("opening the build lock", path))?;
match flock(&file, FlockOperation::NonBlockingLockShared) {
Ok(()) => Ok(Some(file)),
Err(rustix::io::Errno::WOULDBLOCK) => Err(Error::SourceBusy {
path: path.to_path_buf(),
}),
Err(errno) => Err(Error::Io {
op: "locking",
path: path.to_path_buf(),
source: errno.into(),
}),
}
}
#[cfg(not(unix))]
fn lock_shared(_path: &Path) -> Result<Option<File>> {
Ok(None)
}