Skip to main content

uv_python_commands/
pin.rs

1use std::fmt::Write;
2use std::path::Path;
3
4use anyhow::{Result, bail};
5use owo_colors::OwoColorize;
6use tracing::debug;
7use uv_python_managed::downloads::ManagedPythonDownloadList;
8
9use uv_cache::Cache;
10use uv_client::BaseClientBuilder;
11use uv_configuration::DependencyGroupsWithDefaults;
12use uv_fs::Simplified;
13use uv_python_discovery::PYTHON_VERSION_FILENAME;
14use uv_python_discovery::PythonInstallation;
15use uv_python_discovery::PythonVersionFile;
16use uv_python_discovery::VersionFileDiscoveryOptions;
17use uv_python_types::{
18    EnvironmentPreference, PythonArchitecture, PythonDownloads, PythonPreference, PythonRequest,
19};
20use uv_settings::PythonInstallMirrors;
21use uv_warnings::{warn_user_once, warn_user_once_with_chain};
22use uv_workspace::{DiscoveryOptions, VirtualProject, WorkspaceCache};
23
24use uv_command_support::ExitStatus;
25use uv_command_support::Printer;
26use uv_python_discovery::PythonDownloadReporter;
27use uv_python_discovery::find_requires_python;
28
29/// Pin to a specific Python version.
30#[expect(clippy::fn_params_excessive_bools)]
31pub async fn pin(
32    project_dir: &Path,
33    request: Option<String>,
34    resolved: bool,
35    python_preference: PythonPreference,
36    python_arch: Option<PythonArchitecture>,
37    python_downloads: PythonDownloads,
38    no_project: bool,
39    global: bool,
40    rm: bool,
41    install_mirrors: PythonInstallMirrors,
42    client_builder: BaseClientBuilder<'_>,
43    cache: &Cache,
44    workspace_cache: &WorkspaceCache,
45    printer: Printer,
46) -> Result<ExitStatus> {
47    let virtual_project = if no_project {
48        None
49    } else {
50        match VirtualProject::discover(
51            project_dir,
52            &DiscoveryOptions::default(),
53            cache,
54            workspace_cache,
55        )
56        .await
57        {
58            Ok(virtual_project) => Some(virtual_project),
59            Err(err) => {
60                debug!("Failed to discover virtual project: {err}");
61                None
62            }
63        }
64    };
65
66    // Search for an existing file, we won't necessarily write to this, we'll construct a target
67    // path if there's a request later on.
68    let version_file = PythonVersionFile::discover(
69        project_dir,
70        &VersionFileDiscoveryOptions::default().with_no_local(global),
71    )
72    .await;
73
74    if rm {
75        let Some(file) = version_file? else {
76            if global {
77                bail!("No global Python pin found");
78            }
79            bail!("No Python version file found");
80        };
81
82        if !global && file.is_global() {
83            bail!("No Python version file found; use `--rm --global` to remove the global pin");
84        }
85
86        fs_err::tokio::remove_file(file.path()).await?;
87        writeln!(
88            printer.stdout(),
89            "Removed {} at `{}`",
90            if global {
91                "global Python pin"
92            } else {
93                "Python version file"
94            },
95            file.path().user_display()
96        )?;
97        return Ok(ExitStatus::Success);
98    }
99
100    let Some(request) = request else {
101        // Display the current pinned Python version
102        if let Some(file) = version_file? {
103            let mut pins = file.versions().peekable();
104            let download_list = if virtual_project.is_some() && pins.peek().is_some() {
105                Some(
106                    ManagedPythonDownloadList::new(
107                        &client_builder,
108                        cache,
109                        install_mirrors.python_downloads_json_url.as_deref(),
110                    )
111                    .await?,
112                )
113            } else {
114                None
115            };
116
117            for pin in pins {
118                writeln!(printer.stdout(), "{}", pin.to_canonical_string())?;
119                if let Some(virtual_project) = &virtual_project
120                    && let Some(download_list) = &download_list
121                {
122                    warn_if_existing_pin_incompatible_with_project(
123                        pin,
124                        virtual_project,
125                        python_preference,
126                        python_arch,
127                        download_list,
128                        cache,
129                    );
130                }
131            }
132            return Ok(ExitStatus::Success);
133        }
134        bail!("No Python version file found; specify a version to create one")
135    };
136    let request = PythonRequest::parse(&request);
137
138    if let PythonRequest::ExecutableName(name) = request {
139        bail!("Requests for arbitrary names (e.g., `{name}`) are not supported in version files");
140    }
141
142    let reporter = PythonDownloadReporter::single(printer);
143
144    let python = match PythonInstallation::find_or_download(
145        Some(&request),
146        EnvironmentPreference::OnlySystem,
147        python_preference,
148        python_arch,
149        python_downloads,
150        &client_builder,
151        cache,
152        Some(&reporter),
153        install_mirrors.mirrors(),
154        install_mirrors.python_downloads_json_url.as_deref(),
155    )
156    .await
157    {
158        Ok(python) => Some(python),
159        // If no matching Python version is found, don't fail unless `resolved` was requested
160        Err(uv_python_discovery::Error::MissingPython(err, ..)) if !resolved => {
161            // N.B. We omit the hint and just show the inner error message
162            warn_user_once!("{err}");
163            None
164        }
165        // If there was some other error, log it
166        Err(err) if !resolved => {
167            debug!("{err}");
168            None
169        }
170        // If `resolved` was requested, we must find an interpreter — fail otherwise
171        Err(err) => return Err(err.into()),
172    };
173
174    if let Some(virtual_project) = &virtual_project {
175        if let Some(request_version) = request.as_pep440_version() {
176            assert_pin_compatible_with_project(
177                &Pin {
178                    request: &request,
179                    version: &request_version,
180                    resolved: false,
181                    existing: false,
182                },
183                virtual_project,
184            )?;
185        } else {
186            if let Some(python) = &python {
187                // Warn if the resolved Python is incompatible with the Python requirement unless --resolved is used
188                if let Err(err) = assert_pin_compatible_with_project(
189                    &Pin {
190                        request: &request,
191                        version: python.python_version(),
192                        resolved: true,
193                        existing: false,
194                    },
195                    virtual_project,
196                ) {
197                    if resolved {
198                        return Err(err);
199                    }
200                    warn_user_once!("{err}");
201                }
202            }
203        }
204    }
205
206    let request = if resolved {
207        // SAFETY: We exit early if Python is not found and resolved is `true`
208        // TODO(zanieb): Maybe avoid reparsing here?
209        PythonRequest::parse(
210            &python
211                .unwrap()
212                .interpreter()
213                .sys_executable()
214                .user_display()
215                .to_string(),
216        )
217    } else {
218        request
219    };
220
221    let existing = version_file.ok().flatten();
222    // TODO(zanieb): Allow updating the discovered version file with an `--update` flag.
223    let new = if global {
224        let Some(new) = PythonVersionFile::global() else {
225            // TODO(zanieb): We should find a nice way to surface that as an error
226            bail!("Failed to determine directory for global Python pin");
227        };
228        new.with_versions(vec![request])
229    } else {
230        PythonVersionFile::new(project_dir.join(PYTHON_VERSION_FILENAME))
231            .with_versions(vec![request])
232    };
233
234    new.write().await?;
235
236    // If we updated an existing version file to a new version
237    if let Some(existing) = existing
238        .as_ref()
239        .filter(|existing| existing.path() == new.path())
240        .and_then(PythonVersionFile::version)
241        .filter(|version| *version != new.version().unwrap())
242    {
243        writeln!(
244            printer.stdout(),
245            "Updated `{}` from `{}` -> `{}`",
246            new.path().user_display().cyan(),
247            existing.to_canonical_string().green(),
248            new.version().unwrap().to_canonical_string().green()
249        )?;
250    } else {
251        writeln!(
252            printer.stdout(),
253            "Pinned `{}` to `{}`",
254            new.path().user_display().cyan(),
255            new.version().unwrap().to_canonical_string().green()
256        )?;
257    }
258
259    Ok(ExitStatus::Success)
260}
261
262/// Check if pinned request is compatible with the workspace/project's `Requires-Python`.
263fn warn_if_existing_pin_incompatible_with_project(
264    pin: &PythonRequest,
265    virtual_project: &VirtualProject,
266    python_preference: PythonPreference,
267    python_arch: Option<PythonArchitecture>,
268    downloads_list: &ManagedPythonDownloadList,
269    cache: &Cache,
270) {
271    // Check if the pinned version is compatible with the project.
272    if let Some(pin_version) = pin.as_pep440_version() {
273        if let Err(err) = assert_pin_compatible_with_project(
274            &Pin {
275                request: pin,
276                version: &pin_version,
277                resolved: false,
278                existing: true,
279            },
280            virtual_project,
281        ) {
282            warn_user_once!("{err}");
283            return;
284        }
285    }
286
287    // If the request itself didn't prove an incompatibility, resolve the pin into an
288    // interpreter to check the concrete version on the current system.
289    match PythonInstallation::find(
290        pin,
291        EnvironmentPreference::OnlySystem,
292        python_preference,
293        python_arch,
294        downloads_list,
295        cache,
296    ) {
297        Ok(python) => {
298            let python_version = python.python_version();
299            debug!(
300                "The pinned Python version `{}` resolves to `{}`",
301                pin, python_version
302            );
303            // Warn on incompatibilities when viewing existing pins
304            if let Err(err) = assert_pin_compatible_with_project(
305                &Pin {
306                    request: pin,
307                    version: python_version,
308                    resolved: true,
309                    existing: true,
310                },
311                virtual_project,
312            ) {
313                warn_user_once!("{err}");
314            }
315        }
316        Err(err) => {
317            warn_user_once_with_chain!(
318                anyhow::Error::from(err)
319                    .context(format!(
320                        "Failed to resolve pinned Python version `{}`",
321                        pin.to_canonical_string(),
322                    ))
323                    .as_ref()
324            );
325        }
326    }
327}
328
329/// Utility struct for representing pins in error messages.
330struct Pin<'a> {
331    request: &'a PythonRequest,
332    version: &'a uv_pep440::Version,
333    resolved: bool,
334    existing: bool,
335}
336
337/// Checks if the pinned Python version is compatible with the workspace/project's `Requires-Python`.
338fn assert_pin_compatible_with_project(pin: &Pin, virtual_project: &VirtualProject) -> Result<()> {
339    // Don't factor in requires-python settings on dependency-groups
340    let groups = DependencyGroupsWithDefaults::none();
341
342    let (requires_python, project_type) = match virtual_project {
343        VirtualProject::Project(project_workspace) => {
344            debug!(
345                "Discovered project `{}` at: {}",
346                project_workspace.project_name(),
347                project_workspace.workspace().install_path().display()
348            );
349
350            let requires_python = find_requires_python(project_workspace.workspace(), &groups)?;
351            (requires_python, "project")
352        }
353        VirtualProject::NonProject(workspace) => {
354            debug!(
355                "Discovered virtual workspace at: {}",
356                workspace.install_path().display()
357            );
358            let requires_python = find_requires_python(workspace, &groups)?;
359            (requires_python, "workspace")
360        }
361    };
362
363    let Some(requires_python) = requires_python else {
364        return Ok(());
365    };
366
367    if requires_python.contains(pin.version) {
368        return Ok(());
369    }
370
371    let given = if pin.existing { "pinned" } else { "requested" };
372    let resolved = if pin.resolved {
373        format!(" resolves to `{}` which ", pin.version)
374    } else {
375        String::new()
376    };
377
378    Err(anyhow::anyhow!(
379        "The {given} Python version `{}`{resolved} is incompatible with the {} `requires-python` value of `{}`.",
380        pin.request.to_canonical_string(),
381        project_type,
382        requires_python
383    ))
384}