Skip to content

Commit 25dcec9

Browse files
committed
Auto merge of #12675 - weihanglo:source-id, r=arlosi
refactor(SourceId): merge `name` and `alt_registry_key` into one enum
2 parents 414d9e3 + 23e91c3 commit 25dcec9

File tree

5 files changed

+103
-79
lines changed

5 files changed

+103
-79
lines changed

src/cargo/core/package_id.rs

Lines changed: 0 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -251,43 +251,6 @@ mod tests {
251251
assert!(PackageId::new("foo", "", repo).is_err());
252252
}
253253

254-
#[test]
255-
fn debug() {
256-
let loc = CRATES_IO_INDEX.into_url().unwrap();
257-
let pkg_id = PackageId::new("foo", "1.0.0", SourceId::for_registry(&loc).unwrap()).unwrap();
258-
assert_eq!(
259-
r#"PackageId { name: "foo", version: "1.0.0", source: "registry `crates-io`" }"#,
260-
format!("{:?}", pkg_id)
261-
);
262-
263-
let expected = r#"
264-
PackageId {
265-
name: "foo",
266-
version: "1.0.0",
267-
source: "registry `crates-io`",
268-
}
269-
"#
270-
.trim();
271-
272-
// Can be removed once trailing commas in Debug have reached the stable
273-
// channel.
274-
let expected_without_trailing_comma = r#"
275-
PackageId {
276-
name: "foo",
277-
version: "1.0.0",
278-
source: "registry `crates-io`"
279-
}
280-
"#
281-
.trim();
282-
283-
let actual = format!("{:#?}", pkg_id);
284-
if actual.ends_with(",\n}") {
285-
assert_eq!(actual, expected);
286-
} else {
287-
assert_eq!(actual, expected_without_trailing_comma);
288-
}
289-
}
290-
291254
#[test]
292255
fn display() {
293256
let loc = CRATES_IO_INDEX.into_url().unwrap();

src/cargo/core/source_id.rs

Lines changed: 56 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,11 @@ struct SourceIdInner {
5151
kind: SourceKind,
5252
/// For example, the exact Git revision of the specified branch for a Git Source.
5353
precise: Option<String>,
54-
/// Name of the registry source for alternative registries
55-
/// WARNING: this is not always set for alt-registries when the name is
56-
/// not known.
57-
name: Option<String>,
58-
/// Name of the alt registry in the `[registries]` table.
59-
/// WARNING: this is not always set for alt-registries when the name is
60-
/// not known.
61-
alt_registry_key: Option<String>,
54+
/// Name of the remote registry.
55+
///
56+
/// WARNING: this is not always set when the name is not known,
57+
/// e.g. registry coming from `--index` or Cargo.lock
58+
registry_key: Option<KeyOf>,
6259
}
6360

6461
/// The possible kinds of code source.
@@ -93,11 +90,22 @@ pub enum GitReference {
9390
DefaultBranch,
9491
}
9592

93+
/// Where the remote source key is defined.
94+
///
95+
/// The purpose of this is to provide better diagnostics for different sources of keys.
96+
#[derive(Debug, Clone, PartialEq, Eq)]
97+
enum KeyOf {
98+
/// Defined in the `[registries]` table or the built-in `crates-io` key.
99+
Registry(String),
100+
/// Defined in the `[source]` replacement table.
101+
Source(String),
102+
}
103+
96104
impl SourceId {
97105
/// Creates a `SourceId` object from the kind and URL.
98106
///
99107
/// The canonical url will be calculated, but the precise field will not
100-
fn new(kind: SourceKind, url: Url, name: Option<&str>) -> CargoResult<SourceId> {
108+
fn new(kind: SourceKind, url: Url, key: Option<KeyOf>) -> CargoResult<SourceId> {
101109
if kind == SourceKind::SparseRegistry {
102110
// Sparse URLs are different because they store the kind prefix (sparse+)
103111
// in the URL. This is because the prefix is necessary to differentiate
@@ -111,8 +119,7 @@ impl SourceId {
111119
canonical_url: CanonicalUrl::new(&url)?,
112120
url,
113121
precise: None,
114-
name: name.map(|n| n.into()),
115-
alt_registry_key: None,
122+
registry_key: key,
116123
});
117124
Ok(source_id)
118125
}
@@ -230,10 +237,18 @@ impl SourceId {
230237
SourceId::new(kind, url.to_owned(), None)
231238
}
232239

233-
/// Creates a `SourceId` from a remote registry URL with given name.
234-
pub fn for_alt_registry(url: &Url, name: &str) -> CargoResult<SourceId> {
240+
/// Creates a `SourceId` for a remote registry from the `[registries]` table or crates.io.
241+
pub fn for_alt_registry(url: &Url, key: &str) -> CargoResult<SourceId> {
235242
let kind = Self::remote_source_kind(url);
236-
SourceId::new(kind, url.to_owned(), Some(name))
243+
let key = KeyOf::Registry(key.into());
244+
SourceId::new(kind, url.to_owned(), Some(key))
245+
}
246+
247+
/// Creates a `SourceId` for a remote registry from the `[source]` replacement table.
248+
pub fn for_source_replacement_registry(url: &Url, key: &str) -> CargoResult<SourceId> {
249+
let kind = Self::remote_source_kind(url);
250+
let key = KeyOf::Source(key.into());
251+
SourceId::new(kind, url.to_owned(), Some(key))
237252
}
238253

239254
/// Creates a `SourceId` from a local registry path.
@@ -262,7 +277,8 @@ impl SourceId {
262277
if Self::crates_io_is_sparse(config)? {
263278
config.check_registry_index_not_set()?;
264279
let url = CRATES_IO_HTTP_INDEX.into_url().unwrap();
265-
SourceId::new(SourceKind::SparseRegistry, url, Some(CRATES_IO_REGISTRY))
280+
let key = KeyOf::Registry(CRATES_IO_REGISTRY.into());
281+
SourceId::new(SourceKind::SparseRegistry, url, Some(key))
266282
} else {
267283
Self::crates_io(config)
268284
}
@@ -289,15 +305,7 @@ impl SourceId {
289305
return Self::crates_io(config);
290306
}
291307
let url = config.get_registry_index(key)?;
292-
let kind = Self::remote_source_kind(&url);
293-
Ok(SourceId::wrap(SourceIdInner {
294-
kind,
295-
canonical_url: CanonicalUrl::new(&url)?,
296-
url,
297-
precise: None,
298-
name: Some(key.to_string()),
299-
alt_registry_key: Some(key.to_string()),
300-
}))
308+
Self::for_alt_registry(&url, key)
301309
}
302310

303311
/// Gets this source URL.
@@ -322,10 +330,8 @@ impl SourceId {
322330

323331
/// Displays the name of a registry if it has one. Otherwise just the URL.
324332
pub fn display_registry_name(self) -> String {
325-
if self.is_crates_io() {
326-
CRATES_IO_REGISTRY.to_string()
327-
} else if let Some(name) = &self.inner.name {
328-
name.clone()
333+
if let Some(key) = self.inner.registry_key.as_ref().map(|k| k.key()) {
334+
key.into()
329335
} else if self.precise().is_some() {
330336
// We remove `precise` here to retrieve an permissive version of
331337
// `SourceIdInner`, which may contain the registry name.
@@ -335,11 +341,10 @@ impl SourceId {
335341
}
336342
}
337343

338-
/// Gets the name of the remote registry as defined in the `[registries]` table.
339-
/// WARNING: alt registries that come from Cargo.lock, or --index will
340-
/// not have a name.
344+
/// Gets the name of the remote registry as defined in the `[registries]` table,
345+
/// or the built-in `crates-io` key.
341346
pub fn alt_registry_key(&self) -> Option<&str> {
342-
self.inner.alt_registry_key.as_deref()
347+
self.inner.registry_key.as_ref()?.alternative_registry()
343348
}
344349

345350
/// Returns `true` if this source is from a filesystem path.
@@ -652,10 +657,9 @@ impl Hash for SourceId {
652657
/// The hash of `SourceIdInner` is used to retrieve its interned value from
653658
/// `SOURCE_ID_CACHE`. We only care about fields that make `SourceIdInner`
654659
/// unique. Optional fields not affecting the uniqueness must be excluded,
655-
/// such as [`name`] and [`alt_registry_key`]. That's why this is not derived.
660+
/// such as [`registry_key`]. That's why this is not derived.
656661
///
657-
/// [`name`]: SourceIdInner::name
658-
/// [`alt_registry_key`]: SourceIdInner::alt_registry_key
662+
/// [`registry_key`]: SourceIdInner::registry_key
659663
impl Hash for SourceIdInner {
660664
fn hash<S: hash::Hasher>(&self, into: &mut S) {
661665
self.kind.hash(into);
@@ -868,6 +872,23 @@ impl<'a> fmt::Display for PrettyRef<'a> {
868872
}
869873
}
870874

875+
impl KeyOf {
876+
/// Gets the underlying key.
877+
fn key(&self) -> &str {
878+
match self {
879+
KeyOf::Registry(k) | KeyOf::Source(k) => k,
880+
}
881+
}
882+
883+
/// Gets the key if it's from an alternative registry.
884+
fn alternative_registry(&self) -> Option<&str> {
885+
match self {
886+
KeyOf::Registry(k) => Some(k),
887+
_ => None,
888+
}
889+
}
890+
}
891+
871892
#[cfg(test)]
872893
mod tests {
873894
use super::{GitReference, SourceId, SourceKind};

src/cargo/sources/config.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ restore the source replacement configuration to continue the build
239239
let mut srcs = Vec::new();
240240
if let Some(registry) = def.registry {
241241
let url = url(&registry, &format!("source.{}.registry", name))?;
242-
srcs.push(SourceId::for_alt_registry(&url, &name)?);
242+
srcs.push(SourceId::for_source_replacement_registry(&url, &name)?);
243243
}
244244
if let Some(local_registry) = def.local_registry {
245245
let path = local_registry.resolve_path(self.config);

src/cargo/util/auth/mod.rs

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
33
use crate::{
44
core::features::cargo_docs_link,
5-
sources::CRATES_IO_REGISTRY,
65
util::{config::ConfigKey, CanonicalUrl, CargoResult, Config, IntoUrl},
76
};
87
use anyhow::{bail, Context as _};
@@ -506,11 +505,7 @@ fn credential_action(
506505
args: &[&str],
507506
require_cred_provider_config: bool,
508507
) -> CargoResult<CredentialResponse> {
509-
let name = if sid.is_crates_io() {
510-
Some(CRATES_IO_REGISTRY)
511-
} else {
512-
sid.alt_registry_key()
513-
};
508+
let name = sid.alt_registry_key();
514509
let registry = RegistryInfo {
515510
index_url: sid.url().as_str(),
516511
name,

tests/testsuite/source_replacement.rs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,3 +248,48 @@ fn undefined_default() {
248248
)
249249
.run();
250250
}
251+
252+
#[cargo_test]
253+
fn source_replacement_with_registry_url() {
254+
let alternative = RegistryBuilder::new().alternative().http_api().build();
255+
Package::new("bar", "0.0.1").alternative(true).publish();
256+
257+
let crates_io = setup_replacement(&format!(
258+
r#"
259+
[source.crates-io]
260+
replace-with = 'using-registry-url'
261+
262+
[source.using-registry-url]
263+
registry = '{}'
264+
"#,
265+
alternative.index_url()
266+
));
267+
268+
let p = project()
269+
.file(
270+
"Cargo.toml",
271+
r#"
272+
[package]
273+
name = "foo"
274+
version = "0.0.1"
275+
[dependencies.bar]
276+
version = "0.0.1"
277+
"#,
278+
)
279+
.file("src/lib.rs", "")
280+
.build();
281+
282+
p.cargo("check")
283+
.replace_crates_io(crates_io.index_url())
284+
.with_stderr(
285+
"\
286+
[UPDATING] `using-registry-url` index
287+
[DOWNLOADING] crates ...
288+
[DOWNLOADED] bar v0.0.1 (registry `using-registry-url`)
289+
[CHECKING] bar v0.0.1
290+
[CHECKING] foo v0.0.1 ([CWD])
291+
[FINISHED] dev [..]
292+
",
293+
)
294+
.run();
295+
}

0 commit comments

Comments
 (0)