1use std::path::Path;
4
5use crate::ConfigDiscovery;
6use crate::PythonInstallation;
7use crate::PythonVersionFile;
8use crate::VersionFileDiscoveryOptions;
9use itertools::Itertools;
10use tracing::debug;
11use uv_cache::Cache;
12use uv_client::BaseClientBuilder;
13use uv_configuration::DependencyGroupsWithDefaults;
14use uv_distribution_types::RequiresPython;
15use uv_fs::Simplified;
16use uv_pep440::TildeVersionSpecifier;
17use uv_python_interpreter::{Interpreter, RequestedInterpreter};
18use uv_python_types::{
19 EnvironmentPreference, PythonArchitecture, PythonDownloads, PythonPreference, PythonRequest,
20};
21use uv_settings::PythonInstallMirrors;
22use uv_warnings::warn_user_once;
23use uv_workspace::{RequiresPythonDeclaration, RequiresPythonSources, Workspace};
24
25use crate::PythonDownloadReporter;
26use crate::PythonSelectionError;
27
28#[derive(Debug)]
34pub struct CompatibleProjectPython(RequestedInterpreter);
35
36impl CompatibleProjectPython {
37 pub fn into_interpreter(self) -> Interpreter {
39 self.0.into_interpreter()
40 }
41
42 pub fn into_requested_interpreter(self) -> RequestedInterpreter {
44 self.0
45 }
46}
47
48#[derive(Debug, Clone)]
49pub enum PythonRequestSource {
50 UserRequest,
52 DotPythonVersion(PythonVersionFile),
54 RequiresPython,
56}
57
58impl std::fmt::Display for PythonRequestSource {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 match self {
61 Self::UserRequest => write!(f, "explicit request"),
62 Self::DotPythonVersion(file) => {
63 write!(f, "version file at `{}`", file.path().user_display())
64 }
65 Self::RequiresPython => write!(f, "`requires-python` metadata"),
66 }
67 }
68}
69
70#[derive(Debug, Clone)]
72pub struct ProjectPythonRequirement {
73 pub requires_python: RequiresPython,
74 pub source: PythonRequirementSource,
75}
76
77#[derive(Debug, Clone)]
79pub struct ProjectPythonRequest {
80 source: PythonRequestSource,
82 pub python_request: Option<PythonRequest>,
86 requirement: Option<ProjectPythonRequirement>,
88}
89
90impl ProjectPythonRequest {
91 pub async fn from_request(
93 python_request: Option<PythonRequest>,
94 workspace: Option<&Workspace>,
95 groups: &DependencyGroupsWithDefaults,
96 project_dir: &Path,
97 config_discovery: ConfigDiscovery,
98 ) -> Result<Self, PythonSelectionError> {
99 let requirement = workspace
100 .map(|workspace| find_workspace_python_requirement(workspace, groups))
101 .transpose()?
102 .flatten();
103
104 Self::from_requirements(
105 python_request,
106 workspace.map(|workspace| workspace.install_path().as_path()),
107 requirement,
108 project_dir,
109 config_discovery,
110 )
111 .await
112 }
113
114 pub async fn from_requirements(
116 python_request: Option<PythonRequest>,
117 workspace_root: Option<&Path>,
118 requirement: Option<ProjectPythonRequirement>,
119 project_dir: &Path,
120 config_discovery: ConfigDiscovery,
121 ) -> Result<Self, PythonSelectionError> {
122 let (source, python_request) = if let Some(request) = python_request {
123 let source = PythonRequestSource::UserRequest;
125 let request = Some(request);
126 (source, request)
127 } else if let Some(file) = PythonVersionFile::discover(
128 project_dir,
129 &VersionFileDiscoveryOptions::default()
130 .with_stop_discovery_at(workspace_root)
131 .with_config_discovery(config_discovery),
132 )
133 .await?
134 .filter(|file| {
135 if !file.is_global() {
137 return true;
138 }
139 match (file.version(), requirement.as_ref()) {
140 (Some(request), Some(requirement)) => request
141 .as_pep440_version()
142 .is_none_or(|version| requirement.requires_python.contains(&version)),
143 _ => true,
144 }
145 }) {
146 let source = PythonRequestSource::DotPythonVersion(file.clone());
148 let request = file.version().cloned();
149 (source, request)
150 } else {
151 let request = requirement.as_ref().and_then(|requirement| {
153 PythonRequest::from_specifiers(requirement.requires_python.specifiers())
154 });
155 let source = PythonRequestSource::RequiresPython;
156 (source, request)
157 };
158
159 if let Some(python_request) = python_request.as_ref() {
160 debug!(
161 "Using Python request `{}` from {source}",
162 python_request.to_canonical_string()
163 );
164 }
165
166 Ok(Self {
167 source,
168 python_request,
169 requirement,
170 })
171 }
172
173 pub fn requires_python(&self) -> Option<&RequiresPython> {
174 self.requirement
175 .as_ref()
176 .map(|requirement| &requirement.requires_python)
177 }
178
179 pub fn check(&self, interpreter: &Interpreter) -> Result<(), PythonSelectionError> {
184 let Some(requirement) = &self.requirement else {
185 return Ok(());
186 };
187 validate_python_requirement(
188 interpreter,
189 &requirement.requires_python,
190 &self.source,
191 &requirement.source,
192 )
193 }
194
195 pub fn validate(
200 &self,
201 interpreter: Interpreter,
202 ) -> Result<CompatibleProjectPython, PythonSelectionError> {
203 self.check(&interpreter)?;
204 Ok(CompatibleProjectPython(RequestedInterpreter::new(
205 interpreter,
206 self.python_request.clone().unwrap_or_default(),
207 )))
208 }
209
210 pub async fn find_or_download(
214 &self,
215 environment_preference: EnvironmentPreference,
216 python_preference: PythonPreference,
217 python_arch: Option<PythonArchitecture>,
218 python_downloads: PythonDownloads,
219 client_builder: &BaseClientBuilder<'_>,
220 cache: &Cache,
221 reporter: &PythonDownloadReporter,
222 install_mirrors: &PythonInstallMirrors,
223 ) -> Result<CompatibleProjectPython, PythonSelectionError> {
224 let interpreter = PythonInstallation::find_or_download(
225 self.python_request.as_ref(),
226 environment_preference,
227 python_preference,
228 python_arch,
229 python_downloads,
230 client_builder,
231 cache,
232 Some(reporter),
233 install_mirrors.mirrors(),
234 install_mirrors.python_downloads_json_url.as_deref(),
235 )
236 .await?
237 .into_interpreter();
238 self.validate(interpreter)
239 }
240}
241
242pub fn find_requires_python(
247 workspace: &Workspace,
248 groups: &DependencyGroupsWithDefaults,
249) -> Result<Option<RequiresPython>, PythonSelectionError> {
250 Ok(find_workspace_python_requirement(workspace, groups)?
251 .map(|requirement| requirement.requires_python))
252}
253
254fn find_workspace_python_requirement(
258 workspace: &Workspace,
259 groups: &DependencyGroupsWithDefaults,
260) -> Result<Option<ProjectPythonRequirement>, PythonSelectionError> {
261 let requires_python = workspace.requires_python(groups)?;
262 if requires_python.is_empty() {
264 return Ok(None);
265 }
266 for (source, specifiers) in &requires_python {
267 if let [spec] = &specifiers[..] {
268 if let Some(spec) = TildeVersionSpecifier::from_specifier_ref(spec) {
269 if spec.has_patch() {
270 continue;
271 }
272 let (lower, upper) = spec.bounding_specifiers();
273 let spec_0 = spec.with_patch_version(0);
274 let (lower_0, upper_0) = spec_0.bounding_specifiers();
275 warn_user_once!(
276 "The `requires-python` specifier (`{spec}`) in `{source}` \
277 uses the tilde specifier (`~=`) without a patch version. This will be \
278 interpreted as `{lower}, {upper}`. Did you mean `{spec_0}` to constrain the \
279 version as `{lower_0}, {upper_0}`? We recommend only using \
280 the tilde specifier with a patch version to avoid ambiguity.",
281 );
282 }
283 }
284 }
285 match RequiresPython::intersection(requires_python.iter().map(|(.., specifiers)| specifiers)) {
286 Some(intersection) => Ok(Some(ProjectPythonRequirement {
287 requires_python: intersection,
288 source: PythonRequirementSource::Workspace {
289 sources: requires_python,
290 multiple_members: workspace.packages().len() > 1,
291 },
292 })),
293 None => Err(PythonSelectionError::DisjointRequiresPython(
294 requires_python,
295 )),
296 }
297}
298
299#[derive(Debug)]
303pub enum PythonRequirementConflicts {
304 Workspace {
305 sources: RequiresPythonSources,
306 multiple_members: bool,
308 },
309 Lockfile {
310 locked: Option<RequiresPython>,
311 groups: RequiresPythonSources,
312 },
313}
314
315impl std::fmt::Display for PythonRequirementConflicts {
316 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
317 match self {
318 Self::Workspace {
319 sources,
320 multiple_members,
321 } => {
322 if sources.len() > 1 {
323 return write!(
324 f,
325 ".\nThe following `requires-python` declarations do not permit this version:\n{}",
326 format_requires_python_sources(sources)
327 );
328 }
329 if let Some((RequiresPythonDeclaration::Workspace(group), _)) =
330 sources.iter().next()
331 {
332 return write!(
333 f,
334 " (from the workspace root's `tool.uv.dependency-groups.{group}.requires-python`)."
335 );
336 }
337 if let Some((RequiresPythonDeclaration::Member(package, group), _)) =
338 sources.iter().next()
339 {
340 if let Some(group) = group {
341 if *multiple_members {
342 return write!(
343 f,
344 " (from workspace member `{package}`'s `tool.uv.dependency-groups.{group}.requires-python`)."
345 );
346 }
347 return write!(
348 f,
349 " (from `tool.uv.dependency-groups.{group}.requires-python`)."
350 );
351 }
352 if *multiple_members {
353 return write!(
354 f,
355 " (from workspace member `{package}`'s `project.requires-python`)."
356 );
357 }
358 return f.write_str(" (from `project.requires-python`)");
359 }
360 Ok(())
361 }
362 Self::Lockfile { locked, groups } => {
363 let count = usize::from(locked.is_some()) + groups.len();
364 if count > 1 {
365 write!(
366 f,
367 ".\nThe following requirements in `uv.lock` do not permit this version:\n"
368 )?;
369 if let Some(locked) = locked {
370 writeln!(f, "- lockfile: {locked}")?;
371 }
372 return f.write_str(&format_requires_python_sources(groups));
373 }
374 if locked.is_some() {
375 return f.write_str(" (from `requires-python` in `uv.lock`).");
376 }
377 if let Some((source, _)) = groups.iter().next() {
378 return write!(f, " (from `{source}` in `uv.lock`).");
379 }
380 f.write_str(" (from `uv.lock`).")
381 }
382 }
383 }
384}
385
386#[derive(Debug, Clone)]
388pub enum PythonRequirementSource {
389 Workspace {
391 sources: RequiresPythonSources,
392 multiple_members: bool,
393 },
394 Lockfile {
396 locked: RequiresPython,
397 groups: RequiresPythonSources,
398 },
399}
400
401fn validate_python_requirement(
405 interpreter: &Interpreter,
406 requires_python: &RequiresPython,
407 source: &PythonRequestSource,
408 requirement_source: &PythonRequirementSource,
409) -> Result<(), PythonSelectionError> {
410 if requires_python.contains(interpreter.python_version()) {
411 return Ok(());
412 }
413
414 let conflicting_requires = match requirement_source {
415 PythonRequirementSource::Workspace {
416 sources,
417 multiple_members,
418 } => {
419 let sources = sources
420 .iter()
421 .filter(|(.., requires)| !requires.contains(interpreter.python_version()))
422 .map(|(key, requires)| (key.clone(), requires.clone()))
423 .collect();
424 PythonRequirementConflicts::Workspace {
425 sources,
426 multiple_members: *multiple_members,
427 }
428 }
429 PythonRequirementSource::Lockfile { locked, groups } => {
430 let version = interpreter.python_version().only_release();
431 let groups = groups
432 .iter()
433 .filter(|(_, requires)| !requires.contains(&version))
434 .map(|(key, requires)| (key.clone(), requires.clone()))
435 .collect();
436 PythonRequirementConflicts::Lockfile {
437 locked: (!locked.contains(interpreter.python_version())).then(|| locked.clone()),
438 groups,
439 }
440 }
441 };
442
443 match source {
444 PythonRequestSource::UserRequest => {
445 Err(PythonSelectionError::RequestedPythonProjectIncompatibility(
446 interpreter.python_version().clone(),
447 requires_python.clone(),
448 Box::new(conflicting_requires),
449 ))
450 }
451 PythonRequestSource::DotPythonVersion(file) => Err(
452 PythonSelectionError::DotPythonVersionProjectIncompatibility {
453 python_request: file.path().user_display().to_string(),
454 version: interpreter.python_version().clone(),
455 requires_python: requires_python.clone(),
456 requires_python_sources: Box::new(conflicting_requires),
457 },
458 ),
459 PythonRequestSource::RequiresPython => {
460 Err(PythonSelectionError::RequiresPythonProjectIncompatibility(
461 interpreter.python_version().clone(),
462 requires_python.clone(),
463 Box::new(conflicting_requires),
464 ))
465 }
466 }
467}
468
469pub fn format_requires_python_sources(conflicts: &RequiresPythonSources) -> String {
470 conflicts
471 .iter()
472 .map(|(source, specifiers)| format!("- {source}: {specifiers}"))
473 .join("\n")
474}