Skip to content

Commit 298dda4

Browse files
kowanietzEliteTK
andauthored
Fix relative indexes in PEP 723 scripts (#21097)
## Summary Relative indexes in PEP 723 scripts were resolved against the current working directory instead of the script's directory, so a script could work when ran from its own directory but fail when ran from elsewhere. This change resolves inline indexes relative to the script and also makes `uv add --script` write index paths relative to the script. It also applies the same behavior to extra build dependencies Fixes #21096 ## Test Plan - Added an offline regression test that runs a script with a relative index from another directory - Ran the focused project and sync tests - Ran Clippy and rustfmt --------- Co-authored-by: Tomasz (Tom) Kramkowski <[email protected]>
1 parent 0f98c5d commit 298dda4

6 files changed

Lines changed: 101 additions & 16 deletions

File tree

‎crates/uv-settings/src/lib.rs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use tracing::info_span;
77
use uv_client::{DEFAULT_CONNECT_TIMEOUT, DEFAULT_READ_TIMEOUT, DEFAULT_READ_TIMEOUT_UPLOAD};
88
use uv_configuration::RequiredVersion;
99
use uv_dirs::{system_config_file, user_config_dir};
10-
use uv_distribution_types::Origin;
10+
use uv_distribution_types::{IndexUrlError, Origin};
1111
use uv_flags::EnvironmentFlags;
1212
use uv_fs::Simplified;
1313
use uv_normalize::{GroupName, PackageName};
@@ -32,6 +32,11 @@ impl FilesystemOptions {
3232
pub fn into_options(self) -> Options {
3333
self.0
3434
}
35+
36+
/// Resolve the [`FilesystemOptions`] relative to the given root directory.
37+
pub fn relative_to(self, root_dir: &Path) -> Result<Self, IndexUrlError> {
38+
Ok(Self(self.0.relative_to(root_dir)?))
39+
}
3540
}
3641

3742
impl Deref for FilesystemOptions {

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ use uv_distribution_types::{
2626
Identifier, Index, IndexLocations, IndexName, IndexUrl, NameRequirementSpecification,
2727
Requirement, RequirementSource, UnresolvedRequirement,
2828
};
29-
use uv_fs::{CWD, LockedFile, LockedFileError, Simplified};
29+
use uv_fs::{LockedFile, LockedFileError, Simplified};
3030
use uv_git::store_credentials;
3131
use uv_normalize::{DEV_DEPENDENCIES, DefaultExtras, DefaultGroups, ExtraName, PackageName};
3232
use uv_pep508::{MarkerTree, VersionOrUrl};
@@ -695,7 +695,9 @@ pub(crate) async fn add(
695695
// Add any indexes that were provided on the command-line, in priority order.
696696
if !raw {
697697
let root_dir = match &target {
698-
AddTarget::Script(_, _) => CWD.as_path(),
698+
AddTarget::Script(script, _) => {
699+
script.path.parent().expect("script path has no parent")
700+
}
699701
AddTarget::Project(project, _) => project.root(),
700702
};
701703
let locations = IndexLocations::new(indexes, Vec::new(), false);

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

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use uv_dispatch::{BuildDispatch, SharedState};
2121
use uv_distribution::{DistributionDatabase, LoweredExtraBuildDependencies, LoweredRequirement};
2222
use uv_distribution_types::{
2323
ExtraBuildRequirement, ExtraBuildRequires, HashGeneration, Index, IndexCredentialsError,
24-
Requirement, RequiresPython, Resolution, UnresolvedRequirement,
24+
IndexUrlError, Requirement, RequiresPython, Resolution, UnresolvedRequirement,
2525
UnresolvedRequirementSpecification,
2626
};
2727
use uv_fs::{CWD, LockedFile, LockedFileError, LockedFileMode, Simplified, verbatim_path};
@@ -312,6 +312,9 @@ pub(crate) enum ProjectError {
312312
#[error(transparent)]
313313
IndexCredentials(#[from] IndexCredentialsError),
314314

315+
#[error(transparent)]
316+
IndexUrl(#[from] IndexUrlError),
317+
315318
#[error(transparent)]
316319
Python(#[from] uv_python::Error),
317320

@@ -3340,7 +3343,12 @@ pub(crate) async fn script_specification(
33403343
};
33413344

33423345
let script_dir = script.directory()?;
3343-
let script_indexes = script.indexes(&settings.sources);
3346+
let script_indexes = script
3347+
.indexes(&settings.sources)
3348+
.iter()
3349+
.cloned()
3350+
.map(|index| index.relative_to(&script_dir))
3351+
.collect::<Result<Vec<_>, _>>()?;
33443352
let script_sources = script.sources(&settings.sources);
33453353

33463354
let mut requirements = Vec::new();
@@ -3350,7 +3358,7 @@ pub(crate) async fn script_specification(
33503358
requirement,
33513359
script_dir.as_ref(),
33523360
script_sources.as_ref(),
3353-
script_indexes,
3361+
&script_indexes,
33543362
&settings.index_locations,
33553363
cache,
33563364
workspace_cache,
@@ -3377,7 +3385,7 @@ pub(crate) async fn script_specification(
33773385
requirement,
33783386
script_dir.as_ref(),
33793387
script_sources.as_ref(),
3380-
script_indexes,
3388+
&script_indexes,
33813389
&settings.index_locations,
33823390
cache,
33833391
workspace_cache,
@@ -3407,7 +3415,7 @@ pub(crate) async fn script_specification(
34073415
requirement,
34083416
script_dir.as_ref(),
34093417
script_sources.as_ref(),
3410-
script_indexes,
3418+
&script_indexes,
34113419
&settings.index_locations,
34123420
cache,
34133421
workspace_cache,
@@ -3427,7 +3435,7 @@ pub(crate) async fn script_specification(
34273435
requirement,
34283436
script_dir.as_ref(),
34293437
script_sources.as_ref(),
3430-
script_indexes,
3438+
&script_indexes,
34313439
&settings.index_locations,
34323440
cache,
34333441
workspace_cache,
@@ -3474,7 +3482,12 @@ pub(crate) async fn script_extra_build_requires(
34743482
credentials_cache: &CredentialsCache,
34753483
) -> Result<LoweredExtraBuildDependencies, ProjectError> {
34763484
let script_dir = script.directory()?;
3477-
let script_indexes = script.indexes(&settings.sources);
3485+
let script_indexes = script
3486+
.indexes(&settings.sources)
3487+
.iter()
3488+
.cloned()
3489+
.map(|index| index.relative_to(&script_dir))
3490+
.collect::<Result<Vec<_>, _>>()?;
34783491
let script_sources = script.sources(&settings.sources);
34793492

34803493
// Collect any `tool.uv.extra-build-dependencies` from the script.
@@ -3501,7 +3514,7 @@ pub(crate) async fn script_extra_build_requires(
35013514
requirement,
35023515
script_dir.as_ref(),
35033516
script_sources.as_ref(),
3504-
script_indexes,
3517+
&script_indexes,
35053518
&settings.index_locations,
35063519
cache,
35073520
workspace_cache,

‎crates/uv/src/lib.rs‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -487,14 +487,22 @@ async fn run_with_workspace_cache(
487487
};
488488

489489
// If the target is a PEP 723 script, merge the metadata into the filesystem metadata.
490-
let filesystem = script
490+
let script_filesystem = script
491491
.as_ref()
492492
.map(Pep723Item::metadata)
493493
.and_then(|metadata| metadata.tool.as_ref())
494494
.and_then(|tool| tool.uv.as_ref())
495495
.map(|uv| Options::simple(uv.globals.clone(), uv.top_level.clone()))
496-
.map(FilesystemOptions::from)
497-
.combine(filesystem);
496+
.map(FilesystemOptions::from);
497+
let script_filesystem = if let Some(Pep723Item::Script(script)) = script.as_ref() {
498+
let script_dir = script.path.parent().expect("script path has no parent");
499+
script_filesystem
500+
.map(|options| options.relative_to(script_dir))
501+
.transpose()?
502+
} else {
503+
script_filesystem
504+
};
505+
let filesystem = script_filesystem.combine(filesystem);
498506

499507
let custom_certificate_file = match &*cli.command {
500508
Commands::Pip(PipNamespace { cert, .. }) => cert.as_deref(),

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10866,7 +10866,7 @@ fn add_index_with_existing_relative_path_in_script() -> Result<()> {
1086610866
#
1086710867
# [[tool.uv.index]]
1086810868
# name = "local"
10869-
# url = "./links"
10869+
# url = "../links"
1087010870
# format = "flat"
1087110871
# ///
1087210872
"#})?;
@@ -10897,7 +10897,7 @@ fn add_index_with_existing_relative_path_in_script() -> Result<()> {
1089710897
#
1089810898
# [[tool.uv.index]]
1089910899
# name = "local"
10900-
# url = "links"
10900+
# url = "../links"
1090110901
# format = "flat"
1090210902
#
1090310903
# [tool.uv.sources]

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

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -813,6 +813,63 @@ fn run_pep723_script_index() -> Result<()> {
813813
Ok(())
814814
}
815815

816+
/// Run a PEP 723-compatible script with a relative index and pinned and unpinned dependencies.
817+
#[test]
818+
fn run_pep723_script_relative_index() -> Result<()> {
819+
let context = uv_test::test_context!("3.12");
820+
821+
let scripts = context.temp_dir.child("scripts");
822+
let links = scripts.child("links");
823+
links.create_dir_all()?;
824+
fs_err::copy(
825+
context
826+
.workspace_root
827+
.join("test/links/ok-1.0.0-py3-none-any.whl"),
828+
links.child("ok-1.0.0-py3-none-any.whl"),
829+
)?;
830+
fs_err::copy(
831+
context
832+
.workspace_root
833+
.join("test/links/validation-1.0.0-py3-none-any.whl"),
834+
links.child("validation-1.0.0-py3-none-any.whl"),
835+
)?;
836+
837+
let test_script = scripts.child("main.py");
838+
test_script.write_str(indoc! { r#"
839+
# /// script
840+
# requires-python = ">=3.11"
841+
# dependencies = ["ok", "validation"]
842+
#
843+
# [[tool.uv.index]]
844+
# name = "local"
845+
# url = "./links"
846+
# format = "flat"
847+
#
848+
# [tool.uv.sources]
849+
# ok = { index = "local" }
850+
# ///
851+
852+
import ok
853+
import validation
854+
"#
855+
})?;
856+
857+
let elsewhere = context.temp_dir.child("elsewhere");
858+
elsewhere.create_dir_all()?;
859+
860+
uv_snapshot!(context.filters(), context.run().current_dir(elsewhere).arg("--offline").arg(test_script.path()), @r"
861+
exit_code: 0 (success)
862+
----- stderr -----
863+
Resolved 2 packages in [TIME]
864+
Prepared 2 packages in [TIME]
865+
Installed 2 packages in [TIME]
866+
+ ok==1.0.0
867+
+ validation==1.0.0
868+
");
869+
870+
Ok(())
871+
}
872+
816873
/// Package-scoped source disabling must not discard unrelated script sources or indexes.
817874
#[test]
818875
fn run_pep723_script_no_sources_package() -> Result<()> {

0 commit comments

Comments
 (0)