scoop-uv 0.9.0

Scoop up your Python envs — pyenv-style workflow powered by uv
Documentation
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
//! Validation utilities for scoop

use std::path::Path;
use std::process::Command;

use once_cell::sync::Lazy;
use regex::Regex;

use crate::error::{Result, ScoopError};

/// Regex for valid environment names
/// - Must start with a letter
/// - Can contain letters, numbers, hyphens, and underscores
static ENV_NAME_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^[a-zA-Z][a-zA-Z0-9_-]*$").expect("ENV_NAME_REGEX is a valid pattern")
});

/// Regex for Python version strings
/// Supports: 3, 3.12, 3.12.0, 3.12.0a1, 3.12.0b2, 3.12.0rc1
static VERSION_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^\d+(\.\d+)*((a|b|rc)\d+)?$").expect("VERSION_REGEX is a valid pattern")
});

/// Reserved names that cannot be used as environment names
const RESERVED_NAMES: &[&str] = &[
    "activate",
    "base",
    "completions",
    "create",
    "deactivate",
    "default",
    "delete",
    "global",
    "help",
    "init",
    "install",
    "list",
    "local",
    "remove",
    "resolve",
    "root",
    "system",
    "uninstall",
    "use",
    "version",
    "versions",
];

/// Maximum length for environment names
const MAX_ENV_NAME_LENGTH: usize = 64;

/// Check if a string is a valid environment name.
///
/// Valid names must:
/// - Start with a letter (a-z, A-Z)
/// - Contain only letters, numbers, hyphens, and underscores
/// - Not be a reserved name (e.g., "activate", "list")
/// - Not look like a version string (e.g., "3.12")
/// - Be at most 64 characters long
///
/// # Examples
///
/// ```
/// use scoop_uv::validate::is_valid_env_name;
///
/// assert!(is_valid_env_name("myenv"));
/// assert!(is_valid_env_name("my-project_v2"));
/// assert!(!is_valid_env_name("3.12"));      // looks like version
/// assert!(!is_valid_env_name("activate"));  // reserved name
/// assert!(!is_valid_env_name("123env"));    // starts with digit
/// ```
pub fn is_valid_env_name(name: &str) -> bool {
    if name.is_empty() || name.len() > MAX_ENV_NAME_LENGTH {
        return false;
    }

    if RESERVED_NAMES.contains(&name.to_lowercase().as_str()) {
        return false;
    }

    if VERSION_REGEX.is_match(name) {
        return false;
    }

    ENV_NAME_REGEX.is_match(name)
}

/// Validate an environment name, returning an error if invalid.
///
/// # Examples
///
/// ```
/// use scoop_uv::validate::validate_env_name;
///
/// assert!(validate_env_name("myenv").is_ok());
/// assert!(validate_env_name("test-project").is_ok());
///
/// // Invalid names return errors
/// assert!(validate_env_name("").is_err());
/// assert!(validate_env_name("123").is_err());
/// assert!(validate_env_name("list").is_err());
/// ```
///
/// # Errors
///
/// Returns [`ScoopError::InvalidEnvName`] if the name is invalid.
pub fn validate_env_name(name: &str) -> Result<()> {
    if name.is_empty() {
        return Err(ScoopError::InvalidEnvName {
            name: name.to_string(),
            reason: "name cannot be empty".to_string(),
        });
    }

    if name.len() > MAX_ENV_NAME_LENGTH {
        return Err(ScoopError::InvalidEnvName {
            name: name.to_string(),
            reason: format!("name exceeds maximum length of {MAX_ENV_NAME_LENGTH} characters"),
        });
    }

    if RESERVED_NAMES.contains(&name.to_lowercase().as_str()) {
        return Err(ScoopError::InvalidEnvName {
            name: name.to_string(),
            reason: "name is reserved".to_string(),
        });
    }

    if VERSION_REGEX.is_match(name) {
        return Err(ScoopError::InvalidEnvName {
            name: name.to_string(),
            reason: "name looks like a version string (must start with a letter)".to_string(),
        });
    }

    if !ENV_NAME_REGEX.is_match(name) {
        return Err(ScoopError::InvalidEnvName {
            name: name.to_string(),
            reason: "name must start with a letter and contain only letters, numbers, hyphens, and underscores".to_string(),
        });
    }

    Ok(())
}

/// Check if a string is a valid Python version.
///
/// Accepts formats like: 3, 3.12, 3.12.0, 3.12.0a1, 3.12.0rc1
///
/// # Examples
///
/// ```
/// use scoop_uv::validate::is_valid_python_version;
///
/// assert!(is_valid_python_version("3"));
/// assert!(is_valid_python_version("3.12"));
/// assert!(is_valid_python_version("3.12.0"));
/// assert!(is_valid_python_version("3.12.0a1"));
/// assert!(is_valid_python_version("3.12.0rc1"));
///
/// assert!(!is_valid_python_version(""));
/// assert!(!is_valid_python_version("abc"));
/// assert!(!is_valid_python_version("v3.12"));
/// ```
pub fn is_valid_python_version(version: &str) -> bool {
    if version.is_empty() {
        return false;
    }
    // Accept formats like: 3, 3.12, 3.12.0, 3.12.0a1, 3.12.0rc1
    VERSION_REGEX.is_match(version) || version.chars().all(|c| c.is_ascii_digit() || c == '.')
}

/// Normalize a Python version string
/// e.g., "3" -> "3", "3.12" -> "3.12", "3.12.0" -> "3.12.0"
pub fn normalize_python_version(version: &str) -> String {
    version.trim().to_string()
}

/// Validate a Python version string, returning an error if invalid
pub fn validate_python_version(version: &str) -> Result<()> {
    let trimmed = version.trim();

    if trimmed.is_empty() {
        return Err(ScoopError::InvalidPythonVersion {
            version: version.to_string(),
        });
    }

    // Allow special version aliases
    if matches!(trimmed.to_lowercase().as_str(), "latest" | "stable") {
        return Ok(());
    }

    if !is_valid_python_version(trimmed) {
        return Err(ScoopError::InvalidPythonVersion {
            version: version.to_string(),
        });
    }

    Ok(())
}

/// Parsed Python version components.
///
/// # Examples
///
/// ```
/// use scoop_uv::validate::PythonVersion;
///
/// let v = PythonVersion::parse("3.12.0").unwrap();
/// assert_eq!(v.major, 3);
/// assert_eq!(v.minor, Some(12));
/// assert_eq!(v.patch, Some(0));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PythonVersion {
    /// Major version number (e.g., 3 in "3.12.0")
    pub major: u32,
    /// Minor version number (e.g., 12 in "3.12.0")
    pub minor: Option<u32>,
    /// Patch version number (e.g., 0 in "3.12.0")
    pub patch: Option<u32>,
    /// Pre-release suffix (e.g., "a1", "rc1")
    pub suffix: Option<String>,
}

impl PythonVersion {
    /// Parse a version string into components.
    ///
    /// # Examples
    ///
    /// ```
    /// use scoop_uv::validate::PythonVersion;
    ///
    /// // Parse major.minor.patch
    /// let v = PythonVersion::parse("3.12.0").unwrap();
    /// assert_eq!(v.major, 3);
    /// assert_eq!(v.minor, Some(12));
    ///
    /// // Parse with pre-release suffix (suffix in minor position)
    /// let v = PythonVersion::parse("3.13a1").unwrap();
    /// assert_eq!(v.suffix, Some("a1".to_string()));
    ///
    /// // Returns None for invalid versions
    /// assert!(PythonVersion::parse("").is_none());
    /// assert!(PythonVersion::parse("latest").is_none());
    /// ```
    pub fn parse(version: &str) -> Option<Self> {
        let trimmed = version.trim();
        if trimmed.is_empty() {
            return None;
        }

        // Handle special aliases
        if matches!(trimmed.to_lowercase().as_str(), "latest" | "stable") {
            return None;
        }

        // Split by dots and parse
        let mut parts = trimmed.split('.');
        let major_str = parts.next()?;
        let major: u32 = major_str.parse().ok()?;

        let minor = parts.next().and_then(|s| {
            // Minor might have suffix like "12a1"
            let digits: String = s.chars().take_while(|c| c.is_ascii_digit()).collect();
            digits.parse().ok()
        });

        let patch = parts.next().and_then(|s| {
            let digits: String = s.chars().take_while(|c| c.is_ascii_digit()).collect();
            digits.parse().ok()
        });

        // Extract suffix (e.g., "a1", "b2", "rc1")
        let suffix = if let Some(minor_str) = trimmed.split('.').nth(1) {
            let suffix_start = minor_str.chars().position(|c| c.is_ascii_alphabetic());
            suffix_start.map(|pos| minor_str[pos..].to_string())
        } else {
            None
        };

        Some(Self {
            major,
            minor,
            patch,
            suffix,
        })
    }

    /// Check if this version matches another (for version resolution)
    /// e.g., "3.12" matches "3.12.0", "3.12.1", etc.
    pub fn matches(&self, other: &Self) -> bool {
        if self.major != other.major {
            return false;
        }

        if let Some(minor) = self.minor {
            if other.minor != Some(minor) {
                return false;
            }
        }

        if let Some(patch) = self.patch {
            if other.patch != Some(patch) {
                return false;
            }
        }

        true
    }
}

impl std::fmt::Display for PythonVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.major)?;
        if let Some(minor) = self.minor {
            write!(f, ".{minor}")?;
        }
        if let Some(patch) = self.patch {
            write!(f, ".{patch}")?;
        }
        if let Some(ref suffix) = self.suffix {
            write!(f, "{suffix}")?;
        }
        Ok(())
    }
}

impl Ord for PythonVersion {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        use std::cmp::Ordering;

        // Compare major version
        match self.major.cmp(&other.major) {
            Ordering::Equal => {}
            ord => return ord,
        }

        // Compare minor version (None treated as 0)
        match self.minor.unwrap_or(0).cmp(&other.minor.unwrap_or(0)) {
            Ordering::Equal => {}
            ord => return ord,
        }

        // Compare patch version (None treated as 0)
        match self.patch.unwrap_or(0).cmp(&other.patch.unwrap_or(0)) {
            Ordering::Equal => {}
            ord => return ord,
        }

        // Compare suffix: None (stable) > Some (pre-release)
        // e.g., 3.12.0 > 3.12.0rc1 > 3.12.0b1 > 3.12.0a1
        match (&self.suffix, &other.suffix) {
            (None, None) => Ordering::Equal,
            (None, Some(_)) => Ordering::Greater, // stable > pre-release
            (Some(_), None) => Ordering::Less,
            (Some(a), Some(b)) => a.cmp(b),
        }
    }
}

impl PartialOrd for PythonVersion {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// Check if a version string is a special alias (latest, stable).
///
/// # Examples
///
/// ```
/// use scoop_uv::validate::is_version_alias;
///
/// assert!(is_version_alias("latest"));
/// assert!(is_version_alias("stable"));
/// assert!(is_version_alias("LATEST"));  // case-insensitive
///
/// assert!(!is_version_alias("3.12"));
/// assert!(!is_version_alias("beta"));
/// ```
pub fn is_version_alias(version: &str) -> bool {
    matches!(version.trim().to_lowercase().as_str(), "latest" | "stable")
}

/// Validate that a path points to a valid Python executable.
///
/// Checks that the path:
/// 1. Exists on the filesystem
/// 2. Is a file (not a directory)
/// 3. Is executable (Unix only: checks mode bits)
///
/// # Examples
///
/// ```no_run
/// use std::path::Path;
/// use scoop_uv::validate::validate_python_path;
///
/// // Valid Python path
/// assert!(validate_python_path(Path::new("/usr/bin/python3")).is_ok());
///
/// // Non-existent path
/// assert!(validate_python_path(Path::new("/nonexistent/python")).is_err());
/// ```
///
/// # Errors
///
/// Returns [`ScoopError::InvalidPythonPath`] if the path is invalid.
pub fn validate_python_path(path: &Path) -> Result<()> {
    if !path.exists() {
        return Err(ScoopError::InvalidPythonPath {
            path: path.to_path_buf(),
            reason: "file not found".to_string(),
        });
    }

    if !path.is_file() {
        return Err(ScoopError::InvalidPythonPath {
            path: path.to_path_buf(),
            reason: "not a file".to_string(),
        });
    }

    // Check executable permission (Unix only)
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let metadata = std::fs::metadata(path)?;
        if metadata.permissions().mode() & 0o111 == 0 {
            return Err(ScoopError::InvalidPythonPath {
                path: path.to_path_buf(),
                reason: "not executable".to_string(),
            });
        }
    }

    Ok(())
}

/// Detect the Python version from a Python executable path.
///
/// Runs `<path> --version` and parses the output to extract the version string.
/// Returns `None` if the version cannot be detected.
///
/// # Examples
///
/// ```no_run
/// use std::path::Path;
/// use scoop_uv::validate::detect_python_version;
///
/// let version = detect_python_version(Path::new("/usr/bin/python3"));
/// // Returns Some("3.12.1") or None
/// ```
pub fn detect_python_version(path: &Path) -> Option<String> {
    let output = Command::new(path).arg("--version").output().ok()?;

    if !output.status.success() {
        return None;
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // Python prints version to stdout (Python 3) or stderr (Python 2)
    let version_text = if stdout.starts_with("Python ") {
        stdout
    } else if stderr.starts_with("Python ") {
        stderr
    } else {
        return None;
    };

    // Parse "Python X.Y.Z" -> "X.Y.Z"
    version_text
        .trim()
        .strip_prefix("Python ")
        .map(|v| v.trim().to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_valid_env_names() {
        assert!(is_valid_env_name("myenv"));
        assert!(is_valid_env_name("MyEnv"));
        assert!(is_valid_env_name("my-env"));
        assert!(is_valid_env_name("my_env"));
        assert!(is_valid_env_name("env123"));
        assert!(is_valid_env_name("a"));
    }

    #[test]
    fn test_invalid_env_names() {
        assert!(!is_valid_env_name(""));
        assert!(!is_valid_env_name("123"));
        assert!(!is_valid_env_name("3.12"));
        assert!(!is_valid_env_name("-env"));
        assert!(!is_valid_env_name("_env"));
        assert!(!is_valid_env_name("my env"));
        assert!(!is_valid_env_name("my.env"));
    }

    #[test]
    fn test_reserved_names() {
        assert!(!is_valid_env_name("activate"));
        assert!(!is_valid_env_name("ACTIVATE"));
        assert!(!is_valid_env_name("list"));
        assert!(!is_valid_env_name("version"));
    }

    #[test]
    fn test_valid_python_versions() {
        assert!(is_valid_python_version("3"));
        assert!(is_valid_python_version("3.12"));
        assert!(is_valid_python_version("3.12.0"));
        assert!(is_valid_python_version("3.12.0a1"));
    }

    #[test]
    fn test_invalid_python_versions() {
        assert!(!is_valid_python_version(""));
        assert!(!is_valid_python_version("abc"));
        assert!(!is_valid_python_version("v3.12")); // "v" prefix is invalid
        assert!(!is_valid_python_version("3.12-beta")); // Hyphen is invalid
    }

    #[test]
    fn test_validate_python_version() {
        assert!(validate_python_version("3.12").is_ok());
        assert!(validate_python_version("3.12.0").is_ok());
        assert!(validate_python_version("latest").is_ok());
        assert!(validate_python_version("LATEST").is_ok());
        assert!(validate_python_version("stable").is_ok());
        assert!(validate_python_version("STABLE").is_ok());
        assert!(validate_python_version("").is_err());
    }

    #[test]
    fn test_python_version_parse() {
        let v = PythonVersion::parse("3").unwrap();
        assert_eq!(v.major, 3);
        assert_eq!(v.minor, None);
        assert_eq!(v.patch, None);

        let v = PythonVersion::parse("3.12").unwrap();
        assert_eq!(v.major, 3);
        assert_eq!(v.minor, Some(12));
        assert_eq!(v.patch, None);

        let v = PythonVersion::parse("3.12.0").unwrap();
        assert_eq!(v.major, 3);
        assert_eq!(v.minor, Some(12));
        assert_eq!(v.patch, Some(0));

        assert!(PythonVersion::parse("latest").is_none());
        assert!(PythonVersion::parse("").is_none());
    }

    #[test]
    fn test_python_version_parse_with_suffix() {
        let v = PythonVersion::parse("3.12.0a1").unwrap();
        assert_eq!(v.major, 3);
        assert_eq!(v.minor, Some(12));
        assert_eq!(v.patch, Some(0));
        // Suffix is parsed from minor string position, so it won't include patch suffix

        let v = PythonVersion::parse("3.13a1").unwrap();
        assert_eq!(v.major, 3);
        assert_eq!(v.minor, Some(13));
        assert!(v.suffix.is_some());
    }

    #[test]
    fn test_python_version_matches() {
        let v312 = PythonVersion::parse("3.12").unwrap();
        let v3120 = PythonVersion::parse("3.12.0").unwrap();
        let v3121 = PythonVersion::parse("3.12.1").unwrap();
        let v311 = PythonVersion::parse("3.11").unwrap();

        // 3.12 matches 3.12.0 and 3.12.1
        assert!(v312.matches(&v3120));
        assert!(v312.matches(&v3121));

        // 3.12 does not match 3.11
        assert!(!v312.matches(&v311));

        // 3.12.0 does not match 3.12.1
        assert!(!v3120.matches(&v3121));
    }

    #[test]
    fn test_python_version_display() {
        assert_eq!(PythonVersion::parse("3").unwrap().to_string(), "3");
        assert_eq!(PythonVersion::parse("3.12").unwrap().to_string(), "3.12");
        assert_eq!(
            PythonVersion::parse("3.12.0").unwrap().to_string(),
            "3.12.0"
        );
    }

    #[test]
    fn test_python_version_ordering() {
        let v3_9 = PythonVersion::parse("3.9").unwrap();
        let v3_10 = PythonVersion::parse("3.10").unwrap();
        let v3_11 = PythonVersion::parse("3.11").unwrap();
        let v3_12 = PythonVersion::parse("3.12").unwrap();
        let v3_12_0 = PythonVersion::parse("3.12.0").unwrap();
        let v3_12_1 = PythonVersion::parse("3.12.1").unwrap();
        let v3_13a1 = PythonVersion::parse("3.13a1").unwrap();
        let v3_13rc1 = PythonVersion::parse("3.13rc1").unwrap();
        let v3_13 = PythonVersion::parse("3.13").unwrap();

        // Major.minor ordering
        assert!(v3_9 < v3_10);
        assert!(v3_10 < v3_11);
        assert!(v3_11 < v3_12);

        // Patch ordering
        assert!(v3_12_0 < v3_12_1);

        // Pre-release < stable
        assert!(v3_13a1 < v3_13rc1);
        assert!(v3_13rc1 < v3_13);
        assert!(v3_13a1 < v3_13);

        // Sorted collection test
        use std::collections::BTreeSet;
        let mut versions = BTreeSet::new();
        versions.insert(v3_12.clone());
        versions.insert(v3_10.clone());
        versions.insert(v3_11.clone());
        versions.insert(v3_9.clone());

        let sorted: Vec<_> = versions.iter().collect();
        assert_eq!(sorted, vec![&v3_9, &v3_10, &v3_11, &v3_12]);
    }

    #[test]
    fn test_is_version_alias() {
        assert!(is_version_alias("latest"));
        assert!(is_version_alias("LATEST"));
        assert!(is_version_alias("stable"));
        assert!(is_version_alias("  stable  "));
        assert!(!is_version_alias("3.12"));
        assert!(!is_version_alias(""));
    }

    #[test]
    fn test_validate_env_name_errors() {
        let err = validate_env_name("").unwrap_err();
        assert!(err.to_string().contains("empty"));

        let err = validate_env_name("activate").unwrap_err();
        assert!(err.to_string().contains("reserved"));

        let err = validate_env_name("3.12").unwrap_err();
        assert!(err.to_string().contains("version"));

        let err = validate_env_name("-invalid").unwrap_err();
        assert!(err.to_string().contains("must start with a letter"));
    }

    #[test]
    fn test_env_name_max_length() {
        let long_name = "a".repeat(64);
        assert!(is_valid_env_name(&long_name));

        let too_long = "a".repeat(65);
        assert!(!is_valid_env_name(&too_long));
    }

    // ==========================================================================
    // Boundary Value Tests
    // ==========================================================================

    #[test]
    fn test_env_name_boundary_values() {
        // Minimum valid length (1 character)
        assert!(is_valid_env_name("a"));
        assert!(is_valid_env_name("Z"));

        // Just below max length (63 characters)
        let just_under = "a".repeat(63);
        assert!(is_valid_env_name(&just_under));

        // Exactly at max length (64 characters)
        let at_max = "a".repeat(64);
        assert!(is_valid_env_name(&at_max));

        // Just above max length (65 characters)
        let just_over = "a".repeat(65);
        assert!(!is_valid_env_name(&just_over));

        // Way over max length
        let way_over = "a".repeat(1000);
        assert!(!is_valid_env_name(&way_over));
    }

    #[test]
    fn test_env_name_whitespace_handling() {
        // Whitespace-only names must be rejected
        assert!(!is_valid_env_name(" "));
        assert!(!is_valid_env_name("  "));
        assert!(!is_valid_env_name("\t"));
        assert!(!is_valid_env_name("\n"));
        assert!(!is_valid_env_name(" \t\n "));

        // Names with leading/trailing whitespace
        assert!(!is_valid_env_name(" myenv"));
        assert!(!is_valid_env_name("myenv "));
        assert!(!is_valid_env_name(" myenv "));
    }

    #[test]
    fn test_python_version_boundary_values() {
        // Single digit major version
        assert!(is_valid_python_version("3"));
        assert!(is_valid_python_version("2"));

        // Two digit major version (future-proofing)
        assert!(is_valid_python_version("12"));
        assert!(is_valid_python_version("99"));

        // Very long version string
        assert!(is_valid_python_version("3.12.0"));
        assert!(is_valid_python_version("3.12.999"));

        // Pre-release versions
        assert!(is_valid_python_version("3.12.0a1"));
        assert!(is_valid_python_version("3.12.0b99"));
        assert!(is_valid_python_version("3.12.0rc1"));
    }

    #[test]
    fn test_reserved_names_case_insensitivity() {
        // All reserved names should be rejected regardless of case
        for reserved in ["activate", "deactivate", "list", "create", "remove", "use"] {
            assert!(
                !is_valid_env_name(reserved),
                "lowercase '{}' should be rejected",
                reserved
            );
            assert!(
                !is_valid_env_name(&reserved.to_uppercase()),
                "uppercase '{}' should be rejected",
                reserved
            );

            // Mixed case
            let mixed: String = reserved
                .chars()
                .enumerate()
                .map(|(i, c)| {
                    if i % 2 == 0 {
                        c.to_uppercase().next().unwrap()
                    } else {
                        c
                    }
                })
                .collect();
            assert!(
                !is_valid_env_name(&mixed),
                "mixed case '{}' should be rejected",
                mixed
            );
        }
    }

    // ==========================================================================
    // Security Tests: Path Traversal and Injection Prevention
    // ==========================================================================

    #[test]
    fn test_env_name_path_traversal_rejected() {
        // Path traversal attempts must be rejected
        assert!(!is_valid_env_name("../"));
        assert!(!is_valid_env_name(".."));
        assert!(!is_valid_env_name("../etc"));
        assert!(!is_valid_env_name("../../../etc/passwd"));
        assert!(!is_valid_env_name("foo/../bar"));
        assert!(!is_valid_env_name("foo/.."));
    }

    #[test]
    fn test_env_name_hidden_file_rejected() {
        // Hidden file/directory names (starting with .) must be rejected
        assert!(!is_valid_env_name(".hidden"));
        assert!(!is_valid_env_name("."));
        assert!(!is_valid_env_name(".."));
        assert!(!is_valid_env_name(".gitignore"));
        assert!(!is_valid_env_name(".env"));
    }

    #[test]
    fn test_env_name_absolute_path_rejected() {
        // Absolute paths must be rejected
        assert!(!is_valid_env_name("/etc/passwd"));
        assert!(!is_valid_env_name("/tmp/evil"));
        assert!(!is_valid_env_name("/"));
    }

    #[test]
    fn test_env_name_special_chars_rejected() {
        // Special shell characters must be rejected
        assert!(!is_valid_env_name("env;ls"));
        assert!(!is_valid_env_name("env|cat"));
        assert!(!is_valid_env_name("env&bg"));
        assert!(!is_valid_env_name("env`cmd`"));
        assert!(!is_valid_env_name("env$(cmd)"));
        assert!(!is_valid_env_name("env>file"));
        assert!(!is_valid_env_name("env<file"));
        assert!(!is_valid_env_name("env\nwhoami"));
        assert!(!is_valid_env_name("env\twhoami"));
    }

    #[test]
    fn test_env_name_null_byte_rejected() {
        // Null bytes must be rejected (C string terminator attack)
        assert!(!is_valid_env_name("env\0hidden"));
        assert!(!is_valid_env_name("\0"));
    }

    #[test]
    fn test_env_name_unicode_rejected() {
        // Unicode homoglyphs and non-ASCII must be rejected
        assert!(!is_valid_env_name("еnv")); // Cyrillic 'е' (U+0435) looks like 'e'
        assert!(!is_valid_env_name("환경")); // Korean
        assert!(!is_valid_env_name("環境")); // Chinese
        assert!(!is_valid_env_name("env™"));
        assert!(!is_valid_env_name("env🐍")); // Emoji
    }

    #[test]
    fn test_validate_env_name_path_traversal_error_message() {
        // Verify error message is helpful for security-related rejections
        let result = validate_env_name("../etc");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("must start with a letter"));
    }
}

// =============================================================================
// Property-based Tests
// =============================================================================

#[cfg(test)]
mod proptests {
    use super::*;
    use proptest::prelude::*;

    // Strategy for generating valid environment names
    fn valid_env_name_strategy() -> impl Strategy<Value = String> {
        // Start with a letter, followed by 0-62 alphanumeric/dash/underscore chars
        "[a-zA-Z][a-zA-Z0-9_-]{0,62}".prop_filter("not reserved", |s| {
            !super::RESERVED_NAMES.contains(&s.to_lowercase().as_str())
        })
    }

    // Strategy for generating valid Python versions
    fn valid_python_version_strategy() -> impl Strategy<Value = String> {
        prop_oneof![
            // Major only: 2, 3, etc.
            (1u32..20).prop_map(|m| m.to_string()),
            // Major.minor: 3.12, 3.13, etc.
            (2u32..4, 0u32..20).prop_map(|(m, n)| format!("{}.{}", m, n)),
            // Major.minor.patch: 3.12.0, 3.12.1, etc.
            (2u32..4, 0u32..20, 0u32..100).prop_map(|(m, n, p)| format!("{}.{}.{}", m, n, p)),
            // With pre-release: 3.12.0a1, 3.12.0b2, 3.12.0rc1
            (
                2u32..4,
                0u32..20,
                0u32..10,
                prop_oneof!["a", "b", "rc"],
                1u32..10
            )
                .prop_map(|(m, n, p, pre, num)| format!("{}.{}.{}{}{}", m, n, p, pre, num)),
        ]
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(500))]

        // Property: Valid env names should always pass validation
        #[test]
        fn prop_valid_env_names_accepted(name in valid_env_name_strategy()) {
            prop_assert!(is_valid_env_name(&name), "Valid name '{}' was rejected", name);
            prop_assert!(validate_env_name(&name).is_ok(), "validate_env_name failed for '{}'", name);
        }

        // Property: Names starting with digits should always be rejected
        #[test]
        fn prop_digit_prefix_rejected(
            digit in "[0-9]",
            rest in "[a-zA-Z0-9_-]{0,10}"
        ) {
            let name = format!("{}{}", digit, rest);
            prop_assert!(!is_valid_env_name(&name), "Digit-prefixed '{}' was accepted", name);
        }

        // Property: Names with path separators should always be rejected
        #[test]
        fn prop_path_separators_rejected(
            prefix in "[a-zA-Z]{1,5}",
            suffix in "[a-zA-Z]{1,5}"
        ) {
            let with_slash = format!("{}/{}", prefix, suffix);
            let with_backslash = format!("{}\\{}", prefix, suffix);
            let with_dots = format!("{}/../{}", prefix, suffix);

            prop_assert!(!is_valid_env_name(&with_slash), "Path '{}' was accepted", with_slash);
            prop_assert!(!is_valid_env_name(&with_backslash), "Path '{}' was accepted", with_backslash);
            prop_assert!(!is_valid_env_name(&with_dots), "Path '{}' was accepted", with_dots);
        }

        // Property: Valid Python versions should always pass
        #[test]
        fn prop_valid_python_versions_accepted(version in valid_python_version_strategy()) {
            prop_assert!(
                is_valid_python_version(&version),
                "Valid version '{}' was rejected", version
            );
        }

        // Property: Python version parsing roundtrip
        #[test]
        fn prop_python_version_parse_roundtrip(
            major in 2u32..4,
            minor in 0u32..20,
            patch in 0u32..100
        ) {
            let version_str = format!("{}.{}.{}", major, minor, patch);
            let parsed = PythonVersion::parse(&version_str);
            prop_assert!(parsed.is_some(), "Failed to parse '{}'", version_str);

            let pv = parsed.unwrap();
            prop_assert_eq!(pv.major, major);
            prop_assert_eq!(pv.minor, Some(minor));
            prop_assert_eq!(pv.patch, Some(patch));
        }

        // Property: Empty strings should always be invalid
        #[test]
        fn prop_empty_always_invalid(spaces in " {0,10}") {
            prop_assert!(!is_valid_env_name(&spaces));
            prop_assert!(!is_valid_python_version(&spaces));
        }

        // Property: Reserved names should always be rejected (case-insensitive)
        #[test]
        fn prop_reserved_names_rejected(
            reserved in prop::sample::select(super::RESERVED_NAMES.to_vec()),
            upper in prop::bool::ANY
        ) {
            let name = if upper { reserved.to_uppercase() } else { reserved.to_string() };
            prop_assert!(!is_valid_env_name(&name), "Reserved '{}' was accepted", name);
        }
    }
}