Skip to main content

cargo/workspace/
source_id.rs

1use crate::context;
2use crate::sources::registry::CRATES_IO_HTTP_INDEX;
3use crate::sources::source::Source;
4use crate::sources::{CRATES_IO_DOMAIN, CRATES_IO_INDEX, CRATES_IO_REGISTRY, DirectorySource};
5use crate::sources::{GitSource, PathSource, RegistrySource};
6use crate::util::data_structures::HashSet;
7use crate::util::interning::InternedString;
8use crate::util::{CanonicalUrl, CargoResult, GlobalContext, IntoUrl};
9use crate::workspace::GitReference;
10use crate::workspace::SourceKind;
11use anyhow::Context as _;
12use serde::de;
13use serde::ser;
14use std::cmp::{self, Ordering};
15use std::fmt::{self, Formatter};
16use std::hash::{self, Hash};
17use std::path::{Path, PathBuf};
18use std::ptr;
19use std::sync::Mutex;
20use std::sync::OnceLock;
21use tracing::trace;
22use url::Url;
23
24static SOURCE_ID_CACHE: OnceLock<Mutex<HashSet<&'static SourceIdInner>>> = OnceLock::new();
25
26/// Unique identifier for a source of packages.
27///
28/// Cargo uniquely identifies packages using [`PackageId`], a combination of the
29/// package name, version, and the code source. `SourceId` exactly represents
30/// the "code source" in `PackageId`. See [`SourceId::hash`] to learn what are
31/// taken into account for the uniqueness of a source.
32///
33/// `SourceId` is usually associated with an instance of [`Source`], which is
34/// supposed to provide a `SourceId` via [`Source::source_id`] method.
35///
36/// [`Source`]: crate::sources::source::Source
37/// [`Source::source_id`]: crate::sources::source::Source::source_id
38/// [`PackageId`]: super::PackageId
39#[derive(Clone, Copy, Eq, Debug)]
40pub struct SourceId {
41    inner: &'static SourceIdInner,
42}
43
44/// The interned version of [`SourceId`] to avoid excessive clones and borrows.
45/// Values are cached in `SOURCE_ID_CACHE` once created.
46#[derive(Eq, Clone, Debug)]
47struct SourceIdInner {
48    /// The source URL.
49    url: Url,
50    /// The canonical version of the above url. See [`CanonicalUrl`] to learn
51    /// why it is needed and how it normalizes a URL.
52    canonical_url: CanonicalUrl,
53    /// The source kind.
54    kind: SourceKind,
55    /// For example, the exact Git revision of the specified branch for a Git Source.
56    precise: Option<Precise>,
57    /// Name of the remote registry.
58    ///
59    /// WARNING: this is not always set when the name is not known,
60    /// e.g. registry coming from `--index` or Cargo.lock
61    registry_key: Option<KeyOf>,
62}
63
64#[derive(Eq, PartialEq, Clone, Debug, Hash)]
65enum Precise {
66    Locked,
67    Updated {
68        name: InternedString,
69        from: semver::Version,
70        to: semver::Version,
71    },
72    GitUrlFragment(String),
73}
74
75impl fmt::Display for Precise {
76    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
77        match self {
78            Precise::Locked => "locked".fmt(f),
79            Precise::Updated { name, from, to } => {
80                write!(f, "{name}={from}->{to}")
81            }
82            Precise::GitUrlFragment(s) => s.fmt(f),
83        }
84    }
85}
86
87/// Where the remote source key is defined.
88///
89/// The purpose of this is to provide better diagnostics for different sources of keys.
90#[derive(Debug, Clone, PartialEq, Eq)]
91enum KeyOf {
92    /// Defined in the `[registries]` table or the built-in `crates-io` key.
93    Registry(String),
94    /// Defined in the `[source]` replacement table.
95    Source(String),
96}
97
98impl SourceId {
99    /// Creates a `SourceId` object from the kind and URL.
100    ///
101    /// The canonical url will be calculated, but the precise field will not
102    fn new(kind: SourceKind, url: Url, key: Option<KeyOf>) -> CargoResult<SourceId> {
103        if kind == SourceKind::SparseRegistry {
104            // Sparse URLs are different because they store the kind prefix (sparse+)
105            // in the URL. This is because the prefix is necessary to differentiate
106            // from regular registries (git-based). The sparse+ prefix is included
107            // everywhere, including user-facing locations such as the `config.toml`
108            // file that defines the registry, or whenever Cargo displays it to the user.
109            assert!(url.as_str().starts_with("sparse+"));
110        }
111        let source_id = SourceId::wrap(SourceIdInner {
112            kind,
113            canonical_url: CanonicalUrl::new(&url)?,
114            url,
115            precise: None,
116            registry_key: key,
117        });
118        Ok(source_id)
119    }
120
121    /// Interns the value and returns the wrapped type.
122    fn wrap(inner: SourceIdInner) -> SourceId {
123        let mut cache = SOURCE_ID_CACHE
124            .get_or_init(|| Default::default())
125            .lock()
126            .unwrap();
127        let inner = cache.get(&inner).cloned().unwrap_or_else(|| {
128            let inner = Box::leak(Box::new(inner));
129            cache.insert(inner);
130            inner
131        });
132        SourceId { inner }
133    }
134
135    fn remote_source_kind(url: &Url) -> SourceKind {
136        if url.as_str().starts_with("sparse+") {
137            SourceKind::SparseRegistry
138        } else {
139            SourceKind::Registry
140        }
141    }
142
143    /// Parses a source URL and returns the corresponding ID.
144    ///
145    /// ## Example
146    ///
147    /// ```
148    /// use cargo::workspace::SourceId;
149    /// SourceId::from_url("git+https://github.com/alexcrichton/\
150    ///                     libssh2-static-sys#80e71a3021618eb05\
151    ///                     656c58fb7c5ef5f12bc747f");
152    /// ```
153    pub fn from_url(string: &str) -> CargoResult<SourceId> {
154        let (kind, url) = string
155            .split_once('+')
156            .ok_or_else(|| anyhow::format_err!("invalid source `{}`", string))?;
157
158        match kind {
159            "git" => {
160                let mut url = url.into_url()?;
161                let reference = GitReference::from_query(url.query_pairs());
162                let precise = url.fragment().map(|s| s.to_owned());
163                url.set_fragment(None);
164                url.set_query(None);
165                Ok(SourceId::for_git(&url, reference)?.with_git_precise(precise))
166            }
167            "registry" => {
168                let url = url.into_url()?;
169                Ok(SourceId::new(SourceKind::Registry, url, None)?.with_locked_precise())
170            }
171            "sparse" => {
172                let url = string.into_url()?;
173                Ok(SourceId::new(SourceKind::SparseRegistry, url, None)?.with_locked_precise())
174            }
175            "path" => {
176                let url = url.into_url()?;
177                SourceId::new(SourceKind::Path, url, None)
178            }
179            kind => Err(anyhow::format_err!("unsupported source protocol: {}", kind)),
180        }
181    }
182
183    /// A view of the [`SourceId`] that can be `Display`ed as a URL.
184    pub fn as_url(&self) -> SourceIdAsUrl<'_> {
185        SourceIdAsUrl {
186            inner: &*self.inner,
187            encoded: false,
188        }
189    }
190
191    /// Like [`Self::as_url`] but with URL parameters encoded.
192    pub fn as_encoded_url(&self) -> SourceIdAsUrl<'_> {
193        SourceIdAsUrl {
194            inner: &*self.inner,
195            encoded: true,
196        }
197    }
198
199    /// Creates a `SourceId` from a filesystem path.
200    ///
201    /// `path`: an absolute path.
202    pub fn for_path(path: &Path) -> CargoResult<SourceId> {
203        let url = path.into_url()?;
204        SourceId::new(SourceKind::Path, url, None)
205    }
206
207    /// Creates a `SourceId` from a filesystem path.
208    ///
209    /// `path`: an absolute path.
210    pub fn for_manifest_path(manifest_path: &Path) -> CargoResult<SourceId> {
211        if crate::workspace::parser::is_embedded(manifest_path) && manifest_path.is_file() {
212            Self::for_path(manifest_path)
213        } else {
214            Self::for_path(manifest_path.parent().unwrap())
215        }
216    }
217
218    /// Creates a `SourceId` from a Git reference.
219    pub fn for_git(url: &Url, reference: GitReference) -> CargoResult<SourceId> {
220        SourceId::new(SourceKind::Git(reference), url.clone(), None)
221    }
222
223    /// Creates a `SourceId` from a remote registry URL when the registry name
224    /// cannot be determined, e.g. a user passes `--index` directly from CLI.
225    ///
226    /// Use [`SourceId::for_alt_registry`] if a name can provided, which
227    /// generates better messages for cargo.
228    pub fn for_registry(url: &Url) -> CargoResult<SourceId> {
229        let kind = Self::remote_source_kind(url);
230        SourceId::new(kind, url.to_owned(), None)
231    }
232
233    /// Creates a `SourceId` for a remote registry from the `[registries]` table or crates.io.
234    pub fn for_alt_registry(url: &Url, key: &str) -> CargoResult<SourceId> {
235        let kind = Self::remote_source_kind(url);
236        let key = KeyOf::Registry(key.into());
237        SourceId::new(kind, url.to_owned(), Some(key))
238    }
239
240    /// Creates a `SourceId` for a remote registry from the `[source]` replacement table.
241    pub fn for_source_replacement_registry(url: &Url, key: &str) -> CargoResult<SourceId> {
242        let kind = Self::remote_source_kind(url);
243        let key = KeyOf::Source(key.into());
244        SourceId::new(kind, url.to_owned(), Some(key))
245    }
246
247    /// Creates a `SourceId` from a local registry path.
248    pub fn for_local_registry(path: &Path) -> CargoResult<SourceId> {
249        let url = path.into_url()?;
250        SourceId::new(SourceKind::LocalRegistry, url, None)
251    }
252
253    /// Creates a `SourceId` from a directory path.
254    pub fn for_directory(path: &Path) -> CargoResult<SourceId> {
255        let url = path.into_url()?;
256        SourceId::new(SourceKind::Directory, url, None)
257    }
258
259    /// Returns the `SourceId` corresponding to the main repository.
260    ///
261    /// This is the main cargo registry by default, but it can be overridden in
262    /// a `.cargo/config.toml`.
263    pub fn crates_io(gctx: &GlobalContext) -> CargoResult<SourceId> {
264        gctx.crates_io_source_id()
265    }
266
267    /// Returns the `SourceId` corresponding to the main repository, using the
268    /// sparse HTTP index if allowed.
269    pub fn crates_io_maybe_sparse_http(gctx: &GlobalContext) -> CargoResult<SourceId> {
270        if Self::crates_io_is_sparse(gctx)? {
271            gctx.check_registry_index_not_set()?;
272            let url = CRATES_IO_HTTP_INDEX.into_url().unwrap();
273            let key = KeyOf::Registry(CRATES_IO_REGISTRY.into());
274            SourceId::new(SourceKind::SparseRegistry, url, Some(key))
275        } else {
276            Self::crates_io(gctx)
277        }
278    }
279
280    /// Returns whether to access crates.io over the sparse protocol.
281    pub fn crates_io_is_sparse(gctx: &GlobalContext) -> CargoResult<bool> {
282        let proto: Option<context::Value<String>> =
283            gctx.get(["registries", "crates-io", "protocol"])?;
284        let is_sparse = match proto.as_ref().map(|v| v.val.as_str()) {
285            Some("sparse") => true,
286            Some("git") => false,
287            Some(unknown) => anyhow::bail!(
288                "unsupported registry protocol `{unknown}` (defined in {})",
289                proto.as_ref().unwrap().definition
290            ),
291            None => true,
292        };
293        Ok(is_sparse)
294    }
295
296    /// Gets the `SourceId` associated with given name of the remote registry.
297    pub fn alt_registry(gctx: &GlobalContext, key: &str) -> CargoResult<SourceId> {
298        if key == CRATES_IO_REGISTRY {
299            return Self::crates_io(gctx);
300        }
301        let url = gctx.get_registry_index(key)?;
302        Self::for_alt_registry(&url, key)
303    }
304
305    /// Gets this source URL.
306    pub fn url(&self) -> &Url {
307        &self.inner.url
308    }
309
310    /// Gets the canonical URL of this source, used for internal comparison
311    /// purposes.
312    pub fn canonical_url(&self) -> &CanonicalUrl {
313        &self.inner.canonical_url
314    }
315
316    /// Displays the text "crates.io index" for Cargo shell status output.
317    pub fn display_index(self) -> String {
318        if self.is_crates_io() {
319            format!("{} index", CRATES_IO_DOMAIN)
320        } else {
321            format!("`{}` index", self.display_registry_name())
322        }
323    }
324
325    /// Displays the name of a registry if it has one. Otherwise just the URL.
326    pub fn display_registry_name(self) -> String {
327        if let Some(key) = self.inner.registry_key.as_ref().map(|k| k.key()) {
328            key.into()
329        } else if self.has_precise() {
330            // We remove `precise` here to retrieve an permissive version of
331            // `SourceIdInner`, which may contain the registry name.
332            self.without_precise().display_registry_name()
333        } else {
334            url_display(self.url())
335        }
336    }
337
338    /// Gets the name of the remote registry as defined in the `[registries]` table,
339    /// or the built-in `crates-io` key.
340    pub fn alt_registry_key(&self) -> Option<&str> {
341        self.inner.registry_key.as_ref()?.alternative_registry()
342    }
343
344    /// Returns `true` if this source is from a filesystem path.
345    pub fn is_path(self) -> bool {
346        self.inner.kind == SourceKind::Path
347    }
348
349    /// Returns the local path if this is a path dependency.
350    pub fn local_path(self) -> Option<PathBuf> {
351        if self.inner.kind != SourceKind::Path {
352            return None;
353        }
354
355        Some(self.inner.url.to_file_path().unwrap())
356    }
357
358    pub fn kind(&self) -> &SourceKind {
359        &self.inner.kind
360    }
361
362    /// Returns `true` if this source is from a registry (either local or not).
363    pub fn is_registry(self) -> bool {
364        matches!(
365            self.inner.kind,
366            SourceKind::Registry | SourceKind::SparseRegistry | SourceKind::LocalRegistry
367        )
368    }
369
370    /// Returns `true` if this source is from a sparse registry.
371    pub fn is_sparse(self) -> bool {
372        matches!(self.inner.kind, SourceKind::SparseRegistry)
373    }
374
375    /// Returns `true` if this source is a "remote" registry.
376    ///
377    /// "remote" may also mean a file URL to a git index, so it is not
378    /// necessarily "remote". This just means it is not `local-registry`.
379    pub fn is_remote_registry(self) -> bool {
380        matches!(
381            self.inner.kind,
382            SourceKind::Registry | SourceKind::SparseRegistry
383        )
384    }
385
386    /// Returns `true` if this source from a Git repository.
387    pub fn is_git(self) -> bool {
388        matches!(self.inner.kind, SourceKind::Git(_))
389    }
390
391    /// Creates an implementation of `Source` corresponding to this ID.
392    pub fn load<'a>(self, gctx: &'a GlobalContext) -> CargoResult<Box<dyn Source + 'a>> {
393        trace!("loading SourceId; {}", self);
394        match self.inner.kind {
395            SourceKind::Git(..) => Ok(Box::new(GitSource::new(self, gctx)?)),
396            SourceKind::Path => {
397                let path = self
398                    .inner
399                    .url
400                    .to_file_path()
401                    .expect("path sources cannot be remote");
402                if crate::workspace::parser::is_embedded(&path) && path.is_file() {
403                    anyhow::bail!("single file packages cannot be used as dependencies")
404                }
405                Ok(Box::new(PathSource::new(&path, self, gctx)))
406            }
407            SourceKind::Registry | SourceKind::SparseRegistry => {
408                Ok(Box::new(RegistrySource::remote(self, gctx)?))
409            }
410            SourceKind::LocalRegistry => {
411                let path = self
412                    .inner
413                    .url
414                    .to_file_path()
415                    .expect("path sources cannot be remote");
416                Ok(Box::new(RegistrySource::local(self, &path, gctx)))
417            }
418            SourceKind::Directory => {
419                let path = self
420                    .inner
421                    .url
422                    .to_file_path()
423                    .expect("path sources cannot be remote");
424                Ok(Box::new(DirectorySource::new(&path, self, gctx)))
425            }
426        }
427    }
428
429    /// Gets the Git reference if this is a git source, otherwise `None`.
430    pub fn git_reference(self) -> Option<&'static GitReference> {
431        match self.inner.kind {
432            SourceKind::Git(ref s) => Some(s),
433            _ => None,
434        }
435    }
436
437    /// Check if the precise data field has bean set
438    pub fn has_precise(self) -> bool {
439        self.inner.precise.is_some()
440    }
441
442    /// Check if the precise data field has bean set to "locked"
443    pub fn has_locked_precise(self) -> bool {
444        self.inner.precise == Some(Precise::Locked)
445    }
446
447    /// Check if two sources have the same precise data field
448    pub fn has_same_precise_as(self, other: Self) -> bool {
449        self.inner.precise == other.inner.precise
450    }
451
452    /// Check if the precise data field stores information for this `name`
453    /// from a call to [`SourceId::with_precise_registry_version`].
454    ///
455    /// If so return the version currently in the lock file and the version to be updated to.
456    pub fn precise_registry_version(
457        self,
458        pkg: &str,
459    ) -> Option<(&semver::Version, &semver::Version)> {
460        match &self.inner.precise {
461            Some(Precise::Updated { name, from, to }) if name == pkg => Some((from, to)),
462            _ => None,
463        }
464    }
465
466    pub fn precise_git_fragment(self) -> Option<&'static str> {
467        match &self.inner.precise {
468            Some(Precise::GitUrlFragment(s)) => Some(&s),
469            _ => None,
470        }
471    }
472
473    /// Creates a new `SourceId` from this source with the given `precise`.
474    pub fn with_git_precise(self, fragment: Option<String>) -> SourceId {
475        self.with_precise(&fragment.map(|f| Precise::GitUrlFragment(f)))
476    }
477
478    /// Creates a new `SourceId` from this source without a `precise`.
479    pub fn without_precise(self) -> SourceId {
480        self.with_precise(&None)
481    }
482
483    /// Creates a new `SourceId` from this source without a `precise`.
484    pub fn with_locked_precise(self) -> SourceId {
485        self.with_precise(&Some(Precise::Locked))
486    }
487
488    /// Creates a new `SourceId` from this source with the `precise` from some other `SourceId`.
489    pub fn with_precise_from(self, v: Self) -> SourceId {
490        self.with_precise(&v.inner.precise)
491    }
492
493    fn with_precise(self, precise: &Option<Precise>) -> SourceId {
494        if &self.inner.precise == precise {
495            self
496        } else {
497            SourceId::wrap(SourceIdInner {
498                precise: precise.clone(),
499                ..(*self.inner).clone()
500            })
501        }
502    }
503
504    /// When updating a lock file on a version using `cargo update --precise`
505    /// the requested version is stored in the precise field.
506    /// On a registry dependency we also need to keep track of the package that
507    /// should be updated and even which of the versions should be updated.
508    /// All of this gets encoded in the precise field using this method.
509    /// The data can be read with [`SourceId::precise_registry_version`]
510    pub fn with_precise_registry_version(
511        self,
512        name: InternedString,
513        version: semver::Version,
514        precise: &str,
515    ) -> CargoResult<SourceId> {
516        let precise = semver::Version::parse(precise).with_context(|| {
517            if let Some(stripped) = precise.strip_prefix("v") {
518                return format!(
519                    "the version provided, `{precise}` is not a \
520                    valid SemVer version\n\n\
521                    help: try changing the version to `{stripped}`",
522                );
523            }
524            format!("invalid version format for precise version `{precise}`")
525        })?;
526
527        Ok(SourceId::wrap(SourceIdInner {
528            precise: Some(Precise::Updated {
529                name,
530                from: version,
531                to: precise,
532            }),
533            ..(*self.inner).clone()
534        }))
535    }
536
537    /// Returns `true` if the remote registry is the standard <https://crates.io>.
538    pub fn is_crates_io(self) -> bool {
539        match self.inner.kind {
540            SourceKind::Registry | SourceKind::SparseRegistry => {}
541            _ => return false,
542        }
543        let url = self.inner.url.as_str();
544        url == CRATES_IO_INDEX || url == CRATES_IO_HTTP_INDEX || is_overridden_crates_io_url(url)
545    }
546
547    /// Hashes `self` to be used in the name of some Cargo folders, so shouldn't vary.
548    ///
549    /// For git and url, `as_str` gives the serialisation of a url (which has a spec) and so
550    /// insulates against possible changes in how the url crate does hashing.
551    ///
552    /// For paths, remove the workspace prefix so the same source will give the
553    /// same hash in different locations, helping reproducible builds.
554    pub fn stable_hash<S: hash::Hasher>(self, workspace: &Path, into: &mut S) {
555        if self.is_path() {
556            if let Ok(p) = self
557                .inner
558                .url
559                .to_file_path()
560                .unwrap()
561                .strip_prefix(workspace)
562            {
563                self.inner.kind.hash(into);
564                p.to_str().unwrap().hash(into);
565                return;
566            }
567        }
568        self.inner.kind.hash(into);
569        match self.inner.kind {
570            SourceKind::Git(_) => (&self).inner.canonical_url.hash(into),
571            _ => (&self).inner.url.as_str().hash(into),
572        }
573    }
574
575    pub fn full_eq(self, other: SourceId) -> bool {
576        ptr::eq(self.inner, other.inner)
577    }
578
579    pub fn full_hash<S: hash::Hasher>(self, into: &mut S) {
580        ptr::NonNull::from(self.inner).hash(into)
581    }
582}
583
584impl PartialEq for SourceId {
585    fn eq(&self, other: &SourceId) -> bool {
586        self.cmp(other) == Ordering::Equal
587    }
588}
589
590impl PartialOrd for SourceId {
591    fn partial_cmp(&self, other: &SourceId) -> Option<Ordering> {
592        Some(self.cmp(other))
593    }
594}
595
596// Custom comparison defined as source kind and canonical URL equality,
597// ignoring the `precise` and `name` fields.
598impl Ord for SourceId {
599    fn cmp(&self, other: &SourceId) -> Ordering {
600        // If our interior pointers are to the exact same `SourceIdInner` then
601        // we're guaranteed to be equal.
602        if ptr::eq(self.inner, other.inner) {
603            return Ordering::Equal;
604        }
605
606        // Sort first based on `kind`, deferring to the URL comparison if
607        // the kinds are equal.
608        let ord_kind = self.inner.kind.cmp(&other.inner.kind);
609        ord_kind.then_with(|| self.inner.canonical_url.cmp(&other.inner.canonical_url))
610    }
611}
612
613impl ser::Serialize for SourceId {
614    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
615    where
616        S: ser::Serializer,
617    {
618        if self.is_path() {
619            None::<String>.serialize(s)
620        } else {
621            s.collect_str(&self.as_url())
622        }
623    }
624}
625
626impl<'de> de::Deserialize<'de> for SourceId {
627    fn deserialize<D>(d: D) -> Result<SourceId, D::Error>
628    where
629        D: de::Deserializer<'de>,
630    {
631        let string = String::deserialize(d)?;
632        SourceId::from_url(&string).map_err(de::Error::custom)
633    }
634}
635
636fn url_display(url: &Url) -> String {
637    if url.scheme() == "file" {
638        if let Ok(path) = url.to_file_path() {
639            if let Some(path_str) = path.to_str() {
640                return path_str.to_string();
641            }
642        }
643    }
644
645    url.as_str().to_string()
646}
647
648impl fmt::Display for SourceId {
649    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
650        match self.inner.kind {
651            SourceKind::Git(ref reference) => {
652                // Don't replace the URL display for git references,
653                // because those are kind of expected to be URLs.
654                write!(f, "{}", self.inner.url)?;
655                if let Some(pretty) = reference.pretty_ref(true) {
656                    write!(f, "?{}", pretty)?;
657                }
658
659                if let Some(s) = &self.inner.precise {
660                    let s = s.to_string();
661                    let len = cmp::min(s.len(), 8);
662                    write!(f, "#{}", &s[..len])?;
663                }
664                Ok(())
665            }
666            SourceKind::Path => write!(f, "{}", url_display(&self.inner.url)),
667            SourceKind::Registry | SourceKind::SparseRegistry => {
668                write!(f, "registry `{}`", self.display_registry_name())
669            }
670            SourceKind::LocalRegistry => write!(f, "registry `{}`", url_display(&self.inner.url)),
671            SourceKind::Directory => write!(f, "dir {}", url_display(&self.inner.url)),
672        }
673    }
674}
675
676impl Hash for SourceId {
677    fn hash<S: hash::Hasher>(&self, into: &mut S) {
678        self.inner.kind.hash(into);
679        self.inner.canonical_url.hash(into);
680    }
681}
682
683/// The hash of `SourceIdInner` is used to retrieve its interned value from
684/// `SOURCE_ID_CACHE`. We only care about fields that make `SourceIdInner`
685/// unique. Optional fields not affecting the uniqueness must be excluded,
686/// such as [`registry_key`]. That's why this is not derived.
687///
688/// [`registry_key`]: SourceIdInner::registry_key
689impl Hash for SourceIdInner {
690    fn hash<S: hash::Hasher>(&self, into: &mut S) {
691        self.kind.hash(into);
692        self.precise.hash(into);
693        self.canonical_url.hash(into);
694    }
695}
696
697/// This implementation must be synced with [`SourceIdInner::hash`].
698impl PartialEq for SourceIdInner {
699    fn eq(&self, other: &Self) -> bool {
700        self.kind == other.kind
701            && self.precise == other.precise
702            && self.canonical_url == other.canonical_url
703    }
704}
705
706/// A `Display`able view into a `SourceId` that will write it as a url
707pub struct SourceIdAsUrl<'a> {
708    inner: &'a SourceIdInner,
709    encoded: bool,
710}
711
712impl<'a> fmt::Display for SourceIdAsUrl<'a> {
713    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
714        if let Some(protocol) = self.inner.kind.protocol() {
715            write!(f, "{protocol}+")?;
716        }
717        write!(f, "{}", self.inner.url)?;
718        if let SourceIdInner {
719            kind: SourceKind::Git(ref reference),
720            ref precise,
721            ..
722        } = *self.inner
723        {
724            if let Some(pretty) = reference.pretty_ref(self.encoded) {
725                write!(f, "?{}", pretty)?;
726            }
727            if let Some(precise) = precise.as_ref() {
728                write!(f, "#{}", precise)?;
729            }
730        }
731        Ok(())
732    }
733}
734
735impl KeyOf {
736    /// Gets the underlying key.
737    fn key(&self) -> &str {
738        match self {
739            KeyOf::Registry(k) | KeyOf::Source(k) => k,
740        }
741    }
742
743    /// Gets the key if it's from an alternative registry.
744    fn alternative_registry(&self) -> Option<&str> {
745        match self {
746            KeyOf::Registry(k) => Some(k),
747            _ => None,
748        }
749    }
750}
751
752#[cfg(test)]
753mod tests {
754    use super::{GitReference, SourceId, SourceKind};
755    use crate::util::{GlobalContext, IntoUrl};
756
757    #[test]
758    fn github_sources_equal() {
759        let loc = "https://github.com/foo/bar".into_url().unwrap();
760        let default = SourceKind::Git(GitReference::DefaultBranch);
761        let s1 = SourceId::new(default.clone(), loc, None).unwrap();
762
763        let loc = "git://github.com/foo/bar".into_url().unwrap();
764        let s2 = SourceId::new(default, loc.clone(), None).unwrap();
765
766        assert_eq!(s1, s2);
767
768        let foo = SourceKind::Git(GitReference::Branch("foo".to_string()));
769        let s3 = SourceId::new(foo, loc, None).unwrap();
770        assert_ne!(s1, s3);
771    }
772
773    // This is a test that the hash of the `SourceId` for crates.io is a well-known
774    // value.
775    //
776    // Note that the hash value matches what the crates.io source id has hashed
777    // since Rust 1.84.0. We strive to keep this value the same across
778    // versions of Cargo because changing it means that users will need to
779    // redownload the index and all crates they use when using a new Cargo version.
780    //
781    // This isn't to say that this hash can *never* change, only that when changing
782    // this it should be explicitly done. If this hash changes accidentally and
783    // you're able to restore the hash to its original value, please do so!
784    // Otherwise please just leave a comment in your PR as to why the hash value is
785    // changing and why the old value can't be easily preserved.
786    // If it takes an ugly hack to restore it,
787    // then leave a link here so we can remove the hack next time we change the hash.
788    //
789    // Hacks to remove next time the hash changes:
790    // - (fill in your code here)
791    //
792    // The hash value should be stable across platforms, and doesn't depend on
793    // endianness and bit-width. One caveat is that absolute paths on Windows
794    // are inherently different than on Unix-like platforms. Unless we omit or
795    // strip the prefix components (e.g. `C:`), there is not way to have a true
796    // cross-platform stable hash for absolute paths.
797    #[test]
798    fn test_stable_hash() {
799        use std::hash::Hasher;
800        use std::path::Path;
801
802        use snapbox::IntoData as _;
803        use snapbox::assert_data_eq;
804        use snapbox::str;
805
806        use crate::util::StableHasher;
807        use crate::util::hex::short_hash;
808
809        #[cfg(not(windows))]
810        let ws_root = Path::new("/tmp/ws");
811        #[cfg(windows)]
812        let ws_root = Path::new(r"C:\\tmp\ws");
813
814        let gen_hash = |source_id: SourceId| {
815            let mut hasher = StableHasher::new();
816            source_id.stable_hash(ws_root, &mut hasher);
817            Hasher::finish(&hasher).to_string()
818        };
819
820        let source_id = SourceId::crates_io(&GlobalContext::default().unwrap()).unwrap();
821        assert_data_eq!(gen_hash(source_id), str!["7062945687441624357"].raw());
822        assert_data_eq!(short_hash(&source_id), str!["25cdd57fae9f0462"].raw());
823
824        let url = "https://my-crates.io".into_url().unwrap();
825        let source_id = SourceId::for_registry(&url).unwrap();
826        assert_data_eq!(gen_hash(source_id), str!["8310250053664888498"].raw());
827        assert_data_eq!(short_hash(&source_id), str!["b2d65deb64f05373"].raw());
828
829        let url = "https://your-crates.io".into_url().unwrap();
830        let source_id = SourceId::for_alt_registry(&url, "alt").unwrap();
831        assert_data_eq!(gen_hash(source_id), str!["14149534903000258933"].raw());
832        assert_data_eq!(short_hash(&source_id), str!["755952de063f5dc4"].raw());
833
834        let url = "sparse+https://my-crates.io".into_url().unwrap();
835        let source_id = SourceId::for_registry(&url).unwrap();
836        assert_data_eq!(gen_hash(source_id), str!["16249512552851930162"].raw());
837        assert_data_eq!(short_hash(&source_id), str!["327cfdbd92dd81e1"].raw());
838
839        let url = "sparse+https://your-crates.io".into_url().unwrap();
840        let source_id = SourceId::for_alt_registry(&url, "alt").unwrap();
841        assert_data_eq!(gen_hash(source_id), str!["6156697384053352292"].raw());
842        assert_data_eq!(short_hash(&source_id), str!["64a713b6a6fb7055"].raw());
843
844        let url = "file:///tmp/ws/crate".into_url().unwrap();
845        let source_id = SourceId::for_git(&url, GitReference::DefaultBranch).unwrap();
846        assert_data_eq!(gen_hash(source_id), str!["473480029881867801"].raw());
847        assert_data_eq!(short_hash(&source_id), str!["199e591d94239206"].raw());
848
849        let path = &ws_root.join("crate");
850        let source_id = SourceId::for_local_registry(path).unwrap();
851        #[cfg(not(windows))]
852        {
853            assert_data_eq!(gen_hash(source_id), str!["11515846423845066584"].raw());
854            assert_data_eq!(short_hash(&source_id), str!["58d73c154f81d09f"].raw());
855        }
856        #[cfg(windows)]
857        {
858            assert_data_eq!(gen_hash(source_id), str!["6146331155906064276"].raw());
859            assert_data_eq!(short_hash(&source_id), str!["946fb2239f274c55"].raw());
860        }
861
862        let source_id = SourceId::for_path(path).unwrap();
863        assert_data_eq!(gen_hash(source_id), str!["215644081443634269"].raw());
864        #[cfg(not(windows))]
865        assert_data_eq!(short_hash(&source_id), str!["64bace89c92b101f"].raw());
866        #[cfg(windows)]
867        assert_data_eq!(short_hash(&source_id), str!["01e1e6c391813fb6"].raw());
868
869        let source_id = SourceId::for_directory(path).unwrap();
870        #[cfg(not(windows))]
871        {
872            assert_data_eq!(gen_hash(source_id), str!["6127590343904940368"].raw());
873            assert_data_eq!(short_hash(&source_id), str!["505191d1f3920955"].raw());
874        }
875        #[cfg(windows)]
876        {
877            assert_data_eq!(gen_hash(source_id), str!["10423446877655960172"].raw());
878            assert_data_eq!(short_hash(&source_id), str!["6c8ad69db585a790"].raw());
879        }
880    }
881
882    #[test]
883    fn serde_roundtrip() {
884        let url = "sparse+https://my-crates.io/".into_url().unwrap();
885        let source_id = SourceId::for_registry(&url).unwrap();
886        let formatted = format!("{}", source_id.as_url());
887        let deserialized = SourceId::from_url(&formatted).unwrap();
888        assert_eq!(formatted, "sparse+https://my-crates.io/");
889        assert_eq!(source_id, deserialized);
890    }
891
892    #[test]
893    fn gitrefs_roundtrip() {
894        let base = "https://host/path".into_url().unwrap();
895        let branch = GitReference::Branch("*-._+20%30 Z/z#foo=bar&zap[]?to\\()'\"".to_string());
896        let s1 = SourceId::for_git(&base, branch).unwrap();
897        let ser1 = format!("{}", s1.as_encoded_url());
898        let s2 = SourceId::from_url(&ser1).expect("Failed to deserialize");
899        let ser2 = format!("{}", s2.as_encoded_url());
900        // Serializing twice should yield the same result
901        assert_eq!(ser1, ser2, "Serialized forms don't match");
902        // SourceId serializing the same should have the same semantics
903        // This used to not be the case (# was ambiguous)
904        assert_eq!(s1, s2, "SourceId doesn't round-trip");
905        // Freeze the format to match an x-www-form-urlencoded query string
906        // https://url.spec.whatwg.org/#application/x-www-form-urlencoded
907        assert_eq!(
908            ser1,
909            "git+https://host/path?branch=*-._%2B20%2530+Z%2Fz%23foo%3Dbar%26zap%5B%5D%3Fto%5C%28%29%27%22"
910        );
911    }
912}
913
914/// Check if `url` equals to the overridden crates.io URL.
915#[expect(
916    clippy::disallowed_methods,
917    reason = "testing only, no reason for config support"
918)]
919fn is_overridden_crates_io_url(url: &str) -> bool {
920    std::env::var("__CARGO_TEST_CRATES_IO_URL_DO_NOT_USE_THIS").map_or(false, |v| v == url)
921}