pub fn to_connection_relative(host_qualified: &str) -> String {
let s = host_qualified.trim();
let s = s.split_once("://").map_or(s, |(_, rest)| rest);
let s = match s.split_once('@') {
Some((user, rest)) if !user.contains('/') => rest,
_ => s,
};
let s = match s.split_once(':') {
Some((host, path)) if !host.contains('/') && !path.starts_with(|c: char| c.is_ascii_digit()) => path,
_ => s,
};
let s = s.trim_matches('/');
let s = s.strip_suffix(".git").unwrap_or(s);
let mut parts: Vec<&str> = s.split('/').filter(|p| !p.is_empty()).collect();
let looks_like_a_host = |seg: &str| seg.contains('.') || seg == "localhost";
if parts.len() >= 3 && looks_like_a_host(parts[0]) {
parts.remove(0);
}
parts.join("/")
}
pub fn matches_scope_entry(candidate: &str, scope_entry: &str) -> bool {
to_connection_relative(candidate) == to_connection_relative(scope_entry)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn host_qualified_becomes_connection_relative() {
assert_eq!(to_connection_relative("github.com/acme/pay"), "acme/pay");
assert_eq!(to_connection_relative("https://github.com/acme/pay"), "acme/pay");
assert_eq!(to_connection_relative("https://github.com/acme/pay.git"), "acme/pay");
assert_eq!(to_connection_relative("git@github.com:acme/pay.git"), "acme/pay");
assert_eq!(to_connection_relative("https://github.example.com:8443/acme/pay"), "acme/pay");
}
#[test]
fn nesting_survives() {
assert_eq!(to_connection_relative("https://gitlab.com/group/sub/app.git"), "group/sub/app");
assert_eq!(to_connection_relative("gitlab.com/group/sub/app"), "group/sub/app");
}
#[test]
fn already_relative_is_returned_unchanged() {
assert_eq!(to_connection_relative("acme/pay"), "acme/pay");
assert_eq!(to_connection_relative("group/sub/app"), "group/sub/app");
assert_eq!(to_connection_relative("my.group/app"), "my.group/app");
assert_eq!(to_connection_relative(&to_connection_relative("github.com/acme/pay")), "acme/pay");
}
#[test]
fn matching_normalises_both_sides() {
assert!(matches_scope_entry("https://github.com/acme/pay", "acme/pay"));
assert!(matches_scope_entry("acme/pay", "acme/pay"));
assert!(!matches_scope_entry("github.com/acme/other", "acme/pay"));
}
}