Skip to main content

uv_python_interpreter/
virtualenv.rs

1use std::borrow::Cow;
2use std::str::FromStr;
3use std::{
4    io,
5    path::{Path, PathBuf},
6};
7
8use fs_err as fs;
9use thiserror::Error;
10
11use uv_pep440::Version;
12use uv_pypi_types::Scheme;
13
14/// The layout of a virtual environment.
15#[derive(Debug)]
16pub struct VirtualEnvironment {
17    /// The absolute path to the root of the virtualenv, e.g., `/path/to/.venv`.
18    pub root: PathBuf,
19
20    /// The path to the Python interpreter inside the virtualenv, e.g., `.venv/bin/python`
21    /// (Unix, Python 3.11).
22    pub executable: PathBuf,
23
24    /// The path to the base executable for the environment, within the `home` directory.
25    pub base_executable: PathBuf,
26
27    /// The [`Scheme`] paths for the virtualenv, as returned by (e.g.) `sysconfig.get_paths()`.
28    pub scheme: Scheme,
29}
30
31/// A parsed `pyvenv.cfg`
32#[derive(Debug, Clone)]
33pub struct PyVenvConfiguration {
34    /// The `PYTHONHOME` directory containing the base Python executable.
35    pub(super) home: Option<PathBuf>,
36    /// Was the virtual environment created with the `virtualenv` package?
37    pub(super) virtualenv: bool,
38    /// Was the virtual environment created with the `uv` package?
39    pub(super) uv: bool,
40    /// Is the virtual environment relocatable?
41    pub(super) relocatable: bool,
42    /// Was the virtual environment populated with seed packages?
43    pub(super) seed: bool,
44    /// Should the virtual environment include system site packages?
45    pub(super) include_system_site_packages: bool,
46    /// The Python version the virtual environment was created with
47    pub(super) version: Option<Version>,
48}
49
50#[derive(Debug, Error)]
51pub enum Error {
52    #[error(transparent)]
53    Io(#[from] io::Error),
54    #[error("Broken virtual environment `{0}`: missing `pyvenv.cfg`")]
55    MissingPyVenvCfg(PathBuf),
56    #[error("Broken virtual environment `{0}`: could not parse `pyvenv.cfg`")]
57    ParsePyVenvCfg(PathBuf, #[source] io::Error),
58}
59
60/// Returns the path to the `python` executable inside a virtual environment.
61pub fn virtualenv_python_executable(venv: impl AsRef<Path>) -> PathBuf {
62    let venv = venv.as_ref();
63    if cfg!(windows) {
64        // Search for `python.exe` in the `Scripts` directory.
65        let default_executable = venv.join("Scripts").join("python.exe");
66        if default_executable.exists() {
67            return default_executable;
68        }
69
70        // Apparently, Python installed via msys2 on Windows _might_ produce a POSIX-like layout.
71        // See: https://github.com/PyO3/maturin/issues/1108
72        let executable = venv.join("bin").join("python.exe");
73        if executable.exists() {
74            return executable;
75        }
76
77        // Fallback for Conda environments.
78        let executable = venv.join("python.exe");
79        if executable.exists() {
80            return executable;
81        }
82
83        // If none of these exist, return the standard location
84        default_executable
85    } else {
86        // Prefer the unversioned `python` command exposed by virtual environments.
87        let default_executable = venv.join("bin").join("python");
88        if default_executable.exists() {
89            return default_executable;
90        }
91
92        // Fall back to `python3` for installations without an unversioned executable.
93        let executable = venv.join("bin").join("python3");
94        if executable.exists() {
95            return executable;
96        }
97
98        // If none of these exist, return the standard location
99        default_executable
100    }
101}
102
103impl PyVenvConfiguration {
104    /// Parse a `pyvenv.cfg` file into a [`PyVenvConfiguration`].
105    pub fn parse(cfg: impl AsRef<Path>) -> Result<Self, Error> {
106        let mut home = None;
107        let mut virtualenv = false;
108        let mut uv = false;
109        let mut relocatable = false;
110        let mut seed = false;
111        let mut include_system_site_packages = true;
112        let mut version = None;
113
114        // Per https://snarky.ca/how-virtual-environments-work/, the `pyvenv.cfg` file is not a
115        // valid INI file, and is instead expected to be parsed by partitioning each line on the
116        // first equals sign.
117        let content = fs::read_to_string(&cfg)
118            .map_err(|err| Error::ParsePyVenvCfg(cfg.as_ref().to_path_buf(), err))?;
119        for line in content.lines() {
120            let Some((key, value)) = line.split_once('=') else {
121                continue;
122            };
123            match key.trim() {
124                "home" => {
125                    home = Some(PathBuf::from(value.trim()));
126                }
127                "virtualenv" => {
128                    virtualenv = true;
129                }
130                "uv" => {
131                    uv = true;
132                }
133                "relocatable" => {
134                    relocatable = value.trim().to_lowercase() == "true";
135                }
136                "seed" => {
137                    seed = value.trim().to_lowercase() == "true";
138                }
139                "include-system-site-packages" => {
140                    include_system_site_packages = value.trim().to_lowercase() == "true";
141                }
142                "version" | "version_info" => {
143                    // An unrecognized version only prevents checking the interpreter version.
144                    version = Version::from_str(value.trim()).ok();
145                }
146                _ => {}
147            }
148        }
149
150        Ok(Self {
151            home,
152            virtualenv,
153            uv,
154            relocatable,
155            seed,
156            include_system_site_packages,
157            version,
158        })
159    }
160
161    /// Returns true if the virtual environment was created with the `virtualenv` package.
162    pub fn is_virtualenv(&self) -> bool {
163        self.virtualenv
164    }
165
166    /// Returns true if the virtual environment was created with the uv package.
167    pub fn is_uv(&self) -> bool {
168        self.uv
169    }
170
171    /// Returns true if the virtual environment is relocatable.
172    pub(crate) fn is_relocatable(&self) -> bool {
173        self.relocatable
174    }
175
176    /// Returns true if the virtual environment was populated with seed packages.
177    pub fn is_seed(&self) -> bool {
178        self.seed
179    }
180
181    /// Returns true if the virtual environment should include system site packages.
182    pub fn include_system_site_packages(&self) -> bool {
183        self.include_system_site_packages
184    }
185
186    /// Set the key-value pair in the `pyvenv.cfg` file.
187    pub fn set(content: &str, key: &str, value: &str) -> String {
188        let mut lines = content.lines().map(Cow::Borrowed).collect::<Vec<_>>();
189        let mut found = false;
190        for line in &mut lines {
191            if let Some((lhs, _)) = line.split_once('=')
192                && lhs.trim() == key
193            {
194                *line = Cow::Owned(format!("{key} = {value}"));
195                found = true;
196                break;
197            }
198        }
199        if !found {
200            lines.push(Cow::Owned(format!("{key} = {value}")));
201        }
202        if lines.is_empty() {
203            String::new()
204        } else {
205            format!("{}\n", lines.join("\n"))
206        }
207    }
208}
209
210#[cfg(test)]
211mod tests {
212
213    use indoc::indoc;
214
215    use super::*;
216
217    #[test]
218    fn test_set_existing_key() {
219        let content = indoc! {"
220            home = /path/to/python
221            version = 3.8.0
222            include-system-site-packages = false
223        "};
224        let result = PyVenvConfiguration::set(content, "version", "3.9.0");
225        assert_eq!(
226            result,
227            indoc! {"
228                home = /path/to/python
229                version = 3.9.0
230                include-system-site-packages = false
231            "}
232        );
233    }
234
235    #[test]
236    fn test_set_new_key() {
237        let content = indoc! {"
238            home = /path/to/python
239            version = 3.8.0
240        "};
241        let result = PyVenvConfiguration::set(content, "include-system-site-packages", "false");
242        assert_eq!(
243            result,
244            indoc! {"
245                home = /path/to/python
246                version = 3.8.0
247                include-system-site-packages = false
248            "}
249        );
250    }
251
252    #[test]
253    fn test_set_key_no_spaces() {
254        let content = indoc! {"
255            home=/path/to/python
256            version=3.8.0
257        "};
258        let result = PyVenvConfiguration::set(content, "include-system-site-packages", "false");
259        assert_eq!(
260            result,
261            indoc! {"
262                home=/path/to/python
263                version=3.8.0
264                include-system-site-packages = false
265            "}
266        );
267    }
268
269    #[test]
270    fn test_set_key_prefix() {
271        let content = indoc! {"
272            home = /path/to/python
273            home_dir = /other/path
274        "};
275        let result = PyVenvConfiguration::set(content, "home", "new/path");
276        assert_eq!(
277            result,
278            indoc! {"
279                home = new/path
280                home_dir = /other/path
281            "}
282        );
283    }
284
285    #[test]
286    fn test_set_empty_content() {
287        let content = "";
288        let result = PyVenvConfiguration::set(content, "version", "3.9.0");
289        assert_eq!(
290            result,
291            indoc! {"
292                version = 3.9.0
293            "}
294        );
295    }
296}