Skip to main content

verctl_core/runtime/
env.rs

1//! Shared environment variables, Actions event payload readers, and
2//! `$GITHUB_OUTPUT` writing.
3
4use std::fs::OpenOptions;
5use std::io::{Read, Seek, SeekFrom, Write};
6use std::path::Path;
7use std::{env, fs};
8
9use anyhow::{Context, Result};
10
11/// The environment variable that supplies a private signing key for
12/// `release packslip`.
13pub const PACKSLIP_KEY: &str = "VERCTL_PACKSLIP_KEY";
14
15/// What every Version PR branch starts with. The rest is the base branch, so
16/// each base gets its own Version PR and the name shows which one it is.
17pub const VERSION_BRANCH_PREFIX: &str = "verctl/release/";
18
19/// The branch the Version PR into `base` is pushed to:
20/// `verctl/release/<base>`.
21#[must_use]
22pub fn version_branch(base: &str) -> String {
23    format!("{VERSION_BRANCH_PREFIX}{base}")
24}
25
26/// Whether `branch` is a Version PR branch: [`VERSION_BRANCH_PREFIX`]
27/// followed by a base branch name.
28#[must_use]
29pub fn is_version_branch(branch: &str) -> bool {
30    branch
31        .strip_prefix(VERSION_BRANCH_PREFIX)
32        .is_some_and(|base| !base.is_empty())
33}
34
35/// Auth for the commands that call the GitHub API.
36///
37/// # Errors
38///
39/// Returns an error when neither `GITHUB_TOKEN` nor `GH_TOKEN` is set to a
40/// non-empty value.
41pub fn resolve_token() -> Result<String> {
42    env_token().context(
43        "this command needs GITHUB_TOKEN or GH_TOKEN (Actions sets GITHUB_TOKEN; locally export the same token, since verctl does not read `gh` logins)",
44    )
45}
46
47/// `GITHUB_TOKEN`, else `GH_TOKEN`, when set to a non-empty value.
48#[must_use]
49pub fn env_token() -> Option<String> {
50    for key in ["GITHUB_TOKEN", "GH_TOKEN"] {
51        if let Ok(value) = env::var(key)
52            && !value.is_empty()
53        {
54            return Some(value);
55        }
56    }
57    None
58}
59
60/// Append to `$GITHUB_OUTPUT`.
61///
62/// # Errors
63///
64/// Returns an error, naming `path`, when the file cannot be opened, read,
65/// or written.
66pub fn write_github_output(path: &Path, body: &str) -> Result<()> {
67    let mut file = OpenOptions::new()
68        .create(true)
69        .read(true)
70        .append(true)
71        .open(path)
72        .with_context(|| path.display().to_string())?;
73    let end = file
74        .metadata()
75        .with_context(|| path.display().to_string())?
76        .len();
77    if end > 0 {
78        let mut last = [0u8];
79        file.seek(SeekFrom::Start(end - 1))
80            .and_then(|_| file.read_exact(&mut last))
81            .with_context(|| path.display().to_string())?;
82        if last[0] != b'\n' {
83            file.write_all(b"\n")
84                .with_context(|| path.display().to_string())?;
85        }
86    }
87    file.write_all(body.as_bytes())
88        .with_context(|| path.display().to_string())
89}
90
91/// The pull request number of a `pull_request` event payload, or `None` when
92/// it does not parse or is another event's.
93#[must_use]
94pub fn pull_request_number(raw: &str) -> Option<u64> {
95    serde_json::from_str::<serde_json::Value>(raw)
96        .ok()?
97        .get("pull_request")?
98        .get("number")?
99        .as_u64()
100}
101
102/// Whether the Actions event is a merge queue's `merge_group` event, read
103/// from its payload. Without an event it is `false`.
104#[must_use]
105pub fn event_is_merge_group() -> bool {
106    env::var("GITHUB_EVENT_PATH")
107        .ok()
108        .and_then(|path| fs::read_to_string(path).ok())
109        .is_some_and(|raw| is_merge_group(&raw))
110}
111
112/// Whether an event payload is a `merge_group` event's.
113#[must_use]
114pub fn is_merge_group(raw: &str) -> bool {
115    serde_json::from_str::<serde_json::Value>(raw)
116        .ok()
117        .and_then(|event| event.get("merge_group").map(serde_json::Value::is_object))
118        .unwrap_or(false)
119}
120
121/// The repository's default branch named by the Actions event payload, or
122/// `None` without an event.
123#[must_use]
124pub fn event_default_branch() -> Option<String> {
125    let raw = fs::read_to_string(env::var("GITHUB_EVENT_PATH").ok()?).ok()?;
126    default_branch_of(&raw)
127}
128
129/// `repository.default_branch` of an event payload, or `None` when it does
130/// not parse or names none.
131#[must_use]
132pub fn default_branch_of(raw: &str) -> Option<String> {
133    serde_json::from_str::<serde_json::Value>(raw)
134        .ok()?
135        .get("repository")?
136        .get("default_branch")?
137        .as_str()
138        .filter(|name| !name.is_empty())
139        .map(str::to_owned)
140}