Skip to content

Commit 714d8f5

Browse files
committed
Split registry inference from registry validation
This is in preparation for reusing infer_registry during publishing (which needs different validation logic). It also changes the registry validation slightly, adding in a check (from the publish logic) forbidding implicit source replacement. This affects the tests (which configure a dummy registry for source replacement), so we also weaken the checks by only erroring for registry issues when there are actually local dependencies.
1 parent 2f54df2 commit 714d8f5

File tree

3 files changed

+103
-89
lines changed

3 files changed

+103
-89
lines changed

src/cargo/ops/cargo_package.rs

Lines changed: 67 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use crate::core::{Feature, PackageIdSpecQuery, Shell, Verbosity, Workspace};
1515
use crate::core::{Package, PackageId, PackageSet, Resolve, SourceId};
1616
use crate::ops::registry::infer_registry;
1717
use crate::sources::registry::index::{IndexPackage, RegistryDependency};
18-
use crate::sources::PathSource;
18+
use crate::sources::{PathSource, CRATES_IO_REGISTRY};
1919
use crate::util::cache_lock::CacheLockMode;
2020
use crate::util::context::JobsConfig;
2121
use crate::util::errors::CargoResult;
@@ -24,7 +24,7 @@ use crate::util::{
2424
self, human_readable_bytes, restricted_names, FileLock, Filesystem, GlobalContext, Graph,
2525
};
2626
use crate::{drop_println, ops};
27-
use anyhow::Context as _;
27+
use anyhow::{bail, Context as _};
2828
use cargo_util::paths;
2929
use flate2::read::GzDecoder;
3030
use flate2::{Compression, GzBuilder};
@@ -33,6 +33,8 @@ use tar::{Archive, Builder, EntryType, Header, HeaderMode};
3333
use tracing::debug;
3434
use unicase::Ascii as UncasedAscii;
3535

36+
use super::RegistryOrIndex;
37+
3638
#[derive(Clone)]
3739
pub struct PackageOpts<'gctx> {
3840
pub gctx: &'gctx GlobalContext,
@@ -173,6 +175,43 @@ fn create_package(
173175
return Ok(dst);
174176
}
175177

178+
/// Determine which registry the packages are for.
179+
///
180+
/// The registry only affects the built packages if there are dependencies within the
181+
/// packages that we're packaging: if we're packaging foo-bin and foo-lib, and foo-bin
182+
/// depends on foo-lib, then the foo-lib entry in foo-bin's lockfile will depend on the
183+
/// registry that we're building packages for.
184+
fn get_registry(
185+
gctx: &GlobalContext,
186+
pkgs: &[&Package],
187+
reg_or_index: Option<RegistryOrIndex>,
188+
) -> CargoResult<SourceId> {
189+
let reg_or_index = match reg_or_index.clone() {
190+
Some(r) => Some(r),
191+
None => infer_registry(pkgs)?,
192+
};
193+
194+
// Validate the registry against the packages' allow-lists.
195+
let reg = reg_or_index
196+
.clone()
197+
.unwrap_or_else(|| RegistryOrIndex::Registry(CRATES_IO_REGISTRY.to_owned()));
198+
if let RegistryOrIndex::Registry(reg_name) = reg {
199+
for pkg in pkgs {
200+
if let Some(allowed) = pkg.publish().as_ref() {
201+
if !allowed.iter().any(|a| a == &reg_name) {
202+
bail!(
203+
"`{}` cannot be packaged.\n\
204+
The registry `{}` is not listed in the `package.publish` value in Cargo.toml.",
205+
pkg.name(),
206+
reg_name
207+
);
208+
}
209+
}
210+
}
211+
}
212+
Ok(ops::registry::get_source_id(gctx, reg_or_index.as_ref())?.replacement)
213+
}
214+
176215
/// Packages an entire workspace.
177216
///
178217
/// Returns the generated package files. If `opts.list` is true, skips
@@ -196,19 +235,34 @@ pub fn package(ws: &Workspace<'_>, opts: &PackageOpts<'_>) -> CargoResult<Vec<Fi
196235
// below, and will be validated during the verification step.
197236
}
198237

238+
let deps = local_deps(pkgs.iter().map(|(p, f)| ((*p).clone(), f.clone())));
199239
let just_pkgs: Vec<_> = pkgs.iter().map(|p| p.0).collect();
200-
let publish_reg = infer_registry(ws.gctx(), &just_pkgs, opts.reg_or_index.clone())?;
201-
debug!("packaging for registry {publish_reg}");
240+
241+
let sid = match get_registry(ws.gctx(), &just_pkgs, opts.reg_or_index.clone()) {
242+
Ok(sid) => {
243+
debug!("packaging for registry {}", sid);
244+
Some(sid)
245+
}
246+
Err(e) => {
247+
if deps.has_no_dependencies() && opts.reg_or_index.is_none() {
248+
// The publish registry doesn't matter unless there are local dependencies,
249+
// so ignore any errors if we don't need it. If they explicitly passed a registry
250+
// on the CLI, we check it no matter what.
251+
None
252+
} else {
253+
return Err(e);
254+
}
255+
}
256+
};
202257

203258
let mut local_reg = if ws.gctx().cli_unstable().package_workspace {
204259
let reg_dir = ws.target_dir().join("package").join("tmp-registry");
205-
Some(TmpRegistry::new(ws.gctx(), reg_dir, publish_reg)?)
260+
sid.map(|sid| TmpRegistry::new(ws.gctx(), reg_dir, sid))
261+
.transpose()?
206262
} else {
207263
None
208264
};
209265

210-
let deps = local_deps(pkgs.iter().map(|(p, f)| ((*p).clone(), f.clone())));
211-
212266
// Packages need to be created in dependency order, because dependencies must
213267
// be added to our local overlay before we can create lockfiles that depend on them.
214268
let sorted_pkgs = deps.sort();
@@ -262,6 +316,12 @@ impl LocalDependencies {
262316
.map(|name| self.packages[&name].clone())
263317
.collect()
264318
}
319+
320+
pub fn has_no_dependencies(&self) -> bool {
321+
self.graph
322+
.iter()
323+
.all(|node| self.graph.edges(node).next().is_none())
324+
}
265325
}
266326

267327
/// Build just the part of the dependency graph that's between the given packages,

src/cargo/ops/registry/mod.rs

Lines changed: 34 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use url::Url;
2121

2222
use crate::core::{Package, PackageId, SourceId};
2323
use crate::sources::source::Source;
24-
use crate::sources::{RegistrySource, SourceConfigMap, CRATES_IO_REGISTRY};
24+
use crate::sources::{RegistrySource, SourceConfigMap};
2525
use crate::util::auth;
2626
use crate::util::cache_lock::CacheLockMode;
2727
use crate::util::context::{GlobalContext, PathAndArgs};
@@ -191,7 +191,7 @@ fn registry(
191191
///
192192
/// The return value is a pair of `SourceId`s: The first may be a built-in replacement of
193193
/// crates.io (such as index.crates.io), while the second is always the original source.
194-
fn get_source_id(
194+
pub(crate) fn get_source_id(
195195
gctx: &GlobalContext,
196196
reg_or_index: Option<&RegistryOrIndex>,
197197
) -> CargoResult<RegistrySourceIds> {
@@ -324,87 +324,40 @@ pub(crate) struct RegistrySourceIds {
324324
}
325325

326326
/// If this set of packages has an unambiguous publish registry, find it.
327-
pub(crate) fn infer_registry(
328-
gctx: &GlobalContext,
329-
pkgs: &[&Package],
330-
reg_or_index: Option<RegistryOrIndex>,
331-
) -> CargoResult<SourceId> {
332-
let reg_or_index = match reg_or_index {
333-
Some(r) => r,
334-
None => {
335-
if pkgs[1..].iter().all(|p| p.publish() == pkgs[0].publish()) {
336-
// If all packages have the same publish settings, we take that as the default.
337-
match pkgs[0].publish().as_deref() {
338-
Some([unique_pkg_reg]) => RegistryOrIndex::Registry(unique_pkg_reg.to_owned()),
339-
None | Some([]) => RegistryOrIndex::Registry(CRATES_IO_REGISTRY.to_owned()),
340-
Some([reg, ..]) if pkgs.len() == 1 => {
341-
// For backwards compatibility, avoid erroring if there's only one package.
342-
// The registry doesn't affect packaging in this case.
343-
RegistryOrIndex::Registry(reg.to_owned())
344-
}
345-
Some(regs) => {
346-
let mut regs: Vec<_> = regs.iter().map(|s| format!("\"{}\"", s)).collect();
347-
regs.sort();
348-
regs.dedup();
349-
// unwrap: the match block ensures that there's more than one reg.
350-
let (last_reg, regs) = regs.split_last().unwrap();
351-
bail!(
352-
"--registry is required to disambiguate between {} or {} registries",
353-
regs.join(", "),
354-
last_reg
355-
)
356-
}
357-
}
358-
} else {
359-
let common_regs = pkgs
360-
.iter()
361-
// `None` means "all registries", so drop them instead of including them
362-
// in the intersection.
363-
.filter_map(|p| p.publish().as_deref())
364-
.map(|p| p.iter().collect::<HashSet<_>>())
365-
.reduce(|xs, ys| xs.intersection(&ys).cloned().collect())
366-
.unwrap_or_default();
367-
if common_regs.is_empty() {
368-
bail!("conflicts between `package.publish` fields in the selected packages");
369-
} else {
370-
bail!(
371-
"--registry is required because not all `package.publish` settings agree",
372-
);
373-
}
327+
pub(crate) fn infer_registry(pkgs: &[&Package]) -> CargoResult<Option<RegistryOrIndex>> {
328+
if pkgs[1..].iter().all(|p| p.publish() == pkgs[0].publish()) {
329+
// If all packages have the same publish settings, we take that as the default.
330+
match pkgs[0].publish().as_deref() {
331+
Some([unique_pkg_reg]) => {
332+
Ok(Some(RegistryOrIndex::Registry(unique_pkg_reg.to_owned())))
374333
}
375-
}
376-
};
377-
378-
// Validate the registry against the packages' allow-lists. For backwards compatibility, we
379-
// skip this if only a single package is being published (because in that case the registry
380-
// doesn't affect the packaging step).
381-
if pkgs.len() > 1 {
382-
if let RegistryOrIndex::Registry(reg_name) = &reg_or_index {
383-
for pkg in pkgs {
384-
if let Some(allowed) = pkg.publish().as_ref() {
385-
if !allowed.iter().any(|a| a == reg_name) {
386-
bail!(
387-
"`{}` cannot be packaged.\n\
388-
The registry `{}` is not listed in the `package.publish` value in Cargo.toml.",
389-
pkg.name(),
390-
reg_name
391-
);
392-
}
393-
}
334+
None | Some([]) => Ok(None),
335+
Some(regs) => {
336+
let mut regs: Vec<_> = regs.iter().map(|s| format!("\"{}\"", s)).collect();
337+
regs.sort();
338+
regs.dedup();
339+
// unwrap: the match block ensures that there's more than one reg.
340+
let (last_reg, regs) = regs.split_last().unwrap();
341+
bail!(
342+
"--registry is required to disambiguate between {} or {} registries",
343+
regs.join(", "),
344+
last_reg
345+
)
394346
}
395347
}
348+
} else {
349+
let common_regs = pkgs
350+
.iter()
351+
// `None` means "all registries", so drop them instead of including them
352+
// in the intersection.
353+
.filter_map(|p| p.publish().as_deref())
354+
.map(|p| p.iter().collect::<HashSet<_>>())
355+
.reduce(|xs, ys| xs.intersection(&ys).cloned().collect())
356+
.unwrap_or_default();
357+
if common_regs.is_empty() {
358+
bail!("conflicts between `package.publish` fields in the selected packages");
359+
} else {
360+
bail!("--registry is required because not all `package.publish` settings agree",);
361+
}
396362
}
397-
398-
let sid = match reg_or_index {
399-
RegistryOrIndex::Index(url) => SourceId::for_registry(&url)?,
400-
RegistryOrIndex::Registry(reg) if reg == CRATES_IO_REGISTRY => SourceId::crates_io(gctx)?,
401-
RegistryOrIndex::Registry(reg) => SourceId::alt_registry(gctx, &reg)?,
402-
};
403-
404-
// Load source replacements that are built-in to Cargo.
405-
let sid = SourceConfigMap::empty(gctx)?
406-
.load(sid, &HashSet::new())?
407-
.replaced_source_id();
408-
409-
Ok(sid)
410363
}

tests/testsuite/package.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5999,7 +5999,8 @@ fn registry_not_in_publish_list() {
59995999
.masquerade_as_nightly_cargo(&["package-workspace"])
60006000
.with_status(101)
60016001
.with_stderr_data(str![[r#"
6002-
[ERROR] registry index was not found in any configuration: `alternative`
6002+
[ERROR] `foo` cannot be packaged.
6003+
The registry `alternative` is not listed in the `package.publish` value in Cargo.toml.
60036004
60046005
"#]])
60056006
.run();

0 commit comments

Comments
 (0)