Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add --script support to uv export for PEP 723 scripts #10160

Merged
merged 1 commit into from
Jan 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions crates/uv-cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3651,6 +3651,14 @@ pub struct ExportArgs {
#[command(flatten)]
pub refresh: RefreshArgs,

/// Export the dependencies for the specified PEP 723 Python script, rather than the current
/// project.
///
/// If provided, uv will resolve the dependencies based on its inline metadata table, in
/// adherence with PEP 723.
#[arg(long, conflicts_with_all = ["all_packages", "package", "no_emit_project", "no_emit_workspace"])]
pub script: Option<PathBuf>,

/// The Python interpreter to use during resolution.
///
/// A Python interpreter is required for building source distributions to
Expand Down
4 changes: 2 additions & 2 deletions crates/uv/src/commands/project/add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1003,8 +1003,8 @@ enum AddTarget {
impl<'lock> From<&'lock AddTarget> for LockTarget<'lock> {
fn from(value: &'lock AddTarget) -> Self {
match value {
AddTarget::Script(script, _) => LockTarget::Script(script),
AddTarget::Project(project, _) => LockTarget::Workspace(project.workspace()),
AddTarget::Script(script, _) => Self::Script(script),
AddTarget::Project(project, _) => Self::Workspace(project.workspace()),
}
}
}
Expand Down
161 changes: 110 additions & 51 deletions crates/uv/src/commands/project/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,39 @@ use uv_dispatch::SharedState;
use uv_normalize::PackageName;
use uv_python::{PythonDownloads, PythonPreference, PythonRequest};
use uv_resolver::RequirementsTxtExport;
use uv_scripts::{Pep723ItemRef, Pep723Script};
use uv_workspace::{DiscoveryOptions, MemberDiscovery, VirtualProject, Workspace};

use crate::commands::pip::loggers::DefaultResolveLogger;
use crate::commands::project::install_target::InstallTarget;
use crate::commands::project::lock::{do_safe_lock, LockMode};
use crate::commands::project::lock_target::LockTarget;
use crate::commands::project::{
default_dependency_groups, detect_conflicts, DependencyGroupsTarget, ProjectError,
ProjectInterpreter,
ProjectInterpreter, ScriptInterpreter,
};
use crate::commands::{diagnostics, ExitStatus, OutputWriter};
use crate::printer::Printer;
use crate::settings::ResolverSettings;

#[derive(Debug, Clone)]
enum ExportTarget {
/// A PEP 723 script, with inline metadata.
Script(Pep723Script),

/// A project with a `pyproject.toml`.
Project(VirtualProject),
}

impl<'lock> From<&'lock ExportTarget> for LockTarget<'lock> {
fn from(value: &'lock ExportTarget) -> Self {
match value {
ExportTarget::Script(script) => Self::Script(script),
ExportTarget::Project(project) => Self::Workspace(project.workspace()),
}
}
}

/// Export the project's `uv.lock` in an alternate format.
#[allow(clippy::fn_params_excessive_bools)]
pub(crate) async fn export(
Expand All @@ -46,6 +66,7 @@ pub(crate) async fn export(
locked: bool,
frozen: bool,
include_header: bool,
script: Option<Pep723Script>,
python: Option<String>,
install_mirrors: PythonInstallMirrors,
settings: ResolverSettings,
Expand All @@ -61,74 +82,108 @@ pub(crate) async fn export(
printer: Printer,
preview: PreviewMode,
) -> Result<ExitStatus> {
// Identify the project.
let project = if frozen {
VirtualProject::discover(
project_dir,
&DiscoveryOptions {
members: MemberDiscovery::None,
..DiscoveryOptions::default()
},
)
.await?
} else if let Some(package) = package.as_ref() {
VirtualProject::Project(
Workspace::discover(project_dir, &DiscoveryOptions::default())
.await?
.with_current_project(package.clone())
.with_context(|| format!("Package `{package}` not found in workspace"))?,
)
// Identify the target.
let target = if let Some(script) = script {
ExportTarget::Script(script)
} else {
VirtualProject::discover(project_dir, &DiscoveryOptions::default()).await?
let project = if frozen {
VirtualProject::discover(
project_dir,
&DiscoveryOptions {
members: MemberDiscovery::None,
..DiscoveryOptions::default()
},
)
.await?
} else if let Some(package) = package.as_ref() {
VirtualProject::Project(
Workspace::discover(project_dir, &DiscoveryOptions::default())
.await?
.with_current_project(package.clone())
.with_context(|| format!("Package `{package}` not found in workspace"))?,
)
} else {
VirtualProject::discover(project_dir, &DiscoveryOptions::default()).await?
};
ExportTarget::Project(project)
};

// Validate that any referenced dependency groups are defined in the workspace.
if !frozen {
let target = match &project {
VirtualProject::Project(project) => {
let target = match &target {
ExportTarget::Project(VirtualProject::Project(project)) => {
if all_packages {
DependencyGroupsTarget::Workspace(project.workspace())
} else {
DependencyGroupsTarget::Project(project)
}
}
VirtualProject::NonProject(workspace) => DependencyGroupsTarget::Workspace(workspace),
ExportTarget::Project(VirtualProject::NonProject(workspace)) => {
DependencyGroupsTarget::Workspace(workspace)
}
ExportTarget::Script(_) => DependencyGroupsTarget::Script,
};
target.validate(&dev)?;
}

// Determine the default groups to include.
let defaults = default_dependency_groups(project.pyproject_toml())?;
let defaults = match &target {
ExportTarget::Project(project) => default_dependency_groups(project.pyproject_toml())?,
ExportTarget::Script(_) => vec![],
};
let dev = dev.with_defaults(defaults);

// Find an interpreter for the project, unless `--frozen` is set.
let interpreter = if frozen {
None
} else {
Some(match &target {
ExportTarget::Script(script) => ScriptInterpreter::discover(
Pep723ItemRef::Script(script),
python.as_deref().map(PythonRequest::parse),
python_preference,
python_downloads,
connectivity,
native_tls,
allow_insecure_host,
&install_mirrors,
no_config,
cache,
printer,
)
.await?
.into_interpreter(),
ExportTarget::Project(project) => ProjectInterpreter::discover(
project.workspace(),
project_dir,
python.as_deref().map(PythonRequest::parse),
python_preference,
python_downloads,
connectivity,
native_tls,
allow_insecure_host,
&install_mirrors,
no_config,
cache,
printer,
)
.await?
.into_interpreter(),
})
};

// Determine the lock mode.
let interpreter;
let mode = if frozen {
LockMode::Frozen
} else if locked {
LockMode::Locked(interpreter.as_ref().unwrap())
} else if matches!(target, ExportTarget::Script(_))
&& !LockTarget::from(&target).lock_path().is_file()
{
// If we're locking a script, avoid creating a lockfile if it doesn't already exist.
LockMode::DryRun(interpreter.as_ref().unwrap())
} else {
// Find an interpreter for the project
interpreter = ProjectInterpreter::discover(
project.workspace(),
project_dir,
python.as_deref().map(PythonRequest::parse),
python_preference,
python_downloads,
connectivity,
native_tls,
allow_insecure_host,
&install_mirrors,
no_config,
cache,
printer,
)
.await?
.into_interpreter();

if locked {
LockMode::Locked(&interpreter)
} else {
LockMode::Write(&interpreter)
}
LockMode::Write(interpreter.as_ref().unwrap())
};

// Initialize any shared state.
Expand All @@ -137,7 +192,7 @@ pub(crate) async fn export(
// Lock the project.
let lock = match do_safe_lock(
mode,
project.workspace().into(),
(&target).into(),
settings.as_ref(),
LowerBound::Warn,
&state,
Expand Down Expand Up @@ -165,8 +220,8 @@ pub(crate) async fn export(
detect_conflicts(&lock, &extras, &dev)?;

// Identify the installation target.
let target = match &project {
VirtualProject::Project(project) => {
let target = match &target {
ExportTarget::Project(VirtualProject::Project(project)) => {
if all_packages {
InstallTarget::Workspace {
workspace: project.workspace(),
Expand All @@ -187,7 +242,7 @@ pub(crate) async fn export(
}
}
}
VirtualProject::NonProject(workspace) => {
ExportTarget::Project(VirtualProject::NonProject(workspace)) => {
if all_packages {
InstallTarget::NonProjectWorkspace {
workspace,
Expand All @@ -207,6 +262,10 @@ pub(crate) async fn export(
}
}
}
ExportTarget::Script(script) => InstallTarget::Script {
script,
lock: &lock,
},
};

// Write the resolved dependencies to the output channel.
Expand Down
14 changes: 14 additions & 0 deletions crates/uv/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,12 @@ async fn run(mut cli: Cli) -> Result<ExitStatus> {
script: Some(script),
..
}) = &**command
{
Pep723Script::read(&script).await?.map(Pep723Item::Script)
} else if let ProjectCommand::Export(uv_cli::ExportArgs {
script: Some(script),
..
}) = &**command
{
Pep723Script::read(&script).await?.map(Pep723Item::Script)
} else {
Expand Down Expand Up @@ -1704,6 +1710,13 @@ async fn run_project(
// Initialize the cache.
let cache = cache.init()?;

// Unwrap the script.
let script = script.map(|script| match script {
Pep723Item::Script(script) => script,
Pep723Item::Stdin(_) => unreachable!("`uv export` does not support stdin"),
Pep723Item::Remote(_) => unreachable!("`uv export` does not support remote files"),
});

commands::export(
project_dir,
args.format,
Expand All @@ -1719,6 +1732,7 @@ async fn run_project(
args.locked,
args.frozen,
args.include_header,
script,
args.python,
args.install_mirrors,
args.settings,
Expand Down
3 changes: 3 additions & 0 deletions crates/uv/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1369,6 +1369,7 @@ pub(crate) struct ExportSettings {
pub(crate) locked: bool,
pub(crate) frozen: bool,
pub(crate) include_header: bool,
pub(crate) script: Option<PathBuf>,
pub(crate) python: Option<String>,
pub(crate) install_mirrors: PythonInstallMirrors,
pub(crate) refresh: Refresh,
Expand Down Expand Up @@ -1409,6 +1410,7 @@ impl ExportSettings {
resolver,
build,
refresh,
script,
python,
} = args;
let install_mirrors = filesystem
Expand Down Expand Up @@ -1440,6 +1442,7 @@ impl ExportSettings {
locked,
frozen,
include_header: flag(header, no_header).unwrap_or(true),
script,
python: python.and_then(Maybe::into_option),
refresh: Refresh::from(refresh),
settings: ResolverSettings::combine(resolver_options(resolver, build), filesystem),
Expand Down
Loading
Loading