Skip to main content

uv_resolver/
preferences.rs

1use std::str::FromStr;
2
3use rustc_hash::FxHashMap;
4use tracing::trace;
5
6use uv_distribution_types::{IndexUrl, InstalledDist, InstalledDistKind};
7use uv_normalize::PackageName;
8use uv_pep440::{Operator, Version};
9use uv_pep508::{MarkerTree, VersionOrUrl};
10use uv_pypi_types::{HashDigest, HashDigests, HashError};
11use uv_requirements_txt::{RequirementEntry, RequirementsTxtRequirement};
12
13use crate::ResolverEnvironment;
14use crate::universal_marker::UniversalMarker;
15
16#[derive(thiserror::Error, Debug)]
17pub enum PreferenceError {
18    #[error(transparent)]
19    Hash(#[from] HashError),
20}
21
22/// A pinned requirement, as extracted from a `requirements.txt` file.
23#[derive(Clone, Debug)]
24pub struct Preference {
25    name: PackageName,
26    version: Version,
27    /// The markers on the requirement itself (those after the semicolon).
28    marker: MarkerTree,
29    /// The index URL of the package, if any.
30    index: PreferenceIndex,
31    /// If coming from a package with diverging versions, the markers of the forks this preference
32    /// is part of, otherwise `None`.
33    fork_markers: Vec<UniversalMarker>,
34    hashes: HashDigests,
35    /// The source of the preference.
36    source: PreferenceSource,
37}
38
39impl Preference {
40    /// Create a [`Preference`] from a [`RequirementEntry`].
41    pub fn from_entry(entry: RequirementEntry) -> Result<Option<Self>, PreferenceError> {
42        let RequirementsTxtRequirement::Named(requirement) = entry.requirement else {
43            return Ok(None);
44        };
45
46        let Some(VersionOrUrl::VersionSpecifier(specifier)) = requirement.version_or_url.as_ref()
47        else {
48            trace!("Excluding {requirement} from preferences due to non-version specifier");
49            return Ok(None);
50        };
51
52        let [specifier] = specifier.as_ref() else {
53            trace!("Excluding {requirement} from preferences due to multiple version specifiers");
54            return Ok(None);
55        };
56
57        if *specifier.operator() != Operator::Equal {
58            trace!("Excluding {requirement} from preferences due to inexact version specifier");
59            return Ok(None);
60        }
61
62        // A false marker cannot select this pin, even during universal resolution.
63        // Resolving a variant alternative can also leave only an unrequested extra.
64        // TODO(konsti): Check extras on all output pins. If parsing already simplified
65        // a variant expression to an extra-only marker, universal resolution reuses the pin.
66        let marker = requirement.marker.resolve_variants_off();
67        if marker.is_false()
68            || (marker != requirement.marker && !marker.evaluate_optional_environment(None, &[]))
69        {
70            return Ok(None);
71        }
72
73        Ok(Some(Self {
74            name: requirement.name,
75            version: specifier.version().clone(),
76            marker,
77            // `requirements.txt` doesn't have fork annotations.
78            fork_markers: vec![],
79            // `requirements.txt` doesn't allow a requirement to specify an explicit index.
80            index: PreferenceIndex::Any,
81            hashes: entry
82                .hashes
83                .iter()
84                .map(String::as_str)
85                .map(HashDigest::from_str)
86                .collect::<Result<_, _>>()?,
87            source: PreferenceSource::RequirementsTxt,
88        }))
89    }
90
91    /// Create a preference for a version recorded in a lockfile.
92    pub fn from_locked(
93        name: PackageName,
94        version: Version,
95        index: Option<IndexUrl>,
96        fork_markers: Vec<UniversalMarker>,
97    ) -> Self {
98        Self {
99            name,
100            version,
101            marker: MarkerTree::TRUE,
102            index: PreferenceIndex::from(index),
103            fork_markers,
104            hashes: HashDigests::empty(),
105            source: PreferenceSource::Lock,
106        }
107    }
108
109    /// Create a [`Preference`] from an installed distribution.
110    pub fn from_installed(dist: &InstalledDist) -> Option<Self> {
111        let InstalledDistKind::Registry(dist) = &dist.kind else {
112            return None;
113        };
114        Some(Self {
115            name: dist.name.clone(),
116            version: dist.version.clone(),
117            marker: MarkerTree::TRUE,
118            index: PreferenceIndex::Any,
119            fork_markers: vec![],
120            hashes: HashDigests::empty(),
121            source: PreferenceSource::Environment,
122        })
123    }
124
125    /// Return the [`PackageName`] of the package for this [`Preference`].
126    pub fn name(&self) -> &PackageName {
127        &self.name
128    }
129}
130
131#[derive(Debug, Clone)]
132pub(crate) enum PreferenceIndex {
133    /// The preference should match to any index.
134    Any,
135    /// The preference should match to an implicit index.
136    Implicit,
137    /// The preference should match to a specific index.
138    Explicit(IndexUrl),
139}
140
141impl PreferenceIndex {
142    /// Returns `true` if the preference matches the given explicit [`IndexUrl`].
143    pub(crate) fn matches(&self, index: &IndexUrl) -> bool {
144        match self {
145            Self::Any => true,
146            Self::Implicit => false,
147            Self::Explicit(preference) => {
148                // Preferences are stored in the lockfile without credentials, while the index URL
149                // in locations such as `pyproject.toml` may contain credentials.
150                *preference.url() == *index.without_credentials()
151            }
152        }
153    }
154}
155
156impl From<Option<IndexUrl>> for PreferenceIndex {
157    fn from(index: Option<IndexUrl>) -> Self {
158        match index {
159            Some(index) => Self::Explicit(index),
160            None => Self::Implicit,
161        }
162    }
163}
164
165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
166pub(crate) enum PreferenceSource {
167    /// The preference is from an installed package in the environment.
168    Environment,
169    /// The preference is from a `uv.ock` file.
170    Lock,
171    /// The preference is from a `requirements.txt` file.
172    RequirementsTxt,
173    /// The preference is from the current solve.
174    Resolver,
175}
176
177#[derive(Debug, Clone)]
178pub(crate) struct Entry {
179    marker: UniversalMarker,
180    index: PreferenceIndex,
181    pin: Pin,
182    source: PreferenceSource,
183}
184
185impl Entry {
186    /// Return the [`UniversalMarker`] associated with the entry.
187    pub(crate) fn marker(&self) -> &UniversalMarker {
188        &self.marker
189    }
190
191    /// Return the [`IndexUrl`] associated with the entry, if any.
192    pub(crate) fn index(&self) -> &PreferenceIndex {
193        &self.index
194    }
195
196    /// Return the pinned data associated with the entry.
197    pub(crate) fn pin(&self) -> &Pin {
198        &self.pin
199    }
200
201    /// Return the source of the entry.
202    pub(crate) fn source(&self) -> PreferenceSource {
203        self.source
204    }
205}
206
207/// A set of pinned packages that should be preserved during resolution, if possible.
208///
209/// The marker is the marker of the fork that resolved to the pin, if any.
210///
211/// Preferences should be prioritized first by whether their marker matches and then by the order
212/// they are stored, so that a lockfile has higher precedence than sibling forks.
213#[derive(Debug, Clone, Default)]
214pub struct Preferences(FxHashMap<PackageName, Vec<Entry>>);
215
216impl Preferences {
217    /// Create a map of pinned packages from an iterator of [`Preference`] entries.
218    ///
219    /// The provided [`ResolverEnvironment`] will be used to filter the preferences
220    /// to an applicable subset.
221    pub fn from_iter(
222        preferences: impl IntoIterator<Item = Preference>,
223        env: &ResolverEnvironment,
224    ) -> Self {
225        let mut map = FxHashMap::<PackageName, Vec<_>>::default();
226        for preference in preferences {
227            // Filter non-matching preferences when resolving for an environment.
228            if let Some(markers) = env.marker_environment() {
229                if !preference.marker.evaluate(markers, &[]) {
230                    trace!("Excluding {preference} from preferences due to unmatched markers");
231                    continue;
232                }
233
234                if !preference.fork_markers.is_empty() {
235                    if !preference
236                        .fork_markers
237                        .iter()
238                        .any(|marker| marker.evaluate_no_extras(markers))
239                    {
240                        trace!(
241                            "Excluding {preference} from preferences due to unmatched fork markers"
242                        );
243                        continue;
244                    }
245                }
246            }
247
248            // Flatten the list of markers into individual entries.
249            if preference.fork_markers.is_empty() {
250                map.entry(preference.name).or_default().push(Entry {
251                    marker: UniversalMarker::TRUE,
252                    index: preference.index,
253                    pin: Pin {
254                        version: preference.version,
255                        hashes: preference.hashes,
256                    },
257                    source: preference.source,
258                });
259            } else {
260                for fork_marker in preference.fork_markers {
261                    map.entry(preference.name.clone()).or_default().push(Entry {
262                        marker: fork_marker,
263                        index: preference.index.clone(),
264                        pin: Pin {
265                            version: preference.version.clone(),
266                            hashes: preference.hashes.clone(),
267                        },
268                        source: preference.source,
269                    });
270                }
271            }
272        }
273
274        Self(map)
275    }
276
277    /// Insert a preference at the back.
278    pub(crate) fn insert(
279        &mut self,
280        package_name: PackageName,
281        index: Option<IndexUrl>,
282        markers: UniversalMarker,
283        pin: impl Into<Pin>,
284        source: PreferenceSource,
285    ) {
286        self.0.entry(package_name).or_default().push(Entry {
287            marker: markers,
288            index: PreferenceIndex::from(index),
289            pin: pin.into(),
290            source,
291        });
292    }
293
294    /// Returns an iterator over the preferences.
295    pub(crate) fn iter(
296        &self,
297    ) -> impl Iterator<
298        Item = (
299            &PackageName,
300            impl Iterator<Item = (&UniversalMarker, &PreferenceIndex, &Version)>,
301        ),
302    > {
303        self.0.iter().map(|(name, preferences)| {
304            (
305                name,
306                preferences
307                    .iter()
308                    .map(|entry| (&entry.marker, &entry.index, entry.pin.version())),
309            )
310        })
311    }
312
313    /// Return the pinned version for a package, if any.
314    pub(crate) fn get(&self, package_name: &PackageName) -> &[Entry] {
315        self.0
316            .get(package_name)
317            .map(Vec::as_slice)
318            .unwrap_or_default()
319    }
320
321    /// Return the hashes for a package, if the version matches that of the pin.
322    pub(crate) fn match_hashes(
323        &self,
324        package_name: &PackageName,
325        version: &Version,
326    ) -> Option<&[HashDigest]> {
327        self.0
328            .get(package_name)
329            .into_iter()
330            .flatten()
331            .find(|entry| entry.pin.version() == version)
332            .map(|entry| entry.pin.hashes())
333    }
334}
335
336impl std::fmt::Display for Preference {
337    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
338        write!(f, "{}=={}", self.name, self.version)
339    }
340}
341
342/// The pinned data associated with a package in a locked `requirements.txt` file (e.g., `flask==1.2.3`).
343#[derive(Debug, Clone)]
344pub(crate) struct Pin {
345    version: Version,
346    hashes: HashDigests,
347}
348
349impl Pin {
350    /// Return the version of the pinned package.
351    pub(crate) fn version(&self) -> &Version {
352        &self.version
353    }
354
355    /// Return the hashes of the pinned package.
356    fn hashes(&self) -> &[HashDigest] {
357        self.hashes.as_slice()
358    }
359}
360
361impl From<Version> for Pin {
362    fn from(version: Version) -> Self {
363        Self {
364            version,
365            hashes: HashDigests::empty(),
366        }
367    }
368}
369
370#[cfg(test)]
371mod tests {
372    use super::*;
373    use std::str::FromStr;
374
375    /// Test that [`PreferenceIndex::matches`] correctly ignores credentials when comparing URLs.
376    ///
377    /// This is relevant for matching lockfile preferences (stored without credentials)
378    /// against index URLs from pyproject.toml (which may include usernames for auth).
379    #[test]
380    fn test_preference_index_matches_ignores_credentials() {
381        // URL without credentials (as stored in lockfile)
382        let index_without_creds = IndexUrl::from_str("https:/pypi_index.com/simple").unwrap();
383
384        // URL with username (as specified in pyproject.toml)
385        let index_with_username =
386            IndexUrl::from_str("https://username@pypi_index.com/simple").unwrap();
387
388        let preference = PreferenceIndex::Explicit(index_without_creds.clone());
389
390        assert!(
391            preference.matches(&index_with_username),
392            "PreferenceIndex should match URLs that differ only in username"
393        );
394    }
395}