-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathlib.rs
More file actions
572 lines (495 loc) · 17.7 KB
/
lib.rs
File metadata and controls
572 lines (495 loc) · 17.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
use std::{
fs,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
use log::trace;
use pet_core::{
env::PythonEnv,
python_environment::{PythonEnvironment, PythonEnvironmentBuilder, PythonEnvironmentKind},
pyvenv_cfg::PyVenvCfg,
reporter::Reporter,
Configuration, Locator, LocatorKind,
};
use pet_python_utils::executable::find_executables;
use serde::Deserialize;
pub struct Uv {
pub workspace_directories: Arc<Mutex<Vec<PathBuf>>>,
}
/// Represents information stored in a `pyvenv.cfg` generated by uv
struct UvVenv {
uv_version: String,
python_version: String,
prompt: String,
}
impl UvVenv {
fn maybe_from_file(file: &Path) -> Option<Self> {
let contents = fs::read_to_string(file).ok()?;
let mut uv_version = None;
let mut python_version = None;
let mut prompt = None;
for line in contents.lines() {
if let Some(uv_version_value) = line.trim_start().strip_prefix("uv = ") {
uv_version = Some(uv_version_value.trim_end().to_string())
}
if let Some(version_info) = line.trim_start().strip_prefix("version_info = ") {
python_version = Some(version_info.to_string());
}
if let Some(prompt_value) = line.trim_start().strip_prefix("prompt = ") {
prompt = Some(prompt_value.trim_end().to_string());
}
if uv_version.is_some() && python_version.is_some() && prompt.is_some() {
// we've found all the values we need, stop parsing
break;
}
}
Some(Self {
uv_version: uv_version?,
python_version: python_version?,
prompt: prompt?,
})
}
}
impl Default for Uv {
fn default() -> Self {
Self::new()
}
}
impl Uv {
pub fn new() -> Self {
Self {
workspace_directories: Arc::new(Mutex::new(Vec::new())),
}
}
}
impl Locator for Uv {
fn get_kind(&self) -> LocatorKind {
LocatorKind::Uv
}
fn supported_categories(&self) -> Vec<PythonEnvironmentKind> {
vec![
PythonEnvironmentKind::Uv,
PythonEnvironmentKind::UvWorkspace,
]
}
fn configure(&self, config: &Configuration) {
if let Some(workspace_directories) = config.workspace_directories.as_ref() {
let mut ws = self
.workspace_directories
.lock()
.expect("workspace_directories mutex poisoned");
ws.clear();
ws.extend(workspace_directories.iter().cloned());
}
}
fn try_from(&self, env: &PythonEnv) -> Option<PythonEnvironment> {
let cfg = env
.executable
.parent()
.and_then(PyVenvCfg::find)
.or_else(|| {
env.prefix
.as_ref()
.and_then(|prefix| PyVenvCfg::find(prefix))
})?;
let uv_venv = UvVenv::maybe_from_file(&cfg.file_path)?;
trace!(
"uv-managed venv found in {}, made by uv {}",
env.executable.display(),
uv_venv.uv_version
);
let prefix = env.prefix.clone().or_else(|| {
env.executable
.parent()
.and_then(|p| p.parent().map(|pp| pp.to_path_buf()))
});
let pyproject = prefix
.as_ref()
.and_then(|prefix| prefix.parent())
.and_then(parse_pyproject_toml_in);
let kind = if pyproject
.and_then(|pyproject| pyproject.tool)
.and_then(|t| t.uv)
.and_then(|uv| uv.workspace)
.is_some()
{
PythonEnvironmentKind::UvWorkspace
} else {
PythonEnvironmentKind::Uv
};
Some(
PythonEnvironmentBuilder::new(Some(kind))
.name(Some(uv_venv.prompt))
.executable(Some(env.executable.clone()))
.version(Some(uv_venv.python_version))
.symlinks(prefix.as_ref().map(find_executables))
.prefix(prefix)
.build(),
)
}
fn find(&self, reporter: &dyn Reporter) {
// look through workspace directories for uv-managed projects and any of their workspaces
let workspaces = self
.workspace_directories
.lock()
.expect("workspace_directories mutex poisoned")
.clone();
for workspace in workspaces {
// TODO: maybe check for workspace in parent folders?
for env in list_envs_in_directory(&workspace) {
reporter.report_environment(&env);
}
}
}
}
fn find_workspace(path: &Path) -> Option<PythonEnvironment> {
for candidate in path.ancestors() {
let pyproject = parse_pyproject_toml_in(candidate);
if pyproject
.as_ref()
.and_then(|pp| pp.tool.as_ref())
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.workspace.as_ref())
.is_none()
{
continue;
}
// TODO: check for workspace members/excludes
trace!("Found workspace at {:?}", candidate);
let prefix = candidate.join(".venv");
let pyvenv_cfg = prefix.join("pyvenv.cfg");
if !pyvenv_cfg.exists() {
trace!(
"Workspace at {} does not have a virtual environment",
candidate.display()
);
return None;
}
let unix_executable = prefix.join("bin/python");
let windows_executable = prefix.join("Scripts/python.exe");
let executable = if unix_executable.exists() {
Some(unix_executable)
} else if windows_executable.exists() {
Some(windows_executable)
} else {
None
};
if let Some(uv_venv) = UvVenv::maybe_from_file(&pyvenv_cfg) {
return Some(
PythonEnvironmentBuilder::new(Some(PythonEnvironmentKind::UvWorkspace))
.name(Some(uv_venv.prompt))
.executable(executable)
.version(Some(uv_venv.python_version))
.symlinks(Some(find_executables(&prefix)))
.prefix(Some(prefix))
.build(),
);
} else {
trace!(
"Workspace at {} does not have a uv-managed virtual environment",
candidate.display()
);
}
return None;
}
None
}
fn list_envs_in_directory(path: &Path) -> Vec<PythonEnvironment> {
let mut envs = Vec::new();
let pyproject = parse_pyproject_toml_in(path);
let Some(pyproject) = pyproject else {
return envs;
};
let pyvenv_cfg = path.join(".venv/pyvenv.cfg");
let prefix = path.join(".venv");
let unix_executable = prefix.join("bin/python");
let windows_executable = prefix.join("Scripts/python.exe");
let executable = if unix_executable.exists() {
Some(unix_executable)
} else if windows_executable.exists() {
Some(windows_executable)
} else {
None
};
if pyproject
.tool
.and_then(|t| t.uv)
.and_then(|uv| uv.workspace)
.is_some()
{
trace!("Workspace found in {}", path.display());
if let Some(uv_venv) = UvVenv::maybe_from_file(&pyvenv_cfg) {
trace!("uv-managed venv found for workspace in {}", path.display());
let env = PythonEnvironmentBuilder::new(Some(PythonEnvironmentKind::UvWorkspace))
.name(Some(uv_venv.prompt))
.symlinks(Some(find_executables(&prefix)))
.prefix(Some(prefix))
.executable(executable)
.version(Some(uv_venv.python_version))
.build();
envs.push(env);
} else {
trace!(
"No uv-managed venv found for workspace in {}",
path.display()
);
}
// prioritize the workspace over the project if it's the same venv
} else if let Some(project) = pyproject.project {
if let Some(uv_venv) = UvVenv::maybe_from_file(&pyvenv_cfg) {
trace!("uv-managed venv found for project in {}", path.display());
let env = PythonEnvironmentBuilder::new(Some(PythonEnvironmentKind::Uv))
.name(Some(uv_venv.prompt))
.symlinks(Some(find_executables(&prefix)))
.prefix(Some(prefix))
.version(Some(uv_venv.python_version))
.display_name(project.name)
.executable(executable)
.build();
envs.push(env);
} else {
trace!("No uv-managed venv found in {}", path.display());
}
if let Some(workspace) = path.parent().and_then(find_workspace) {
envs.push(workspace);
}
}
envs
}
fn parse_pyproject_toml_in(path: &Path) -> Option<PyProjectToml> {
let contents = fs::read_to_string(path.join("pyproject.toml")).ok()?;
toml::from_str(&contents).ok()
}
#[derive(Deserialize, Debug)]
struct PyProjectToml {
project: Option<Project>,
tool: Option<Tool>,
}
#[derive(Deserialize, Debug)]
struct Project {
name: Option<String>,
}
#[derive(Deserialize, Debug)]
struct Tool {
uv: Option<ToolUv>,
}
#[derive(Deserialize, Debug)]
struct ToolUv {
workspace: Option<serde::de::IgnoredAny>,
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn test_uv_venv_parse_valid_pyvenv_cfg() {
let temp_dir = TempDir::new().unwrap();
let cfg_path = temp_dir.path().join("pyvenv.cfg");
let contents = r#"home = /usr/bin
include-system-site-packages = false
version = 3.11.0
executable = /usr/bin/python3.11
uv = 0.1.0
version_info = 3.11.0
prompt = test-env"#;
std::fs::write(&cfg_path, contents).unwrap();
let uv_venv = UvVenv::maybe_from_file(&cfg_path);
assert!(uv_venv.is_some());
let uv_venv = uv_venv.unwrap();
assert_eq!(uv_venv.uv_version, "0.1.0");
assert_eq!(uv_venv.python_version, "3.11.0");
assert_eq!(uv_venv.prompt, "test-env");
}
#[test]
fn test_uv_venv_parse_missing_uv_field() {
let temp_dir = TempDir::new().unwrap();
let cfg_path = temp_dir.path().join("pyvenv.cfg");
let contents = r#"home = /usr/bin
version_info = 3.11.0
prompt = test-env"#;
std::fs::write(&cfg_path, contents).unwrap();
let uv_venv = UvVenv::maybe_from_file(&cfg_path);
assert!(
uv_venv.is_none(),
"Should return None when 'uv' field is missing"
);
}
#[test]
fn test_uv_venv_parse_missing_version_info() {
let temp_dir = TempDir::new().unwrap();
let cfg_path = temp_dir.path().join("pyvenv.cfg");
let contents = r#"home = /usr/bin
uv = 0.1.0
prompt = test-env"#;
std::fs::write(&cfg_path, contents).unwrap();
let uv_venv = UvVenv::maybe_from_file(&cfg_path);
assert!(
uv_venv.is_none(),
"Should return None when 'version_info' field is missing"
);
}
#[test]
fn test_uv_venv_parse_missing_prompt() {
let temp_dir = TempDir::new().unwrap();
let cfg_path = temp_dir.path().join("pyvenv.cfg");
let contents = r#"home = /usr/bin
uv = 0.1.0
version_info = 3.11.0"#;
std::fs::write(&cfg_path, contents).unwrap();
let uv_venv = UvVenv::maybe_from_file(&cfg_path);
assert!(
uv_venv.is_none(),
"Should return None when 'prompt' field is missing"
);
}
#[test]
fn test_uv_venv_parse_with_whitespace() {
let temp_dir = TempDir::new().unwrap();
let cfg_path = temp_dir.path().join("pyvenv.cfg");
let contents = r#" uv = 0.2.5
version_info = 3.12.1
prompt = my-project "#;
std::fs::write(&cfg_path, contents).unwrap();
let uv_venv = UvVenv::maybe_from_file(&cfg_path);
assert!(uv_venv.is_some());
let uv_venv = uv_venv.unwrap();
assert_eq!(uv_venv.uv_version, "0.2.5");
assert_eq!(uv_venv.python_version, "3.12.1");
assert_eq!(uv_venv.prompt, "my-project");
}
#[test]
fn test_uv_venv_parse_nonexistent_file() {
let uv_venv = UvVenv::maybe_from_file(Path::new("/nonexistent/path/pyvenv.cfg"));
assert!(uv_venv.is_none());
}
#[test]
fn test_parse_pyproject_toml_with_workspace() {
let temp_dir = TempDir::new().unwrap();
let pyproject_path = temp_dir.path().join("pyproject.toml");
let contents = r#"[project]
name = "my-workspace"
[tool.uv.workspace]
members = ["packages/*"]"#;
std::fs::write(&pyproject_path, contents).unwrap();
let pyproject = parse_pyproject_toml_in(temp_dir.path());
assert!(pyproject.is_some());
let pyproject = pyproject.unwrap();
assert!(pyproject.project.is_some());
assert_eq!(
pyproject.project.unwrap().name,
Some("my-workspace".to_string())
);
assert!(pyproject.tool.is_some());
assert!(pyproject.tool.unwrap().uv.is_some());
}
#[test]
fn test_parse_pyproject_toml_without_workspace() {
let temp_dir = TempDir::new().unwrap();
let pyproject_path = temp_dir.path().join("pyproject.toml");
let contents = r#"[project]
name = "my-project"
[tool.uv]
dev-dependencies = ["pytest"]"#;
std::fs::write(&pyproject_path, contents).unwrap();
let pyproject = parse_pyproject_toml_in(temp_dir.path());
assert!(pyproject.is_some());
let pyproject = pyproject.unwrap();
assert!(pyproject.project.is_some());
assert_eq!(
pyproject.project.unwrap().name,
Some("my-project".to_string())
);
}
#[test]
fn test_parse_pyproject_toml_missing_file() {
let temp_dir = TempDir::new().unwrap();
let pyproject = parse_pyproject_toml_in(temp_dir.path());
assert!(pyproject.is_none());
}
#[test]
fn test_parse_pyproject_toml_invalid_toml() {
let temp_dir = TempDir::new().unwrap();
let pyproject_path = temp_dir.path().join("pyproject.toml");
let contents = r#"[project
name = "invalid"#;
std::fs::write(&pyproject_path, contents).unwrap();
let pyproject = parse_pyproject_toml_in(temp_dir.path());
assert!(pyproject.is_none());
}
#[test]
fn test_list_envs_in_directory_with_workspace() {
let temp_dir = TempDir::new().unwrap();
let project_path = temp_dir.path();
// Create pyproject.toml with workspace
let pyproject_path = project_path.join("pyproject.toml");
let pyproject_contents = r#"[tool.uv.workspace]
members = ["packages/*"]"#;
std::fs::write(&pyproject_path, pyproject_contents).unwrap();
// Create .venv directory
let venv_path = project_path.join(".venv");
std::fs::create_dir_all(&venv_path).unwrap();
// Create pyvenv.cfg
let pyvenv_cfg_path = venv_path.join("pyvenv.cfg");
let pyvenv_contents = r#"uv = 0.1.0
version_info = 3.11.0
prompt = workspace-env"#;
std::fs::write(&pyvenv_cfg_path, pyvenv_contents).unwrap();
// Create executables directory (Unix style for testing)
let bin_path = venv_path.join("bin");
std::fs::create_dir_all(&bin_path).unwrap();
let python_path = bin_path.join("python");
std::fs::File::create(&python_path).unwrap();
let envs = list_envs_in_directory(project_path);
assert_eq!(envs.len(), 1);
assert_eq!(envs[0].kind, Some(PythonEnvironmentKind::UvWorkspace));
assert_eq!(envs[0].name, Some("workspace-env".to_string()));
}
#[test]
fn test_list_envs_in_directory_with_project() {
let temp_dir = TempDir::new().unwrap();
let project_path = temp_dir.path();
// Create pyproject.toml with project (no workspace)
let pyproject_path = project_path.join("pyproject.toml");
let pyproject_contents = r#"[project]
name = "my-project"
[tool.uv]
dev-dependencies = []"#;
std::fs::write(&pyproject_path, pyproject_contents).unwrap();
// Create .venv directory
let venv_path = project_path.join(".venv");
std::fs::create_dir_all(&venv_path).unwrap();
// Create pyvenv.cfg
let pyvenv_cfg_path = venv_path.join("pyvenv.cfg");
let pyvenv_contents = r#"uv = 0.1.0
version_info = 3.11.0
prompt = my-project"#;
std::fs::write(&pyvenv_cfg_path, pyvenv_contents).unwrap();
// Create executables directory
let bin_path = venv_path.join("bin");
std::fs::create_dir_all(&bin_path).unwrap();
let python_path = bin_path.join("python");
std::fs::File::create(&python_path).unwrap();
let envs = list_envs_in_directory(project_path);
assert_eq!(envs.len(), 1);
assert_eq!(envs[0].kind, Some(PythonEnvironmentKind::Uv));
assert_eq!(envs[0].display_name, Some("my-project".to_string()));
}
#[test]
fn test_list_envs_in_directory_no_pyproject() {
let temp_dir = TempDir::new().unwrap();
let envs = list_envs_in_directory(temp_dir.path());
assert_eq!(envs.len(), 0);
}
#[test]
fn test_list_envs_in_directory_no_venv() {
let temp_dir = TempDir::new().unwrap();
let project_path = temp_dir.path();
// Create pyproject.toml but no .venv
let pyproject_path = project_path.join("pyproject.toml");
let pyproject_contents = r#"[project]
name = "my-project""#;
std::fs::write(&pyproject_path, pyproject_contents).unwrap();
let envs = list_envs_in_directory(project_path);
assert_eq!(envs.len(), 0);
}
}