Skip to content

Commit 3fddcfe

Browse files
committed
More infer_registry to a more public place
1 parent db2fd3d commit 3fddcfe

File tree

3 files changed

+86
-78
lines changed

3 files changed

+86
-78
lines changed

src/cargo/ops/cargo_package.rs

Lines changed: 43 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::collections::{BTreeSet, HashMap, HashSet};
1+
use std::collections::{BTreeSet, HashMap};
22
use std::fs::{self, File};
33
use std::io::prelude::*;
44
use std::io::SeekFrom;
@@ -13,8 +13,9 @@ use crate::core::resolver::CliFeatures;
1313
use crate::core::resolver::HasDevUnits;
1414
use crate::core::{Feature, PackageIdSpecQuery, Shell, Verbosity, Workspace};
1515
use crate::core::{Package, PackageId, PackageSet, Resolve, SourceId};
16+
use crate::ops::registry::infer_registry;
1617
use crate::sources::registry::index::{IndexPackage, RegistryDependency};
17-
use crate::sources::{PathSource, SourceConfigMap, CRATES_IO_REGISTRY};
18+
use crate::sources::{PathSource, CRATES_IO_REGISTRY};
1819
use crate::util::cache_lock::CacheLockMode;
1920
use crate::util::context::JobsConfig;
2021
use crate::util::errors::CargoResult;
@@ -180,89 +181,35 @@ fn create_package(
180181
/// packages that we're packaging: if we're packaging foo-bin and foo-lib, and foo-bin
181182
/// depends on foo-lib, then the foo-lib entry in foo-bin's lockfile will depend on the
182183
/// registry that we're building packages for.
183-
fn infer_registry(
184+
fn get_registry(
184185
gctx: &GlobalContext,
185186
pkgs: &[&Package],
186187
reg_or_index: Option<RegistryOrIndex>,
187188
) -> CargoResult<SourceId> {
188-
let reg_or_index = match reg_or_index {
189-
Some(r) => r,
190-
None => {
191-
if pkgs[1..].iter().all(|p| p.publish() == pkgs[0].publish()) {
192-
// If all packages have the same publish settings, we take that as the default.
193-
match pkgs[0].publish().as_deref() {
194-
Some([unique_pkg_reg]) => RegistryOrIndex::Registry(unique_pkg_reg.to_owned()),
195-
None | Some([]) => RegistryOrIndex::Registry(CRATES_IO_REGISTRY.to_owned()),
196-
Some([reg, ..]) if pkgs.len() == 1 => {
197-
// For backwards compatibility, avoid erroring if there's only one package.
198-
// The registry doesn't affect packaging in this case.
199-
RegistryOrIndex::Registry(reg.to_owned())
200-
}
201-
Some(regs) => {
202-
let mut regs: Vec<_> = regs.iter().map(|s| format!("\"{}\"", s)).collect();
203-
regs.sort();
204-
regs.dedup();
205-
// unwrap: the match block ensures that there's more than one reg.
206-
let (last_reg, regs) = regs.split_last().unwrap();
207-
bail!(
208-
"--registry is required to disambiguate between {} or {} registries",
209-
regs.join(", "),
210-
last_reg
211-
)
212-
}
213-
}
214-
} else {
215-
let common_regs = pkgs
216-
.iter()
217-
// `None` means "all registries", so drop them instead of including them
218-
// in the intersection.
219-
.filter_map(|p| p.publish().as_deref())
220-
.map(|p| p.iter().collect::<HashSet<_>>())
221-
.reduce(|xs, ys| xs.intersection(&ys).cloned().collect())
222-
.unwrap_or_default();
223-
if common_regs.is_empty() {
224-
bail!("conflicts between `package.publish` fields in the selected packages");
225-
} else {
226-
bail!(
227-
"--registry is required because not all `package.publish` settings agree",
228-
);
229-
}
230-
}
231-
}
189+
let reg_or_index = match reg_or_index.clone() {
190+
Some(r) => Some(r),
191+
None => infer_registry(pkgs)?,
232192
};
233193

234-
// Validate the registry against the packages' allow-lists. For backwards compatibility, we
235-
// skip this if only a single package is being published (because in that case the registry
236-
// doesn't affect the packaging step).
237-
if pkgs.len() > 1 {
238-
if let RegistryOrIndex::Registry(reg_name) = &reg_or_index {
239-
for pkg in pkgs {
240-
if let Some(allowed) = pkg.publish().as_ref() {
241-
if !allowed.iter().any(|a| a == reg_name) {
242-
bail!(
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!(
243203
"`{}` cannot be packaged.\n\
244204
The registry `{}` is not listed in the `package.publish` value in Cargo.toml.",
245205
pkg.name(),
246206
reg_name
247207
);
248-
}
249208
}
250209
}
251210
}
252211
}
253-
254-
let sid = match reg_or_index {
255-
RegistryOrIndex::Index(url) => SourceId::for_registry(&url)?,
256-
RegistryOrIndex::Registry(reg) if reg == CRATES_IO_REGISTRY => SourceId::crates_io(gctx)?,
257-
RegistryOrIndex::Registry(reg) => SourceId::alt_registry(gctx, &reg)?,
258-
};
259-
260-
// Load source replacements that are built-in to Cargo.
261-
let sid = SourceConfigMap::empty(gctx)?
262-
.load(sid, &HashSet::new())?
263-
.replaced_source_id();
264-
265-
Ok(sid)
212+
Ok(ops::registry::get_source_id(gctx, reg_or_index.as_ref())?.replacement)
266213
}
267214

268215
/// Packages an entire workspace.
@@ -288,19 +235,34 @@ pub fn package(ws: &Workspace<'_>, opts: &PackageOpts<'_>) -> CargoResult<Vec<Fi
288235
// below, and will be validated during the verification step.
289236
}
290237

238+
let deps = local_deps(pkgs.iter().map(|(p, f)| ((*p).clone(), f.clone())));
291239
let just_pkgs: Vec<_> = pkgs.iter().map(|p| p.0).collect();
292-
let publish_reg = infer_registry(ws.gctx(), &just_pkgs, opts.reg_or_index.clone())?;
293-
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+
};
294257

295258
let mut local_reg = if ws.gctx().cli_unstable().package_workspace {
296259
let reg_dir = ws.target_dir().join("package").join("tmp-registry");
297-
Some(TmpRegistry::new(ws.gctx(), reg_dir, publish_reg)?)
260+
sid.map(|sid| TmpRegistry::new(ws.gctx(), reg_dir, sid))
261+
.transpose()?
298262
} else {
299263
None
300264
};
301265

302-
let deps = local_deps(pkgs.iter().map(|(p, f)| ((*p).clone(), f.clone())));
303-
304266
// Packages need to be created in dependency order, because dependencies must
305267
// be added to our local overlay before we can create lockfiles that depend on them.
306268
let sorted_pkgs = deps.sort();
@@ -354,6 +316,12 @@ impl LocalDependencies {
354316
.map(|name| self.packages[&name].clone())
355317
.collect()
356318
}
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+
}
357325
}
358326

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

src/cargo/ops/registry/mod.rs

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use cargo_credential::{Operation, Secret};
1919
use crates_io::Registry;
2020
use url::Url;
2121

22-
use crate::core::{PackageId, SourceId};
22+
use crate::core::{Package, PackageId, SourceId};
2323
use crate::sources::source::Source;
2424
use crate::sources::{RegistrySource, SourceConfigMap};
2525
use crate::util::auth;
@@ -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> {
@@ -322,3 +322,42 @@ pub(crate) struct RegistrySourceIds {
322322
/// User-defined source replacement is not applied.
323323
pub(crate) replacement: SourceId,
324324
}
325+
326+
/// If this set of packages has an unambiguous publish registry, find it.
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())))
333+
}
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+
)
346+
}
347+
}
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+
}
362+
}
363+
}

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)