Skip to main content

verctl_core/
repo.rs

1//! GitHub repository slug and remote URL parsing.
2
3use anyhow::{Context, Result, ensure};
4
5/// A GitHub repository, as `owner/name`.
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct Repo {
8    /// The user or organization that owns the repository.
9    pub owner: String,
10    /// The repository name, without a `.git` suffix.
11    pub name: String,
12}
13
14/// Parses an `owner/name` slug.
15///
16/// # Errors
17///
18/// Returns an error when `slug` has no `/`, an empty owner or name, or more
19/// than one `/`.
20pub fn parse_slug(slug: &str) -> Result<Repo> {
21    let (owner, name) = slug
22        .split_once('/')
23        .context("GITHUB_REPOSITORY must be owner/name")?;
24    ensure!(
25        !owner.is_empty() && !name.is_empty() && !name.contains('/'),
26        "GITHUB_REPOSITORY must be owner/name"
27    );
28    Ok(Repo {
29        owner: owner.to_owned(),
30        name: name.trim_end_matches(".git").to_owned(),
31    })
32}
33
34/// Parses an ssh or https remote URL on github.com or a `*.github.com` host.
35///
36/// # Errors
37///
38/// Returns an error when the URL is not an ssh or http(s) URL with a path.
39/// It also returns one when its host is not GitHub or the path is not
40/// `owner/name`.
41pub fn parse_remote(url: &str) -> Result<Repo> {
42    let url = url.trim();
43    if let Some(rest) = url.strip_prefix("git@") {
44        let (host, path) = rest
45            .split_once(':')
46            .context("ssh remote must be git@host:owner/name")?;
47        ensure!(
48            host == "github.com" || host.ends_with(".github.com"),
49            "origin is not GitHub ({host})"
50        );
51        return parse_slug(path);
52    }
53    let rest = url
54        .strip_prefix("https://")
55        .or_else(|| url.strip_prefix("http://"))
56        .or_else(|| url.strip_prefix("ssh://git@"))
57        .context("origin URL is not ssh or https")?;
58    let (host, path) = rest.split_once('/').context("origin URL has no path")?;
59    ensure!(
60        host == "github.com" || host.ends_with(".github.com"),
61        "origin is not GitHub ({host})"
62    );
63    parse_slug(path)
64}