use anyhow::{Context, Result, ensure};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Repo {
pub owner: String,
pub name: String,
}
pub fn parse_slug(slug: &str) -> Result<Repo> {
let (owner, name) = slug
.split_once('/')
.context("GITHUB_REPOSITORY must be owner/name")?;
ensure!(
!owner.is_empty() && !name.is_empty() && !name.contains('/'),
"GITHUB_REPOSITORY must be owner/name"
);
Ok(Repo {
owner: owner.to_owned(),
name: name.trim_end_matches(".git").to_owned(),
})
}
pub fn parse_remote(url: &str) -> Result<Repo> {
let url = url.trim();
if let Some(rest) = url.strip_prefix("git@") {
let (host, path) = rest
.split_once(':')
.context("ssh remote must be git@host:owner/name")?;
ensure!(
host == "github.com" || host.ends_with(".github.com"),
"origin is not GitHub ({host})"
);
return parse_slug(path);
}
let rest = url
.strip_prefix("https://")
.or_else(|| url.strip_prefix("http://"))
.or_else(|| url.strip_prefix("ssh://git@"))
.context("origin URL is not ssh or https")?;
let (host, path) = rest.split_once('/').context("origin URL has no path")?;
ensure!(
host == "github.com" || host.ends_with(".github.com"),
"origin is not GitHub ({host})"
);
parse_slug(path)
}