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
//! Virtual environment service

use std::fs;
use std::path::{Path, PathBuf};

use crate::core::Metadata;
use crate::error::{Result, ScoopError};
use crate::paths;
use crate::uv::UvClient;
use crate::validate;

/// Information about a virtual environment
#[derive(Debug, Clone)]
pub struct VirtualenvInfo {
    /// Name of the environment
    pub name: String,
    /// Path to the environment
    pub path: PathBuf,
    /// Python version (if metadata exists)
    pub python_version: Option<String>,
}

/// Service for managing virtual environments
pub struct VirtualenvService {
    uv: UvClient,
}

impl VirtualenvService {
    /// Create a new service with the given uv client
    pub fn new(uv: UvClient) -> Self {
        Self { uv }
    }

    /// Create a new service, finding uv automatically
    pub fn auto() -> Result<Self> {
        Ok(Self::new(UvClient::new()?))
    }

    /// List all virtual environments
    pub fn list(&self) -> Result<Vec<VirtualenvInfo>> {
        let venvs_dir = paths::virtualenvs_dir()?;

        if !venvs_dir.exists() {
            return Ok(Vec::new());
        }

        let mut envs = Vec::new();

        for entry in fs::read_dir(&venvs_dir)? {
            // Per-entry tolerance — transient IO errors on a single entry
            // shouldn't hide the rest of the directory from callers.
            let entry = match entry {
                Ok(e) => e,
                Err(_) => continue,
            };
            // Reject symlinks via file_type() (no traversal) instead of
            // path.is_dir() (which follows symlinks). A symlink under
            // virtualenvs/ would otherwise be enumerated as a normal env,
            // and downstream commands like `scoop verify` would exec the
            // target's bin/python — arbitrary execution under the user's
            // UID. This is the same hardening gc::scan_orphan_envs does;
            // doing it here makes every caller of list() consistent.
            let ft = match entry.file_type() {
                Ok(t) => t,
                Err(_) => continue,
            };
            if !ft.is_dir() || ft.is_symlink() {
                continue;
            }
            let path = entry.path();
            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                let metadata = self.read_metadata(&path);
                envs.push(VirtualenvInfo {
                    name: name.to_string(),
                    path: path.clone(),
                    python_version: metadata.map(|m| m.python_version),
                });
            }
        }

        envs.sort_by(|a, b| a.name.cmp(&b.name));
        Ok(envs)
    }

    /// Create a new virtual environment
    pub fn create(&self, name: &str, python_version: &str) -> Result<PathBuf> {
        self.create_inner(name, python_version, None)
    }

    /// Create a new virtual environment using a specific Python executable path.
    ///
    /// The `python_path` is passed directly to uv's `--python` flag, which
    /// accepts both version strings and paths. The `python_version` should be
    /// the detected version string from the binary. The canonical path is stored
    /// in metadata.
    pub fn create_with_python_path(
        &self,
        name: &str,
        python_version: &str,
        python_path: &Path,
    ) -> Result<PathBuf> {
        self.create_inner(
            name,
            &python_path.display().to_string(),
            Some((python_version, python_path)),
        )
    }

    /// Internal create implementation shared by both create methods.
    fn create_inner(
        &self,
        name: &str,
        uv_python_arg: &str,
        python_path_info: Option<(&str, &Path)>,
    ) -> Result<PathBuf> {
        validate::validate_env_name(name)?;

        let path = paths::virtualenv_path(name)?;

        if path.exists() {
            return Err(ScoopError::VirtualenvExists {
                name: name.to_string(),
            });
        }

        // Ensure parent directory exists
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }

        // Create the virtual environment
        self.uv.create_venv(&path, uv_python_arg)?;

        // Write metadata
        let uv_version = self.uv.version().ok();
        // Resolve actual version: prefer pyvenv.cfg (handles specifiers like cpython@3.12),
        // then explicit python_path version, then fall back to the raw uv arg.
        let actual_version = super::parse_pyvenv_version(&path)
            .or_else(|| python_path_info.map(|(ver, _)| ver.to_string()))
            .unwrap_or_else(|| uv_python_arg.to_string());
        let mut metadata = Metadata::new(name.to_string(), actual_version, uv_version);

        if let Some((_, pp)) = python_path_info {
            metadata = metadata.with_python_path(pp.display().to_string());
        }

        self.write_metadata(&path, &metadata)?;

        Ok(path)
    }

    /// Delete a virtual environment
    pub fn delete(&self, name: &str) -> Result<()> {
        let path = paths::virtualenv_path(name)?;

        if !path.exists() {
            return Err(ScoopError::VirtualenvNotFound {
                name: name.to_string(),
            });
        }

        fs::remove_dir_all(&path)?;
        Ok(())
    }

    /// Check whether a Python version matching `version` is already installed
    /// via uv. Thin pass-through to [`UvClient::find_python`] so command
    /// handlers don't need direct access to the private `uv` field.
    pub fn is_python_installed(&self, version: &str) -> Result<bool> {
        Ok(self.uv.find_python(version)?.is_some())
    }

    /// Install a Python version through uv. Thin pass-through that lets command
    /// handlers stay decoupled from the private `uv` field.
    pub fn install_python(&self, version: &str) -> Result<()> {
        self.uv.install_python(version)
    }

    /// Install Python packages into the env via uv. Thin pass-through so the
    /// sync handler doesn't need direct access to the private `uv` field.
    pub fn pip_install(&self, venv_path: &Path, packages: &[String]) -> Result<()> {
        self.uv.pip_install(venv_path, packages)
    }

    /// Check if a virtual environment exists
    pub fn exists(&self, name: &str) -> Result<bool> {
        let path = paths::virtualenv_path(name)?;
        Ok(path.exists())
    }

    /// Get the path to a virtual environment
    pub fn get_path(&self, name: &str) -> Result<PathBuf> {
        let path = paths::virtualenv_path(name)?;
        if !path.exists() {
            return Err(ScoopError::VirtualenvNotFound {
                name: name.to_string(),
            });
        }
        Ok(path)
    }

    /// Read metadata from a virtual environment
    pub fn read_metadata(&self, path: &Path) -> Option<Metadata> {
        let metadata_path = path.join(Metadata::FILE_NAME);
        let content = fs::read_to_string(metadata_path).ok()?;
        serde_json::from_str(&content).ok()
    }

    /// Write metadata to a virtual environment
    fn write_metadata(&self, path: &Path, metadata: &Metadata) -> Result<()> {
        let metadata_path = path.join(Metadata::FILE_NAME);
        let content = serde_json::to_string_pretty(metadata)?;
        fs::write(metadata_path, content)?;
        Ok(())
    }
}

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

    /// Helper to get VirtualenvService, skipping test if uv not available.
    /// Returns None if uv is not installed, allowing graceful test skip.
    fn get_service() -> Option<VirtualenvService> {
        crate::uv::UvClient::new().ok().map(VirtualenvService::new)
    }

    /// Macro to skip test if uv is not available.
    /// This makes the skip explicit in test output.
    macro_rules! require_uv {
        () => {
            match get_service() {
                Some(service) => service,
                None => {
                    eprintln!("SKIPPED: uv not installed");
                    return;
                }
            }
        };
    }

    #[test]
    fn test_virtualenv_info_struct() {
        let info = VirtualenvInfo {
            name: "testenv".to_string(),
            path: PathBuf::from("/path/to/env"),
            python_version: Some("3.12".to_string()),
        };

        assert_eq!(info.name, "testenv");
        assert_eq!(info.path, PathBuf::from("/path/to/env"));
        assert_eq!(info.python_version, Some("3.12".to_string()));
    }

    #[test]
    #[serial]
    fn test_list_empty_when_no_venvs_dir() {
        with_temp_scoop_home(|_temp_dir| {
            let service = require_uv!();
            let result = service.list().unwrap();
            assert!(result.is_empty());
        });
    }

    #[test]
    #[serial]
    fn test_list_returns_envs_sorted() {
        with_temp_scoop_home(|temp_dir| {
            // Arrange: Create mock venvs in reverse alphabetical order
            create_mock_venv(temp_dir, "zeta", Some("3.11"));
            create_mock_venv(temp_dir, "alpha", Some("3.12"));
            create_mock_venv(temp_dir, "beta", None);

            // Act
            let service = require_uv!();
            let envs = service.list().unwrap();

            // Assert
            assert_eq!(envs.len(), 3);
            assert_eq!(envs[0].name, "alpha");
            assert_eq!(envs[1].name, "beta");
            assert_eq!(envs[2].name, "zeta");
        });
    }

    #[test]
    #[serial]
    fn test_list_reads_python_version_from_metadata() {
        with_temp_scoop_home(|temp_dir| {
            create_mock_venv(temp_dir, "withversion", Some("3.12.1"));
            create_mock_venv(temp_dir, "noversion", None);

            let service = require_uv!();
            let envs = service.list().unwrap();

            let with_ver = envs.iter().find(|e| e.name == "withversion").unwrap();
            let no_ver = envs.iter().find(|e| e.name == "noversion").unwrap();

            assert_eq!(with_ver.python_version, Some("3.12.1".to_string()));
            assert_eq!(no_ver.python_version, None);
        });
    }

    #[test]
    #[serial]
    fn test_exists_returns_false_for_nonexistent() {
        with_temp_scoop_home(|_temp_dir| {
            let service = require_uv!();
            assert!(!service.exists("nonexistent").unwrap());
        });
    }

    #[test]
    #[serial]
    fn test_exists_returns_true_for_existing() {
        with_temp_scoop_home(|temp_dir| {
            create_mock_venv(temp_dir, "exists", None);

            let service = require_uv!();
            assert!(service.exists("exists").unwrap());
        });
    }

    #[test]
    #[serial]
    fn test_get_path_returns_error_for_nonexistent() {
        with_temp_scoop_home(|_temp_dir| {
            let service = require_uv!();
            let result = service.get_path("nonexistent");

            assert!(result.is_err());
            let err = result.unwrap_err();
            assert!(matches!(err, ScoopError::VirtualenvNotFound { .. }));
        });
    }

    #[test]
    #[serial]
    fn test_get_path_returns_path_for_existing() {
        with_temp_scoop_home(|temp_dir| {
            create_mock_venv(temp_dir, "myenv", None);

            let service = require_uv!();
            let path = service.get_path("myenv").unwrap();
            assert!(path.ends_with("myenv"));
            assert!(path.exists());
        });
    }

    #[test]
    #[serial]
    fn test_delete_removes_directory() {
        with_temp_scoop_home(|temp_dir| {
            create_mock_venv(temp_dir, "todelete", Some("3.12"));
            let venv_path = temp_dir.path().join("virtualenvs").join("todelete");
            assert!(venv_path.exists());

            let service = require_uv!();
            service.delete("todelete").unwrap();
            assert!(!venv_path.exists());
        });
    }

    #[test]
    #[serial]
    fn test_delete_returns_error_for_nonexistent() {
        with_temp_scoop_home(|temp_dir| {
            // Arrange: Create virtualenvs dir but not the specific venv
            fs::create_dir_all(temp_dir.path().join("virtualenvs")).unwrap();

            // Act
            let service = require_uv!();
            let result = service.delete("nonexistent");

            // Assert
            assert!(result.is_err());
            let err = result.unwrap_err();
            assert!(matches!(err, ScoopError::VirtualenvNotFound { .. }));
        });
    }

    #[test]
    #[serial]
    fn test_list_ignores_files() {
        with_temp_scoop_home(|temp_dir| {
            let venvs_dir = temp_dir.path().join("virtualenvs");
            fs::create_dir_all(&venvs_dir).unwrap();

            // Create a file (not directory) - should be ignored
            fs::write(venvs_dir.join("notadir"), "test").unwrap();
            // Create a real venv directory
            create_mock_venv(temp_dir, "realenv", None);

            let service = require_uv!();
            let envs = service.list().unwrap();

            assert_eq!(envs.len(), 1);
            assert_eq!(envs[0].name, "realenv");
        });
    }

    // C2 regression — symlinks under virtualenvs/ must NOT be enumerated.
    // Otherwise downstream commands (gc, verify, ...) would treat the
    // symlink target as a real env and end up scanning / exec'ing files
    // outside the venvs dir.
    #[cfg(unix)]
    #[test]
    #[serial]
    fn test_list_skips_symlink_entries() {
        with_temp_scoop_home(|temp_dir| {
            let venvs_dir = temp_dir.path().join("virtualenvs");
            fs::create_dir_all(&venvs_dir).unwrap();

            // Real env so the list isn't empty (controls for "filter is
            // entirely broken" vs "filter caught the symlink").
            create_mock_venv(temp_dir, "real", None);

            // Plant a symlink → some other (existing) directory. Without
            // the symlink filter this would be enumerated as an env.
            let other = tempfile::TempDir::new().unwrap();
            std::os::unix::fs::symlink(other.path(), venvs_dir.join("symlinked")).unwrap();

            let service = require_uv!();
            let envs = service.list().unwrap();
            assert_eq!(envs.len(), 1, "symlink entries must be skipped: {envs:?}");
            assert_eq!(envs[0].name, "real");
        });
    }
}