verctl-core 0.9.3

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
Documentation
//! Shared environment variables, Actions event payload readers, and
//! `$GITHUB_OUTPUT` writing.

use std::fs::OpenOptions;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::Path;
use std::{env, fs};

use anyhow::{Context, Result};

/// The environment variable that supplies a private signing key for
/// `release packslip`.
pub const PACKSLIP_KEY: &str = "VERCTL_PACKSLIP_KEY";

/// What every Version PR branch starts with. The rest is the base branch, so
/// each base gets its own Version PR and the name shows which one it is.
pub const VERSION_BRANCH_PREFIX: &str = "verctl/release/";

/// The branch the Version PR into `base` is pushed to:
/// `verctl/release/<base>`.
#[must_use]
pub fn version_branch(base: &str) -> String {
    format!("{VERSION_BRANCH_PREFIX}{base}")
}

/// Whether `branch` is a Version PR branch: [`VERSION_BRANCH_PREFIX`]
/// followed by a base branch name.
#[must_use]
pub fn is_version_branch(branch: &str) -> bool {
    branch
        .strip_prefix(VERSION_BRANCH_PREFIX)
        .is_some_and(|base| !base.is_empty())
}

/// Auth for the commands that call the GitHub API.
///
/// # Errors
///
/// Returns an error when neither `GITHUB_TOKEN` nor `GH_TOKEN` is set to a
/// non-empty value.
pub fn resolve_token() -> Result<String> {
    env_token().context(
        "this command needs GITHUB_TOKEN or GH_TOKEN (Actions sets GITHUB_TOKEN; locally export the same token, since verctl does not read `gh` logins)",
    )
}

/// `GITHUB_TOKEN`, else `GH_TOKEN`, when set to a non-empty value.
#[must_use]
pub fn env_token() -> Option<String> {
    for key in ["GITHUB_TOKEN", "GH_TOKEN"] {
        if let Ok(value) = env::var(key)
            && !value.is_empty()
        {
            return Some(value);
        }
    }
    None
}

/// Append to `$GITHUB_OUTPUT`.
///
/// # Errors
///
/// Returns an error, naming `path`, when the file cannot be opened, read,
/// or written.
pub fn write_github_output(path: &Path, body: &str) -> Result<()> {
    let mut file = OpenOptions::new()
        .create(true)
        .read(true)
        .append(true)
        .open(path)
        .with_context(|| path.display().to_string())?;
    let end = file
        .metadata()
        .with_context(|| path.display().to_string())?
        .len();
    if end > 0 {
        let mut last = [0u8];
        file.seek(SeekFrom::Start(end - 1))
            .and_then(|_| file.read_exact(&mut last))
            .with_context(|| path.display().to_string())?;
        if last[0] != b'\n' {
            file.write_all(b"\n")
                .with_context(|| path.display().to_string())?;
        }
    }
    file.write_all(body.as_bytes())
        .with_context(|| path.display().to_string())
}

/// The pull request number of a `pull_request` event payload, or `None` when
/// it does not parse or is another event's.
#[must_use]
pub fn pull_request_number(raw: &str) -> Option<u64> {
    serde_json::from_str::<serde_json::Value>(raw)
        .ok()?
        .get("pull_request")?
        .get("number")?
        .as_u64()
}

/// Whether the Actions event is a merge queue's `merge_group` event, read
/// from its payload. Without an event it is `false`.
#[must_use]
pub fn event_is_merge_group() -> bool {
    env::var("GITHUB_EVENT_PATH")
        .ok()
        .and_then(|path| fs::read_to_string(path).ok())
        .is_some_and(|raw| is_merge_group(&raw))
}

/// Whether an event payload is a `merge_group` event's.
#[must_use]
pub fn is_merge_group(raw: &str) -> bool {
    serde_json::from_str::<serde_json::Value>(raw)
        .ok()
        .and_then(|event| event.get("merge_group").map(serde_json::Value::is_object))
        .unwrap_or(false)
}

/// The repository's default branch named by the Actions event payload, or
/// `None` without an event.
#[must_use]
pub fn event_default_branch() -> Option<String> {
    let raw = fs::read_to_string(env::var("GITHUB_EVENT_PATH").ok()?).ok()?;
    default_branch_of(&raw)
}

/// `repository.default_branch` of an event payload, or `None` when it does
/// not parse or names none.
#[must_use]
pub fn default_branch_of(raw: &str) -> Option<String> {
    serde_json::from_str::<serde_json::Value>(raw)
        .ok()?
        .get("repository")?
        .get("default_branch")?
        .as_str()
        .filter(|name| !name.is_empty())
        .map(str::to_owned)
}