use std::fs;
use std::path::{Path, PathBuf};
pub fn resolve_project_name(cwd: &Path) -> Option<String> {
for ancestor in cwd.ancestors() {
let git = ancestor.join(".git");
if let Ok(meta) = fs::metadata(&git) {
if meta.is_dir() {
return ancestor
.file_name()
.map(|s| s.to_string_lossy().into_owned());
}
if let Some(name) = resolve_worktree_repo_name(&git) {
return Some(name);
}
return ancestor
.file_name()
.map(|s| s.to_string_lossy().into_owned());
}
}
cwd.file_name().map(|s| s.to_string_lossy().into_owned())
}
fn resolve_worktree_repo_name(git_file: &Path) -> Option<String> {
let content = fs::read_to_string(git_file).ok()?;
let gitdir = parse_gitdir_pointer(&content)?;
let config_path = repo_config_path_from_gitdir(Path::new(&gitdir))?;
let config = fs::read_to_string(&config_path).ok()?;
let url = parse_remote_origin_url(&config)?;
Some(repo_name_from_url(&url))
}
pub fn parse_gitdir_pointer(content: &str) -> Option<String> {
content.lines().find_map(|l| {
l.trim()
.strip_prefix("gitdir:")
.map(|p| p.trim().to_string())
.filter(|s| !s.is_empty())
})
}
pub fn repo_config_path_from_gitdir(gitdir: &Path) -> Option<PathBuf> {
for dir in gitdir.ancestors() {
let name = dir.file_name()?.to_str()?;
if name.ends_with(".git") {
return Some(dir.join("config"));
}
}
None
}
pub fn parse_remote_origin_url(config: &str) -> Option<String> {
let mut in_origin = false;
for line in config.lines() {
let trimmed = line.trim();
if trimmed.starts_with('[') {
in_origin = trimmed.contains("\"origin\"");
continue;
}
if in_origin {
if let Some(rest) = trimmed.strip_prefix("url") {
if let Some(val) = rest.trim_start().strip_prefix('=') {
let val = val.trim().to_string();
if !val.is_empty() {
return Some(val);
}
}
}
}
}
None
}
pub fn repo_name_from_url(url: &str) -> String {
let url = url.trim().trim_end_matches('/');
let last = url.rsplit(['/', ':']).next().unwrap_or(url);
last.trim_end_matches(".git").to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_gitdir_basic() {
assert_eq!(
parse_gitdir_pointer("gitdir: /repo/.git/worktrees/wt1"),
Some("/repo/.git/worktrees/wt1".to_string())
);
}
#[test]
fn parse_gitdir_with_whitespace() {
assert_eq!(
parse_gitdir_pointer(" gitdir: /path/to/gitdir \n"),
Some("/path/to/gitdir".to_string())
);
}
#[test]
fn parse_gitdir_empty_value_returns_none() {
assert!(parse_gitdir_pointer("gitdir: \n").is_none());
assert!(parse_gitdir_pointer("not a pointer").is_none());
}
#[test]
fn config_path_from_standard_worktree_gitdir() {
let gitdir = Path::new("/home/x/repo.git/worktrees/wt1");
assert_eq!(
repo_config_path_from_gitdir(gitdir),
Some(PathBuf::from("/home/x/repo.git/config"))
);
}
#[test]
fn config_path_returns_none_without_git_ancestor() {
assert!(repo_config_path_from_gitdir(Path::new("/home/x/repo/worktrees/wt1")).is_none());
}
const SAMPLE_CONFIG: &str = "\
[core]
\trepositoryformatversion = 0
\tfilemode = true
[remote \"origin\"]
\turl = https://github.com/ppetermann/firstmate
\tfetch = +refs/heads/*:refs/remotes/origin/*
[branch \"main\"]
\tremote = origin
";
#[test]
fn parse_origin_url() {
assert_eq!(
parse_remote_origin_url(SAMPLE_CONFIG),
Some("https://github.com/ppetermann/firstmate".to_string())
);
}
#[test]
fn parse_origin_url_missing_returns_none() {
let config = "[core]\n\tfilemode = true\n";
assert!(parse_remote_origin_url(config).is_none());
}
#[test]
fn parse_origin_url_empty_value_returns_none() {
let config = "[remote \"origin\"]\n\turl = \n";
assert!(parse_remote_origin_url(config).is_none());
}
#[test]
fn name_from_https_url() {
assert_eq!(
repo_name_from_url("https://github.com/ppetermann/firstmate"),
"firstmate"
);
}
#[test]
fn name_from_https_url_with_dot_git() {
assert_eq!(
repo_name_from_url("https://github.com/ppetermann/firstmate.git"),
"firstmate"
);
}
#[test]
fn name_from_scp_style_ssh_url() {
assert_eq!(
repo_name_from_url("git@github.com:ppetermann/firstmate.git"),
"firstmate"
);
}
#[test]
fn name_from_ssh_protocol_url() {
assert_eq!(
repo_name_from_url("ssh://git@github.com/ppetermann/crew-watch.git"),
"crew-watch"
);
}
#[test]
fn name_strips_trailing_slash() {
assert_eq!(repo_name_from_url("https://github.com/x/y/"), "y");
}
#[test]
fn resolve_falls_back_to_basename_outside_git() {
let cwd = Path::new("/tmp/some-random-dir-12345");
assert_eq!(
resolve_project_name(cwd),
Some("some-random-dir-12345".to_string())
);
}
#[test]
fn resolve_root_path_returns_none() {
assert!(resolve_project_name(Path::new("/")).is_none());
}
}