use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use serde::Deserialize;
mod resolve;
use resolve::BUN_QUERY;
pub use resolve::{
CargoPublish, Publisher, RELEASE_ONLY, check_options, prerelease_tag, publisher_name, resolve,
resolve_for_version, stock_publisher_for_file,
};
#[derive(Debug, Clone, Default, Deserialize)]
#[non_exhaustive]
pub struct PublisherSpec {
pub noun: Option<String>,
pub argv: Option<Vec<String>>,
pub config_name: Option<String>,
pub config_argv: Option<Vec<String>>,
pub registry_argv: Option<Vec<String>>,
pub default_argv: Option<Vec<String>>,
#[serde(default)]
pub registries: BTreeMap<String, String>,
pub query: Option<Vec<String>>,
}
impl PublisherSpec {
#[must_use]
pub fn stock(name: &str) -> Option<Self> {
match name {
"cargo" => Some(Self {
noun: Some("crate".into()),
argv: Some(vec![
"cargo".into(),
"publish".into(),
"--locked".into(),
"--manifest-path".into(),
"{path}".into(),
]),
registry_argv: Some(vec!["--registry".into(), "{registry}".into()]),
registries: BTreeMap::from([("crates-io".into(), String::new())]),
..Self::default()
}),
"bun" => Some(Self {
noun: Some("package".into()),
argv: Some(vec![
"bun".into(),
"publish".into(),
"--tolerate-republish".into(),
"--cwd".into(),
"{dir}".into(),
]),
config_name: Some("bunfig.toml".into()),
config_argv: Some(vec!["--config".into(), "{config}".into()]),
registry_argv: Some(vec!["--registry".into(), "{registry}".into()]),
default_argv: Some(vec!["--access".into(), "public".into()]),
registries: BTreeMap::from([
("npm".into(), String::new()),
("github".into(), "https://npm.pkg.github.com".into()),
]),
query: Some(BUN_QUERY.iter().map(|part| (*part).to_owned()).collect()),
}),
_ => None,
}
}
fn merge(self, over: Self) -> Self {
Self {
noun: over.noun.or(self.noun),
argv: over.argv.or(self.argv),
config_name: over.config_name.or(self.config_name),
config_argv: over.config_argv.or(self.config_argv),
registry_argv: over.registry_argv.or(self.registry_argv),
default_argv: over.default_argv.or(self.default_argv),
registries: if over.registries.is_empty() {
self.registries
} else {
over.registries
},
query: over.query.or(self.query),
}
}
pub fn render(
&self,
name: &str,
manifest: &Path,
registry: Option<&str>,
) -> Result<(String, Vec<String>)> {
let argv = self
.argv
.as_ref()
.with_context(|| format!("publisher {name:?} needs argv"))?;
let out = self.assemble(argv, manifest, registry, &[], ExtraArgs::Upload)?;
let noun = self.noun.clone().unwrap_or_else(|| "package".into());
Ok((noun, out))
}
pub fn assemble(
&self,
argv: &[String],
manifest: &Path,
registry: Option<&str>,
extra: &[(&'static str, String)],
appended: ExtraArgs,
) -> Result<Vec<String>> {
let dir = package_dir(manifest);
let config = self
.config_name
.as_deref()
.and_then(|file| find_config(manifest, file));
let registry = resolve_registry(&self.registries, registry);
let mut ctx = BTreeMap::from([
("path", manifest.display().to_string()),
("dir", dir.display().to_string()),
]);
ctx.extend(extra.iter().cloned());
if let Some(path) = &config {
ctx.insert("config", path.display().to_string());
}
if let Some(registry) = ®istry {
ctx.insert("registry", registry.clone());
}
let mut out = expand(argv, &ctx)?;
let (recipe, default) = match appended {
ExtraArgs::Upload => (true, true),
ExtraArgs::StockQuery => (true, false),
ExtraArgs::Nothing => (false, false),
};
if recipe
&& config.is_some()
&& let Some(extra) = &self.config_argv
{
out.extend(expand(extra, &ctx)?);
}
if recipe && config.is_none() && registry.is_some() {
if let Some(extra) = &self.registry_argv {
out.extend(expand(extra, &ctx)?);
}
} else if default
&& registry.is_none()
&& let Some(extra) = &self.default_argv
{
out.extend(expand(extra, &ctx)?);
}
Ok(out)
}
}
#[derive(Debug, Clone, Copy)]
pub enum ExtraArgs {
Upload,
StockQuery,
Nothing,
}
#[must_use]
pub fn package_dir(manifest: &Path) -> &Path {
manifest
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."))
}
#[must_use]
pub fn resolve_registry(
aliases: &BTreeMap<String, String>,
registry: Option<&str>,
) -> Option<String> {
let raw = registry?.trim();
if raw.is_empty() {
return None;
}
match aliases.get(raw) {
Some(mapped) if mapped.is_empty() => None,
Some(mapped) => Some(mapped.clone()),
None => Some(raw.to_owned()),
}
}
pub fn expand(parts: &[String], ctx: &BTreeMap<&str, String>) -> Result<Vec<String>> {
let mut out = Vec::with_capacity(parts.len());
for part in parts {
let mut expanded = part.clone();
for (key, value) in ctx {
expanded = expanded.replace(&format!("{{{key}}}"), value);
}
if let Some(name) = placeholder_in(&expanded) {
let known = ctx
.keys()
.map(|key| format!("{{{key}}}"))
.collect::<Vec<_>>()
.join(" ");
bail!(
"argument {part:?} uses {{{name}}}, which has no value for this package; the placeholders with a value are {known}"
);
}
if !expanded.is_empty() {
out.push(expanded);
}
}
Ok(out)
}
fn placeholder_in(text: &str) -> Option<&str> {
let mut rest = text;
while let Some(open) = rest.find('{') {
let after = &rest[open + 1..];
let close = after.find('}')?;
let name = &after[..close];
let mut chars = name.chars();
if chars
.next()
.is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
{
return Some(name);
}
rest = after;
}
None
}
fn find_config(manifest: &Path, file_name: &str) -> Option<PathBuf> {
let start = manifest.parent().unwrap_or(manifest);
for dir in start.ancestors() {
let candidate = dir.join(file_name);
if candidate.is_file() {
return Some(candidate);
}
if dir.join(".git").exists() {
break;
}
}
None
}