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 {
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) };
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()
}
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)
}
pub fn clean_remote(url: &str) -> Option<String> {
let rest = match url.split_once("://") {
Some((_, rest)) => rest.to_string(),
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);
}
}