use std::io::Read;
use std::path::Path;
pub const TAG_FILE_NAME: &str = "CACHEDIR.TAG";
const SIGNATURE: &[u8] = b"Signature: 8a477f597d28d172789f06886806bc55";
#[must_use]
pub fn is_tagged(dir: &Path) -> bool {
let tag = dir.join(TAG_FILE_NAME);
if !std::fs::symlink_metadata(&tag).is_ok_and(|metadata| metadata.is_file()) {
return false;
}
let Ok(mut file) = std::fs::File::open(&tag) else {
return false;
};
let mut head = [0_u8; SIGNATURE.len()];
file.read_exact(&mut head).is_ok() && head == *SIGNATURE
}
#[must_use]
pub fn is_virtualenv(dir: &Path) -> bool {
std::fs::symlink_metadata(dir.join("pyvenv.cfg")).is_ok_and(|metadata| metadata.is_file())
}
#[cfg(test)]
mod tests {
use std::fs;
use tempfile::TempDir;
use super::*;
fn dir() -> TempDir {
TempDir::new().expect("a temporary directory")
}
fn tag(at: &Path, body: &[u8]) {
fs::write(at.join(TAG_FILE_NAME), body).expect("writing the tag");
}
#[test]
fn should_accept_a_directory_carrying_the_exact_signature() {
let root = dir();
tag(root.path(), SIGNATURE);
assert!(is_tagged(root.path()), "{} carries a valid tag", root.path().display());
}
#[test]
fn should_accept_a_tag_with_the_usual_explanatory_body_after_the_signature() {
let root = dir();
let mut body = SIGNATURE.to_vec();
body.extend_from_slice(b"\n# This directory contains a cache.\n");
tag(root.path(), &body);
assert!(is_tagged(root.path()), "the signature is a prefix, not the whole file");
}
#[test]
fn should_refuse_a_directory_with_no_tag() {
let root = dir();
assert!(!is_tagged(root.path()), "no tag proves nothing");
}
#[test]
fn should_refuse_a_tag_whose_signature_is_wrong() {
let root = dir();
tag(root.path(), b"Signature: 0000000000000000000000000000000000");
assert!(
!is_tagged(root.path()),
"a file merely named CACHEDIR.TAG must not license a removal"
);
}
#[test]
fn should_refuse_a_tag_too_short_to_carry_the_signature() {
let root = dir();
tag(root.path(), b"Signature: 8a47");
assert!(!is_tagged(root.path()), "a truncated tag is not a tag");
}
#[test]
fn should_refuse_a_tag_that_is_a_directory() {
let root = dir();
fs::create_dir(root.path().join(TAG_FILE_NAME)).expect("creating the decoy");
assert!(!is_tagged(root.path()), "only a regular file is a tag");
}
#[cfg(unix)]
#[test]
fn should_refuse_a_tag_that_is_a_symlink_to_a_real_one() {
let root = dir();
let elsewhere = dir();
tag(elsewhere.path(), SIGNATURE);
std::os::unix::fs::symlink(elsewhere.path().join(TAG_FILE_NAME), root.path().join(TAG_FILE_NAME))
.expect("linking the tag");
assert!(
!is_tagged(root.path()),
"a symlinked tag must not borrow another directory's declaration"
);
}
#[test]
fn should_refuse_a_directory_that_does_not_exist() {
let root = dir();
assert!(
!is_tagged(&root.path().join("absent")),
"an absent directory is not tagged"
);
}
}