cargo/core/
registry.rs

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