scoop-uv 0.12.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
//! Path utilities for scoop

use std::path::PathBuf;

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

/// Environment variable for scoop home directory
pub const SCOOP_HOME_ENV: &str = "SCOOP_HOME";

/// Default scoop home directory name
const SCOOP_HOME_DIR: &str = ".scoop";

/// Version file name
pub const VERSION_FILE: &str = ".scoop-version";

/// Get the scoop home directory (~/.scoop or $SCOOP_HOME)
pub fn scoop_home() -> Result<PathBuf> {
    if let Ok(home) = std::env::var(SCOOP_HOME_ENV) {
        return Ok(PathBuf::from(home));
    }

    dirs::home_dir()
        .map(|h| h.join(SCOOP_HOME_DIR))
        .ok_or(ScoopError::HomeNotFound)
}

/// Get the virtualenvs directory (~/.scoop/virtualenvs)
pub fn virtualenvs_dir() -> Result<PathBuf> {
    Ok(scoop_home()?.join("virtualenvs"))
}

/// Get the pythons directory (~/.scoop/pythons)
pub fn pythons_dir() -> Result<PathBuf> {
    Ok(scoop_home()?.join("pythons"))
}

/// Get the global version file path (~/.scoop/version)
pub fn global_version_file() -> Result<PathBuf> {
    Ok(scoop_home()?.join("version"))
}

/// Get the local version file path in the given directory
pub fn local_version_file(dir: &std::path::Path) -> PathBuf {
    dir.join(VERSION_FILE)
}

/// Get the path to a specific virtualenv
pub fn virtualenv_path(name: &str) -> Result<PathBuf> {
    Ok(virtualenvs_dir()?.join(name))
}

/// Get the bin directory of a virtualenv
pub fn virtualenv_bin(name: &str) -> Result<PathBuf> {
    Ok(virtualenv_path(name)?.join("bin"))
}

/// Get the python executable in a virtualenv
pub fn virtualenv_python(name: &str) -> Result<PathBuf> {
    Ok(virtualenv_bin(name)?.join("python"))
}

/// Ensure all scoop directories exist
///
/// Creates the following directory structure:
/// - ~/.scoop/
/// - ~/.scoop/virtualenvs/
/// - ~/.scoop/pythons/
pub fn ensure_scoop_dirs() -> Result<()> {
    let home = scoop_home()?;
    std::fs::create_dir_all(&home)?;
    std::fs::create_dir_all(home.join("virtualenvs"))?;
    std::fs::create_dir_all(home.join("pythons"))?;
    Ok(())
}

/// Check if a virtualenv exists
pub fn virtualenv_exists(name: &str) -> Result<bool> {
    let path = virtualenv_path(name)?;
    Ok(path.exists() && path.is_dir())
}

/// Get the activate script path for a virtualenv
#[cfg(unix)]
pub fn virtualenv_activate(name: &str) -> Result<PathBuf> {
    Ok(virtualenv_bin(name)?.join("activate"))
}

/// Get the activate script path for a virtualenv (Windows)
#[cfg(windows)]
pub fn virtualenv_activate(name: &str) -> Result<PathBuf> {
    Ok(virtualenv_path(name)?.join("Scripts").join("activate.bat"))
}

/// Calculate directory size recursively
///
/// Symlinks are skipped to prevent infinite loops.
///
/// # Errors
///
/// Returns `std::io::Error` if:
/// - Directory cannot be read (permission denied)
/// - File metadata cannot be accessed
///
/// # Examples
///
/// ```no_run
/// use std::path::Path;
/// use scoop_uv::paths::calculate_dir_size;
///
/// let size = calculate_dir_size(Path::new("/tmp/mydir"))?;
/// println!("Directory size: {} bytes", size);
/// # Ok::<(), std::io::Error>(())
/// ```
pub fn calculate_dir_size(path: &std::path::Path) -> std::io::Result<u64> {
    let mut total: u64 = 0;
    // Skip symlinks to prevent infinite loops
    if path.is_dir() && !path.is_symlink() {
        for entry in std::fs::read_dir(path)? {
            let entry = entry?;
            let entry_path = entry.path(); // Fixed: avoid variable shadowing
            // Skip symlinks in size calculation
            if entry_path.is_symlink() {
                continue;
            }
            if entry_path.is_dir() {
                total += calculate_dir_size(&entry_path)?;
            } else {
                total += entry.metadata()?.len();
            }
        }
    }
    Ok(total)
}

/// Locate `exe` inside `dir`, returning the full path if a matching file
/// exists. On Windows the standard executable extensions are probed in turn.
///
/// Shared by `scoop which` (display the resolved path) and `scoop run`
/// (preflight a program lookup against the env's `bin/` before spawning).
///
/// # Examples
///
/// ```
/// # use std::path::PathBuf;
/// use scoop_uv::paths::find_executable_in;
///
/// let dir = tempfile::tempdir().unwrap();
/// std::fs::write(dir.path().join("python"), b"").unwrap();
/// assert_eq!(
///     find_executable_in(dir.path(), "python"),
///     Some(dir.path().join("python")),
/// );
/// assert!(find_executable_in(dir.path(), "missing").is_none());
/// ```
pub fn find_executable_in(dir: &std::path::Path, exe: &str) -> Option<PathBuf> {
    executable_candidates(exe)
        .into_iter()
        .map(|name| dir.join(name))
        .find(|p| p.is_file())
}

#[cfg(windows)]
fn executable_candidates(exe: &str) -> Vec<String> {
    if exe.contains('.') {
        vec![exe.to_string()]
    } else {
        vec![
            exe.to_string(),
            format!("{exe}.exe"),
            format!("{exe}.bat"),
            format!("{exe}.cmd"),
        ]
    }
}

#[cfg(not(windows))]
fn executable_candidates(exe: &str) -> Vec<String> {
    vec![exe.to_string()]
}

/// Abbreviate home directory to `~` for display.
///
/// # Examples
///
/// ```
/// use std::path::Path;
/// use scoop_uv::paths::abbreviate_home;
///
/// // Home directory paths get abbreviated
/// let home = dirs::home_dir().unwrap();
/// let path = home.join(".scoop/virtualenvs/myenv");
/// let abbreviated = abbreviate_home(&path);
/// assert!(abbreviated.starts_with("~/"));
/// ```
pub fn abbreviate_home(path: &std::path::Path) -> String {
    if let Some(home) = dirs::home_dir() {
        if let Ok(stripped) = path.strip_prefix(&home) {
            return format!("~/{}", stripped.display());
        }
    }
    path.display().to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::{with_no_scoop_home, with_temp_scoop_home};
    use serial_test::serial;

    #[test]
    fn test_scoop_home_default() {
        with_no_scoop_home(|| {
            let home = scoop_home().unwrap();
            assert!(home.ends_with(".scoop"));
        });
    }

    #[test]
    fn test_scoop_home_env() {
        with_temp_scoop_home(|temp_dir| {
            let home = scoop_home().unwrap();
            assert_eq!(home, temp_dir.path());
        });
    }

    #[test]
    #[serial]
    fn test_virtualenvs_dir() {
        with_temp_scoop_home(|temp_dir| {
            let venvs = virtualenvs_dir().unwrap();
            assert_eq!(venvs, temp_dir.path().join("virtualenvs"));
        });
    }

    #[test]
    #[serial]
    fn test_pythons_dir() {
        with_temp_scoop_home(|temp_dir| {
            let pythons = pythons_dir().unwrap();
            assert_eq!(pythons, temp_dir.path().join("pythons"));
        });
    }

    #[test]
    #[serial]
    fn test_virtualenv_path() {
        with_temp_scoop_home(|temp_dir| {
            let path = virtualenv_path("myenv").unwrap();
            assert_eq!(path, temp_dir.path().join("virtualenvs").join("myenv"));
        });
    }

    #[test]
    #[serial]
    fn test_virtualenv_bin() {
        with_temp_scoop_home(|temp_dir| {
            let bin = virtualenv_bin("myenv").unwrap();
            assert_eq!(
                bin,
                temp_dir
                    .path()
                    .join("virtualenvs")
                    .join("myenv")
                    .join("bin")
            );
        });
    }

    #[test]
    #[serial]
    fn test_virtualenv_python() {
        with_temp_scoop_home(|temp_dir| {
            let python = virtualenv_python("myenv").unwrap();
            assert_eq!(
                python,
                temp_dir
                    .path()
                    .join("virtualenvs")
                    .join("myenv")
                    .join("bin")
                    .join("python")
            );
        });
    }

    #[test]
    #[serial]
    fn test_ensure_scoop_dirs() {
        with_temp_scoop_home(|temp_dir| {
            ensure_scoop_dirs().unwrap();
            assert!(temp_dir.path().exists());
            assert!(temp_dir.path().join("virtualenvs").exists());
            assert!(temp_dir.path().join("pythons").exists());
        });
    }

    #[test]
    #[serial]
    fn test_virtualenv_exists() {
        with_temp_scoop_home(|temp_dir| {
            // Create the virtualenvs directory
            let venv_path = temp_dir.path().join("virtualenvs").join("existing");
            std::fs::create_dir_all(&venv_path).unwrap();

            assert!(virtualenv_exists("existing").unwrap());
            assert!(!virtualenv_exists("nonexistent").unwrap());
        });
    }

    #[test]
    fn test_local_version_file() {
        // This test doesn't use environment variables
        let dir = PathBuf::from("/some/project");
        let version_file = local_version_file(&dir);
        assert_eq!(version_file, dir.join(".scoop-version"));
    }

    #[test]
    #[serial]
    fn test_global_version_file() {
        with_temp_scoop_home(|temp_dir| {
            let version_file = global_version_file().unwrap();
            assert_eq!(version_file, temp_dir.path().join("version"));
        });
    }

    #[cfg(unix)]
    #[test]
    #[serial]
    fn test_virtualenv_activate_unix() {
        with_temp_scoop_home(|temp_dir| {
            let activate = virtualenv_activate("myenv").unwrap();
            assert_eq!(
                activate,
                temp_dir
                    .path()
                    .join("virtualenvs")
                    .join("myenv")
                    .join("bin")
                    .join("activate")
            );
        });
    }

    // ==========================================================================
    // Symlink and Edge Case Tests
    // ==========================================================================

    #[cfg(unix)]
    #[test]
    #[serial]
    fn test_virtualenv_exists_with_symlink() {
        with_temp_scoop_home(|temp_dir| {
            use std::os::unix::fs::symlink;

            // Create a real directory
            let real_dir = temp_dir.path().join("real_venv");
            std::fs::create_dir_all(&real_dir).unwrap();

            // Create virtualenvs directory and symlink
            let venvs_dir = temp_dir.path().join("virtualenvs");
            std::fs::create_dir_all(&venvs_dir).unwrap();
            let symlink_path = venvs_dir.join("symlinked");
            symlink(&real_dir, &symlink_path).unwrap();

            // Symlinked virtualenv should be detected as existing
            assert!(virtualenv_exists("symlinked").unwrap());
        });
    }

    #[cfg(unix)]
    #[test]
    #[serial]
    fn test_virtualenv_exists_with_broken_symlink() {
        with_temp_scoop_home(|temp_dir| {
            use std::os::unix::fs::symlink;

            // Create virtualenvs directory
            let venvs_dir = temp_dir.path().join("virtualenvs");
            std::fs::create_dir_all(&venvs_dir).unwrap();

            // Create a symlink to non-existent target
            let broken_symlink = venvs_dir.join("broken");
            symlink("/nonexistent/path", &broken_symlink).unwrap();

            // Broken symlink should NOT be detected as existing directory
            assert!(!virtualenv_exists("broken").unwrap());
        });
    }

    #[cfg(unix)]
    #[test]
    #[serial]
    fn test_virtualenv_exists_symlink_to_file() {
        with_temp_scoop_home(|temp_dir| {
            use std::os::unix::fs::symlink;

            // Create a regular file
            let file_path = temp_dir.path().join("regular_file");
            std::fs::write(&file_path, "test").unwrap();

            // Create virtualenvs directory and symlink to file
            let venvs_dir = temp_dir.path().join("virtualenvs");
            std::fs::create_dir_all(&venvs_dir).unwrap();
            let symlink_path = venvs_dir.join("filelink");
            symlink(&file_path, &symlink_path).unwrap();

            // Symlink to file should NOT be detected as existing (needs to be directory)
            assert!(!virtualenv_exists("filelink").unwrap());
        });
    }

    #[test]
    #[serial]
    fn test_path_with_special_characters() {
        with_temp_scoop_home(|temp_dir| {
            // Environment names with allowed special characters
            let venvs_dir = temp_dir.path().join("virtualenvs");
            std::fs::create_dir_all(venvs_dir.join("my-env")).unwrap();
            std::fs::create_dir_all(venvs_dir.join("my_env")).unwrap();
            std::fs::create_dir_all(venvs_dir.join("env123")).unwrap();

            assert!(virtualenv_exists("my-env").unwrap());
            assert!(virtualenv_exists("my_env").unwrap());
            assert!(virtualenv_exists("env123").unwrap());
        });
    }

    // ==========================================================================
    // calculate_dir_size Tests
    // ==========================================================================

    #[test]
    fn test_calculate_dir_size_empty_dir() {
        let dir = tempfile::tempdir().unwrap();
        let size = calculate_dir_size(dir.path()).unwrap();
        assert_eq!(size, 0);
    }

    #[test]
    fn test_calculate_dir_size_with_file() {
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("test.txt");
        std::fs::write(&file_path, b"hello").unwrap();

        let size = calculate_dir_size(dir.path()).unwrap();
        assert_eq!(size, 5);
    }

    #[test]
    fn test_calculate_dir_size_nested_dirs() {
        let dir = tempfile::tempdir().unwrap();
        let subdir = dir.path().join("subdir");
        std::fs::create_dir(&subdir).unwrap();

        std::fs::write(subdir.join("test.txt"), b"hello world").unwrap();

        let size = calculate_dir_size(dir.path()).unwrap();
        assert_eq!(size, 11);
    }

    #[test]
    fn test_calculate_dir_size_nonexistent() {
        // is_dir() returns false for nonexistent, so returns 0
        let result = calculate_dir_size(std::path::Path::new("/nonexistent/path"));
        assert_eq!(result.unwrap(), 0);
    }

    #[cfg(unix)]
    #[test]
    fn test_calculate_dir_size_skips_symlinks() {
        use std::os::unix::fs::symlink;

        let dir = tempfile::tempdir().unwrap();

        // Create a file
        std::fs::write(dir.path().join("file.txt"), b"test").unwrap();

        // Create a symlink to the file (should be skipped)
        symlink(dir.path().join("file.txt"), dir.path().join("link")).unwrap();

        // Size should only include the file, not the symlink
        let size = calculate_dir_size(dir.path()).unwrap();
        assert_eq!(size, 4); // Only "test" (4 bytes)
    }

    #[cfg(unix)]
    #[test]
    fn test_calculate_dir_size_circular_symlink() {
        use std::os::unix::fs::symlink;

        let dir = tempfile::tempdir().unwrap();
        let subdir = dir.path().join("sub");
        std::fs::create_dir(&subdir).unwrap();

        // Create circular symlink: sub/loop -> ..
        symlink(dir.path(), subdir.join("loop")).unwrap();

        // Should not hang or overflow - symlinks are skipped
        let result = calculate_dir_size(dir.path());
        assert!(result.is_ok());
    }

    // ==========================================================================
    // abbreviate_home Tests
    // ==========================================================================

    #[test]
    fn test_abbreviate_home_with_home_path() {
        // Path under home directory should be abbreviated
        if let Some(home) = dirs::home_dir() {
            let path = home.join(".scoop").join("virtualenvs").join("myenv");
            let result = abbreviate_home(&path);
            assert!(result.starts_with("~/"));
            assert!(result.contains(".scoop/virtualenvs/myenv"));
        }
    }

    #[test]
    fn test_abbreviate_home_outside_home() {
        // Path outside home directory should remain unchanged
        let path = PathBuf::from("/tmp/some/path");
        let result = abbreviate_home(&path);
        assert_eq!(result, "/tmp/some/path");
    }

    #[test]
    fn test_abbreviate_home_root_path() {
        // Root path should remain unchanged
        let path = PathBuf::from("/");
        let result = abbreviate_home(&path);
        assert_eq!(result, "/");
    }

    // ==========================================================================
    // find_executable_in / executable_candidates Tests
    // ==========================================================================

    #[test]
    fn find_executable_in_locates_existing_file() {
        let dir = tempfile::tempdir().unwrap();
        let exe = dir.path().join("python");
        std::fs::write(&exe, b"").unwrap();
        assert_eq!(find_executable_in(dir.path(), "python"), Some(exe));
    }

    #[test]
    fn find_executable_in_returns_none_for_missing() {
        let dir = tempfile::tempdir().unwrap();
        assert!(find_executable_in(dir.path(), "python").is_none());
    }

    #[test]
    fn find_executable_in_ignores_directories() {
        // A subdirectory whose name matches the executable must not satisfy
        // the lookup — we want files only.
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join("python")).unwrap();
        assert!(find_executable_in(dir.path(), "python").is_none());
    }

    #[test]
    fn find_executable_in_returns_none_when_dir_missing() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("does-not-exist");
        assert!(find_executable_in(&missing, "python").is_none());
    }

    #[cfg(not(windows))]
    #[test]
    fn executable_candidates_unix_is_single_entry() {
        assert_eq!(executable_candidates("python"), vec!["python".to_string()]);
    }

    #[cfg(windows)]
    #[test]
    fn executable_candidates_windows_probes_standard_extensions() {
        let candidates = executable_candidates("python");
        assert!(candidates.contains(&"python".to_string()));
        assert!(candidates.contains(&"python.exe".to_string()));
        assert!(candidates.contains(&"python.bat".to_string()));
        assert!(candidates.contains(&"python.cmd".to_string()));
    }

    #[cfg(windows)]
    #[test]
    fn executable_candidates_windows_respects_explicit_extension() {
        assert_eq!(executable_candidates("python.exe"), vec!["python.exe"]);
    }
}