egrix 0.2.1

Find leaked credentials and suspicious network destinations in AI agent transcripts. Local, offline, redacted by default.
//! Turning the working directory recorded in a transcript into a repository:
//! its root, its short name and its remote. Reads `.git/config` directly, so
//! there is no `git` subprocess and no network.

use crate::model::Repo;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

#[derive(Default)]
pub struct RepoResolver {
    cache: HashMap<String, Repo>,
}

impl RepoResolver {
    pub fn resolve(&mut self, cwd: &str) -> Repo {
        if let Some(repo) = self.cache.get(cwd) {
            return repo.clone();
        }
        let repo = lookup(Path::new(cwd));
        self.cache.insert(cwd.to_string(), repo.clone());
        repo
    }
}

fn lookup(cwd: &Path) -> Repo {
    let root = cwd.ancestors().find(|dir| dir.join(".git").exists());
    let base = root.unwrap_or(cwd);
    Repo {
        name: base.file_name().map_or_else(|| base.display().to_string(), |n| n.to_string_lossy().into_owned()),
        path: base.display().to_string(),
        remote: root.and_then(git_config).and_then(|text| remote_from_config(&text)),
    }
}

fn git_config(root: &Path) -> Option<String> {
    let dot_git = root.join(".git");
    let dir: PathBuf = if dot_git.is_dir() {
        dot_git
    } else {
        // Worktrees and submodules: `.git` is a file pointing at the real dir.
        let pointer = std::fs::read_to_string(&dot_git).ok()?;
        let target = PathBuf::from(pointer.trim().strip_prefix("gitdir:")?.trim());
        let target = if target.is_absolute() { target } else { root.join(target) };
        // A worktree's git dir has a `commondir` file naming the shared one.
        match std::fs::read_to_string(target.join("commondir")) {
            Ok(common) => target.join(common.trim()),
            Err(_) => target,
        }
    };
    std::fs::read_to_string(dir.join("config")).ok()
}

/// The `origin` URL, or the first remote when there is no origin.
fn remote_from_config(config: &str) -> Option<String> {
    let (mut section, mut first, mut origin) = (String::new(), None, None);
    for line in config.lines().map(str::trim) {
        if line.starts_with('[') {
            section = line.to_string();
        } else if section.starts_with("[remote ") {
            if let Some(url) = line.strip_prefix("url").map(str::trim_start).and_then(|r| r.strip_prefix('=')) {
                let clean = clean_remote(url.trim());
                if section == "[remote \"origin\"]" {
                    origin = origin.or(clean);
                } else {
                    first = first.or(clean);
                }
            }
        }
    }
    origin.or(first)
}

/// `host/owner/name` with scheme, credentials, port and `.git` removed, so a
/// token embedded in a remote URL is never displayed.
pub fn clean_remote(url: &str) -> Option<String> {
    let rest = match url.split_once("://") {
        Some((_, rest)) => rest.to_string(),
        // scp-like `git@host:owner/name.git`
        None => url.replacen(':', "/", 1),
    };
    let rest = rest.rsplit_once('@').map_or(rest.as_str(), |(_, r)| r);
    let (host, path) = rest.split_once('/')?;
    let host = host.split(':').next()?.to_ascii_lowercase();
    let path = path.trim_end_matches('/').trim_end_matches(".git");
    (!host.is_empty() && !path.is_empty()).then(|| format!("{host}/{path}"))
}

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

    #[test]
    fn cleans_every_remote_shape() {
        assert_eq!(clean_remote("https://github.com/acme/api.git").as_deref(), Some("github.com/acme/api"));
        assert_eq!(clean_remote("git@gitlab.com:acme/bot.git").as_deref(), Some("gitlab.com/acme/bot"));
        assert_eq!(clean_remote("ssh://git@host.dev:2222/acme/x").as_deref(), Some("host.dev/acme/x"));
        assert_eq!(clean_remote("https://user:s3cret@github.com/acme/api").as_deref(), Some("github.com/acme/api"));
        assert_eq!(clean_remote("nonsense"), None);
    }

    #[test]
    fn prefers_origin_over_other_remotes() {
        let cfg = "[core]\n\tbare = false\n[remote \"fork\"]\n\turl = https://github.com/me/api.git\n[remote \"origin\"]\n\turl = git@github.com:acme/api.git\n";
        assert_eq!(remote_from_config(cfg).as_deref(), Some("github.com/acme/api"));
        assert_eq!(remote_from_config("[core]\n").as_deref(), None);
    }

    #[test]
    fn directory_without_git_still_gets_a_name() {
        let repo = lookup(Path::new("/definitely/not/here/project"));
        assert_eq!(repo.name, "project");
        assert_eq!(repo.remote, None);
    }
}