#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Forge {
GitHub,
GitLab,
Bitbucket,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WebRepo {
pub forge: Forge,
pub scheme: &'static str,
pub host: String,
pub path: String,
}
pub fn web_repo(url: &str) -> Option<WebRepo> {
let url = url.trim();
let mut web_scheme = "https";
let (host, path) = if let Some((scheme, rest)) = url.split_once("://") {
let (authority, path) = rest.split_once('/')?;
let authority = authority.rsplit('@').next()?;
let host = match scheme {
"https" => authority,
"http" => {
web_scheme = "http";
authority
}
"ssh" | "git" | "git+ssh" | "ssh+git" => authority.split(':').next()?,
_ => return None,
};
(host, path)
} else {
let (authority, path) = url.split_once(':')?;
if authority.contains('/') || authority.len() < 2 {
return None;
}
(authority.rsplit('@').next()?, path)
};
let host = host.to_ascii_lowercase();
let path = path.trim_matches('/');
let path = path
.strip_suffix(".git")
.unwrap_or(path)
.trim_end_matches('/');
if host.is_empty() || path.split('/').filter(|p| !p.is_empty()).count() < 2 {
return None;
}
let name = host.split(':').next().unwrap_or(&host);
let forge = if name == "bitbucket.org" {
Forge::Bitbucket
} else if name.split('.').any(|label| label == "gitlab") {
Forge::GitLab
} else if name.split('.').any(|label| label == "github") {
Forge::GitHub
} else {
return None;
};
Some(WebRepo {
forge,
scheme: web_scheme,
host,
path: path.to_string(),
})
}
pub fn file_url(repo: &WebRepo, rev: &str, rel: &str, lines: Option<(usize, usize)>) -> String {
let blob = match repo.forge {
Forge::GitHub => "blob",
Forge::GitLab => "-/blob",
Forge::Bitbucket => "src",
};
let fragment = match lines {
None => String::new(),
Some((a, b)) if a == b => match repo.forge {
Forge::Bitbucket => format!("#lines-{a}"),
_ => format!("#L{a}"),
},
Some((a, b)) => match repo.forge {
Forge::GitHub => format!("#L{a}-L{b}"),
Forge::GitLab => format!("#L{a}-{b}"),
Forge::Bitbucket => format!("#lines-{a}:{b}"),
},
};
format!(
"{}://{}/{}/{blob}/{}/{}{fragment}",
repo.scheme,
repo.host,
repo.path,
encode_path(rev),
encode_path(rel),
)
}
fn encode_path(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
if b.is_ascii_alphanumeric() || b"-._~/!$&'()*+,;=:@".contains(&b) {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn github(path: &str) -> WebRepo {
WebRepo {
forge: Forge::GitHub,
scheme: "https",
host: String::from("github.com"),
path: path.to_string(),
}
}
#[test]
fn ssh_and_https_origins_name_the_same_repository() {
let want = Some(github("acme/widgets"));
for url in [
"git@github.com:acme/widgets.git",
"git@github.com:acme/widgets",
"ssh://git@github.com/acme/widgets.git",
"ssh://git@github.com:22/acme/widgets.git",
"https://github.com/acme/widgets.git",
"https://token@github.com/acme/widgets/",
"git://github.com/acme/widgets.git",
" https://GitHub.com/acme/widgets ",
] {
assert_eq!(web_repo(url), want, "{url}");
}
}
#[test]
fn gitlab_bitbucket_and_enterprise_hosts_are_recognised() {
let gl = web_repo("git@gitlab.com:group/sub/proj.git").unwrap();
assert_eq!(
(gl.forge, gl.path.as_str()),
(Forge::GitLab, "group/sub/proj")
);
let own = web_repo("https://gitlab.example.com:8443/team/app").unwrap();
assert_eq!(
(own.forge, own.host.as_str()),
(Forge::GitLab, "gitlab.example.com:8443")
);
let bb = web_repo("git@bitbucket.org:team/app.git").unwrap();
assert_eq!(bb.forge, Forge::Bitbucket);
let ghe = web_repo("git@github.acme.com:eng/core.git").unwrap();
assert_eq!(
(ghe.forge, ghe.host.as_str()),
(Forge::GitHub, "github.acme.com")
);
}
#[test]
fn remotes_croft_cannot_link_to_give_none() {
for url in [
"/srv/git/widgets.git",
"../widgets",
"C:/repos/widgets",
"file:///srv/git/widgets.git",
"git@git.example.com:acme/widgets.git",
"https://codeberg.org/acme/widgets",
"https://github.com/acme",
"git@github.com:",
"",
] {
assert_eq!(web_repo(url), None, "{url}");
}
}
#[test]
fn each_host_gets_its_own_line_fragment() {
let gh = github("acme/widgets");
assert_eq!(
file_url(&gh, "abc123", "src/main.rs", Some((2, 4))),
"https://github.com/acme/widgets/blob/abc123/src/main.rs#L2-L4"
);
assert_eq!(
file_url(&gh, "main", "src/main.rs", Some((2, 2))),
"https://github.com/acme/widgets/blob/main/src/main.rs#L2"
);
let gl = web_repo("git@gitlab.com:acme/widgets.git").unwrap();
assert_eq!(
file_url(&gl, "abc123", "src/main.rs", Some((2, 4))),
"https://gitlab.com/acme/widgets/-/blob/abc123/src/main.rs#L2-4"
);
let bb = web_repo("git@bitbucket.org:acme/widgets.git").unwrap();
assert_eq!(
file_url(&bb, "abc123", "src/main.rs", Some((2, 4))),
"https://bitbucket.org/acme/widgets/src/abc123/src/main.rs#lines-2:4"
);
assert_eq!(
file_url(&bb, "abc123", "a.rs", Some((7, 7))),
"https://bitbucket.org/acme/widgets/src/abc123/a.rs#lines-7"
);
}
#[test]
fn an_http_remote_keeps_its_scheme() {
let own = web_repo("http://gitlab.example.com:8080/team/app.git").unwrap();
assert_eq!(
file_url(&own, "main", "a.rs", Some((3, 3))),
"http://gitlab.example.com:8080/team/app/-/blob/main/a.rs#L3"
);
}
#[test]
fn odd_paths_are_encoded_and_no_lines_means_no_fragment() {
let gh = github("acme/widgets");
assert_eq!(
file_url(&gh, "feat/x#1", "docs/a b#1?.md", None),
"https://github.com/acme/widgets/blob/feat/x%231/docs/a%20b%231%3F.md"
);
}
}