uv 0.12.2

A Python package and project manager
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
use anyhow::Result;
use assert_cmd::prelude::*;
use assert_fs::prelude::*;

#[cfg(target_os = "linux")]
use std::process::Command;

use uv_cache::Cache;
#[cfg(unix)]
use uv_fs::link::{LinkMode, LinkOptions, link_dir};
use uv_static::EnvVars;

use uv_test::uv_snapshot;

/// `cache clean` should remove all packages.
#[test]
fn clean_all() -> Result<()> {
    let context = uv_test::test_context!("3.12");

    let requirements_txt = context.temp_dir.child("requirements.txt");
    requirements_txt.write_str("typing-extensions\niniconfig")?;

    // Install a requirement, to populate the cache.
    context
        .pip_sync()
        .arg("requirements.txt")
        .assert()
        .success();

    uv_snapshot!(context.with_filtered_counts().filters(), context.clean().arg("--verbose"), @"
    exit_code: 0 (success)
    ----- stderr -----
    DEBUG Searching for user configuration in: `[UV_USER_CONFIG_DIR]/uv.toml`
    DEBUG uv [VERSION] ([COMMIT] DATE)
    Clearing cache at: [CACHE_DIR]/
    Removed [N] files ([SIZE])
    ");

    Ok(())
}

/// `cache clean` should report physical space for hardlinks only when the preview is enabled.
#[cfg(unix)]
#[test]
fn clean_all_hardlinked_file() -> Result<()> {
    let context = uv_test::test_context!("3.12").with_filtered_counts();

    // Keep the retained hardlink beside the cache so both entries share a filesystem.
    let retained = context.cache_dir.path().with_file_name("retained.bin");
    fs_err::write(&retained, vec![42; 1024 * 1024])?;
    fs_err::OpenOptions::new()
        .write(true)
        .open(&retained)?
        .sync_all()?;

    let cached = context.cache_dir.child("hardlinked.bin");
    fs_err::hard_link(&retained, &cached)?;

    let filters = size_filters(&context);

    uv_snapshot!(&filters, context.clean(), @"
    exit_code: 0 (success)
    ----- stderr -----
    Clearing cache at: [CACHE_DIR]/
    Removed [N] files (1.0MiB)
    ");

    context.cache_dir.create_dir_all()?;
    fs_err::hard_link(&retained, &cached)?;

    uv_snapshot!(&filters, context.clean().arg("--preview-features").arg("cache-physical-space"), @"
    exit_code: 0 (success)
    ----- stderr -----
    Clearing cache at: [CACHE_DIR]/
    Removed [N] files (0B)
    ");

    assert!(retained.is_file());

    context.cache_dir.create_dir_all()?;
    cached.write_binary(&vec![42; 1024 * 1024])?;
    fs_err::OpenOptions::new()
        .write(true)
        .open(cached.path())?
        .sync_all()?;
    fs_err::hard_link(&cached, context.cache_dir.child("second-hardlink.bin"))?;

    uv_snapshot!(&filters, context.clean().arg("--preview-features").arg("cache-physical-space"), @"
    exit_code: 0 (success)
    ----- stderr -----
    Clearing cache at: [CACHE_DIR]/
    Removed [N] files (1.0MiB)
    ");

    Ok(())
}

/// `cache clean` should report physical space for copy-on-write clones in preview mode.
#[cfg(unix)]
#[test]
fn clean_all_cloned_file() -> Result<()> {
    let context = copy_on_write_test_context()?;
    let retained = context.cache_dir.path().with_file_name("retained");
    fs_err::create_dir_all(&retained)?;
    let original = retained.join("original.bin");
    fs_err::write(&original, vec![42; 1024 * 1024])?;

    // Remove unrelated cache entries so the cloned file is the only allocated data being cleaned.
    context.clean().assert().success();
    context.cache_dir.create_dir_all()?;

    let cached = context.cache_dir.child("cloned");
    let link_mode = link_dir(&retained, &cached, &LinkOptions::new(LinkMode::Clone))?;
    if link_mode != LinkMode::Clone {
        assert!(
            std::env::var_os(EnvVars::UV_INTERNAL__TEST_COW_FS).is_none(),
            "the configured copy-on-write filesystem did not clone the cached file"
        );
        return Ok(());
    }

    let filters = size_filters(&context);

    uv_snapshot!(&filters, context.clean().arg("--preview"), @"
    exit_code: 0 (success)
    ----- stderr -----
    Clearing cache at: [CACHE_DIR]/
    Removed [N] files (0B)
    ");

    assert!(original.is_file());

    Ok(())
}

/// Clones shared only within the cache should be counted once when their final reference is removed.
#[cfg(unix)]
#[test]
fn clean_all_cached_clones() -> Result<()> {
    let context = copy_on_write_test_context()?;
    let original = context.cache_dir.child("original");
    original.create_dir_all()?;
    original
        .child("original.bin")
        .write_binary(&vec![42; 1024 * 1024])?;

    let cloned = context.cache_dir.child("cloned");
    let link_mode = link_dir(&original, &cloned, &LinkOptions::new(LinkMode::Clone))?;
    if link_mode != LinkMode::Clone {
        assert!(
            std::env::var_os(EnvVars::UV_INTERNAL__TEST_COW_FS).is_none(),
            "the configured copy-on-write filesystem did not clone the cached file"
        );
        return Ok(());
    }

    let filters = size_filters(&context);

    uv_snapshot!(&filters, context.clean().arg("--preview-features").arg("cache-physical-space"), @"
    exit_code: 0 (success)
    ----- stderr -----
    Clearing cache at: [CACHE_DIR]/
    Removed [N] files (1.0MiB)
    ");

    Ok(())
}

/// Unknown compressed extents should not discard measurements for unrelated cache entries.
#[cfg(target_os = "linux")]
#[test]
fn clean_all_compressed_file() -> Result<()> {
    if std::env::var_os(EnvVars::UV_INTERNAL__TEST_COW_FS).is_none() {
        return Ok(());
    }

    let context = copy_on_write_test_context()?;
    let measured = context.cache_dir.child("measured.bin");
    measured.write_binary(&vec![42; 1024 * 1024])?;
    fs_err::OpenOptions::new()
        .write(true)
        .open(measured.path())?
        .sync_all()?;

    let compressed = context.cache_dir.child("compressed.bin");
    fs_err::File::create(compressed.path())?;
    Command::new("btrfs")
        .args(["property", "set"])
        .arg(compressed.path())
        .args(["compression", "zstd"])
        .assert()
        .success();
    compressed.write_binary(&vec![42; 1024 * 1024])?;
    fs_err::OpenOptions::new()
        .write(true)
        .open(compressed.path())?
        .sync_all()?;

    let filters = size_filters(&context);

    uv_snapshot!(&filters, context.clean().arg("--preview-features").arg("cache-physical-space"), @"
    exit_code: 0 (success)
    ----- stderr -----
    Clearing cache at: [CACHE_DIR]/
    Removed [N] files (at least 1.0MiB)
    ");

    Ok(())
}

/// Put the cache and retained files on CI's Btrfs or APFS volume, when configured.
#[cfg(unix)]
fn copy_on_write_test_context() -> Result<uv_test::TestContext> {
    let context = uv_test::test_context!("3.12").with_filtered_counts();
    if std::env::var_os(EnvVars::UV_INTERNAL__TEST_COW_FS).is_none() {
        return Ok(context);
    }

    let Some(context) = context.with_cache_on_cow_fs()? else {
        anyhow::bail!("the configured copy-on-write cache filesystem was unavailable");
    };

    let cache_dir = context.cache_dir.path().to_path_buf();
    Ok(context.with_filtered_path(&cache_dir, "CACHE_DIR"))
}

/// Preserve physical sizes while applying the context's other snapshot filters.
#[cfg(unix)]
fn size_filters(context: &uv_test::TestContext) -> Vec<(&str, &str)> {
    context
        .filters()
        .into_iter()
        .filter(|(_, replacement)| *replacement != "$1[SIZE]")
        .collect()
}

/// `cache clear` should behave as an alias of `cache clean`.
#[test]
fn clear_all_alias() -> Result<()> {
    let context = uv_test::test_context!("3.12");

    let requirements_txt = context.temp_dir.child("requirements.txt");
    requirements_txt.write_str("typing-extensions\niniconfig")?;

    // Install a requirement, to populate the cache.
    context
        .pip_sync()
        .arg("requirements.txt")
        .assert()
        .success();

    let mut command = context.command();
    command.arg("cache").arg("clear").arg("--verbose");

    uv_snapshot!(context.with_filtered_counts().filters(), command, @"
    exit_code: 0 (success)
    ----- stderr -----
    DEBUG Searching for user configuration in: `[UV_USER_CONFIG_DIR]/uv.toml`
    DEBUG uv [VERSION] ([COMMIT] DATE)
    Clearing cache at: [CACHE_DIR]/
    Removed [N] files ([SIZE])
    ");

    Ok(())
}

#[tokio::test]
async fn clean_force() -> Result<()> {
    let context = uv_test::test_context!("3.12").with_filtered_counts();

    let requirements_txt = context.temp_dir.child("requirements.txt");
    requirements_txt.write_str("typing-extensions\niniconfig")?;

    // Install a requirement, to populate the cache.
    context
        .pip_sync()
        .arg("requirements.txt")
        .assert()
        .success();

    // When unlocked, `--force` should still take a lock
    uv_snapshot!(context.filters(), context.clean().arg("--verbose").arg("--force"), @"
    exit_code: 0 (success)
    ----- stderr -----
    DEBUG Searching for user configuration in: `[UV_USER_CONFIG_DIR]/uv.toml`
    DEBUG uv [VERSION] ([COMMIT] DATE)
    Clearing cache at: [CACHE_DIR]/
    Removed [N] files ([SIZE])
    ");

    // Install a requirement, to re-populate the cache.
    context
        .pip_sync()
        .arg("requirements.txt")
        .assert()
        .success();

    // When locked, `--force` should proceed without blocking
    let _cache = uv_cache::Cache::from_path(context.cache_dir.path())
        .with_exclusive_lock()
        .await;
    uv_snapshot!(context.filters(), context.clean().arg("--verbose").arg("--force"), @"
    exit_code: 0 (success)
    ----- stderr -----
    DEBUG Searching for user configuration in: `[UV_USER_CONFIG_DIR]/uv.toml`
    DEBUG uv [VERSION] ([COMMIT] DATE)
    DEBUG Lock is busy for `[CACHE_DIR]/`
    DEBUG Cache is currently in use, proceeding due to `--force`
    Clearing cache at: [CACHE_DIR]/
    Removed [N] files ([SIZE])
    ");

    Ok(())
}

/// `cache clean iniconfig` should remove a single package (`iniconfig`).
#[test]
fn clean_package_pypi() -> Result<()> {
    let context = uv_test::test_context!("3.12");

    let requirements_txt = context.temp_dir.child("requirements.txt");
    requirements_txt.write_str("anyio\niniconfig")?;

    // Install a requirement, to populate the cache.
    context
        .pip_sync()
        .arg("requirements.txt")
        .assert()
        .success();

    // Assert that the `.rkyv` file is created for `iniconfig`.
    let rkyv = context
        .cache_dir
        .child("simple-v24")
        .child("pypi")
        .child("iniconfig.rkyv");
    assert!(
        rkyv.exists(),
        "Expected the `.rkyv` file to exist for `iniconfig`"
    );

    let filters: Vec<_> = context
        .filters()
        .into_iter()
        .chain([
            // The cache entry does not have a stable key, so we filter it out.
            (
                r"\[CACHE_DIR\](\\|\/)(.+)(\\|\/).*",
                "[CACHE_DIR]/$2/[ENTRY]",
            ),
            // The file count varies by operating system, so we filter it out.
            ("Removed \\d+ files?", "Removed [N] files"),
        ])
        .collect();

    uv_snapshot!(&filters, context.clean().arg("--verbose").arg("iniconfig"), @"
    exit_code: 0 (success)
    ----- stderr -----
    DEBUG Searching for user configuration in: `[UV_USER_CONFIG_DIR]/uv.toml`
    DEBUG uv [VERSION] ([COMMIT] DATE)
    DEBUG Removing dangling cache entry: [CACHE_DIR]/archive-v0/[ENTRY]
    Removed [N] files ([SIZE])
    ");

    // Assert that the `.rkyv` file is removed for `iniconfig`.
    assert!(
        !rkyv.exists(),
        "Expected the `.rkyv` file to be removed for `iniconfig`"
    );

    // Running `uv cache prune` should have no effect.
    uv_snapshot!(&filters, context.prune().arg("--verbose"), @"
    exit_code: 0 (success)
    ----- stderr -----
    DEBUG Searching for user configuration in: `[UV_USER_CONFIG_DIR]/uv.toml`
    DEBUG uv [VERSION] ([COMMIT] DATE)
    Pruning cache at: [CACHE_DIR]/
    No unused entries found
    ");

    Ok(())
}

/// `cache clean iniconfig` should remove a single package (`iniconfig`).
#[test]
fn clean_package_index() -> Result<()> {
    let context = uv_test::test_context!("3.12");

    let requirements_txt = context.temp_dir.child("requirements.txt");
    requirements_txt.write_str("anyio\niniconfig")?;

    // Install a requirement, to populate the cache.
    context
        .pip_sync()
        .arg("requirements.txt")
        .arg("--index-url")
        .arg("https://test.pypi.org/simple")
        .assert()
        .success();

    // Assert that the `.rkyv` file is created for `iniconfig`.
    let rkyv = context
        .cache_dir
        .child("simple-v24")
        .child("index")
        .child("e8208120cae3ba69")
        .child("iniconfig.rkyv");
    assert!(
        rkyv.exists(),
        "Expected the `.rkyv` file to exist for `iniconfig`"
    );

    let filters: Vec<_> = context
        .filters()
        .into_iter()
        .chain([
            // The cache entry does not have a stable key, so we filter it out.
            (
                r"\[CACHE_DIR\](\\|\/)(.+)(\\|\/).*",
                "[CACHE_DIR]/$2/[ENTRY]",
            ),
            // The file count varies by operating system, so we filter it out.
            ("Removed \\d+ files?", "Removed [N] files"),
        ])
        .collect();

    uv_snapshot!(&filters, context.clean().arg("--verbose").arg("iniconfig"), @"
    exit_code: 0 (success)
    ----- stderr -----
    DEBUG Searching for user configuration in: `[UV_USER_CONFIG_DIR]/uv.toml`
    DEBUG uv [VERSION] ([COMMIT] DATE)
    DEBUG Removing dangling cache entry: [CACHE_DIR]/archive-v0/[ENTRY]
    Removed [N] files ([SIZE])
    ");

    // Assert that the `.rkyv` file is removed for `iniconfig`.
    assert!(
        !rkyv.exists(),
        "Expected the `.rkyv` file to be removed for `iniconfig`"
    );

    Ok(())
}

#[cfg(unix)]
#[test]
fn clean_package_does_not_follow_symlinks() -> Result<()> {
    let context = uv_test::test_context!("3.12");
    let victim_dir = context.temp_dir.child("victim");
    let archive_entry = context.cache_dir.child("archive-v0").child("archive");
    let package_entry = context
        .cache_dir
        .child("wheels-v6")
        .child("pypi")
        .child("demo");

    victim_dir.create_dir_all()?;
    victim_dir.child("payload.txt").write_str("payload")?;
    archive_entry.create_dir_all()?;
    archive_entry.child("payload.txt").write_str("payload")?;
    package_entry.create_dir_all()?;

    // Preserve external targets while still removing unreferenced entries in the archive bucket.
    fs_err::os::unix::fs::symlink(&victim_dir, package_entry.join("escape"))?;
    fs_err::os::unix::fs::symlink(&archive_entry, package_entry.join("archive"))?;

    uv_snapshot!(context.filters(), context.clean().arg("demo"), @"
    exit_code: 0 (success)
    ----- stderr -----
    Removed 3 files ([SIZE])
    ");

    assert!(victim_dir.is_dir());
    assert!(victim_dir.child("payload.txt").is_file());
    assert!(fs_err::symlink_metadata(package_entry).is_err());
    assert!(fs_err::symlink_metadata(archive_entry).is_err());

    Ok(())
}

#[tokio::test]
async fn cache_timeout() {
    let context = uv_test::test_context!("3.12");

    // Simulate another uv process running and locking the cache, e.g., with a source build.
    let _cache = Cache::from_path(context.cache_dir.path())
        .with_exclusive_lock()
        .await;

    uv_snapshot!(context.filters(), context.clean().env(EnvVars::UV_LOCK_TIMEOUT, "1"), @"
    exit_code: 2 (failure)
    ----- stderr -----
    Cache is currently in-use, waiting for other uv processes to finish (use `--force` to override)
    error: Timeout ([TIME]) when waiting for lock on `[CACHE_DIR]/` at `[CACHE_DIR]/.lock`, is another uv process running? You can set `UV_LOCK_TIMEOUT` to increase the timeout.
    ");
}

/// `cache clean` should handle file paths normally restricted by Win32 path normalization.
#[cfg(windows)]
#[test]
fn clean_handles_verbatim_paths() -> Result<()> {
    let context = uv_test::test_context!("3.12");

    // Clean slate
    fs_err::remove_dir_all(&context.cache_dir)?;

    // Cached sdist path resembling the uwsgi==2.0.31 build failure.
    let uwsgi_shard = context
        .cache_dir
        .child("sdists-v9")
        .child("pypi")
        .child("uwsgi")
        .child("2.0.31")
        .child("QxDIp0qpjbsWjWURKmegK")
        .child("src")
        .child("core");

    // Attempt to create a file with a trailing dot (we need to make it verbatim to do so)
    uwsgi_shard.create_dir_all()?;
    let invalid_path = uwsgi_shard.child("logging.").to_path_buf();
    let invalid_file = uv_fs::verbatim_path(invalid_path.as_path());
    fs_err::write(&invalid_file, b"")?;

    // Confirm Win32 normalized path causes an os error when attempting to remove
    let remove_err = fs_err::remove_file(&invalid_path).expect_err("expected to fail");
    assert_eq!(remove_err.kind(), std::io::ErrorKind::NotFound);

    // Tests cache clean leverages verbatim conversion
    uv_snapshot!(context.filters(), context.clean().arg("--verbose"), @"
    exit_code: 0 (success)
    ----- stderr -----
    DEBUG Searching for user configuration in: `[UV_USER_CONFIG_DIR]/uv.toml`
    DEBUG uv [VERSION] ([COMMIT] DATE)
    Clearing cache at: [CACHE_DIR]/
    Removed 2 files
    ");

    Ok(())
}