#
cargo/core/
registry.rs

    1//! Types that hold source information for a group of packages.
    2//!
    3//! The primary type you're looking for is [`PackageRegistry`]. It is an
    4//! abstraction over multiple [`Source`]s. [`PackageRegistry`] also implements
    5//! the [`Registry`] trait, allowing a dependency resolver to query necessary
    6//! package metadata (i.e., [Summary]) from it.
    7//!
    8//! Not to be confused with [`crate::sources::registry`] and [`crate::ops::registry`].
    9//! The former is just one kind of source,
    10//! while the latter involves operations on the registry Web API.
    11
    12use std::collections::{HashMap, HashSet};
    13use std::task::{Poll, ready};
    14
    15use crate::core::PackageSet;
    16use crate::core::{Dependency, PackageId, SourceId, Summary};
    17use crate::sources::IndexSummary;
    18use crate::sources::config::SourceConfigMap;
    19use crate::sources::source::QueryKind;
    20use crate::sources::source::Source;
    21use crate::sources::source::SourceMap;
    22use crate::util::errors::CargoResult;
    23use crate::util::interning::InternedString;
    24use crate::util::{CanonicalUrl, GlobalContext};
    25use annotate_snippets::Level;
    26use anyhow::{Context as _, bail};
    27use tracing::{debug, trace};
    28use url::Url;
    29
    30/// An abstraction provides a set of methods for querying source information
    31/// about a group of packages, without leaking too much implementation details
    32/// of the actual registry.
    33///
    34/// As of 2024-04, only [`PackageRegistry`] and `MyRegistry` in resolver-tests
    35/// are found implementing this.
    36///
    37/// See also the [`Source`] trait, as many of the methods here mirror and
    38/// abstract over its functionalities.
    39pub trait Registry {
    40    /// Attempt to find the packages that match a dependency request.
    41    fn query(
    42        &mut self,
    43        dep: &Dependency,
    44        kind: QueryKind,
    45        f: &mut dyn FnMut(IndexSummary),
    46    ) -> Poll<CargoResult<()>>;
    47
    48    /// Gathers the result from [`Registry::query`] as a list of [`IndexSummary`] items
    49    /// when they become available.
    50    fn query_vec(
    51        &mut self,
    52        dep: &Dependency,
    53        kind: QueryKind,
    54    ) -> Poll<CargoResult<Vec<IndexSummary>>> {
    55        let mut ret = Vec::new();
    56        self.query(dep, kind, &mut |s| ret.push(s)).map_ok(|()| ret)
    57    }
    58
    59    /// Gets the description of a source, to provide useful messages.
    60    fn describe_source(&self, source: SourceId) -> String;
    61
    62    /// Checks if a source is replaced with some other source.
    63    fn is_replaced(&self, source: SourceId) -> bool;
    64
    65    /// Block until all outstanding [`Poll::Pending`] requests are [`Poll::Ready`].
    66    fn block_until_ready(&mut self) -> CargoResult<()>;
    67}
    68
    69/// This structure represents a registry of known packages. It internally
    70/// contains a number of [`Source`] instances which are used to load a
    71/// [`Package`] from.
    72///
    73/// The resolution phase of Cargo uses this to drive knowledge about new
    74/// packages as well as querying for lists of new packages.
    75/// It is here that sources are updated (e.g., network operations) and
    76/// overrides/patches are handled.
    77///
    78/// The general idea behind this registry is that it is centered around the
    79/// [`SourceMap`] structure, contained within which is a mapping of a [`SourceId`]
    80/// to a [`Source`]. Each [`Source`] in the map has been updated (using network
    81/// operations if necessary) and is ready to be queried for packages.
    82///
    83/// [`Package`]: crate::core::Package
    84pub struct PackageRegistry<'gctx> {
    85    gctx: &'gctx GlobalContext,
    86    sources: SourceMap<'gctx>,
    87
    88    /// A list of sources which are considered "path-overrides" which take
    89    /// precedent when querying for packages.
    90    overrides: Vec<SourceId>,
    91
    92    /// Use for tracking sources that are already loaded into the registry.
    93    // Note that each SourceId does not take into account its `precise` field
    94    // when hashing or testing for equality. When adding a new `SourceId`, we
    95    // want to avoid duplicates in the `SourceMap` (to prevent re-updating the
    96    // same git repo twice for example), but we also want to ensure that the
    97    // loaded source is always updated.
    98    //
    99    // Sources with a `precise` field normally don't need to be updated because
    100    // their contents are already on disk, but sources without a `precise` field
    101    // almost always need to be updated. If we have a cached `Source` for a
    102    // precise `SourceId`, then when we add a new `SourceId` that is not precise
    103    // we want to ensure that the underlying source is updated.
    104    //
    105    // This is basically a long-winded way of saying that we want to know
    106    // precisely what the keys of `sources` are, so this is a mapping of key to
    107    // what exactly the key is.
    108    source_ids: HashMap<SourceId, (SourceId, Kind)>,
    109
    110    /// This is constructed via [`PackageRegistry::register_lock`].
    111    /// See also [`LockedMap`].
    112    locked: LockedMap,
    113    /// Packages allowed to be used, even if they are yanked.
    114    yanked_whitelist: HashSet<PackageId>,
    115    source_config: SourceConfigMap<'gctx>,
    116
    117    /// Patches registered during calls to [`PackageRegistry::patch`].
    118    ///
    119    /// These are available for `query` after calling [`PackageRegistry::lock_patches`],
    120    /// which `lock`s them all to specific versions.
    121    patches: HashMap<CanonicalUrl, Vec<Summary>>,
    122    /// Whether patches are locked. That is, they are available to resolution.
    123    ///
    124    /// See [`PackageRegistry::lock_patches`] and [`PackageRegistry::patch`] for more.
    125    patches_locked: bool,
    126    /// Patches available for each source.
    127    ///
    128    /// This is for determining whether a dependency entry from a lockfile
    129    /// happened through `[patch]`, during calls to [`lock`] to rewrite
    130    /// summaries to point directly at these patched entries.
    131    ///
    132    /// This is constructed during calls to [`PackageRegistry::patch`],
    133    /// along with the `patches` field, thoough these entries never get locked.
    134    patches_available: HashMap<CanonicalUrl, Vec<PackageId>>,
    135}
    136
    137/// A map of all "locked packages" which is filled in when parsing a lock file
    138/// and is used to guide dependency resolution by altering summaries as they're
    139/// queried from this source.
    140///
    141/// This map can be thought of as a glorified `Vec<MySummary>` where `MySummary`
    142/// has a `PackageId` for which package it represents as well as a list of
    143/// `PackageId` for the resolved dependencies. The hash map is otherwise
    144/// structured though for easy access throughout this registry.
    145type LockedMap = HashMap<
    146    // The first level of key-ing done in this hash map is the source that
    147    // dependencies come from, identified by a `SourceId`.
    148    // The next level is keyed by the name of the package...
    149    (SourceId, InternedString),
    150    // ... and the value here is a list of tuples. The first element of each
    151    // tuple is a package which has the source/name used to get to this
    152    // point. The second element of each tuple is the list of locked
    153    // dependencies that the first element has.
    154    Vec<(PackageId, Vec<PackageId>)>,
    155>;
    156
    157/// Kinds of sources a [`PackageRegistry`] has loaded.
    158#[derive(PartialEq, Eq, Clone, Copy)]
    159enum Kind {
    160    /// A source from a [path override].
    161    ///
    162    /// [path overrides]: https://doc.rust-lang.org/nightly/cargo/reference/overriding-dependencies.html#paths-overrides
    163    Override,
    164    /// A source that is locked and not going to change.
    165    ///
    166    /// For example, sources of workspace members are loaded during the
    167    /// workspace initialization, so not allowed to change.
    168    Locked,
    169    /// A source that is not locked nor a path-override.
    170    Normal,
    171}
    172
    173/// This tuple is an argument to [`PackageRegistry::patch`].
    174///
    175/// * The first element is the patch definition straight from the manifest.
    176/// * The second element is an optional variant where the patch has been locked.
    177///   It is the patch locked to a specific version found in Cargo.lock.
    178///   This will be `None` if `Cargo.lock` doesn't exist,
    179///   or the patch did not match any existing entries in `Cargo.lock`.
    180pub type PatchDependency<'a> = (&'a Dependency, Option<LockedPatchDependency>);
    181
    182/// Argument to [`PackageRegistry::patch`] which is information about a `[patch]`
    183/// directive that we found in a lockfile, if present.
    184pub struct LockedPatchDependency {
    185    /// The original `Dependency` directive, except "locked" so it's version
    186    /// requirement is Locked to `foo` and its `SourceId` has a "precise" listed.
    187    pub dependency: Dependency,
    188    /// The `PackageId` that was previously found in a lock file which
    189    /// `dependency` matches.
    190    pub package_id: PackageId,
    191    /// Something only used for backwards compatibility with the v2 lock file
    192    /// format where `branch=master` is considered the same as `DefaultBranch`.
    193    /// For more comments on this see the code in `ops/resolve.rs`.
    194    pub alt_package_id: Option<PackageId>,
    195}
    196
    197impl<'gctx> PackageRegistry<'gctx> {
    198    pub fn new_with_source_config(
    199        gctx: &'gctx GlobalContext,
    200        source_config: SourceConfigMap<'gctx>,
    201    ) -> CargoResult<PackageRegistry<'gctx>> {
    202        Ok(PackageRegistry {
    203            gctx,
    204            sources: SourceMap::new(),
    205            source_ids: HashMap::new(),
    206            overrides: Vec::new(),
    207            source_config,
    208            locked: HashMap::new(),
    209            yanked_whitelist: HashSet::new(),
    210            patches: HashMap::new(),
    211            patches_locked: false,
    212            patches_available: HashMap::new(),
    213        })
    214    }
    215
    216    pub fn get(self, package_ids: &[PackageId]) -> CargoResult<PackageSet<'gctx>> {
    217        trace!("getting packages; sources={}", self.sources.len());
    218        PackageSet::new(package_ids, self.sources, self.gctx)
    219    }
    220
    221    /// Ensures the [`Source`] of the given [`SourceId`] is loaded.
    222    /// If not, this will block until the source is ready.
    223    fn ensure_loaded(&mut self, namespace: SourceId, kind: Kind) -> CargoResult<()> {
    224        match self.source_ids.get(&namespace) {
    225            // We've previously loaded this source, and we've already locked it,
    226            // so we're not allowed to change it even if `namespace` has a
    227            // slightly different precise version listed.
    228            Some((_, Kind::Locked)) => {
    229                debug!("load/locked   {}", namespace);
    230                return Ok(());
    231            }
    232
    233            // If the previous source was not a precise source, then we can be
    234            // sure that it's already been updated if we've already loaded it.
    235            Some((previous, _)) if !previous.has_precise() => {
    236                debug!("load/precise  {}", namespace);
    237                return Ok(());
    238            }
    239
    240            // If the previous source has the same precise version as we do,
    241            // then we're done, otherwise we need to move forward
    242            // updating this source.
    243            Some((previous, _)) => {
    244                if previous.has_same_precise_as(namespace) {
    245                    debug!("load/match    {}", namespace);
    246                    return Ok(());
    247                }
    248                debug!("load/mismatch {}", namespace);
    249            }
    250            None => {
    251                debug!("load/missing  {}", namespace);
    252            }
    253        }
    254
    255        self.load(namespace, kind)?;
    256
    257        // This isn't strictly necessary since it will be called later.
    258        // However it improves error messages for sources that issue errors
    259        // in `block_until_ready` because the callers here have context about
    260        // which deps are being resolved.
    261        self.block_until_ready()?;
    262        Ok(())
    263    }
    264
    265    pub fn add_sources(&mut self, ids: impl IntoIterator<Item = SourceId>) -> CargoResult<()> {
    266        for id in ids {
    267            self.ensure_loaded(id, Kind::Locked)?;
    268        }
    269        Ok(())
    270    }
    271
    272    /// Adds a source which will be locked.
    273    /// Useful for path sources such as the source of a workspace member.
    274    pub fn add_preloaded(&mut self, source: Box<dyn Source + 'gctx>) {
    275        self.add_source(source, Kind::Locked);
    276    }
    277
    278    /// Adds a source to the registry.
    279    fn add_source(&mut self, source: Box<dyn Source + 'gctx>, kind: Kind) {
    280        let id = source.source_id();
    281        self.sources.insert(source);
    282        self.source_ids.insert(id, (id, kind));
    283    }
    284
    285    /// Adds a source from a [path override].
    286    ///
    287    /// [path override]: https://doc.rust-lang.org/nightly/cargo/reference/overriding-dependencies.html#paths-overrides
    288    pub fn add_override(&mut self, source: Box<dyn Source + 'gctx>) {
    289        self.overrides.push(source.source_id());
    290        self.add_source(source, Kind::Override);
    291    }
    292
    293    /// Allows a group of package to be available to query even if they are yanked.
    294    pub fn add_to_yanked_whitelist(&mut self, iter: impl Iterator<Item = PackageId>) {
    295        let pkgs = iter.collect::<Vec<_>>();
    296        for (_, source) in self.sources.sources_mut() {
    297            source.add_to_yanked_whitelist(&pkgs);
    298        }
    299        self.yanked_whitelist.extend(pkgs);
    300    }
    301
    302    /// remove all residual state from previous lock files.
    303    pub fn clear_lock(&mut self) {
    304        trace!("clear_lock");
    305        self.locked = HashMap::new();
    306    }
    307
    308    /// Registers one "locked package" to the registry, for guiding the
    309    /// dependency resolution. See [`LockedMap`] for more.
    310    pub fn register_lock(&mut self, id: PackageId, deps: Vec<PackageId>) {
    311        trace!("register_lock: {}", id);
    312        for dep in deps.iter() {
    313            trace!("\t-> {}", dep);
    314        }
    315        let sub_vec = self
    316            .locked
    317            .entry((id.source_id(), id.name()))
    318            .or_insert_with(Vec::new);
    319        sub_vec.push((id, deps));
    320    }
    321
    322    /// Insert a `[patch]` section into this registry.
    323    ///
    324    /// This method will insert a `[patch]` section for the `url` specified,
    325    /// with the given list of dependencies. The `url` specified is the URL of
    326    /// the source to patch (for example this is `crates-io` in the manifest).
    327    /// The `deps` is an array of all the entries in the `[patch]` section of
    328    /// the manifest.
    329    ///
    330    /// Here the `patch_deps` will be resolved to a precise version and stored
    331    /// internally for future calls to `query` below.
    332    ///
    333    /// Note that the patch list specified here *will not* be available to
    334    /// [`Registry::query`] until [`PackageRegistry::lock_patches`] is called
    335    /// below, which should be called once all patches have been added.
    336    ///
    337    /// The return value is a `Vec` of patches that should *not* be locked.
    338    /// This happens when the patch is locked, but the patch has been updated
    339    /// so the locked value is no longer correct.
    340    #[tracing::instrument(skip(self, patch_deps))]
    341    pub fn patch(
    342        &mut self,
    343        url: &Url,
    344        patch_deps: &[PatchDependency<'_>],
    345    ) -> CargoResult<Vec<(Dependency, PackageId)>> {
    346        // NOTE: None of this code is aware of required features. If a patch
    347        // is missing a required feature, you end up with an "unused patch"
    348        // warning, which is very hard to understand. Ideally the warning
    349        // would be tailored to indicate *why* it is unused.
    350        let canonical = CanonicalUrl::new(url)?;
    351
    352        // Return value of patches that shouldn't be locked.
    353        let mut unlock_patches = Vec::new();
    354
    355        // First up we need to actually resolve each `patch_deps` specification
    356        // to precisely one summary. We're not using the `query` method below
    357        // as it internally uses maps we're building up as part of this method
    358        // (`patches_available` and `patches`). Instead we're going straight to
    359        // the source to load information from it.
    360        //
    361        // Remember that each dependency listed in `[patch]` has to resolve to
    362        // precisely one package, so that's why we're just creating a flat list
    363        // of summaries which should be the same length as `deps` above.
    364
    365        let mut patch_deps_remaining: Vec<_> = patch_deps.iter().collect();
    366        let mut unlocked_summaries = Vec::new();
    367        while !patch_deps_remaining.is_empty() {
    368            let mut patch_deps_pending = Vec::new();
    369            for patch_dep_remaining in patch_deps_remaining {
    370                let (orig_patch, locked) = patch_dep_remaining;
    371
    372                // Use the locked patch if it exists, otherwise use the original.
    373                let dep = match locked {
    374                    Some(lock) => &lock.dependency,
    375                    None => *orig_patch,
    376                };
    377                debug!(
    378                    "registering a patch for `{}` with `{}`",
    379                    url,
    380                    dep.package_name()
    381                );
    382
    383                let mut unused_fields = Vec::new();
    384                if dep.features().len() != 0 {
    385                    unused_fields.push("`features`");
    386                }
    387                if !dep.uses_default_features() {
    388                    unused_fields.push("`default-features`")
    389                }
    390                if !unused_fields.is_empty() {
    391                    self.source_config.gctx().shell().print_report(
    392                        &[Level::WARNING
    393                            .secondary_title(format!(
    394                                "unused field in patch for `{}`: {}",
    395                                dep.package_name(),
    396                                unused_fields.join(", ")
    397                            ))
    398                            .element(Level::HELP.message(format!(
    399                                "configure {} in the `dependencies` entry",
    400                                unused_fields.join(", ")
    401                            )))],
    402                        false,
    403                    )?;
    404                }
    405
    406                // Go straight to the source for resolving `dep`. Load it as we
    407                // normally would and then ask it directly for the list of summaries
    408                // corresponding to this `dep`.
    409                self.ensure_loaded(dep.source_id(), Kind::Normal)
    410                    .with_context(|| {
    411                        format!(
    412                            "failed to load source for dependency `{}`",
    413                            dep.package_name()
    414                        )
    415                    })?;
    416
    417                let source = self
    418                    .sources
    419                    .get_mut(dep.source_id())
    420                    .expect("loaded source not present");
    421
    422                let summaries = match source.query_vec(dep, QueryKind::Exact)? {
    423                    Poll::Ready(deps) => deps,
    424                    Poll::Pending => {
    425                        patch_deps_pending.push(patch_dep_remaining);
    426                        continue;
    427                    }
    428                };
    429
    430                let summaries = summaries.into_iter().map(|s| s.into_summary()).collect();
    431
    432                let (summary, should_unlock) =
    433                    match summary_for_patch(orig_patch, &locked, summaries, source) {
    434                        Poll::Ready(x) => x,
    435                        Poll::Pending => {
    436                            patch_deps_pending.push(patch_dep_remaining);
    437                            continue;
    438                        }
    439                    }
    440                    .with_context(|| {
    441                        format!(
    442                            "patch for `{}` in `{}` failed to resolve",
    443                            orig_patch.package_name(),
    444                            url,
    445                        )
    446                    })
    447                    .with_context(|| format!("failed to resolve patches for `{}`", url))?;
    448
    449                debug!(
    450                    "patch summary is {:?} should_unlock={:?}",
    451                    summary, should_unlock
    452                );
    453                if let Some(unlock_id) = should_unlock {
    454                    unlock_patches.push(((*orig_patch).clone(), unlock_id));
    455                }
    456
    457                if *summary.package_id().source_id().canonical_url() == canonical {
    458                    return Err(anyhow::anyhow!(
    459                        "patch for `{}` in `{}` points to the same source, but \
    460                        patches must point to different sources",
    461                        dep.package_name(),
    462                        url
    463                    )
    464                    .context(format!("failed to resolve patches for `{}`", url)));
    465                }
    466                unlocked_summaries.push(summary);
    467            }
    468
    469            patch_deps_remaining = patch_deps_pending;
    470            self.block_until_ready()?;
    471        }
    472
    473        let mut name_and_version = HashSet::new();
    474        for summary in unlocked_summaries.iter() {
    475            let name = summary.package_id().name();
    476            let version = summary.package_id().version();
    477            if !name_and_version.insert((name, version)) {
    478                bail!(
    479                    "cannot have two `[patch]` entries which both resolve \
    480                     to `{} v{}`",
    481                    name,
    482                    version
    483                );
    484            }
    485        }
    486
    487        // Calculate a list of all patches available for this source.
    488        let mut ids = Vec::new();
    489        for (summary, (_, lock)) in unlocked_summaries.iter().zip(patch_deps) {
    490            ids.push(summary.package_id());
    491            // This is subtle where the list of `ids` for a canonical URL is
    492            // extend with possibly two ids per summary. This is done to handle
    493            // the transition from the v2->v3 lock file format where in v2
    494            // DefaultBranch was either DefaultBranch or Branch("master") for
    495            // git dependencies. In this case if `summary.package_id()` is
    496            // Branch("master") then alt_package_id will be DefaultBranch. This
    497            // signifies that there's a patch available for either of those
    498            // dependency directives if we see them in the dependency graph.
    499            if let Some(lock) = lock {
    500                ids.extend(lock.alt_package_id);
    501            }
    502        }
    503        self.patches_available.insert(canonical.clone(), ids);
    504
    505        // Note that we do not use `lock` here to lock summaries! That step
    506        // happens later once `lock_patches` is invoked. In the meantime though
    507        // we want to fill in the `patches_available` map (later used in the
    508        // `lock` method) and otherwise store the unlocked summaries in
    509        // `patches` to get locked in a future call to `lock_patches`.
    510        self.patches.insert(canonical, unlocked_summaries);
    511
    512        Ok(unlock_patches)
    513    }
    514
    515    /// Lock all patch summaries added via [`patch`](Self::patch),
    516    /// making them available to resolution via [`Registry::query`].
    517    pub fn lock_patches(&mut self) {
    518        assert!(!self.patches_locked);
    519        for summaries in self.patches.values_mut() {
    520            for summary in summaries {
    521                debug!("locking patch {:?}", summary);
    522                *summary = lock(&self.locked, &self.patches_available, summary.clone());
    523            }
    524        }
    525        self.patches_locked = true;
    526    }
    527
    528    /// Gets all patches grouped by the source URLs they are going to patch.
    529    ///
    530    /// These patches are mainly collected from [`patch`](Self::patch).
    531    /// They might not be the same as patches actually used during dependency resolving.
    532    pub fn patches(&self) -> &HashMap<CanonicalUrl, Vec<Summary>> {
    533        &self.patches
    534    }
    535
    536    /// Loads the [`Source`] for a given [`SourceId`] to this registry, making
    537    /// them available to resolution.
    538    fn load(&mut self, source_id: SourceId, kind: Kind) -> CargoResult<()> {
    539        debug!("loading source {}", source_id);
    540        let source = self
    541            .source_config
    542            .load(source_id, &self.yanked_whitelist)
    543            .with_context(|| format!("Unable to update {}", source_id))?;
    544        assert_eq!(source.source_id(), source_id);
    545
    546        if kind == Kind::Override {
    547            self.overrides.push(source_id);
    548        }
    549        self.add_source(source, kind);
    550
    551        // If we have an imprecise version then we don't know what we're going
    552        // to look for, so we always attempt to perform an update here.
    553        //
    554        // If we have a precise version, then we'll update lazily during the
    555        // querying phase. Note that precise in this case is only
    556        // `"locked"` as other values indicate a `cargo update
    557        // --precise` request
    558        if !source_id.has_locked_precise() {
    559            self.sources.get_mut(source_id).unwrap().invalidate_cache();
    560        } else {
    561            debug!("skipping update due to locked registry");
    562        }
    563        Ok(())
    564    }
    565
    566    /// Queries path overrides from this registry.
    567    fn query_overrides(&mut self, dep: &Dependency) -> Poll<CargoResult<Option<IndexSummary>>> {
    568        for &s in self.overrides.iter() {
    569            let src = self.sources.get_mut(s).unwrap();
    570            let dep = Dependency::new_override(dep.package_name(), s);
    571
    572            let mut results = None;
    573            ready!(src.query(&dep, QueryKind::Exact, &mut |s| results = Some(s)))?;
    574            if results.is_some() {
    575                return Poll::Ready(Ok(results));
    576            }
    577        }
    578        Poll::Ready(Ok(None))
    579    }
    580
    581    /// This function is used to transform a summary to another locked summary
    582    /// if possible. This is where the concept of a lock file comes into play.
    583    ///
    584    /// If a summary points at a package ID which was previously locked, then we
    585    /// override the summary's ID itself, as well as all dependencies, to be
    586    /// rewritten to the locked versions. This will transform the summary's
    587    /// source to a precise source (listed in the locked version) as well as
    588    /// transforming all of the dependencies from range requirements on
    589    /// imprecise sources to exact requirements on precise sources.
    590    ///
    591    /// If a summary does not point at a package ID which was previously locked,
    592    /// or if any dependencies were added and don't have a previously listed
    593    /// version, we still want to avoid updating as many dependencies as
    594    /// possible to keep the graph stable. In this case we map all of the
    595    /// summary's dependencies to be rewritten to a locked version wherever
    596    /// possible. If we're unable to map a dependency though, we just pass it on
    597    /// through.
    598    pub fn lock(&self, summary: Summary) -> Summary {
    599        assert!(self.patches_locked);
    600        lock(&self.locked, &self.patches_available, summary)
    601    }
    602
    603    fn warn_bad_override(
    604        &self,
    605        override_summary: &Summary,
    606        real_summary: &Summary,
    607    ) -> CargoResult<()> {
    608        let mut real_deps = real_summary.dependencies().iter().collect::<Vec<_>>();
    609
    610        let boilerplate = "\
    611This is currently allowed but is known to produce buggy behavior with spurious
    612recompiles and changes to the crate graph. Path overrides unfortunately were
    613never intended to support this feature, so for now this message is just a
    614warning. In the future, however, this message will become a hard error.
    615
    616To change the dependency graph via an override it's recommended to use the
    617`[patch]` feature of Cargo instead of the path override feature. This is
    618documented online at the url below for more information.
    619
    620https://doc.rust-lang.org/cargo/reference/overriding-dependencies.html
    621";
    622
    623        for dep in override_summary.dependencies() {
    624            if let Some(i) = real_deps.iter().position(|d| dep == *d) {
    625                real_deps.remove(i);
    626                continue;
    627            }
    628            let msg = format!(
    629                "path override for crate `{}` has altered the original list of\n\
    630                 dependencies; the dependency on `{}` was either added or\n\
    631                 modified to not match the previously resolved version\n\n\
    632                 {}",
    633                override_summary.package_id().name(),
    634                dep.package_name(),
    635                boilerplate
    636            );
    637            self.source_config.gctx().shell().warn(&msg)?;
    638            return Ok(());
    639        }
    640
    641        if let Some(dep) = real_deps.get(0) {
    642            let msg = format!(
    643                "path override for crate `{}` has altered the original list of\n\
    644                 dependencies; the dependency on `{}` was removed\n\n\
    645                 {}",
    646                override_summary.package_id().name(),
    647                dep.package_name(),
    648                boilerplate
    649            );
    650            self.source_config.gctx().shell().warn(&msg)?;
    651            return Ok(());
    652        }
    653
    654        Ok(())
    655    }
    656}
    657
    658impl<'gctx> Registry for PackageRegistry<'gctx> {
    659    fn query(
    660        &mut self,
    661        dep: &Dependency,
    662        kind: QueryKind,
    663        f: &mut dyn FnMut(IndexSummary),
    664    ) -> Poll<CargoResult<()>> {
    665        assert!(self.patches_locked);
    666        // Look for an override and get ready to query the real source.
    667        let override_summary = ready!(self.query_overrides(dep))?;
    668
    669        // Next up on our list of candidates is to check the `[patch]` section
    670        // of the manifest. Here we look through all patches relevant to the
    671        // source that `dep` points to, and then we match name/version. Note
    672        // that we don't use `dep.matches(..)` because the patches, by definition,
    673        // come from a different source. This means that `dep.matches(..)` will
    674        // always return false, when what we really care about is the name/version match.
    675        let mut patches = Vec::<Summary>::new();
    676        if let Some(extra) = self.patches.get(dep.source_id().canonical_url()) {
    677            patches.extend(
    678                extra
    679                    .iter()
    680                    .filter(|s| dep.matches_ignoring_source(s.package_id()))
    681                    .cloned(),
    682            );
    683        }
    684
    685        // A crucial feature of the `[patch]` feature is that we don't query the
    686        // actual registry if we have a "locked" dependency. A locked dep basically
    687        // just means a version constraint of `=a.b.c`, and because patches take
    688        // priority over the actual source then if we have a candidate we're done.
    689        if patches.len() == 1 && dep.is_locked() {
    690            let patch = patches.remove(0);
    691            match override_summary {
    692                Some(override_summary) => {
    693                    self.warn_bad_override(override_summary.as_summary(), &patch)?;
    694                    let override_summary =
    695                        override_summary.map_summary(|summary| self.lock(summary));
    696                    f(override_summary);
    697                }
    698                None => f(IndexSummary::Candidate(patch)),
    699            }
    700
    701            return Poll::Ready(Ok(()));
    702        }
    703
    704        if !patches.is_empty() {
    705            debug!(
    706                "found {} patches with an unlocked dep on `{}` at {} \
    707                     with `{}`, \
    708                     looking at sources",
    709                patches.len(),
    710                dep.package_name(),
    711                dep.source_id(),
    712                dep.version_req()
    713            );
    714        }
    715
    716        // Ensure the requested source_id is loaded
    717        self.ensure_loaded(dep.source_id(), Kind::Normal)
    718            .with_context(|| {
    719                format!(
    720                    "failed to load source for dependency `{}`",
    721                    dep.package_name()
    722                )
    723            })?;
    724
    725        let source = self.sources.get_mut(dep.source_id());
    726        match (override_summary, source) {
    727            (Some(_), None) => {
    728                return Poll::Ready(Err(anyhow::anyhow!("override found but no real ones")));
    729            }
    730            (None, None) => return Poll::Ready(Ok(())),
    731
    732            // If we don't have an override then we just ship everything upstairs after locking the summary
    733            (None, Some(source)) => {
    734                for patch in patches.iter() {
    735                    f(IndexSummary::Candidate(patch.clone()));
    736                }
    737
    738                // Our sources shouldn't ever come back to us with two summaries
    739                // that have the same version. We could, however, have an `[patch]`
    740                // section which is in use to override a version in the registry.
    741                // This means that if our `summary` in this loop has the same
    742                // version as something in `patches` that we've already selected,
    743                // then we skip this `summary`.
    744                let locked = &self.locked;
    745                let all_patches = &self.patches_available;
    746                let callback = &mut |summary: IndexSummary| {
    747                    for patch in patches.iter() {
    748                        let patch = patch.package_id().version();
    749                        if summary.package_id().version() == patch {
    750                            return;
    751                        }
    752                    }
    753                    let summary = summary.map_summary(|summary| lock(locked, all_patches, summary));
    754                    f(summary)
    755                };
    756                return source.query(dep, kind, callback);
    757            }
    758
    759            // If we have an override summary then we query the source to sanity check its results.
    760            // We don't actually use any of the summaries it gives us though.
    761            (Some(override_summary), Some(source)) => {
    762                if !patches.is_empty() {
    763                    return Poll::Ready(Err(anyhow::anyhow!("found patches and a path override")));
    764                }
    765                let mut n = 0;
    766                let mut to_warn = None;
    767                let callback = &mut |summary| {
    768                    n += 1;
    769                    to_warn = Some(summary);
    770                };
    771                let pend = source.query(dep, kind, callback);
    772                if pend.is_pending() {
    773                    return Poll::Pending;
    774                }
    775                if n > 1 {
    776                    return Poll::Ready(Err(anyhow::anyhow!(
    777                        "found an override with a non-locked list"
    778                    )));
    779                }
    780                if let Some(to_warn) = to_warn {
    781                    self.warn_bad_override(override_summary.as_summary(), to_warn.as_summary())?;
    782                }
    783                let override_summary = override_summary.map_summary(|summary| self.lock(summary));
    784                f(override_summary);
    785            }
    786        }
    787
    788        Poll::Ready(Ok(()))
    789    }
    790
    791    fn describe_source(&self, id: SourceId) -> String {
    792        match self.sources.get(id) {
    793            Some(src) => src.describe(),
    794            None => id.to_string(),
    795        }
    796    }
    797
    798    fn is_replaced(&self, id: SourceId) -> bool {
    799        match self.sources.get(id) {
    800            Some(src) => src.is_replaced(),
    801            None => false,
    802        }
    803    }
    804
    805    #[tracing::instrument(skip_all)]
    806    fn block_until_ready(&mut self) -> CargoResult<()> {
    807        // Ensure `shell` is not already in use,
    808        // regardless of which source is used and how it happens to behave this time
    809        self.gctx.debug_assert_shell_not_borrowed();
    810        for (source_id, source) in self.sources.sources_mut() {
    811            source
    812                .block_until_ready()
    813                .with_context(|| format!("Unable to update {}", source_id))?;
    814        }
    815        Ok(())
    816    }
    817}
    818
    819/// See [`PackageRegistry::lock`].
    820fn lock(
    821    locked: &LockedMap,
    822    patches: &HashMap<CanonicalUrl, Vec<PackageId>>,
    823    summary: Summary,
    824) -> Summary {
    825    let pair = locked
    826        .get(&(summary.source_id(), summary.name()))
    827        .and_then(|vec| vec.iter().find(|&&(id, _)| id == summary.package_id()));
    828
    829    trace!("locking summary of {}", summary.package_id());
    830
    831    // Lock the summary's ID if possible
    832    let summary = match pair {
    833        Some((precise, _)) => summary.override_id(*precise),
    834        None => summary,
    835    };
    836    summary.map_dependencies(|dep| {
    837        trace!(
    838            "\t{}/{}/{}",
    839            dep.package_name(),
    840            dep.version_req(),
    841            dep.source_id()
    842        );
    843
    844        // If we've got a known set of overrides for this summary, then
    845        // one of a few cases can arise:
    846        //
    847        // 1. We have a lock entry for this dependency from the same
    848        //    source as it's listed as coming from. In this case we make
    849        //    sure to lock to precisely the given package ID.
    850        //
    851        // 2. We have a lock entry for this dependency, but it's from a
    852        //    different source than what's listed, or the version
    853        //    requirement has changed. In this case we must discard the
    854        //    locked version because the dependency needs to be
    855        //    re-resolved.
    856        //
    857        // 3. We have a lock entry for this dependency, but it's from a
    858        //    different source than what's listed. This lock though happens
    859        //    through `[patch]`, so we want to preserve it.
    860        //
    861        // 4. We don't have a lock entry for this dependency, in which
    862        //    case it was likely an optional dependency which wasn't
    863        //    included previously so we just pass it through anyway.
    864        //
    865        // Cases 1/2 are handled by `matches_id`, case 3 is handled specially,
    866        // and case 4 is handled by falling through to the logic below.
    867        if let Some((_, locked_deps)) = pair {
    868            let locked = locked_deps.iter().find(|&&id| {
    869                // If the dependency matches the package id exactly then we've
    870                // found a match, this is the id the dependency was previously
    871                // locked to.
    872                if dep.matches_id(id) {
    873                    return true;
    874                }
    875
    876                // If the name/version doesn't match, then we definitely don't
    877                // have a match whatsoever. Otherwise we need to check
    878                // `[patch]`...
    879                if !dep.matches_ignoring_source(id) {
    880                    return false;
    881                }
    882
    883                // ... so here we look up the dependency url in the patches
    884                // map, and we see if `id` is contained in the list of patches
    885                // for that url. If it is then this lock is still valid,
    886                // otherwise the lock is no longer valid.
    887                match patches.get(dep.source_id().canonical_url()) {
    888                    Some(list) => list.contains(&id),
    889                    None => false,
    890                }
    891            });
    892
    893            if let Some(&locked) = locked {
    894                trace!("\tfirst hit on {}", locked);
    895                let mut dep = dep;
    896
    897                // If we found a locked version where the sources match, then
    898                // we can `lock_to` to get an exact lock on this dependency.
    899                // Otherwise we got a lock via `[patch]` so we only lock the
    900                // version requirement, not the source.
    901                if locked.source_id() == dep.source_id() {
    902                    dep.lock_to(locked);
    903                } else {
    904                    dep.lock_version(locked.version());
    905                }
    906                return dep;
    907            }
    908        }
    909
    910        // If this dependency did not have a locked version, then we query
    911        // all known locked packages to see if they match this dependency.
    912        // If anything does then we lock it to that and move on.
    913        let v = locked
    914            .get(&(dep.source_id(), dep.package_name()))
    915            .and_then(|vec| vec.iter().find(|&&(id, _)| dep.matches_id(id)));
    916        if let Some(&(id, _)) = v {
    917            trace!("\tsecond hit on {}", id);
    918            let mut dep = dep;
    919            dep.lock_to(id);
    920            return dep;
    921        }
    922
    923        trace!("\tnope, unlocked");
    924        dep
    925    })
    926}
    927
    928/// A helper for selecting the summary, or generating a helpful error message.
    929///
    930/// Returns a tuple that the first element is the summary selected. The second
    931/// is a package ID indicating that the patch entry should be unlocked. This
    932/// happens when a match cannot be found with the `locked` one, but found one
    933/// via the original patch, so we need to inform the resolver to "unlock" it.
    934fn summary_for_patch(
    935    orig_patch: &Dependency,
    936    locked: &Option<LockedPatchDependency>,
    937    mut summaries: Vec<Summary>,
    938    source: &mut dyn Source,
    939) -> Poll<CargoResult<(Summary, Option<PackageId>)>> {
    940    if summaries.len() == 1 {
    941        return Poll::Ready(Ok((summaries.pop().unwrap(), None)));
    942    }
    943    if summaries.len() > 1 {
    944        // TODO: In the future, it might be nice to add all of these
    945        // candidates so that version selection would just pick the
    946        // appropriate one. However, as this is currently structured, if we
    947        // added these all as patches, the unselected versions would end up in
    948        // the "unused patch" listing, and trigger a warning. It might take a
    949        // fair bit of restructuring to make that work cleanly, and there
    950        // isn't any demand at this time to support that.
    951        let mut vers: Vec<_> = summaries.iter().map(|summary| summary.version()).collect();
    952        vers.sort();
    953        let versions: Vec<_> = vers.into_iter().map(|v| v.to_string()).collect();
    954        return Poll::Ready(Err(anyhow::anyhow!(
    955            "patch for `{}` in `{}` resolved to more than one candidate\n\
    956            Found versions: {}\n\
    957            Update the patch definition to select only one package.\n\
    958            For example, add an `=` version requirement to the patch definition, \
    959            such as `version = \"={}\"`.",
    960            orig_patch.package_name(),
    961            orig_patch.source_id(),
    962            versions.join(", "),
    963            versions.last().unwrap()
    964        )));
    965    }
    966    assert!(summaries.is_empty());
    967    // No summaries found, try to help the user figure out what is wrong.
    968    if let Some(locked) = locked {
    969        // Since the locked patch did not match anything, try the unlocked one.
    970        let orig_matches =
    971            ready!(source.query_vec(orig_patch, QueryKind::Exact)).unwrap_or_else(|e| {
    972                tracing::warn!(
    973                    "could not determine unlocked summaries for dep {:?}: {:?}",
    974                    orig_patch,
    975                    e
    976                );
    977                Vec::new()
    978            });
    979
    980        let orig_matches = orig_matches.into_iter().map(|s| s.into_summary()).collect();
    981
    982        let summary = ready!(summary_for_patch(orig_patch, &None, orig_matches, source))?;
    983        return Poll::Ready(Ok((summary.0, Some(locked.package_id))));
    984    }
    985    // Try checking if there are *any* packages that match this by name.
    986    let name_only_dep = Dependency::new_override(orig_patch.package_name(), orig_patch.source_id());
    987
    988    let name_summaries =
    989        ready!(source.query_vec(&name_only_dep, QueryKind::Exact)).unwrap_or_else(|e| {
    990            tracing::warn!(
    991                "failed to do name-only summary query for {:?}: {:?}",
    992                name_only_dep,
    993                e
    994            );
    995            Vec::new()
    996        });
    997    let mut vers = name_summaries
    998        .iter()
    999        .map(|summary| summary.as_summary().version())
    1000        .collect::<Vec<_>>();
    1001    let found = match vers.len() {
    1002        0 => format!(""),
    1003        1 => format!("version `{}`", vers[0]),
    1004        _ => {
    1005            vers.sort();
    1006            let strs: Vec<_> = vers.into_iter().map(|v| v.to_string()).collect();
    1007            format!("versions `{}`", strs.join(", "))
    1008        }
    1009    };
    1010    Poll::Ready(Err(if found.is_empty() {
    1011        anyhow::anyhow!(
    1012            "The patch location `{}` does not appear to contain any packages \
    1013            matching the name `{}`.",
    1014            orig_patch.source_id(),
    1015            orig_patch.package_name()
    1016        )
    1017    } else {
    1018        anyhow::anyhow!(
    1019            "The patch location `{}` contains a `{}` package with {}, but the patch \
    1020            definition requires `{}`.\n\
    1021            Check that the version in the patch location is what you expect, \
    1022            and update the patch definition to match.",
    1023            orig_patch.source_id(),
    1024            orig_patch.package_name(),
    1025            found,
    1026            orig_patch.version_req()
    1027        )
    1028    }))
    1029}