uv 0.11.26

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
use std::fmt::Write;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::vec;

use anyhow::Result;
use owo_colors::OwoColorize;
use thiserror::Error;
use tracing::warn;

use uv_cache::Cache;
use uv_client::{BaseClientBuilder, FlatIndexClient, RegistryClientBuilder};
use uv_configuration::{
    BuildOptions, Concurrency, Constraints, DependencyGroups, DryRun, IndexStrategy,
    KeyringProviderType, NoBinary, NoBuild, NoSources,
};
use uv_dispatch::{BuildDispatch, SharedState};
use uv_distribution_types::{
    ConfigSettings, DependencyMetadata, ExtraBuildRequires, Index, IndexLocations,
    PackageConfigSettings, Requirement,
};
use uv_fs::Simplified;
use uv_install_wheel::LinkMode;
use uv_normalize::DefaultGroups;
use uv_preview::Preview;
use uv_python::{
    EnvironmentPreference, PythonDownloads, PythonInstallation, PythonPreference, PythonRequest,
};
use uv_resolver::{ExcludeNewer, FlatIndex};
use uv_settings::PythonInstallMirrors;
use uv_shell::{Shell, shlex_posix, shlex_windows};
use uv_types::{
    AnyErrorBuild, BuildContext, BuildIsolation, BuildStack, HashStrategy, SourceTreeEditablePolicy,
};
use uv_virtualenv::{OnExisting, RemovalReason};
use uv_warnings::warn_user;
use uv_workspace::{DiscoveryOptions, VirtualProject, WorkspaceCache, WorkspaceErrorKind};

use crate::commands::ExitStatus;
use crate::commands::pip::loggers::{DefaultInstallLogger, InstallLogger};
use crate::commands::pip::operations::{Changelog, report_interpreter};
use crate::commands::project::{
    LinkErrorReporting, WorkspacePython, centralized_environment_root,
    centralized_environments_enabled, is_centralized_environment_link, lock_project_environment,
    update_project_environment_link, validate_project_requires_python,
};
use crate::commands::reporters::PythonDownloadReporter;
use crate::printer::Printer;

use super::project::default_dependency_groups;

#[derive(Error, Debug)]
enum VenvError {
    #[error("Failed to create virtual environment")]
    Creation(#[source] uv_virtualenv::Error),

    #[error("Failed to install seed packages into virtual environment")]
    Seed(#[source] AnyErrorBuild),

    #[error("Failed to extract interpreter tags for installing seed packages")]
    Tags(#[source] uv_platform_tags::TagsError),

    #[error("Failed to resolve `--find-links` entry")]
    FlatIndex(#[source] uv_client::FlatIndexError),
}

/// Create a virtual environment.
#[expect(clippy::fn_params_excessive_bools)]
pub(crate) async fn venv(
    project_dir: &Path,
    path: Option<PathBuf>,
    python_request: Option<PythonRequest>,
    install_mirrors: PythonInstallMirrors,
    python_preference: PythonPreference,
    python_downloads: PythonDownloads,
    link_mode: LinkMode,
    index_locations: &IndexLocations,
    index_strategy: IndexStrategy,
    dependency_metadata: DependencyMetadata,
    keyring_provider: KeyringProviderType,
    client_builder: &BaseClientBuilder<'_>,
    prompt: uv_virtualenv::Prompt,
    system_site_packages: bool,
    seed: bool,
    on_existing: OnExisting,
    exclude_newer: ExcludeNewer,
    concurrency: Concurrency,
    no_config: bool,
    no_project: bool,
    cache: &Cache,
    workspace_cache: &WorkspaceCache,
    printer: Printer,
    relocatable: bool,
    preview: Preview,
) -> Result<ExitStatus> {
    let project = if no_project {
        None
    } else {
        match VirtualProject::discover(
            project_dir,
            &DiscoveryOptions::default(),
            cache,
            workspace_cache,
        )
        .await
        {
            Ok(project) => Some(project),
            Err(err) => {
                match err.as_ref() {
                    WorkspaceErrorKind::MissingProject(_)
                    | WorkspaceErrorKind::MissingPyprojectToml
                    | WorkspaceErrorKind::NonWorkspace(_) => {}
                    WorkspaceErrorKind::Toml(path, err) => {
                        warn_user!(
                            "Failed to parse `{}` during environment creation:\n{}",
                            path.user_display().cyan(),
                            textwrap::indent(&err.to_string(), "  ")
                        );
                    }
                    _ => warn_user!("{err}"),
                }
                None
            }
        }
    };

    // Only use the project environment path if we're invoked from the root with no explicit path.
    // This isn't strictly necessary and we may want to change it later, but this avoids a breaking
    // change when adding project environment support to `uv venv`.
    let project_environment = project
        .as_ref()
        .map(VirtualProject::workspace)
        .filter(|workspace| path.is_none() && workspace.install_path() == project_dir)
        .map(|workspace| (workspace, workspace.environment_selection(Some(false))));

    let centralized_workspace = project_environment
        .as_ref()
        .filter(|(_, selection)| centralized_environments_enabled(selection, cache))
        .map(|(workspace, _)| *workspace);

    let reporter = PythonDownloadReporter::single(printer);

    // If the default dependency-groups demand a higher requires-python
    // we should bias an empty venv to that to avoid churn.
    let default_groups = match &project {
        Some(project) => default_dependency_groups(project.pyproject_toml())?,
        None => DefaultGroups::default(),
    };
    let groups = DependencyGroups::default().with_defaults(default_groups);
    let WorkspacePython {
        source,
        python_request,
        requires_python,
    } = WorkspacePython::from_request(
        python_request,
        project.as_ref().map(VirtualProject::workspace),
        &groups,
        project_dir,
        no_config,
    )
    .await?;

    // Locate the Python interpreter to use in the environment
    let interpreter = {
        let python = PythonInstallation::find_or_download(
            python_request.as_ref(),
            EnvironmentPreference::OnlySystem,
            python_preference,
            python_downloads,
            client_builder,
            cache,
            Some(&reporter),
            install_mirrors.python_install_mirror.as_deref(),
            install_mirrors.pypy_install_mirror.as_deref(),
            install_mirrors.python_downloads_json_url.as_deref(),
        )
        .await?;
        report_interpreter(&python, false, printer)?;
        python.into_interpreter()
    };

    let upgradeable = python_request
        .as_ref()
        .is_none_or(|request| !request.includes_patch());

    // Determine the default path.
    let path = if let Some(workspace) = centralized_workspace {
        centralized_environment_root(workspace, &interpreter, upgradeable, cache)
    } else {
        path.or_else(|| {
            project_environment.as_ref().map(|(_, selection)| {
                selection
                    .explicit_path()
                    .map_or_else(|| project_dir.join(".venv"), Path::to_path_buf)
            })
        })
        .unwrap_or_else(|| PathBuf::from(".venv"))
    };

    // Check if the discovered Python version is incompatible with the current workspace
    if let Some(requires_python) = requires_python {
        match validate_project_requires_python(
            &interpreter,
            project.as_ref().map(VirtualProject::workspace),
            &groups,
            &requires_python,
            &source,
        ) {
            Ok(()) => {}
            Err(err) => {
                warn_user!("{err}");
            }
        }
    }

    let with_seed = if seed { " with seed packages" } else { "" };
    if centralized_workspace.is_some() {
        writeln!(
            printer.stderr(),
            "Creating virtual environment `{}`{with_seed}",
            path.file_name()
                .unwrap_or(path.as_os_str())
                .to_string_lossy()
                .cyan(),
        )?;
    } else {
        writeln!(
            printer.stderr(),
            "Creating virtual environment{with_seed} at: {}",
            path.user_display().cyan()
        )?;
    }

    // Lock the project environment to avoid synchronization issues.
    let _lock = if let Some((workspace, _)) = project_environment.as_ref() {
        lock_project_environment(workspace)
            .await
            .inspect_err(|err| {
                warn!("Failed to acquire project environment lock: {err}");
            })
            .ok()
    } else {
        None
    };

    let on_existing = match on_existing {
        OnExisting::Prompt | OnExisting::Remove(_) if centralized_workspace.is_some() => {
            // Centralized environments are managed by uv, so replace them without prompting.
            OnExisting::Remove(RemovalReason::ManagedEnvironment)
        }
        OnExisting::Prompt | OnExisting::Remove(_)
            if is_centralized_environment_link(&path, cache) =>
        {
            // Remove `.venv` without following it into the cache.
            uv_fs::remove_symlink(&path).map_err(|err| VenvError::Creation(err.into()))?;
            on_existing
        }
        _ => on_existing,
    };

    // Create the virtual environment.
    let venv = uv_virtualenv::create_venv(
        &path,
        interpreter,
        prompt,
        system_site_packages,
        on_existing,
        relocatable,
        seed,
        upgradeable,
    )
    .map_err(VenvError::Creation)?;

    // Install seed packages.
    if seed {
        // Extract the interpreter.
        let interpreter = venv.interpreter();

        // Instantiate a client.
        let client = RegistryClientBuilder::new(client_builder.clone(), cache.clone())
            .index_locations(index_locations.clone())
            .index_strategy(index_strategy)
            .keyring(keyring_provider)
            .markers(interpreter.markers())
            .platform(interpreter.platform())
            .build()?;

        // Resolve the flat indexes from `--find-links`.
        let flat_index = {
            let tags = interpreter.tags().map_err(VenvError::Tags)?;
            let client = FlatIndexClient::new(client.cached_client(), client.connectivity(), cache);
            let entries = client
                .fetch_all(index_locations.flat_indexes().map(Index::url))
                .await
                .map_err(VenvError::FlatIndex)?;
            FlatIndex::from_entries(
                entries,
                Some(tags),
                &HashStrategy::None,
                &BuildOptions::new(NoBinary::None, NoBuild::All),
            )
        };

        // Initialize any shared state.
        let state = SharedState::default();

        // For seed packages, assume a bunch of default settings are sufficient.
        let build_constraints = Constraints::default();
        let build_hasher = HashStrategy::default();
        let config_settings = ConfigSettings::default();
        let config_settings_package = PackageConfigSettings::default();
        let sources = NoSources::All;

        // Do not allow builds
        let build_options = BuildOptions::new(NoBinary::None, NoBuild::All);
        let extra_build_requires = ExtraBuildRequires::default();
        let extra_build_variables = uv_distribution_types::ExtraBuildVariables::default();
        // Prep the build context.
        let build_dispatch = BuildDispatch::new(
            &client,
            cache,
            &build_constraints,
            interpreter,
            index_locations,
            &flat_index,
            &dependency_metadata,
            state.clone(),
            index_strategy,
            &config_settings,
            &config_settings_package,
            BuildIsolation::Isolated,
            &extra_build_requires,
            &extra_build_variables,
            link_mode,
            &build_options,
            &build_hasher,
            exclude_newer,
            sources,
            SourceTreeEditablePolicy::Project,
            workspace_cache.clone(),
            concurrency,
            preview,
        );

        // Resolve the seed packages.
        let requirements = if interpreter.python_tuple() >= (3, 12) {
            vec![Requirement::from(
                uv_pep508::Requirement::from_str("pip").unwrap(),
            )]
        } else {
            // Include `setuptools` and `wheel` on Python <3.12.
            vec![
                Requirement::from(uv_pep508::Requirement::from_str("pip").unwrap()),
                Requirement::from(uv_pep508::Requirement::from_str("setuptools").unwrap()),
                Requirement::from(uv_pep508::Requirement::from_str("wheel").unwrap()),
            ]
        };

        let build_stack = BuildStack::default();

        // Resolve and install the requirements.
        //
        // Since the virtual environment is empty, and the set of requirements is trivial (no
        // constraints, no editables, etc.), we can use the build dispatch APIs directly.
        let requirements = build_dispatch
            .resolve(&requirements, &build_stack)
            .await
            .map_err(|err| VenvError::Seed(err.into()))?;
        let installed = build_dispatch
            .install(&requirements, &venv, &build_stack)
            .await
            .map_err(|err| VenvError::Seed(err.into()))?;

        let changelog = Changelog::from_installed(installed);
        DefaultInstallLogger.on_complete(&changelog, printer, DryRun::Disabled)?;
    }

    // Determine the appropriate environment path.
    let scripts = if let Some(workspace) = centralized_workspace
        && update_project_environment_link(&venv, workspace, LinkErrorReporting::User)
        && let Ok(suffix) = venv.scripts().strip_prefix(&path)
    {
        workspace.install_path().join(".venv").join(suffix)
    } else {
        venv.scripts().to_path_buf()
    };

    // Determine the appropriate activation command.
    let activation = match Shell::from_env() {
        None => None,
        Some(Shell::Bash | Shell::Zsh | Shell::Ksh) => {
            Some(format!("source {}", shlex_posix(scripts.join("activate"))))
        }
        Some(Shell::Fish) => Some(format!(
            "source {}",
            shlex_posix(scripts.join("activate.fish"))
        )),
        Some(Shell::Nushell) => Some(format!(
            "overlay use {}",
            shlex_posix(scripts.join("activate.nu"))
        )),
        Some(Shell::Csh) => Some(format!(
            "source {}",
            shlex_posix(scripts.join("activate.csh"))
        )),
        Some(Shell::Powershell) => Some(shlex_windows(scripts.join("activate"), Shell::Powershell)),
        Some(Shell::Cmd) => Some(shlex_windows(scripts.join("activate"), Shell::Cmd)),
    };
    if let Some(act) = activation {
        writeln!(printer.stderr(), "Activate with: {}", act.green())?;
    }

    Ok(ExitStatus::Success)
}