-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathlib.rs
More file actions
1328 lines (1152 loc) · 44.3 KB
/
lib.rs
File metadata and controls
1328 lines (1152 loc) · 44.3 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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
fs,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
use glob::{MatchOptions, Pattern};
use log::trace;
use pet_core::{
env::PythonEnv,
os_environment::Environment,
python_environment::{PythonEnvironment, PythonEnvironmentBuilder, PythonEnvironmentKind},
pyvenv_cfg::PyVenvCfg,
reporter::Reporter,
Configuration, Locator, LocatorKind, RefreshStatePersistence,
};
use pet_fs::path::norm_case;
use pet_python_utils::executable::{find_executable, find_executables};
use serde::Deserialize;
pub struct Uv {
pub workspace_directories: Arc<Mutex<Vec<PathBuf>>>,
/// Directory where uv stores managed Python installations,
/// e.g. `~/.local/share/uv/python` on Unix or `%APPDATA%\uv\python` on Windows.
uv_install_dir: Option<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::from(&pet_core::os_environment::EnvironmentApi::new())
}
}
impl Uv {
pub fn new() -> Self {
Self::default()
}
pub fn from(environment: &dyn Environment) -> Self {
Self {
workspace_directories: Arc::new(Mutex::new(Vec::new())),
uv_install_dir: get_uv_python_install_dir(environment),
}
}
}
impl Locator for Uv {
fn get_kind(&self) -> LocatorKind {
LocatorKind::Uv
}
fn refresh_state(&self) -> RefreshStatePersistence {
RefreshStatePersistence::ConfiguredOnly
}
fn supported_categories(&self) -> Vec<PythonEnvironmentKind> {
vec![
PythonEnvironmentKind::Uv,
PythonEnvironmentKind::UvWorkspace,
]
}
fn configure(&self, config: &Configuration) {
let mut ws = self
.workspace_directories
.lock()
.expect("workspace_directories mutex poisoned");
ws.clear();
if let Some(workspace_directories) = config.workspace_directories.as_ref() {
ws.extend(workspace_directories.iter().cloned());
}
}
fn try_from(&self, env: &PythonEnv) -> Option<PythonEnvironment> {
// Check if this is a uv-managed global Python installation
if let Some(uv_env) = self.try_from_managed_install(env) {
return Some(uv_env);
}
// Check if this is a uv-managed virtual environment (pyvenv.cfg with uv marker)
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) {
// Discover globally-installed Python versions from `uv python install`
if let Some(ref install_dir) = self.uv_install_dir {
for env in find_managed_python_installs(install_dir) {
reporter.report_environment(&env);
}
}
// 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 {
for env in list_envs_in_directory(workspace) {
reporter.report_environment(&env);
}
}
}
}
impl Uv {
/// Check if a Python executable is from a uv-managed global installation.
fn try_from_managed_install(&self, env: &PythonEnv) -> Option<PythonEnvironment> {
let install_dir = self.uv_install_dir.as_ref()?;
let executable = &env.executable;
// Check if the executable lives under the uv install directory.
// Both paths are normalized (install_dir via norm_case at construction,
// executable via PythonEnv normalization), but symlinks/junctions that
// resolve outside install_dir won't match — consistent with other locators.
if !executable.starts_with(install_dir) {
return None;
}
// Determine the version-specific subdirectory.
// Path: <install_dir>/<cpython-X.Y.Z-os-arch-libc>/bin/python
let relative = executable.strip_prefix(install_dir).ok()?;
let version_dir_name = relative.iter().next()?.to_string_lossy();
let version = parse_version_from_uv_dir_name(&version_dir_name)?;
let prefix = install_dir.join(version_dir_name.as_ref());
// Skip minor-version junction/symlink directories (e.g., cpython-3.12-*)
// to avoid duplicating the actual patch-version directories they point to.
if is_symlink_or_junction(&prefix) {
return None;
}
trace!(
"uv-managed Python {} found at {}",
version,
executable.display()
);
Some(
PythonEnvironmentBuilder::new(Some(PythonEnvironmentKind::Uv))
.executable(Some(executable.clone()))
.version(Some(version))
.prefix(Some(prefix.clone()))
.symlinks(Some(find_executables(&prefix)))
.build(),
)
}
}
/// Determine the directory where uv stores managed Python installations.
fn get_uv_python_install_dir(environment: &dyn Environment) -> Option<PathBuf> {
// 1. Check UV_PYTHON_INSTALL_DIR env var
if let Some(dir) = environment.get_env_var("UV_PYTHON_INSTALL_DIR".to_string()) {
let path = PathBuf::from(dir);
if path.is_dir() {
return Some(norm_case(path));
}
}
// 2. Platform-specific defaults
get_default_uv_python_install_dir(environment)
}
#[cfg(windows)]
fn get_default_uv_python_install_dir(environment: &dyn Environment) -> Option<PathBuf> {
// Windows: %APPDATA%\uv\python
let appdata = environment.get_env_var("APPDATA".to_string())?;
let path = PathBuf::from(appdata).join("uv").join("python");
if path.is_dir() {
Some(norm_case(path))
} else {
None
}
}
#[cfg(unix)]
fn get_default_uv_python_install_dir(environment: &dyn Environment) -> Option<PathBuf> {
// Unix: $XDG_DATA_HOME/uv/python or ~/.local/share/uv/python
if let Some(xdg) = environment.get_env_var("XDG_DATA_HOME".to_string()) {
let path = PathBuf::from(xdg).join("uv").join("python");
if path.is_dir() {
return Some(norm_case(path));
}
}
let home = environment.get_user_home()?;
let path = home.join(".local").join("share").join("uv").join("python");
if path.is_dir() {
Some(norm_case(path))
} else {
None
}
}
/// Scan the uv Python install directory for managed Python installations.
/// Skips symlinks and junctions (minor-version aliases like `cpython-3.12-*`)
/// to avoid duplicating the actual patch-version directories they point to.
fn find_managed_python_installs(install_dir: &Path) -> Vec<PythonEnvironment> {
let mut envs = Vec::new();
let entries = match fs::read_dir(install_dir) {
Ok(entries) => entries,
Err(_) => return envs,
};
for entry in entries.filter_map(Result::ok) {
let path = entry.path();
if !path.is_dir() {
continue;
}
// Skip symlinks (Unix) and junctions (Windows) — these are minor-version
// aliases (e.g., cpython-3.12-*) pointing to full patch-version directories.
if is_symlink_or_junction(&path) {
trace!("Skipping symlink/junction directory {}", path.display());
continue;
}
let dir_name = match path.file_name() {
Some(name) => name.to_string_lossy().to_string(),
None => continue,
};
let version = match parse_version_from_uv_dir_name(&dir_name) {
Some(v) => v,
None => continue,
};
if let Some(executable) = find_executable(&path) {
trace!("uv-managed Python {} found in {}", version, path.display());
let env = PythonEnvironmentBuilder::new(Some(PythonEnvironmentKind::Uv))
.executable(Some(executable))
.version(Some(version))
.prefix(Some(path.clone()))
.symlinks(Some(find_executables(&path)))
.build();
envs.push(env);
}
}
envs
}
/// Check if a path is a symlink (Unix) or junction/symlink (Windows).
#[cfg(windows)]
fn is_symlink_or_junction(path: &Path) -> bool {
use std::os::windows::fs::MetadataExt;
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
fs::symlink_metadata(path)
.map(|m| m.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0)
.unwrap_or(false)
}
#[cfg(unix)]
fn is_symlink_or_junction(path: &Path) -> bool {
fs::symlink_metadata(path)
.map(|m| m.file_type().is_symlink())
.unwrap_or(false)
}
/// Parse version from a uv Python install directory name.
/// Directory names follow the pattern: `cpython-3.14.3-linux-x86_64-gnu`
/// Returns the version string (e.g., "3.14.3").
fn parse_version_from_uv_dir_name(dir_name: &str) -> Option<String> {
// Format: <implementation>-<version>-<os>-<arch>-<libc>
// e.g., cpython-3.14.3-linux-x86_64-gnu, pypy-3.10.14-linux-x86_64-gnu
let mut parts = dir_name.splitn(3, '-');
let _impl = parts.next()?;
let version = parts.next()?;
// Require the platform segment to exist (rejects bare "<impl>-<version>").
let platform = parts.next()?;
if platform.is_empty() {
return None;
}
// Verify at minimum X.Y format (e.g., "3.12" or "3.12.3").
// Major and minor must always be purely numeric.
// Only the patch component (3rd+) may have a pre-release suffix (e.g., "0a4", "0rc1").
let components: Vec<&str> = version.split('.').collect();
if components.len() < 2 {
return None;
}
let is_numeric = |c: &str| !c.is_empty() && c.chars().all(|ch| ch.is_ascii_digit());
// Major and minor must be purely numeric.
if !is_numeric(components[0]) || !is_numeric(components[1]) {
return None;
}
// For X.Y versions (no patch), we're done.
if components.len() == 2 {
return Some(version.to_string());
}
// Any components between minor and the last must be purely numeric.
let middle = &components[2..components.len() - 1];
if !middle.iter().all(|c| is_numeric(c)) {
return None;
}
// The last component (patch or beyond) must start with a digit
// (allows pre-release suffix like "0a4").
let last = components.last()?;
if last.is_empty() || !last.starts_with(|ch: char| ch.is_ascii_digit()) {
return None;
}
Some(version.to_string())
}
/// Walks up from `project_path` looking for a workspace that this project belongs to.
/// Starts from `project_path` itself because a project can also define `[tool.uv.workspace]`
/// alongside `[project]` (i.e. the workspace root is itself a package).
/// Returns the workspace environment if found and the project is a valid member.
fn find_workspace_for_project(project_path: &Path) -> Option<PythonEnvironment> {
for candidate in project_path.ancestors() {
let pyproject = parse_pyproject_toml_in(candidate);
let workspace = pyproject
.as_ref()
.and_then(|pp| pp.tool.as_ref())
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.workspace.as_ref());
let Some(workspace) = workspace else {
continue;
};
if !is_workspace_member(candidate, project_path, workspace) {
trace!(
"Path {} is not a member of workspace at {}",
project_path.display(),
candidate.display()
);
// The first workspace found walking upward is the authoritative one;
// if the project isn't a member, it's not part of any workspace.
return None;
}
trace!(
"Found workspace at {:?} for project {:?}",
candidate,
project_path
);
return build_workspace_env(candidate);
}
None
}
/// Builds a `PythonEnvironment` for a uv workspace root if it has a `.venv` with a valid
/// uv-managed pyvenv.cfg.
fn build_workspace_env(workspace_root: &Path) -> Option<PythonEnvironment> {
let prefix = workspace_root.join(".venv");
let pyvenv_cfg = prefix.join("pyvenv.cfg");
if !pyvenv_cfg.exists() {
trace!(
"Workspace at {} does not have a virtual environment",
workspace_root.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) {
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",
workspace_root.display()
);
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) = find_workspace_for_project(path) {
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()
}
/// Checks whether `project_path` is a workspace member of the workspace rooted at
/// `workspace_root` according to the given `members` and `exclude` globs.
///
/// If `members` is empty (or absent), uv treats all subdirectories as implicit members.
/// A project that matches an `exclude` pattern is never a member.
///
/// Patterns are evaluated relative to the workspace root. For example,
/// `members = ["packages/*"]` matches `<workspace_root>/packages/foo`.
fn is_workspace_member(
workspace_root: &Path,
project_path: &Path,
workspace: &UvWorkspace,
) -> bool {
// The project must be underneath the workspace root
let relative = match project_path.strip_prefix(workspace_root) {
Ok(r) => r,
Err(_) => return false,
};
// The workspace root itself is always a member of its own workspace
if relative.as_os_str().is_empty() {
return true;
}
// Normalise to forward slashes for glob matching
let relative_str = relative.to_string_lossy().replace('\\', "/");
// Use require_literal_separator so `*` matches a single path component only
let match_options = MatchOptions {
require_literal_separator: true,
..MatchOptions::new()
};
// Check excludes first — an excluded path is never a member
for exclude in &workspace.exclude {
match Pattern::new(exclude) {
Ok(pattern) => {
if pattern.matches_with(&relative_str, match_options) {
trace!(
"Path {} excluded from workspace by pattern '{}'",
project_path.display(),
exclude
);
return false;
}
}
Err(e) => {
trace!("Invalid exclude glob pattern '{}': {}", exclude, e);
}
}
}
// If no members are specified, all subdirectories are implicit members
if workspace.members.is_empty() {
return true;
}
// Check if the path matches any member pattern
for member in &workspace.members {
match Pattern::new(member) {
Ok(pattern) => {
if pattern.matches_with(&relative_str, match_options) {
return true;
}
}
Err(e) => {
trace!("Invalid member glob pattern '{}': {}", member, e);
}
}
}
false
}
#[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<UvWorkspace>,
}
#[derive(Deserialize, Debug, Default)]
struct UvWorkspace {
#[serde(default)]
members: Vec<String>,
#[serde(default)]
exclude: Vec<String>,
}
#[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);
}
#[test]
fn test_is_workspace_member_matches_glob() {
let root = Path::new("/workspace");
let project = Path::new("/workspace/packages/foo");
let ws = UvWorkspace {
members: vec!["packages/*".to_string()],
exclude: vec![],
};
assert!(is_workspace_member(root, project, &ws));
}
#[test]
fn test_is_workspace_member_no_match() {
let root = Path::new("/workspace");
let project = Path::new("/workspace/other/bar");
let ws = UvWorkspace {
members: vec!["packages/*".to_string()],
exclude: vec![],
};
assert!(!is_workspace_member(root, project, &ws));
}
#[test]
fn test_is_workspace_member_excluded() {
let root = Path::new("/workspace");
let project = Path::new("/workspace/packages/excluded");
let ws = UvWorkspace {
members: vec!["packages/*".to_string()],
exclude: vec!["packages/excluded".to_string()],
};
assert!(!is_workspace_member(root, project, &ws));
}
#[test]
fn test_is_workspace_member_empty_members_implies_all() {
let root = Path::new("/workspace");
let project = Path::new("/workspace/anything/here");
let ws = UvWorkspace {
members: vec![],
exclude: vec![],
};
assert!(is_workspace_member(root, project, &ws));
}
#[test]
fn test_is_workspace_member_outside_workspace() {
let root = Path::new("/workspace");
let project = Path::new("/other/project");
let ws = UvWorkspace {
members: vec!["packages/*".to_string()],
exclude: vec![],
};
assert!(!is_workspace_member(root, project, &ws));
}
#[test]
fn test_is_workspace_member_workspace_root_is_always_member() {
let root = Path::new("/workspace");
let ws = UvWorkspace {
members: vec!["packages/*".to_string()],
exclude: vec![],
};
assert!(is_workspace_member(root, root, &ws));
}
#[test]
fn test_is_workspace_member_exclude_takes_precedence() {
let root = Path::new("/workspace");
let project = Path::new("/workspace/packages/foo");
let ws = UvWorkspace {
members: vec!["packages/*".to_string()],
exclude: vec!["packages/foo".to_string()],
};
assert!(!is_workspace_member(root, project, &ws));
}
#[test]
fn test_find_workspace_for_project_discovers_parent() {
let temp_dir = TempDir::new().unwrap();
let workspace_root = temp_dir.path();
// Create workspace pyproject.toml
let pyproject_contents = r#"[project]
name = "my-workspace"
[tool.uv.workspace]
members = ["packages/*"]"#;
std::fs::write(workspace_root.join("pyproject.toml"), pyproject_contents).unwrap();
// Create workspace .venv with uv pyvenv.cfg
let venv_path = workspace_root.join(".venv");
std::fs::create_dir_all(&venv_path).unwrap();
let pyvenv_contents = r#"uv = 0.5.0
version_info = 3.12.0