-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathlib.rs
More file actions
800 lines (717 loc) · 28.9 KB
/
lib.rs
File metadata and controls
800 lines (717 loc) · 28.9 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
use env_variables::EnvVariables;
use lazy_static::lazy_static;
use log::trace;
use manager::PipenvManager;
use pet_core::env::PythonEnv;
use pet_core::os_environment::Environment;
use pet_core::LocatorKind;
use pet_core::{
python_environment::{PythonEnvironment, PythonEnvironmentBuilder, PythonEnvironmentKind},
reporter::Reporter,
Configuration, Locator, RefreshStatePersistence,
};
use pet_fs::path::norm_case;
use pet_python_utils::executable::find_executables;
use pet_python_utils::version;
use regex::Regex;
use std::path::Path;
use std::sync::{Arc, RwLock};
use std::{fs, path::PathBuf};
mod env_variables;
pub mod manager;
lazy_static! {
/// Regex pattern for pipenv environment directory names.
/// Pipenv uses the naming convention: `{sanitized-project-name}-{8-char-hash}`
/// The hash is 8 characters of URL-safe base64 encoding of SHA256.
/// Pattern: one or more name segments (letters, digits, underscores) separated by hyphens,
/// followed by a hyphen and exactly 8 alphanumeric characters (including _ and -).
static ref PIPENV_ENV_NAME_PATTERN: Regex = Regex::new(r"^.+-[A-Za-z0-9_-]{8}$")
.expect("Error creating pipenv environment name pattern regex");
}
/// Returns the list of directories where pipenv stores centralized virtual environments.
/// These are the known locations where pipenv creates virtualenvs when not using in-project mode.
/// See: https://github.com/pypa/pipenv/blob/main/pipenv/utils/shell.py#L184
fn get_pipenv_virtualenv_dirs(env_vars: &EnvVariables) -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = vec![];
// WORKON_HOME can be used by pipenv as well
if let Some(workon_home) = &env_vars.workon_home {
if workon_home.exists() {
trace!("Pipenv: Found WORKON_HOME directory: {:?}", workon_home);
dirs.push(norm_case(workon_home));
}
}
// XDG_DATA_HOME/virtualenvs (common on Linux)
if let Some(xdg_data_home) = &env_vars.xdg_data_home {
let xdg_venvs = PathBuf::from(xdg_data_home).join("virtualenvs");
if xdg_venvs.exists() {
trace!("Pipenv: Found XDG_DATA_HOME/virtualenvs: {:?}", xdg_venvs);
dirs.push(norm_case(xdg_venvs));
}
}
if let Some(home) = &env_vars.home {
// ~/.local/share/virtualenvs - default pipenv location on macOS/Linux
let local_share_venvs = home.join(".local").join("share").join("virtualenvs");
if local_share_venvs.exists() {
trace!(
"Pipenv: Found ~/.local/share/virtualenvs: {:?}",
local_share_venvs
);
dirs.push(norm_case(local_share_venvs));
}
// ~/.venvs - alternative pipenv location
let dot_venvs = home.join(".venvs");
if dot_venvs.exists() {
trace!("Pipenv: Found ~/.venvs: {:?}", dot_venvs);
dirs.push(norm_case(dot_venvs));
}
// ~/.virtualenvs - can also be used by pipenv
let dot_virtualenvs = home.join(".virtualenvs");
if dot_virtualenvs.exists() {
trace!("Pipenv: Found ~/.virtualenvs: {:?}", dot_virtualenvs);
dirs.push(norm_case(dot_virtualenvs));
}
}
trace!("Pipenv: Centralized virtualenv directories: {:?}", dirs);
dirs
}
/// Checks if the given environment is in one of pipenv's centralized virtualenv directories.
/// Pipenv uses a specific naming convention: <project-name>-<hash>
fn is_in_pipenv_centralized_dir(env: &PythonEnv, env_vars: &EnvVariables) -> bool {
let prefix = match &env.prefix {
Some(p) => p,
None => {
// Try to derive prefix from executable path
if let Some(bin) = env.executable.parent() {
if bin.file_name().unwrap_or_default() == Path::new("bin")
|| bin.file_name().unwrap_or_default() == Path::new("Scripts")
{
if let Some(p) = bin.parent() {
p
} else {
trace!(
"Pipenv: Cannot derive prefix from executable {:?}",
env.executable
);
return false;
}
} else {
return false;
}
} else {
return false;
}
}
};
let pipenv_dirs = get_pipenv_virtualenv_dirs(env_vars);
for pipenv_dir in &pipenv_dirs {
if let Some(parent) = prefix.parent() {
if norm_case(parent) == *pipenv_dir {
// Primary check: .project file (pipenv always creates this for centralized envs)
let project_file = prefix.join(".project");
if project_file.exists() {
trace!(
"Pipenv: Detected centralized pipenv env at {:?} (in {:?}, has .project file)",
prefix,
pipenv_dir
);
return true;
}
// Fallback: Check if directory name matches pipenv naming pattern
// Pattern: {sanitized-project-name}-{8-char-hash}
// This handles edge cases where .project was deleted, corrupted,
// or environments from older pipenv versions.
if let Some(dir_name) = prefix.file_name().and_then(|n| n.to_str()) {
if PIPENV_ENV_NAME_PATTERN.is_match(dir_name) {
trace!(
"Pipenv: Detected centralized pipenv env at {:?} (in {:?}, matched naming pattern, no .project file)",
prefix,
pipenv_dir
);
return true;
} else {
trace!(
"Pipenv: Env {:?} is in pipenv dir {:?} but missing .project file and name doesn't match pattern",
prefix,
pipenv_dir
);
}
}
}
}
}
trace!(
"Pipenv: Env {:?} is not in any centralized pipenv directory",
prefix
);
false
}
fn get_pipenv_project(env: &PythonEnv) -> Option<PathBuf> {
if let Some(prefix) = &env.prefix {
if let Some(project) = get_pipenv_project_from_prefix(prefix) {
return Some(project);
}
// If there's no .project file, but the venv lives inside the project folder
// (e.g., <project>/.venv or <project>/venv), then the project is the parent
// directory of the venv. Detect that by checking for a Pipfile next to the venv.
if let Some(parent) = prefix.parent() {
let project_folder = parent;
if project_folder.join("Pipfile").exists() {
return Some(project_folder.to_path_buf());
}
}
}
// We can also have a venv in the workspace that has pipenv installed in it.
// In such cases, the project is the workspace folder containing the venv.
// Derive the project folder from the executable path when prefix isn't available.
// Typical layout: <project>/.venv/{bin|Scripts}/python
// So walk up to {bin|Scripts} -> venv dir -> project dir and check for Pipfile.
if let Some(bin) = env.executable.parent() {
let venv_dir = if bin.file_name().unwrap_or_default() == Path::new("bin")
|| bin.file_name().unwrap_or_default() == Path::new("Scripts")
{
bin.parent()
} else {
Some(bin)
};
if let Some(venv_dir) = venv_dir {
if let Some(project_dir) = venv_dir.parent() {
if project_dir.join("Pipfile").exists() {
return Some(project_dir.to_path_buf());
}
}
}
}
// If the parent is bin or script, then get the parent.
let bin = env.executable.parent()?;
if bin.file_name().unwrap_or_default() == Path::new("bin")
|| bin.file_name().unwrap_or_default() == Path::new("Scripts")
{
get_pipenv_project_from_prefix(env.executable.parent()?.parent()?)
} else {
get_pipenv_project_from_prefix(env.executable.parent()?)
}
}
fn get_pipenv_project_from_prefix(prefix: &Path) -> Option<PathBuf> {
let project_file = prefix.join(".project");
if !project_file.exists() {
return None;
}
let contents = fs::read_to_string(project_file).ok()?;
let project_folder = norm_case(PathBuf::from(contents.trim().to_string()));
// Return the project folder path even if it doesn't exist.
// This allows us to identify pipenv environments in centralized directories
// even when the original project has been moved or deleted.
Some(project_folder)
}
fn is_pipenv_from_project(env: &PythonEnv) -> bool {
// If the env prefix is inside a project folder, check that folder for a Pipfile.
if let Some(prefix) = &env.prefix {
if let Some(project_dir) = prefix.parent() {
if project_dir.join("Pipfile").exists() {
return true;
}
}
}
// Derive from the executable path as a fallback.
if let Some(bin) = env.executable.parent() {
let venv_dir = if bin.file_name().unwrap_or_default() == Path::new("bin")
|| bin.file_name().unwrap_or_default() == Path::new("Scripts")
{
bin.parent()
} else {
Some(bin)
};
if let Some(venv_dir) = venv_dir {
if let Some(project_dir) = venv_dir.parent() {
if project_dir.join("Pipfile").exists() {
return true;
}
}
}
}
false
}
fn is_pipenv(env: &PythonEnv, env_vars: &EnvVariables) -> bool {
trace!(
"Pipenv: Checking if {:?} is a pipenv environment",
env.executable
);
// Check if the environment is in a pipenv centralized directory.
// This is the primary way to detect pipenv environments that are stored
// in ~/.local/share/virtualenvs/ or similar locations.
if is_in_pipenv_centralized_dir(env, env_vars) {
trace!(
"Pipenv: {:?} identified via centralized directory",
env.executable
);
return true;
}
// Check if there's a .project file pointing to a project with a Pipfile
if let Some(project_path) = get_pipenv_project(env) {
let pipfile_path = project_path.join(env_vars.pipenv_pipfile.clone());
if pipfile_path.exists() {
trace!(
"Pipenv: {:?} identified via .project file pointing to project with Pipfile at {:?}",
env.executable,
pipfile_path
);
return true;
} else {
trace!(
"Pipenv: {:?} has .project pointing to {:?} but no Pipfile found",
env.executable,
project_path
);
}
}
// Check if the venv is inside a project folder with a Pipfile
if is_pipenv_from_project(env) {
trace!(
"Pipenv: {:?} identified via in-project Pipfile",
env.executable
);
return true;
}
trace!("Pipenv: {:?} is NOT a pipenv environment", env.executable);
false
}
/// Get the default virtualenvs directory for pipenv
/// - If WORKON_HOME is set, use that
/// - Linux/macOS: ~/.local/share/virtualenvs/
/// - Windows: %USERPROFILE%\.virtualenvs\
fn get_virtualenvs_dir(env_vars: &EnvVariables) -> Option<PathBuf> {
// First check WORKON_HOME environment variable
if let Some(workon_home) = &env_vars.workon_home {
if workon_home.is_dir() {
return Some(workon_home.clone());
}
}
// Fall back to default locations
if let Some(home) = &env_vars.home {
if std::env::consts::OS == "windows" {
let dir = home.join(".virtualenvs");
if dir.is_dir() {
return Some(dir);
}
} else {
let dir = home.join(".local").join("share").join("virtualenvs");
if dir.is_dir() {
return Some(dir);
}
}
}
None
}
/// Discover pipenv environments from the virtualenvs directory
fn list_environments(env_vars: &EnvVariables) -> Vec<PythonEnvironment> {
let mut environments = vec![];
if let Some(virtualenvs_dir) = get_virtualenvs_dir(env_vars) {
trace!("Searching for pipenv environments in {:?}", virtualenvs_dir);
if let Ok(entries) = fs::read_dir(&virtualenvs_dir) {
for entry in entries.flatten() {
let path = entry.path();
if !path.is_dir() {
continue;
}
// Check if this directory is a valid virtualenv with a .project file
let project_file = path.join(".project");
if !project_file.exists() {
continue;
}
// Read the project path from .project file
if let Ok(project_contents) = fs::read_to_string(&project_file) {
let project_path = PathBuf::from(project_contents.trim());
let project_path = norm_case(project_path);
// Check if the project has a Pipfile
if !project_path.join(&env_vars.pipenv_pipfile).exists() {
continue;
}
// Find the Python executable in the virtualenv
let bin_dir = if std::env::consts::OS == "windows" {
path.join("Scripts")
} else {
path.join("bin")
};
let python_exe = if std::env::consts::OS == "windows" {
bin_dir.join("python.exe")
} else {
bin_dir.join("python")
};
if python_exe.is_file() {
let symlinks = find_executables(&bin_dir);
let version = version::from_creator_for_virtual_env(&path);
let env =
PythonEnvironmentBuilder::new(Some(PythonEnvironmentKind::Pipenv))
.executable(Some(norm_case(python_exe)))
.version(version)
.prefix(Some(norm_case(path.clone())))
.project(Some(project_path))
.symlinks(Some(symlinks))
.build();
trace!("Found pipenv environment: {:?}", env);
environments.push(env);
}
}
}
}
}
environments
}
pub struct PipEnv {
env_vars: EnvVariables,
pipenv_executable: Arc<RwLock<Option<PathBuf>>>,
}
impl PipEnv {
pub fn from(environment: &dyn Environment) -> PipEnv {
PipEnv {
env_vars: EnvVariables::from(environment),
pipenv_executable: Arc::new(RwLock::new(None)),
}
}
}
impl Locator for PipEnv {
fn get_kind(&self) -> LocatorKind {
LocatorKind::PipEnv
}
fn refresh_state(&self) -> RefreshStatePersistence {
RefreshStatePersistence::ConfiguredOnly
}
fn configure(&self, config: &Configuration) {
self.pipenv_executable
.write()
.unwrap()
.clone_from(&config.pipenv_executable);
}
fn supported_categories(&self) -> Vec<PythonEnvironmentKind> {
vec![PythonEnvironmentKind::Pipenv]
}
fn try_from(&self, env: &PythonEnv) -> Option<PythonEnvironment> {
if !is_pipenv(env, &self.env_vars) {
return None;
}
// Project path is optional - centralized pipenv envs may have a .project file
// pointing to a project that no longer exists
let project_path = get_pipenv_project(env);
trace!(
"Pipenv: Building environment for {:?}, project: {:?}",
env.executable,
project_path
);
let mut prefix = env.prefix.clone();
if prefix.is_none() {
if let Some(bin) = env.executable.parent() {
if bin.file_name().unwrap_or_default() == Path::new("bin")
|| bin.file_name().unwrap_or_default() == Path::new("Scripts")
{
if let Some(dir) = bin.parent() {
prefix = Some(dir.to_owned());
}
}
}
}
let bin = env.executable.parent()?;
let symlinks = find_executables(bin);
let mut version = env.version.clone();
if version.is_none() && prefix.is_some() {
if let Some(prefix) = &prefix {
version = version::from_creator_for_virtual_env(prefix);
}
}
Some(
PythonEnvironmentBuilder::new(Some(PythonEnvironmentKind::Pipenv))
.executable(Some(env.executable.clone()))
.version(version)
.prefix(prefix)
.project(project_path)
.symlinks(Some(symlinks))
.build(),
)
}
fn find(&self, reporter: &dyn Reporter) {
// First, find and report the pipenv manager
let pipenv_exe = self.pipenv_executable.read().unwrap().clone();
if let Some(manager) = PipenvManager::find(pipenv_exe, &self.env_vars) {
trace!("Found pipenv manager: {:?}", manager);
reporter.report_manager(&manager.to_manager());
}
// Then discover and report pipenv environments
let environments = list_environments(&self.env_vars);
for env in environments {
reporter.report_environment(&env);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{SystemTime, UNIX_EPOCH};
fn unique_temp_dir() -> PathBuf {
let mut dir = std::env::temp_dir();
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
dir.push(format!("pet_pipenv_test_{}", nanos));
dir
}
fn create_test_env_vars(home: Option<PathBuf>) -> EnvVariables {
EnvVariables {
pipenv_max_depth: 3,
pipenv_pipfile: "Pipfile".to_string(),
home,
xdg_data_home: None,
workon_home: None,
path: None,
}
}
#[test]
fn infer_project_for_venv_in_project() {
let project_dir = unique_temp_dir();
let venv_dir = project_dir.join(".venv");
let bin_dir = if cfg!(windows) {
venv_dir.join("Scripts")
} else {
venv_dir.join("bin")
};
let python_exe = if cfg!(windows) {
bin_dir.join("python.exe")
} else {
bin_dir.join("python")
};
// Create directories and files
std::fs::create_dir_all(&bin_dir).unwrap();
std::fs::write(project_dir.join("Pipfile"), b"[[source]]\n").unwrap();
// Touch python exe file
std::fs::write(&python_exe, b"").unwrap();
// Touch pyvenv.cfg in venv root so PythonEnv::new logic would normally detect prefix
std::fs::write(venv_dir.join("pyvenv.cfg"), b"version = 3.12.0\n").unwrap();
// Construct PythonEnv directly
let env = PythonEnv {
executable: norm_case(python_exe.clone()),
prefix: Some(norm_case(venv_dir.clone())),
version: None,
symlinks: None,
};
// Validate helper infers project
let inferred = get_pipenv_project(&env).expect("expected project path");
assert_eq!(inferred, norm_case(project_dir.clone()));
// Validate locator populates project
let locator = PipEnv {
env_vars: create_test_env_vars(None),
pipenv_executable: Arc::new(RwLock::new(None)),
};
let result = locator
.try_from(&env)
.expect("expected locator to return environment");
assert_eq!(result.project, Some(norm_case(project_dir.clone())));
// Cleanup
std::fs::remove_dir_all(&project_dir).ok();
}
#[test]
fn detect_pipenv_centralized_env() {
// Simulate pipenv's centralized directory structure:
// ~/.local/share/virtualenvs/myproject-Abc123/
let temp_home = unique_temp_dir();
let virtualenvs_dir = temp_home.join(".local").join("share").join("virtualenvs");
let venv_dir = virtualenvs_dir.join("myproject-Abc123XyZ");
let bin_dir = if cfg!(windows) {
venv_dir.join("Scripts")
} else {
venv_dir.join("bin")
};
let python_exe = if cfg!(windows) {
bin_dir.join("python.exe")
} else {
bin_dir.join("python")
};
// Create the project directory with a Pipfile
let project_dir = temp_home.join("projects").join("myproject");
std::fs::create_dir_all(&project_dir).unwrap();
std::fs::write(project_dir.join("Pipfile"), b"[[source]]\n").unwrap();
// Create the centralized venv with .project file
std::fs::create_dir_all(&bin_dir).unwrap();
std::fs::write(&python_exe, b"").unwrap();
std::fs::write(venv_dir.join("pyvenv.cfg"), b"version = 3.13.0\n").unwrap();
std::fs::write(
venv_dir.join(".project"),
project_dir.to_string_lossy().as_bytes(),
)
.unwrap();
// Construct PythonEnv
let env = PythonEnv {
executable: norm_case(python_exe.clone()),
prefix: Some(norm_case(venv_dir.clone())),
version: None,
symlinks: None,
};
// Create env_vars with home pointing to our temp directory
let env_vars = EnvVariables {
pipenv_max_depth: 3,
pipenv_pipfile: "Pipfile".to_string(),
home: Some(temp_home.clone()),
xdg_data_home: None,
workon_home: None,
path: None,
};
// Validate is_in_pipenv_centralized_dir detects it
assert!(
is_in_pipenv_centralized_dir(&env, &env_vars),
"Expected env to be detected in centralized dir"
);
// Validate is_pipenv returns true
assert!(
is_pipenv(&env, &env_vars),
"Expected env to be identified as pipenv"
);
// Validate locator returns the environment
let locator = PipEnv {
env_vars,
pipenv_executable: Arc::new(RwLock::new(None)),
};
let result = locator
.try_from(&env)
.expect("expected locator to return environment");
assert_eq!(result.kind, Some(PythonEnvironmentKind::Pipenv));
assert_eq!(result.project, Some(norm_case(project_dir.clone())));
// Cleanup
std::fs::remove_dir_all(&temp_home).ok();
}
#[test]
fn detect_pipenv_centralized_env_without_existing_project() {
// Test that we still identify as pipenv even if the project folder doesn't exist
let temp_home = unique_temp_dir();
let virtualenvs_dir = temp_home.join(".local").join("share").join("virtualenvs");
let venv_dir = virtualenvs_dir.join("deleted-project-Xyz789");
let bin_dir = if cfg!(windows) {
venv_dir.join("Scripts")
} else {
venv_dir.join("bin")
};
let python_exe = if cfg!(windows) {
bin_dir.join("python.exe")
} else {
bin_dir.join("python")
};
// Don't create the project directory - simulating it was deleted
// Create the centralized venv with .project file pointing to non-existent path
std::fs::create_dir_all(&bin_dir).unwrap();
std::fs::write(&python_exe, b"").unwrap();
std::fs::write(venv_dir.join("pyvenv.cfg"), b"version = 3.13.0\n").unwrap();
std::fs::write(venv_dir.join(".project"), "/path/to/deleted/project").unwrap();
// Construct PythonEnv
let env = PythonEnv {
executable: norm_case(python_exe.clone()),
prefix: Some(norm_case(venv_dir.clone())),
version: None,
symlinks: None,
};
let env_vars = EnvVariables {
pipenv_max_depth: 3,
pipenv_pipfile: "Pipfile".to_string(),
home: Some(temp_home.clone()),
xdg_data_home: None,
workon_home: None,
path: None,
};
// Should still be detected as pipenv (centralized directory + .project file)
assert!(
is_in_pipenv_centralized_dir(&env, &env_vars),
"Expected env to be detected in centralized dir"
);
assert!(
is_pipenv(&env, &env_vars),
"Expected env to be identified as pipenv"
);
// Locator should return the environment, but project will point to non-existent path
let locator = PipEnv {
env_vars,
pipenv_executable: Arc::new(RwLock::new(None)),
};
let result = locator
.try_from(&env)
.expect("expected locator to return environment");
assert_eq!(result.kind, Some(PythonEnvironmentKind::Pipenv));
// Cleanup
std::fs::remove_dir_all(&temp_home).ok();
}
#[test]
fn detect_pipenv_centralized_env_without_project_file_via_naming_pattern() {
// Test fallback detection when .project file is missing but directory name matches
// pipenv's naming pattern: {project-name}-{8-char-hash}
let temp_home = unique_temp_dir();
let virtualenvs_dir = temp_home.join(".local").join("share").join("virtualenvs");
// Use a name that matches pipenv pattern: name + hyphen + 8 alphanumeric chars
let venv_dir = virtualenvs_dir.join("myproject-AbC12xYz");
let bin_dir = if cfg!(windows) {
venv_dir.join("Scripts")
} else {
venv_dir.join("bin")
};
let python_exe = if cfg!(windows) {
bin_dir.join("python.exe")
} else {
bin_dir.join("python")
};
// Create the venv WITHOUT a .project file (simulating corrupted/deleted .project)
std::fs::create_dir_all(&bin_dir).unwrap();
std::fs::write(&python_exe, b"").unwrap();
std::fs::write(venv_dir.join("pyvenv.cfg"), b"version = 3.13.0\n").unwrap();
// Explicitly NOT creating .project file
// Construct PythonEnv
let env = PythonEnv {
executable: norm_case(python_exe.clone()),
prefix: Some(norm_case(venv_dir.clone())),
version: None,
symlinks: None,
};
let env_vars = EnvVariables {
pipenv_max_depth: 3,
pipenv_pipfile: "Pipfile".to_string(),
home: Some(temp_home.clone()),
xdg_data_home: None,
workon_home: None,
path: None,
};
// Should be detected via naming pattern fallback
assert!(
is_in_pipenv_centralized_dir(&env, &env_vars),
"Expected env to be detected in centralized dir via naming pattern"
);
assert!(
is_pipenv(&env, &env_vars),
"Expected env to be identified as pipenv via naming pattern"
);
// Locator should return the environment
let locator = PipEnv {
env_vars,
pipenv_executable: Arc::new(RwLock::new(None)),
};
let result = locator
.try_from(&env)
.expect("expected locator to return environment");
assert_eq!(result.kind, Some(PythonEnvironmentKind::Pipenv));
// Project should be None since there's no .project file and no Pipfile nearby
assert_eq!(result.project, None);
// Cleanup
std::fs::remove_dir_all(&temp_home).ok();
}
#[test]
fn test_pipenv_naming_pattern_regex() {
// Test that our regex correctly matches pipenv naming patterns
// Valid patterns: {name}-{8-char-hash}
assert!(PIPENV_ENV_NAME_PATTERN.is_match("myproject-AbC12xYz"));
assert!(PIPENV_ENV_NAME_PATTERN.is_match("my-project-AbC12xYz"));
assert!(PIPENV_ENV_NAME_PATTERN.is_match("my_project-AbC12xYz"));
assert!(PIPENV_ENV_NAME_PATTERN.is_match("project123-12345678"));
assert!(PIPENV_ENV_NAME_PATTERN.is_match("a-b-c-d-12345678"));
// URL-safe base64 can include _ and -
assert!(PIPENV_ENV_NAME_PATTERN.is_match("myproject-AbC_2-Yz"));
// Invalid patterns (should NOT match)
assert!(!PIPENV_ENV_NAME_PATTERN.is_match("myproject")); // no hash
assert!(!PIPENV_ENV_NAME_PATTERN.is_match("myproject-abc")); // hash too short (3 chars)
assert!(!PIPENV_ENV_NAME_PATTERN.is_match("myproject-abcdefg")); // hash too short (7 chars)
assert!(!PIPENV_ENV_NAME_PATTERN.is_match("-AbC12xYz")); // no project name
}
}