artifactize-foundation 0.27.1

Native file, path and executable primitives for Artifactize.
Documentation
//! Owned, empty probe directories outside all declared or marked workspaces.

use std::{
    ffi::OsStr,
    io,
    path::{Path, PathBuf},
};

use super::{
    files::{path_text, portable_basename},
    paths::{canonical_target, directory_name_policy, is_within},
    private::{PrivateTempDir, ScratchParent},
};

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error(transparent)]
    Io(#[from] io::Error),
    #[error("temporary probe directory would be inside {}", path_text(.0))]
    Enclosed(PathBuf),
}

/// Recognize a workspace by any specified basename or filename suffix, independently of
/// what kind of entries they are or where links would lead.
pub struct Markers<'a> {
    pub names: &'a [&'a str],
    pub suffixes: &'a [&'a str],
}

impl Markers<'_> {
    fn validate(&self) -> io::Result<()> {
        if (self.names.is_empty() && self.suffixes.is_empty())
            || !self
                .names
                .iter()
                .chain(self.suffixes)
                .all(|name| portable_basename(name))
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "invalid workspace markers",
            ));
        }
        Ok(())
    }

    fn present(&self, ancestor: &Path) -> io::Result<bool> {
        for name in self.names {
            match ancestor.join(name).symlink_metadata() {
                Ok(_) => return Ok(true),
                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
                Err(error) => return Err(error),
            }
        }
        if !self.suffixes.is_empty() {
            let policy = directory_name_policy(ancestor)?;
            let suffixes = self
                .suffixes
                .iter()
                .map(|&suffix| policy.key(OsStr::new(suffix)))
                .collect::<io::Result<Vec<_>>>()?;
            for entry in std::fs::read_dir(ancestor)? {
                let name = policy.key(&entry?.file_name())?;
                if suffixes
                    .iter()
                    .any(|suffix| name.as_encoded_bytes().ends_with(suffix.as_encoded_bytes()))
                {
                    return Ok(true);
                }
            }
        }
        Ok(false)
    }
}

/// Allocate only outside every known workspace root and every ancestor containing a
/// workspace marker. The caller supplies the naming policy, not the result of the
/// exclusion check. The lease removes the private directory whenever it is dropped.
pub fn directory(
    prefix: &str,
    parent: &Path,
    workspace_roots: &[&Path],
    markers: &Markers<'_>,
) -> Result<PrivateTempDir, Error> {
    markers.validate()?;
    let parent = ScratchParent::open(parent)?;
    for root in workspace_roots {
        let root = canonical_target(root)?;
        if is_within(parent.path(), &root) {
            return Err(Error::Enclosed(root));
        }
    }
    for ancestor in parent.path().ancestors() {
        if markers.present(ancestor)? {
            return Err(Error::Enclosed(ancestor.to_owned()));
        }
    }
    Ok(parent.create_temp(prefix)?)
}

#[cfg(test)]
mod tests;