use std::io;
use std::path::Path;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DestinationState {
Fresh,
NotFresh,
}
pub(crate) fn parent_or_cwd(path: &Path) -> &Path {
path.parent()
.filter(|parent| !parent.is_empty())
.unwrap_or_else(|| Path::new("."))
}
impl DestinationState {
#[must_use]
pub fn probe(destination: &Path) -> Self {
let parent = parent_or_cwd(destination);
let absent = matches!(
destination.symlink_metadata(),
Err(ref error) if error.kind() == io::ErrorKind::NotFound
);
if absent && parent.is_dir() {
Self::Fresh
} else {
Self::NotFresh
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::DestinationState;
#[test]
fn an_absent_name_in_an_existing_parent_is_fresh() {
let temp = tempfile::tempdir().unwrap();
assert_eq!(
DestinationState::probe(&temp.path().join("out")),
DestinationState::Fresh
);
}
#[test]
fn an_existing_name_or_a_missing_parent_is_not_fresh() {
let temp = tempfile::tempdir().unwrap();
std::fs::create_dir(temp.path().join("out")).unwrap();
assert_eq!(
DestinationState::probe(&temp.path().join("out")),
DestinationState::NotFresh
);
assert_eq!(
DestinationState::probe(&temp.path().join("missing").join("out")),
DestinationState::NotFresh
);
}
#[cfg(unix)]
#[test]
fn a_dangling_symlink_is_not_fresh() {
let temp = tempfile::tempdir().unwrap();
std::os::unix::fs::symlink("nowhere", temp.path().join("out")).unwrap();
assert_eq!(
DestinationState::probe(&temp.path().join("out")),
DestinationState::NotFresh
);
}
#[test]
fn a_bare_name_resolves_its_parent_to_the_working_directory() {
assert_eq!(
DestinationState::probe("exarch-test-never-created-name".as_ref()),
DestinationState::Fresh
);
}
}