Skip to main content

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