use std::fs;
use std::io::ErrorKind;
use std::path::{Component, Path, PathBuf};
use anyhow::{Context, Result};
use toml_edit::{DocumentMut, Item};
pub fn opt_out(manifest: &Path, tree: &Path) -> Result<Option<&'static str>> {
let Some(bytes) = read_optional(manifest)? else {
return Ok(None);
};
let text = String::from_utf8(bytes).with_context(|| manifest.display().to_string())?;
let opted = match manifest.file_name().and_then(|name| name.to_str()) {
Some("Cargo.toml") => {
cargo_opts_out(manifest, &text, tree).with_context(|| manifest.display().to_string())?
}
Some("package.json") => {
let json: serde_json::Value =
serde_json::from_str(&text).with_context(|| manifest.display().to_string())?;
(json.get("private") == Some(&serde_json::Value::Bool(true)))
.then_some(r#"package.json sets "private": true"#)
}
_ => None,
};
Ok(opted)
}
fn cargo_opts_out(manifest: &Path, text: &str, tree: &Path) -> Result<Option<&'static str>> {
let document = text.parse::<DocumentMut>()?;
let Some(package) = document.get("package") else {
return Ok(None);
};
let Some(publish) = package.get("publish") else {
return Ok(None);
};
if publish.get("workspace").and_then(Item::as_bool) != Some(true) {
return Ok(denies(publish).map(|denial| match denial {
Reason::False => "Cargo.toml sets publish = false",
Reason::NoRegistry => "Cargo.toml sets publish = []",
}));
}
let Some(workspace) = workspace_root(manifest, &document, tree)? else {
return Ok(None);
};
Ok(workspace
.get("workspace")
.and_then(|table| table.get("package"))
.and_then(|package| package.get("publish"))
.and_then(denies)
.map(|denial| match denial {
Reason::False => "Cargo.toml inherits publish = false from its workspace",
Reason::NoRegistry => "Cargo.toml inherits publish = [] from its workspace",
}))
}
enum Reason {
False,
NoRegistry,
}
fn denies(publish: &Item) -> Option<Reason> {
if publish.as_bool() == Some(false) {
Some(Reason::False)
} else if publish.as_array().is_some_and(toml_edit::Array::is_empty) {
Some(Reason::NoRegistry)
} else {
None
}
}
fn workspace_root(
manifest: &Path,
document: &DocumentMut,
tree: &Path,
) -> Result<Option<DocumentMut>> {
if document.contains_key("workspace") {
return Ok(Some(document.clone()));
}
let parent = manifest.parent().unwrap_or_else(|| Path::new(""));
let Ok(package) = parent.strip_prefix(tree) else {
return Ok(None);
};
if without_links(tree, package)?.is_none() {
return Ok(None);
}
let named = document
.get("package")
.and_then(|package| package.get("workspace"))
.and_then(Item::as_str);
let dirs: Vec<PathBuf> = named.map_or_else(
|| package.ancestors().skip(1).map(Path::to_path_buf).collect(),
|path| vec![package.join(path)],
);
for dir in dirs {
let Some(candidate) = without_links(tree, &dir.join("Cargo.toml"))? else {
continue;
};
let Some(bytes) = read_optional(&candidate)? else {
continue;
};
let text = String::from_utf8(bytes).with_context(|| candidate.display().to_string())?;
let parsed = text
.parse::<DocumentMut>()
.with_context(|| candidate.display().to_string())?;
if parsed.contains_key("workspace") {
return Ok(Some(parsed));
}
}
Ok(None)
}
fn without_links(tree: &Path, path: &Path) -> Result<Option<PathBuf>> {
let mut resolved = tree.to_path_buf();
let mut depth = 0_usize;
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
if depth == 0 {
return Ok(None);
}
resolved.pop();
depth -= 1;
}
Component::Normal(name) => {
resolved.push(name);
depth += 1;
match fs::symlink_metadata(&resolved) {
Ok(metadata) if metadata.file_type().is_symlink() => return Ok(None),
Ok(_) => {}
Err(error)
if matches!(
error.kind(),
ErrorKind::NotFound | ErrorKind::NotADirectory
) =>
{
return Ok(None);
}
Err(error) => {
return Err(error).with_context(|| resolved.display().to_string());
}
}
}
Component::RootDir | Component::Prefix(_) => return Ok(None),
}
}
Ok(Some(resolved))
}
fn read_optional(path: &Path) -> Result<Option<Vec<u8>>> {
match fs::read(path) {
Ok(bytes) => Ok(Some(bytes)),
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
Err(error) => Err(error).with_context(|| path.display().to_string()),
}
}
#[cfg(test)]
mod tests;