uv_python_interpreter/
virtualenv.rs1use 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#[derive(Debug)]
16pub struct VirtualEnvironment {
17 pub root: PathBuf,
19
20 pub executable: PathBuf,
23
24 pub base_executable: PathBuf,
26
27 pub scheme: Scheme,
29}
30
31#[derive(Debug, Clone)]
33pub struct PyVenvConfiguration {
34 pub(super) home: Option<PathBuf>,
36 pub(super) virtualenv: bool,
38 pub(super) uv: bool,
40 pub(super) relocatable: bool,
42 pub(super) seed: bool,
44 pub(super) include_system_site_packages: bool,
46 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
60pub fn virtualenv_python_executable(venv: impl AsRef<Path>) -> PathBuf {
62 let venv = venv.as_ref();
63 if cfg!(windows) {
64 let default_executable = venv.join("Scripts").join("python.exe");
66 if default_executable.exists() {
67 return default_executable;
68 }
69
70 let executable = venv.join("bin").join("python.exe");
73 if executable.exists() {
74 return executable;
75 }
76
77 let executable = venv.join("python.exe");
79 if executable.exists() {
80 return executable;
81 }
82
83 default_executable
85 } else {
86 let default_executable = venv.join("bin").join("python");
88 if default_executable.exists() {
89 return default_executable;
90 }
91
92 let executable = venv.join("bin").join("python3");
94 if executable.exists() {
95 return executable;
96 }
97
98 default_executable
100 }
101}
102
103impl PyVenvConfiguration {
104 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 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 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 pub fn is_virtualenv(&self) -> bool {
163 self.virtualenv
164 }
165
166 pub fn is_uv(&self) -> bool {
168 self.uv
169 }
170
171 pub(crate) fn is_relocatable(&self) -> bool {
173 self.relocatable
174 }
175
176 pub fn is_seed(&self) -> bool {
178 self.seed
179 }
180
181 pub fn include_system_site_packages(&self) -> bool {
183 self.include_system_site_packages
184 }
185
186 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}