use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};
pub const IDENTITY: &str = "IDENTITY";
pub const ADOPTED: &str = "ADOPTED";
pub const PAUSED: &str = "PAUSED";
pub const MAX_IDLE: Duration = Duration::from_secs(7 * 24 * 60 * 60);
const MAGIC: &[u8; 8] = b"AFTWSID2";
#[cfg(unix)]
const ROOT_ENCODING: u8 = 1;
#[cfg(windows)]
const ROOT_ENCODING: u8 = 2;
#[cfg(not(any(unix, windows)))]
const ROOT_ENCODING: u8 = 3;
fn root_bytes(root: &Path) -> Vec<u8> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt as _;
root.as_os_str().as_bytes().to_vec()
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStrExt as _;
root.as_os_str()
.encode_wide()
.flat_map(u16::to_le_bytes)
.collect()
}
#[cfg(not(any(unix, windows)))]
{
root.to_string_lossy().into_owned().into_bytes()
}
}
fn root_from_bytes(bytes: Vec<u8>) -> Option<PathBuf> {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStringExt as _;
Some(PathBuf::from(std::ffi::OsString::from_vec(bytes)))
}
#[cfg(windows)]
{
use std::os::windows::ffi::OsStringExt as _;
if bytes.len() % 2 != 0 {
return None;
}
let wide = bytes
.chunks_exact(2)
.map(|pair| u16::from_le_bytes([pair[0], pair[1]]))
.collect::<Vec<_>>();
Some(PathBuf::from(std::ffi::OsString::from_wide(&wide)))
}
#[cfg(not(any(unix, windows)))]
{
String::from_utf8(bytes).ok().map(PathBuf::from)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkspaceIdentity {
pub root: PathBuf,
pub payload: Vec<u8>,
}
pub fn write_identity(workspace: &Path, identity: &WorkspaceIdentity) -> io::Result<()> {
let root = root_bytes(&identity.root);
let mut bytes = Vec::with_capacity(64 + root.len() + identity.payload.len());
bytes.extend_from_slice(MAGIC);
bytes.push(ROOT_ENCODING);
push_part(&mut bytes, &root)?;
push_part(&mut bytes, &identity.payload)?;
let length = bytes.len() as u64;
bytes.extend_from_slice(&length.to_le_bytes());
let checksum = blake3::hash(&bytes[..usize::try_from(length).unwrap_or(usize::MAX)]);
bytes.extend_from_slice(checksum.as_bytes());
let part = workspace.join(format!("{IDENTITY}.part"));
{
let mut file = std::fs::File::create(&part)?;
file.write_all(&bytes)?;
}
std::fs::rename(&part, workspace.join(IDENTITY))
}
fn push_part(bytes: &mut Vec<u8>, part: &[u8]) -> io::Result<()> {
let length = u32::try_from(part.len())
.map_err(|_| io::Error::other("a workspace identity part is 4 GiB or larger"))?;
bytes.extend_from_slice(&length.to_le_bytes());
bytes.extend_from_slice(part);
Ok(())
}
#[must_use]
pub fn read_identity(workspace: &Path) -> Option<WorkspaceIdentity> {
let bytes = std::fs::read(workspace.join(IDENTITY)).ok()?;
let body = bytes.len().checked_sub(40)?;
let length = crate::le::u64_at(&bytes, body);
if length != body as u64
|| blake3::hash(&bytes[..body]).as_bytes() != &bytes[body + 8..]
|| bytes.get(..8)? != MAGIC
{
return None;
}
if *bytes.get(8)? != ROOT_ENCODING {
return None;
}
let mut at = 9;
let mut part = || -> Option<Vec<u8>> {
let length = u32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?) as usize;
let part = bytes.get(at + 4..at + 4 + length)?.to_vec();
at += 4 + length;
Some(part)
};
let root = root_from_bytes(part()?)?;
let payload = part()?;
(at == body).then_some(WorkspaceIdentity { root, payload })
}
pub fn mark_adopted(workspace: &Path) -> io::Result<()> {
let file = std::fs::File::create(workspace.join(ADOPTED))?;
file.set_modified(SystemTime::now())
}
#[must_use]
pub fn last_used(workspace: &Path) -> Option<SystemTime> {
[IDENTITY, ADOPTED]
.iter()
.filter_map(|name| {
std::fs::metadata(workspace.join(name))
.ok()?
.modified()
.ok()
})
.max()
}
#[must_use]
pub fn is_paused(workspace: &Path) -> bool {
workspace.join(PAUSED).exists()
}
#[must_use]
pub fn worth_keeping(workspace: &Path, now: SystemTime) -> bool {
let Some(identity) = read_identity(workspace) else {
return false;
};
if matches!(
std::fs::symlink_metadata(&identity.root),
Err(error) if error.kind() == io::ErrorKind::NotFound
) {
return false;
}
last_used(workspace)
.is_some_and(|used| now.duration_since(used).unwrap_or_default() <= MAX_IDLE)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn identity_reads_back_and_a_changed_or_torn_one_does_not() {
let dir = tempfile::tempdir().unwrap();
let identity = WorkspaceIdentity {
root: dir.path().join("checkout"),
payload: b"build=1\n".to_vec(),
};
assert_eq!(read_identity(dir.path()), None);
write_identity(dir.path(), &identity).unwrap();
assert_eq!(read_identity(dir.path()), Some(identity.clone()));
assert!(!dir.path().join("IDENTITY.part").exists());
let path = dir.path().join(IDENTITY);
let mut bytes = std::fs::read(&path).unwrap();
let last = bytes.len() - 41;
bytes[last] ^= 1;
std::fs::write(&path, &bytes).unwrap();
assert_eq!(read_identity(dir.path()), None, "a changed byte");
write_identity(dir.path(), &identity).unwrap();
let bytes = std::fs::read(&path).unwrap();
std::fs::write(&path, &bytes[..bytes.len() - 1]).unwrap();
assert_eq!(read_identity(dir.path()), None, "a torn file");
}
#[cfg(target_os = "linux")]
#[test]
fn a_root_that_is_not_unicode_reads_back_as_the_same_path() {
use std::os::unix::ffi::OsStrExt as _;
let dir = tempfile::tempdir().unwrap();
let root = dir
.path()
.join(std::ffi::OsStr::from_bytes(b"checkout-\xff-\xfe"));
let identity = WorkspaceIdentity {
root: root.clone(),
payload: Vec::new(),
};
write_identity(dir.path(), &identity).unwrap();
assert_eq!(read_identity(dir.path()).unwrap().root, root);
std::fs::create_dir(&root).unwrap();
assert!(worth_keeping(dir.path(), SystemTime::now()));
}
#[test]
fn a_workspace_is_kept_while_its_checkout_exists_and_it_was_used_lately() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("checkout");
std::fs::create_dir(&root).unwrap();
let workspace = dir.path().join("workspace");
std::fs::create_dir(&workspace).unwrap();
let now = SystemTime::now();
assert!(!worth_keeping(&workspace, now), "no identity");
write_identity(
&workspace,
&WorkspaceIdentity {
root: root.clone(),
payload: Vec::new(),
},
)
.unwrap();
assert!(worth_keeping(&workspace, now));
let later = now + MAX_IDLE + Duration::from_secs(60);
assert!(!worth_keeping(&workspace, later), "idle too long");
mark_adopted(&workspace).unwrap();
assert!(!worth_keeping(&workspace, later + MAX_IDLE));
std::fs::remove_dir(&root).unwrap();
assert!(!worth_keeping(&workspace, now), "checkout gone");
}
}