agix-base 0.4.4

Agix — foundation types, traits, and context
Documentation
//! Path sanitization utilities.
//!
//! Provides `sanitize_for_fs()` which transforms an arbitrary string into a
//! filesystem-safe identifier using a djb2 hash and radix-36 encoding. Used
//! for session directories, worktree slugs, and any other case where an
//! untrusted string must become a safe directory or file name.

use std::path::{Component, Path, PathBuf};

/// `p` with `.` dropped and each `..` taking off the component before it,
/// without touching the filesystem, so it does not know a `..` after a
/// symlink climbs out of the link's target ([`resolve_physically`] does).
pub fn normalize_lexically(p: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for c in p.components() {
        match c {
            Component::ParentDir => {
                out.pop();
            }
            Component::CurDir => {}
            other => out.push(other),
        }
    }
    out
}

/// How many symbolic links a resolution follows before it takes a loop for
/// one, as the OS does (`SYMLOOP_MAX`).
pub const MAX_LINK_HOPS: u32 = 40;

/// Where `path` lands on this machine's disk: its deepest prefix that exists,
/// resolved by the OS, with the rest put back on lexically. The rest does not
/// exist, so it holds no symlink a lexical `..` could misjudge — except its
/// first name, a link the OS cannot resolve because what it points at does
/// not exist yet, which a write follows and so is followed here.
pub fn resolve_physically(path: &Path) -> PathBuf {
    let mut wanted = path.to_path_buf();
    for _ in 0..=MAX_LINK_HOPS {
        let parts: Vec<Component> = wanted.components().collect();
        let Some((split, out)) = (1..=parts.len()).rev().find_map(|split| {
            let prefix: PathBuf = parts[..split].iter().collect();
            Some((split, std::fs::canonicalize(prefix).ok()?))
        }) else {
            return normalize_lexically(&wanted);
        };
        let rest = &parts[split..];
        match first_below(&out, rest)
            .and_then(|(link, after)| Some(out.join(std::fs::read_link(link).ok()?).join(after)))
        {
            Some(next) => wanted = next,
            None => return put_back(out, rest),
        }
    }
    wanted
}

/// When `rest` starts with a name: that name under the resolved `out` — a
/// link the OS could not resolve, if it is one — and the rest after it.
pub fn first_below(out: &Path, rest: &[Component]) -> Option<(PathBuf, PathBuf)> {
    let (Component::Normal(name), after) = rest.split_first()? else {
        return None;
    };
    Some((out.join(name), after.iter().collect()))
}

/// `rest` put onto the resolved `out` lexically.
pub fn put_back(mut out: PathBuf, rest: &[Component]) -> PathBuf {
    for part in rest {
        match part {
            Component::ParentDir => {
                out.pop();
            }
            Component::CurDir => {}
            other => out.push(other),
        }
    }
    out
}

/// djb2 hash constant for initial value.
const DJB2_INIT: u64 = 5381;

/// Compute a djb2 hash of the given string, returning a u64.
fn djb2_hash(s: &str) -> u64 {
    let mut hash = DJB2_INIT;
    for byte in s.bytes() {
        hash = hash.wrapping_mul(33).wrapping_add(byte as u64);
    }
    hash
}

/// Encode a u64 value into a radix-36 (base36) string.
///
/// Uses digits 0-9 and lowercase letters a-z for 36 symbols.
fn radix36_encode(mut value: u64) -> String {
    const CHARS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";
    if value == 0 {
        return "0".to_string();
    }
    let mut digits = Vec::new();
    while value > 0 {
        digits.push(CHARS[(value % 36) as usize]);
        value /= 36;
    }
    digits.iter().rev().map(|&d| d as char).collect()
}

/// Maximum length before truncation with hash suffix.
const SANITIZE_MAX_LEN: usize = 200;
/// Public constant for external crates (e.g. agix-history tests) that need
/// to verify sanitized output length bounds.
pub const MAX_SANITIZED_LENGTH: usize = SANITIZE_MAX_LEN;

/// Sanitize a string for use as a filesystem component (file name or directory).
///
/// 1. Replaces all non-`[a-zA-Z0-9]` characters with `-`
/// 2. If the result exceeds `SANITIZE_MAX_LEN` (200) bytes, truncates and appends
///    a djb2 hash of the original string encoded in radix-36.
///
/// The output is guaranteed to be safe for all major filesystems.
pub fn sanitize_for_fs(name: &str) -> String {
    let sanitized: String = name
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
        .collect();

    if sanitized.len() <= SANITIZE_MAX_LEN {
        return sanitized;
    }

    let hash = djb2_hash(name);
    let suffix = radix36_encode(hash);
    let prefix_len = SANITIZE_MAX_LEN.saturating_sub(suffix.len() + 1);
    let prefix: String = sanitized.chars().take(prefix_len).collect();
    format!("{prefix}-{suffix}")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn lexical_normalization_drops_dots_and_pops_parents() {
        assert_eq!(
            normalize_lexically(Path::new("/a/./b/../c")),
            PathBuf::from("/a/c")
        );
    }

    #[test]
    fn physical_resolution_pops_a_parent_after_a_missing_component() {
        let dir = tempfile::tempdir().unwrap();
        let real = std::fs::canonicalize(dir.path()).unwrap();
        let got = resolve_physically(&dir.path().join("missing/../x"));
        assert_eq!(got, real.join("x"));
    }

    #[cfg(unix)]
    #[test]
    fn physical_resolution_follows_a_symlink_before_a_parent_step() {
        let dir = tempfile::tempdir().unwrap();
        let real = std::fs::canonicalize(dir.path()).unwrap();
        std::fs::create_dir_all(real.join("target/inner")).unwrap();
        std::os::unix::fs::symlink(real.join("target/inner"), real.join("link")).unwrap();
        let got = resolve_physically(&real.join("link/../x"));
        assert_eq!(got, real.join("target/x"));
    }

    #[cfg(unix)]
    #[test]
    fn physical_resolution_follows_a_dangling_symlink_and_a_chain_of_them() {
        let dir = tempfile::tempdir().unwrap();
        let real = std::fs::canonicalize(dir.path()).unwrap();
        std::fs::create_dir_all(real.join("forge")).unwrap();
        std::os::unix::fs::symlink("../.git/hooks/pre-commit", real.join("forge/h")).unwrap();
        assert_eq!(
            resolve_physically(&real.join("forge/h")),
            real.join(".git/hooks/pre-commit")
        );
        std::os::unix::fs::symlink(real.join("forge/h"), real.join("chained")).unwrap();
        assert_eq!(
            resolve_physically(&real.join("chained")),
            real.join(".git/hooks/pre-commit")
        );
        std::os::unix::fs::symlink(real.join("absent"), real.join("dir-link")).unwrap();
        assert_eq!(
            resolve_physically(&real.join("dir-link/new.txt")),
            real.join("absent/new.txt")
        );
    }

    #[cfg(unix)]
    #[test]
    fn physical_resolution_of_a_symlink_loop_ends() {
        let dir = tempfile::tempdir().unwrap();
        let real = std::fs::canonicalize(dir.path()).unwrap();
        std::os::unix::fs::symlink(real.join("b"), real.join("a")).unwrap();
        std::os::unix::fs::symlink(real.join("a"), real.join("b")).unwrap();
        let got = resolve_physically(&real.join("a"));
        assert!(got == real.join("a") || got == real.join("b"), "{got:?}");
    }

    #[test]
    fn test_basic_string() {
        let result = sanitize_for_fs("hello");
        assert_eq!(result, "hello");
    }

    #[test]
    fn test_special_chars_replaced() {
        let result = sanitize_for_fs("/Users/foo/my-project");
        assert_eq!(result, "-Users-foo-my-project");
    }

    #[test]
    fn test_spaces_replaced() {
        let result = sanitize_for_fs("hello world");
        assert_eq!(result, "hello-world");
    }

    #[test]
    fn test_djb2_hash_consistency() {
        let h1 = djb2_hash("test");
        let h2 = djb2_hash("test");
        assert_eq!(h1, h2);
    }

    #[test]
    fn test_djb2_hash_different_inputs() {
        let h1 = djb2_hash("abc");
        let h2 = djb2_hash("xyz");
        assert_ne!(h1, h2);
    }

    #[test]
    fn test_radix36_zero() {
        assert_eq!(radix36_encode(0), "0");
    }

    #[test]
    fn test_radix36_encoding() {
        let encoded = radix36_encode(10);
        assert_eq!(encoded, "a");
    }

    #[test]
    fn test_sanitize_produces_different_outputs_for_different_inputs() {
        let r1 = sanitize_for_fs("project alpha");
        let r2 = sanitize_for_fs("project beta");
        assert_ne!(r1, r2);
    }

    #[test]
    fn test_sanitize_truncates_long_inputs() {
        let long = "a".repeat(300);
        let result = sanitize_for_fs(&long);
        // Should be truncated with hash suffix
        assert!(result.len() < 300);
        assert!(!result.is_empty());
    }

    #[test]
    fn test_sanitize_allows_alphanumeric() {
        let result = sanitize_for_fs("MyProject_v2.0");
        assert_eq!(result, "MyProject-v2-0");
    }
}