1use std::fs::OpenOptions;
5use std::io::{Read, Seek, SeekFrom, Write};
6use std::path::Path;
7use std::{env, fs};
8
9use anyhow::{Context, Result};
10
11pub const PACKSLIP_KEY: &str = "VERCTL_PACKSLIP_KEY";
14
15pub const VERSION_BRANCH_PREFIX: &str = "verctl/release/";
18
19#[must_use]
22pub fn version_branch(base: &str) -> String {
23 format!("{VERSION_BRANCH_PREFIX}{base}")
24}
25
26#[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
35pub 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#[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
60pub 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#[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#[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#[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#[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#[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}