Skip to content

Commit 0b7099a

Browse files
committed
Reuse environments when PEP 723 dependencies are omitted
1 parent 6c907a7 commit 0b7099a

4 files changed

Lines changed: 139 additions & 135 deletions

File tree

‎crates/uv/src/commands/project/mod.rs‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3286,10 +3286,12 @@ pub(crate) async fn script_specification(
32863286
cache: &Cache,
32873287
workspace_cache: &WorkspaceCache,
32883288
credentials_cache: &CredentialsCache,
3289-
) -> Result<Option<RequirementsSpecification>, ProjectError> {
3290-
let Some(dependencies) = script.metadata().dependencies.as_ref() else {
3291-
return Ok(None);
3292-
};
3289+
) -> Result<RequirementsSpecification, ProjectError> {
3290+
let dependencies = script
3291+
.metadata()
3292+
.dependencies
3293+
.as_deref()
3294+
.unwrap_or_default();
32933295

32943296
let script_dir = script.directory()?;
32953297
let script_indexes = script
@@ -3419,7 +3421,7 @@ pub(crate) async fn script_specification(
34193421
RequirementsSpecification::from_excludes(requirements, constraints, Vec::new(), Vec::new());
34203422
specification.override_dependencies = overrides;
34213423
specification.excludes = excludes;
3422-
Ok(Some(specification))
3424+
Ok(specification)
34233425
}
34243426

34253427
/// Determine the extra build requires for a script.

‎crates/uv/src/commands/project/run.rs‎

Lines changed: 91 additions & 127 deletions
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,9 @@ use crate::commands::project::lock::LockMode;
7272
use crate::commands::project::lock_target::LockTarget;
7373
use crate::commands::project::{
7474
EnvironmentSpecification, LinkErrorReporting, PreferenceLocation, ProjectEnvironment,
75-
ProjectError, ScriptEnvironment, ScriptInterpreter, UniversalState, WorkspacePython,
76-
default_dependency_groups, script_extra_build_requires, script_specification,
77-
update_environment, validate_project_requires_python,
75+
ProjectError, ScriptEnvironment, UniversalState, WorkspacePython, default_dependency_groups,
76+
script_extra_build_requires, script_specification, update_environment,
77+
validate_project_requires_python,
7878
};
7979
use crate::commands::reporters::PythonDownloadReporter;
8080
use crate::commands::{ExitStatus, diagnostics, project, read_env_files};
@@ -178,7 +178,6 @@ pub(crate) async fn run(
178178
let mut base_lock: Option<(Lock, PathBuf)> = None;
179179

180180
// Determine whether the command to execute is a PEP 723 script.
181-
let temp_dir;
182181
let script_interpreter = if let Some(script) = script {
183182
match &script {
184183
Pep723Item::Script(script) => {
@@ -361,140 +360,105 @@ pub(crate) async fn run(
361360
}
362361
}
363362

364-
// Install the script requirements, if necessary. Otherwise, use an isolated environment.
365-
if let Some(spec) = script_specification(
363+
// Install the script requirements, if necessary.
364+
let spec = script_specification(
365+
(&script).into(),
366+
&settings.resolver,
367+
&cache,
368+
workspace_cache,
369+
client_builder.credentials_cache(),
370+
)
371+
.await?;
372+
let script_extra_build_requires = script_extra_build_requires(
366373
(&script).into(),
367374
&settings.resolver,
368375
&cache,
369376
workspace_cache,
370377
client_builder.credentials_cache(),
371378
)
372379
.await?
373-
{
374-
let script_extra_build_requires = script_extra_build_requires(
375-
(&script).into(),
376-
&settings.resolver,
377-
&cache,
378-
workspace_cache,
379-
client_builder.credentials_cache(),
380-
)
381-
.await?
382-
.into_inner();
383-
let environment = ScriptEnvironment::get_or_init(
384-
(&script).into(),
385-
python.as_deref().map(PythonRequest::parse),
386-
&client_builder,
387-
python_preference,
388-
python_downloads,
389-
&install_mirrors,
390-
no_sync,
391-
config_discovery,
392-
active.map_or(Some(false), Some),
393-
&cache,
394-
DryRun::Disabled,
395-
printer,
396-
)
397-
.await?
398-
.into_environment()?;
380+
.into_inner();
381+
let environment = ScriptEnvironment::get_or_init(
382+
(&script).into(),
383+
python.as_deref().map(PythonRequest::parse),
384+
&client_builder,
385+
python_preference,
386+
python_downloads,
387+
&install_mirrors,
388+
no_sync,
389+
config_discovery,
390+
active.map_or(Some(false), Some),
391+
&cache,
392+
DryRun::Disabled,
393+
printer,
394+
)
395+
.await?
396+
.into_environment()?;
399397

400-
let build_constraints = script
401-
.metadata()
402-
.tool
403-
.as_ref()
404-
.and_then(|tool| {
405-
tool.uv
406-
.as_ref()
407-
.and_then(|uv| uv.build_constraint_dependencies.as_ref())
408-
})
409-
.map(|constraints| {
410-
Constraints::from_requirements(
411-
constraints
412-
.iter()
413-
.map(|constraint| Requirement::from(constraint.clone())),
414-
)
415-
});
416-
417-
let _lock = environment
418-
.lock()
419-
.await
420-
.inspect_err(|err| {
421-
warn!("Failed to acquire environment lock: {err}");
422-
})
423-
.ok();
398+
let build_constraints = script
399+
.metadata()
400+
.tool
401+
.as_ref()
402+
.and_then(|tool| {
403+
tool.uv
404+
.as_ref()
405+
.and_then(|uv| uv.build_constraint_dependencies.as_ref())
406+
})
407+
.map(|constraints| {
408+
Constraints::from_requirements(
409+
constraints
410+
.iter()
411+
.map(|constraint| Requirement::from(constraint.clone())),
412+
)
413+
});
424414

425-
match update_environment(
426-
environment,
427-
spec,
428-
modifications,
429-
python_platform.as_ref(),
430-
SourceTreeEditablePolicy::Project,
431-
build_constraints.unwrap_or_default(),
432-
script_extra_build_requires,
433-
&settings,
434-
&client_builder,
435-
&sync_state,
436-
if show_resolution {
437-
Box::new(DefaultResolveLogger)
438-
} else {
439-
Box::new(SummaryResolveLogger)
440-
},
441-
if show_resolution {
442-
Box::new(DefaultInstallLogger)
443-
} else {
444-
Box::new(SummaryInstallLogger)
445-
},
446-
installer_metadata,
447-
&concurrency,
448-
&cache,
449-
workspace_cache,
450-
DryRun::Disabled,
451-
printer,
452-
preview,
453-
)
415+
let _lock = environment
416+
.lock()
454417
.await
455-
{
456-
Ok(update) => Some(update.into_environment().into_interpreter()),
457-
Err(ProjectError::Operation(err)) => {
458-
return diagnostics::OperationDiagnostic::default()
459-
.with_context("script")
460-
.report(err)
461-
.map_or(Ok(ExitStatus::Failure), |err| Err(err.into()));
462-
}
463-
Err(err) => return Err(err.into()),
464-
}
465-
} else {
466-
// Create a virtual environment.
467-
let interpreter = ScriptInterpreter::discover(
468-
(&script).into(),
469-
python.as_deref().map(PythonRequest::parse),
470-
&client_builder,
471-
python_preference,
472-
python_downloads,
473-
&install_mirrors,
474-
no_sync,
475-
config_discovery,
476-
active.map_or(Some(false), Some),
477-
&cache,
478-
printer,
479-
)
480-
.await?
481-
.into_interpreter();
482-
483-
temp_dir = cache.venv_dir()?;
484-
let environment = uv_virtualenv::create_venv(
485-
temp_dir.path(),
486-
interpreter,
487-
uv_virtualenv::Prompt::None,
488-
false,
489-
uv_virtualenv::OnExisting::Remove(
490-
uv_virtualenv::RemovalReason::TemporaryEnvironment,
491-
),
492-
false,
493-
uv_virtualenv::Seed::Disabled,
494-
false,
495-
)?;
418+
.inspect_err(|err| {
419+
warn!("Failed to acquire environment lock: {err}");
420+
})
421+
.ok();
496422

497-
Some(environment.into_interpreter())
423+
match update_environment(
424+
environment,
425+
spec,
426+
modifications,
427+
python_platform.as_ref(),
428+
SourceTreeEditablePolicy::Project,
429+
build_constraints.unwrap_or_default(),
430+
script_extra_build_requires,
431+
&settings,
432+
&client_builder,
433+
&sync_state,
434+
if show_resolution {
435+
Box::new(DefaultResolveLogger)
436+
} else {
437+
Box::new(SummaryResolveLogger)
438+
},
439+
if show_resolution {
440+
Box::new(DefaultInstallLogger)
441+
} else {
442+
Box::new(SummaryInstallLogger)
443+
},
444+
installer_metadata,
445+
&concurrency,
446+
&cache,
447+
workspace_cache,
448+
DryRun::Disabled,
449+
printer,
450+
preview,
451+
)
452+
.await
453+
{
454+
Ok(update) => Some(update.into_environment().into_interpreter()),
455+
Err(ProjectError::Operation(err)) => {
456+
return diagnostics::OperationDiagnostic::default()
457+
.with_context("script")
458+
.report(err)
459+
.map_or(Ok(ExitStatus::Failure), |err| Err(err.into()));
460+
}
461+
Err(err) => return Err(err.into()),
498462
}
499463
}
500464
} else {

‎crates/uv/src/commands/project/sync.rs‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -248,8 +248,7 @@ pub(crate) async fn sync(
248248
workspace_cache,
249249
client_builder.credentials_cache(),
250250
)
251-
.await?
252-
.unwrap_or_default();
251+
.await?;
253252
let script_extra_build_requires = script_extra_build_requires(
254253
script.into(),
255254
&settings.resolver,

‎crates/uv/tests/project/run.rs‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -382,13 +382,16 @@ fn run_pep723_script() -> Result<()> {
382382
Checked 4 packages in [TIME]
383383
");
384384

385-
// If the script contains a PEP 723 tag, it can omit the dependencies field.
385+
// Omitting the dependencies field should retain previously installed script requirements,
386+
// just like an empty dependency list.
386387
let test_script = context.temp_dir.child("main.py");
387388
test_script.write_str(indoc! { r#"
388389
# /// script
389390
# requires-python = ">=3.11"
390391
# ///
391392
393+
import iniconfig
394+
392395
print("Hello, world!")
393396
"#
394397
})?;
@@ -501,6 +504,42 @@ fn run_pep723_script() -> Result<()> {
501504
Ok(())
502505
}
503506

507+
/// Omitting dependencies should use the cached or explicitly requested active environment.
508+
#[test]
509+
fn run_pep723_script_without_dependencies() -> Result<()> {
510+
let context = uv_test::test_context!("3.12");
511+
context.temp_dir.child("main.py").write_str(indoc! { r#"
512+
# /// script
513+
# requires-python = ">=3.12"
514+
# ///
515+
516+
import sys
517+
518+
print(sys.prefix)
519+
"#
520+
})?;
521+
522+
uv_snapshot!(context.filters(), context.run().arg("main.py"), @"
523+
exit_code: 0 (success)
524+
----- stdout -----
525+
[CACHE_DIR]/environments-v2/main-[HASH]
526+
");
527+
528+
uv_snapshot!(context.filters(), context.run().arg("--active").arg("--no-sync").arg("main.py")
529+
.env(EnvVars::VIRTUAL_ENV, "active"), @"
530+
exit_code: 0 (success)
531+
----- stdout -----
532+
[TEMP_DIR]/active
533+
534+
----- stderr -----
535+
warning: `--no-sync` is a no-op for Python scripts with inline metadata, which always run in isolation
536+
");
537+
538+
assert!(!context.temp_dir.child("main.py.lock").exists());
539+
540+
Ok(())
541+
}
542+
504543
#[test]
505544
fn run_pep723_script_empty_dependency() -> Result<()> {
506545
let context = uv_test::test_context!("3.12");

0 commit comments

Comments
 (0)
⌂ 换网址