verctl-core 0.9.4

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
Documentation
//! GitHub repository slug and remote URL parsing.

use anyhow::{Context, Result, ensure};

/// A GitHub repository, as `owner/name`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Repo {
    /// The user or organization that owns the repository.
    pub owner: String,
    /// The repository name, without a `.git` suffix.
    pub name: String,
}

/// Parses an `owner/name` slug.
///
/// # Errors
///
/// Returns an error when `slug` has no `/`, an empty owner or name, or more
/// than one `/`.
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(),
    })
}

/// Parses an ssh or https remote URL on github.com or a `*.github.com` host.
///
/// # Errors
///
/// Returns an error when the URL is not an ssh or http(s) URL with a path.
/// It also returns one when its host is not GitHub or the path is not
/// `owner/name`.
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)
}