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