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 cargo_util::collections::{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 = self.gctx.version_req_match_mode();
506        for summaries in self.patches.values_mut() {
507            for summary in summaries {
508                debug!("locking patch {:?}", summary);
509                *summary = lock(&self.locked, &self.patches_available, summary.clone(), mode);
510            }
511        }
512        self.patches_locked = true;
513    }
514
515    /// Gets all patches grouped by the source URLs they are going to patch.
516    ///
517    /// These patches are mainly collected from [`patch`](Self::patch).
518    /// They might not be the same as patches actually used during dependency resolving.
519    pub fn patches(&self) -> &HashMap<CanonicalUrl, Vec<Summary>> {
520        &self.patches
521    }
522
523    /// Loads the [`Source`] for a given [`SourceId`] to this registry, making
524    /// them available to resolution.
525    fn load(&self, source_id: SourceId, kind: Kind) -> CargoResult<()> {
526        debug!("loading source {}", source_id);
527        let source = self
528            .source_config
529            .load(source_id)
530            .with_context(|| format!("unable to update {}", source_id))?;
531        assert_eq!(source.source_id(), source_id);
532
533        if kind == Kind::Override {
534            self.overrides.borrow_mut().push(source_id);
535        }
536        self.add_source(source, kind);
537
538        // If we have an imprecise version then we don't know what we're going
539        // to look for, so we always attempt to perform an update here.
540        //
541        // If we have a precise version, then we'll update lazily during the
542        // querying phase. Note that precise in this case is only
543        // `"locked"` as other values indicate a `cargo update
544        // --precise` request
545        if !source_id.has_locked_precise() {
546            self.sources
547                .borrow()
548                .get(source_id)
549                .unwrap()
550                .invalidate_cache();
551        } else {
552            debug!("skipping update due to locked registry");
553        }
554        Ok(())
555    }
556
557    /// Queries path overrides from this registry.
558    async fn query_overrides(&self, dep: &Dependency) -> CargoResult<Option<Summary>> {
559        let overrides = self.overrides.borrow();
560        for &s in overrides.iter() {
561            let dep = Dependency::new_override(dep.package_name(), s);
562            let mut results = None;
563            self.sources
564                .borrow()
565                .get(s)
566                .unwrap()
567                .query(&dep, QueryKind::Exact, &mut |s| {
568                    if let IndexSummary::Candidate(s) = s {
569                        results = Some(s);
570                    }
571                })
572                .await?;
573            if results.is_some() {
574                return Ok(results);
575            }
576        }
577        Ok(None)
578    }
579
580    /// This function is used to transform a summary to another locked summary
581    /// if possible. This is where the concept of a lock file comes into play.
582    ///
583    /// If a summary points at a package ID which was previously locked, then we
584    /// override the summary's ID itself, as well as all dependencies, to be
585    /// rewritten to the locked versions. This will transform the summary's
586    /// source to a precise source (listed in the locked version) as well as
587    /// transforming all of the dependencies from range requirements on
588    /// imprecise sources to exact requirements on precise sources.
589    ///
590    /// If a summary does not point at a package ID which was previously locked,
591    /// or if any dependencies were added and don't have a previously listed
592    /// version, we still want to avoid updating as many dependencies as
593    /// possible to keep the graph stable. In this case we map all of the
594    /// summary's dependencies to be rewritten to a locked version wherever
595    /// possible. If we're unable to map a dependency though, we just pass it on
596    /// through.
597    pub fn lock(&self, summary: Summary) -> Summary {
598        assert!(self.patches_locked);
599        let mode = self.gctx.version_req_match_mode();
600        lock(&self.locked, &self.patches_available, summary, mode)
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    async fn query(
660        &self,
661        dep: &Dependency,
662        kind: QueryKind,
663        f: &mut dyn FnMut(IndexSummary),
664    ) -> CargoResult<()> {
665        assert!(self.patches_locked);
666        // Look for an override and get ready to query the real source.
667        let override_summary = self.query_overrides(dep).await?;
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            let mode = self.gctx.version_req_match_mode();
678            patches.extend(
679                extra
680                    .iter()
681                    .filter(|s| dep.matches_ignoring_source(s.package_id(), mode))
682                    .cloned(),
683            );
684        }
685
686        // A crucial feature of the `[patch]` feature is that we don't query the
687        // actual registry if we have a "locked" dependency. A locked dep basically
688        // just means a version constraint of `=a.b.c`, and because patches take
689        // priority over the actual source then if we have a candidate we're done.
690        if patches.len() == 1 && dep.is_locked() {
691            let patch = patches.remove(0);
692            match override_summary {
693                Some(override_summary) => {
694                    self.warn_bad_override(&override_summary, &patch)?;
695                    let override_summary = self.lock(override_summary);
696                    f(IndexSummary::Candidate(override_summary));
697                }
698                None => f(IndexSummary::Candidate(patch)),
699            }
700
701            return 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        // Helper function to add context for query errors.
726        async fn query_with_context(
727            source: &dyn Source,
728            dep: &Dependency,
729            kind: QueryKind,
730            f: &mut dyn FnMut(IndexSummary),
731        ) -> CargoResult<()> {
732            source
733                .query(dep, kind, f)
734                .await
735                .with_context(|| format!("unable to update {}", source.source_id()))
736                .with_context(|| {
737                    format!(
738                        "failed to load source for dependency `{}`",
739                        dep.package_name()
740                    )
741                })
742        }
743
744        let source = self.sources.borrow().get(dep.source_id()).cloned();
745        match (override_summary, source) {
746            (Some(_), None) => {
747                return Err(anyhow::anyhow!("override found but no real ones"));
748            }
749            (None, None) => return Ok(()),
750
751            // If we don't have an override then we just ship everything upstairs after locking the summary
752            (None, Some(source)) => {
753                for patch in patches.iter() {
754                    f(IndexSummary::Candidate(patch.clone()));
755                }
756
757                // Our sources shouldn't ever come back to us with two summaries
758                // that have the same version. We could, however, have an `[patch]`
759                // section which is in use to override a version in the registry.
760                // This means that if our `summary` in this loop has the same
761                // version as something in `patches` that we've already selected,
762                // then we skip this `summary`.
763                let locked = &self.locked;
764                let all_patches = &self.patches_available;
765                let mode = self.gctx.version_req_match_mode();
766                let callback = &mut |summary: IndexSummary| {
767                    for patch in patches.iter() {
768                        let patch = patch.package_id().version();
769                        if summary.package_id().version() == patch {
770                            return;
771                        }
772                    }
773                    let summary =
774                        summary.map_summary(|summary| lock(locked, all_patches, summary, mode));
775                    f(summary)
776                };
777                return query_with_context(&*source, dep, kind, callback).await;
778            }
779
780            // If we have an override summary then we query the source to sanity check its results.
781            // We don't actually use any of the summaries it gives us though.
782            (Some(override_summary), Some(source)) => {
783                if !patches.is_empty() {
784                    return Err(anyhow::anyhow!("found patches and a path override"));
785                }
786                let mut n = 0;
787                let mut to_warn = None;
788                let callback = &mut |summary| {
789                    n += 1;
790                    match summary {
791                        IndexSummary::Candidate(summary)
792                        | IndexSummary::Yanked(summary)
793                        | IndexSummary::Offline(summary)
794                        | IndexSummary::Unsupported(summary, _)
795                        | IndexSummary::Invalid(summary) => {
796                            to_warn = Some(summary);
797                        }
798                    }
799                };
800                query_with_context(&*source, dep, kind, callback).await?;
801                if n > 1 {
802                    return Err(anyhow::anyhow!("found an override with a non-locked list"));
803                }
804                if let Some(to_warn) = to_warn {
805                    self.warn_bad_override(&override_summary, &to_warn)?;
806                }
807                let override_summary = self.lock(override_summary);
808                f(IndexSummary::Candidate(override_summary));
809            }
810        }
811
812        Ok(())
813    }
814
815    fn describe_source(&self, id: SourceId) -> String {
816        match self.sources.borrow().get(id) {
817            Some(src) => src.describe(),
818            None => id.to_string(),
819        }
820    }
821
822    fn is_replaced(&self, id: SourceId) -> bool {
823        match self.sources.borrow().get(id) {
824            Some(src) => src.is_replaced(),
825            None => false,
826        }
827    }
828}
829
830/// See [`PackageRegistry::lock`].
831fn lock(
832    locked: &LockedMap,
833    patches: &HashMap<CanonicalUrl, Vec<PackageId>>,
834    summary: Summary,
835    mode: VersionReqMatchMode,
836) -> Summary {
837    let pair = locked
838        .get(&(summary.source_id(), summary.name()))
839        .and_then(|vec| vec.iter().find(|&&(id, _)| id == summary.package_id()));
840
841    trace!("locking summary of {}", summary.package_id());
842
843    // Lock the summary's ID if possible
844    let summary = match pair {
845        Some((precise, _)) => summary.override_id(*precise),
846        None => summary,
847    };
848    summary.map_dependencies(|dep| {
849        trace!(
850            "\t{}/{}/{}",
851            dep.package_name(),
852            dep.version_req(),
853            dep.source_id()
854        );
855
856        // If we've got a known set of overrides for this summary, then
857        // one of a few cases can arise:
858        //
859        // 1. We have a lock entry for this dependency from the same
860        //    source as it's listed as coming from. In this case we make
861        //    sure to lock to precisely the given package ID.
862        //
863        // 2. We have a lock entry for this dependency, but it's from a
864        //    different source than what's listed, or the version
865        //    requirement has changed. In this case we must discard the
866        //    locked version because the dependency needs to be
867        //    re-resolved.
868        //
869        // 3. We have a lock entry for this dependency, but it's from a
870        //    different source than what's listed. This lock though happens
871        //    through `[patch]`, so we want to preserve it.
872        //
873        // 4. We don't have a lock entry for this dependency, in which
874        //    case it was likely an optional dependency which wasn't
875        //    included previously so we just pass it through anyway.
876        //
877        // Cases 1/2 are handled by `matches_id`, case 3 is handled specially,
878        // and case 4 is handled by falling through to the logic below.
879        if let Some((_, locked_deps)) = pair {
880            let locked = locked_deps.iter().find(|&&id| {
881                // If the dependency matches the package id exactly then we've
882                // found a match, this is the id the dependency was previously
883                // locked to.
884                if dep.matches_id(id, mode) {
885                    return true;
886                }
887
888                // If the name/version doesn't match, then we definitely don't
889                // have a match whatsoever. Otherwise we need to check
890                // `[patch]`...
891                if !dep.matches_ignoring_source(id, mode) {
892                    return false;
893                }
894
895                // ... so here we look up the dependency url in the patches
896                // map, and we see if `id` is contained in the list of patches
897                // for that url. If it is then this lock is still valid,
898                // otherwise the lock is no longer valid.
899                match patches.get(dep.source_id().canonical_url()) {
900                    Some(list) => list.contains(&id),
901                    None => false,
902                }
903            });
904
905            if let Some(&locked) = locked {
906                trace!("\tfirst hit on {}", locked);
907                let mut dep = dep;
908
909                // If we found a locked version where the sources match, then
910                // we can `lock_to` to get an exact lock on this dependency.
911                // Otherwise we got a lock via `[patch]` so we only lock the
912                // version requirement, not the source.
913                if locked.source_id() == dep.source_id() {
914                    dep.lock_to(locked, mode);
915                } else {
916                    dep.lock_version(locked.version(), mode);
917                }
918                return dep;
919            }
920        }
921
922        // If this dependency did not have a locked version, then we query
923        // all known locked packages to see if they match this dependency.
924        // If anything does then we lock it to that and move on.
925        let v = locked
926            .get(&(dep.source_id(), dep.package_name()))
927            .and_then(|vec| vec.iter().find(|&&(id, _)| dep.matches_id(id, mode)));
928        if let Some(&(id, _)) = v {
929            trace!("\tsecond hit on {}", id);
930            let mut dep = dep;
931            dep.lock_to(id, mode);
932            return dep;
933        }
934
935        trace!("\tnope, unlocked");
936        dep
937    })
938}
939
940/// A helper for selecting the summary, or generating a helpful error message.
941///
942/// Returns a tuple that the first element is the summary selected. The second
943/// is a package ID indicating that the patch entry should be unlocked. This
944/// happens when a match cannot be found with the `locked` one, but found one
945/// via the original patch, so we need to inform the resolver to "unlock" it.
946async fn summary_for_patch(
947    original_patch: &Patch,
948    orig_patch_url: &Url,
949    locked: &Option<LockedPatchDependency>,
950    mut summaries: Vec<Summary>,
951    source: &dyn Source,
952) -> CargoResult<(Summary, Option<PackageId>)> {
953    if summaries.len() == 1 {
954        return Ok((summaries.pop().unwrap(), None));
955    }
956    if summaries.len() > 1 {
957        // TODO: In the future, it might be nice to add all of these
958        // candidates so that version selection would just pick the
959        // appropriate one. However, as this is currently structured, if we
960        // added these all as patches, the unselected versions would end up in
961        // the "unused patch" listing, and trigger a warning. It might take a
962        // fair bit of restructuring to make that work cleanly, and there
963        // isn't any demand at this time to support that.
964        let mut vers: Vec<_> = summaries.iter().map(|summary| summary.version()).collect();
965        vers.sort();
966        let versions: Vec<_> = vers.into_iter().map(|v| v.to_string()).collect();
967        return Err(anyhow::anyhow!(
968            "patch for `{}` in `{}` resolved to more than one candidate\n\
969            note: found versions: {}\n\
970            help: check `{}` patch definition for `{}` in `{}`\n\
971            help: select only one package using `version = \"={}\"`",
972            &original_patch.dep.package_name(),
973            &original_patch.dep.source_id(),
974            versions.join(", "),
975            &original_patch.dep.package_name(),
976            orig_patch_url,
977            original_patch.loc,
978            versions.last().unwrap()
979        ));
980    }
981    assert!(summaries.is_empty());
982    // No summaries found, try to help the user figure out what is wrong.
983    if let Some(locked) = locked {
984        // Since the locked patch did not match anything, try the unlocked one.
985        let orig_matches = source
986            .query_vec(&original_patch.dep, QueryKind::Exact)
987            .await
988            .unwrap_or_else(|e| {
989                tracing::warn!(
990                    "could not determine unlocked summaries for dep {:?}: {:?}",
991                    &original_patch.dep,
992                    e
993                );
994                Vec::new()
995            });
996
997        let orig_matches = orig_matches
998            .into_iter()
999            .filter_map(|s| match s {
1000                IndexSummary::Candidate(s) => Some(s),
1001                _ => None,
1002            })
1003            .collect();
1004
1005        let summary = Box::pin(summary_for_patch(
1006            original_patch,
1007            orig_patch_url,
1008            &None,
1009            orig_matches,
1010            source,
1011        ))
1012        .await?;
1013        return Ok((summary.0, Some(locked.package_id)));
1014    }
1015    // Try checking if there are *any* packages that match this by name.
1016    let name_only_dep = Dependency::new_override(
1017        original_patch.dep.package_name(),
1018        original_patch.dep.source_id(),
1019    );
1020
1021    let name_summaries = source
1022        .query_vec(&name_only_dep, QueryKind::Exact)
1023        .await
1024        .unwrap_or_else(|e| {
1025            tracing::warn!(
1026                "failed to do name-only summary query for {:?}: {:?}",
1027                name_only_dep,
1028                e
1029            );
1030            Vec::new()
1031        });
1032    let mut vers = name_summaries
1033        .iter()
1034        .filter_map(|s| match s {
1035            IndexSummary::Candidate(s) => Some(s.version()),
1036            _ => None,
1037        })
1038        .collect::<Vec<_>>();
1039    let found = match vers.len() {
1040        0 => "".to_string(),
1041        1 => format!("version `{}`", vers[0]),
1042        _ => {
1043            vers.sort();
1044            let strs: Vec<_> = vers.into_iter().map(|v| v.to_string()).collect();
1045            format!("versions `{}`", strs.join(", "))
1046        }
1047    };
1048    Err(if found.is_empty() {
1049        anyhow::anyhow!(
1050            "patch location `{}` does not contain packages matching `{}`\n\
1051            help: check `{}` patch definition for `{}` in `{}`",
1052            &original_patch.dep.source_id(),
1053            &original_patch.dep.package_name(),
1054            &original_patch.dep.package_name(),
1055            orig_patch_url,
1056            original_patch.loc
1057        )
1058    } else {
1059        anyhow::anyhow!(
1060            "patch `{}` version mismatch\n\
1061            note: patch location contains {}, but patch definition requires `{}`\n\
1062            help: check patch location `{}`\n\
1063            help: check `{}` patch definition for `{}` in `{}`",
1064            &original_patch.dep.package_name(),
1065            found,
1066            &original_patch.dep.version_req(),
1067            &original_patch.dep.source_id(),
1068            &original_patch.dep.package_name(),
1069            orig_patch_url,
1070            original_patch.loc
1071        )
1072    })
1073}