use std::fs::OpenOptions;
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::Path;
use std::{env, fs};
use anyhow::{Context, Result};
pub const PACKSLIP_KEY: &str = "VERCTL_PACKSLIP_KEY";
pub const VERSION_BRANCH_PREFIX: &str = "verctl/release/";
#[must_use]
pub fn version_branch(base: &str) -> String {
format!("{VERSION_BRANCH_PREFIX}{base}")
}
#[must_use]
pub fn is_version_branch(branch: &str) -> bool {
branch
.strip_prefix(VERSION_BRANCH_PREFIX)
.is_some_and(|base| !base.is_empty())
}
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)",
)
}
#[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
}
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())
}
#[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()
}
#[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))
}
#[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)
}
#[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)
}
#[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)
}