use std::{env, fmt};
use anyhow::{Result, bail};
pub const SECRET: &str = "VERCTL_REGISTRY_TOKEN";
pub const TRUSTED: &str = "VERCTL_TRUSTED_PUBLISHING_TOKEN";
pub const SOURCES: [&str; 2] = [SECRET, TRUSTED];
pub const OWNER: &str = "VERCTL_OWNER_TOKEN";
#[must_use]
pub fn owner_token() -> Option<String> {
env::var(OWNER).ok().filter(|token| !token.is_empty())
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum NewCrates {
#[default]
Off,
Every,
Only(Vec<String>),
}
impl NewCrates {
#[must_use]
pub fn allows(&self, name: &str) -> bool {
match self {
Self::Off => false,
Self::Every => true,
Self::Only(names) => names.iter().any(|only| only == name),
}
}
#[must_use]
pub const fn is_on(&self) -> bool {
!matches!(self, Self::Off)
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct RegistryToken {
variable: String,
token: String,
creation: Option<String>,
has_trusted_publishing: bool,
}
impl fmt::Debug for RegistryToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RegistryToken")
.field("variable", &self.variable)
.finish_non_exhaustive()
}
}
impl RegistryToken {
pub fn from_env(variable: &str) -> Result<Option<Self>> {
let read = |key| {
env::var(key)
.ok()
.filter(|value: &String| !value.is_empty())
};
Self::resolve(read(SECRET), read(TRUSTED), variable)
}
pub fn resolve(
secret: Option<String>,
trusted: Option<String>,
variable: &str,
) -> Result<Option<Self>> {
let (token, has_trusted_publishing) = match (secret, trusted) {
(Some(_), Some(_)) => bail!(
"{SECRET} and {TRUSTED} are both set: pass either the registry-token secret or crates-io-trusted-publishing"
),
(Some(token), None) => (token, false),
(None, Some(token)) => (token, true),
(None, None) => return Ok(None),
};
Ok(Some(Self {
variable: variable.to_owned(),
token,
creation: None,
has_trusted_publishing,
}))
}
pub fn from_env_new(variable: &str) -> Result<Self> {
let read = |key| {
env::var(key)
.ok()
.filter(|value: &String| !value.is_empty())
};
Self::resolve_new(read(SECRET), read(TRUSTED), variable)
}
pub fn resolve_new(
secret: Option<String>,
trusted: Option<String>,
variable: &str,
) -> Result<Self> {
let Some(secret) = secret else {
bail!(
"--new needs {SECRET}, which the release workflow sets from its `registry-token` secret: set it to the crates.io token that creates new crates"
);
};
Ok(match trusted {
Some(token) => Self {
variable: variable.to_owned(),
token,
creation: Some(secret),
has_trusted_publishing: true,
},
None => Self {
variable: variable.to_owned(),
token: secret,
creation: None,
has_trusted_publishing: false,
},
})
}
#[must_use]
pub const fn has_trusted_publishing(&self) -> bool {
self.has_trusted_publishing
}
#[must_use]
pub fn env(&self) -> (&str, &str) {
(&self.variable, &self.token)
}
#[must_use]
pub fn creation_env(&self) -> (&str, &str) {
self.creation
.as_ref()
.map_or_else(|| self.env(), |creation| (&self.variable, creation))
}
}
#[cfg(test)]
mod tests;