egrix 0.2.1

Find leaked credentials and suspicious network destinations in AI agent transcripts. Local, offline, redacted by default.
//! Where egrix reads and writes. Nothing else in the crate builds a path under
//! the user's home, so this file is the whole filesystem contract.

use anyhow::{Context, Result};
use std::env;
use std::path::{Path, PathBuf};

#[derive(Clone, Debug)]
pub struct Paths {
    /// The user's home: agent transcripts are discovered under it.
    pub home: PathBuf,
    /// `~/.config/egrix`: rules, host lists and finding state.
    pub config: PathBuf,
    /// `~/.local/share/egrix`: backups made before a transcript is edited.
    pub data: PathBuf,
}

impl Paths {
    pub fn from_env() -> Result<Self> {
        let home = env::var_os("HOME")
            .or_else(|| env::var_os("USERPROFILE"))
            .map(PathBuf::from)
            .context("cannot find your home directory (HOME is not set)")?;
        let base = |var: &str, fallback: &[&str]| {
            env::var_os(var)
                .filter(|v| !v.is_empty())
                .map(PathBuf::from)
                .unwrap_or_else(|| fallback.iter().fold(home.clone(), |p, s| p.join(s)))
                .join("egrix")
        };
        Ok(Self { config: base("XDG_CONFIG_HOME", &[".config"]), data: base("XDG_DATA_HOME", &[".local", "share"]), home })
    }

    pub fn rules_dir(&self) -> PathBuf {
        self.config.join("rules")
    }
    pub fn hosts_file(&self) -> PathBuf {
        self.config.join("hosts.toml")
    }
    pub fn state_file(&self) -> PathBuf {
        self.config.join("state.json")
    }
    pub fn backup_dir(&self) -> PathBuf {
        self.data.join("backup")
    }

    /// Display form of a path: `~/…` when it lives under the home directory.
    pub fn tilde(&self, p: &Path) -> String {
        match p.strip_prefix(&self.home) {
            Ok(rest) => format!("~/{}", rest.display().to_string().replace('\\', "/")),
            Err(_) => p.display().to_string(),
        }
    }
}

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

    #[test]
    fn tilde_display_uses_forward_slashes_inside_the_home() {
        let home = PathBuf::from("home");
        let paths = Paths { home: home.clone(), config: home.join("c"), data: home.join("d") };
        let shown = paths.tilde(&home.join(".claude").join("projects").join("s.jsonl"));
        assert_eq!(shown, "~/.claude/projects/s.jsonl");
    }
}