-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathrun.rs
790 lines (720 loc) · 27.4 KB
/
run.rs
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::fmt::Write;
use std::path::{Path, PathBuf};
use anstream::eprint;
use anyhow::{anyhow, bail, Context};
use itertools::Itertools;
use owo_colors::OwoColorize;
use tokio::process::Command;
use tracing::debug;
use uv_cache::Cache;
use uv_cli::ExternalCommand;
use uv_client::{BaseClientBuilder, Connectivity};
use uv_configuration::{Concurrency, ExtrasSpecification};
use uv_distribution::LoweredRequirement;
use uv_fs::{PythonExt, Simplified, CWD};
use uv_installer::{SatisfiesResult, SitePackages};
use uv_normalize::PackageName;
use uv_python::{
request_from_version_file, EnvironmentPreference, Interpreter, PythonDownloads,
PythonEnvironment, PythonInstallation, PythonPreference, PythonRequest, VersionRequest,
};
use uv_requirements::{RequirementsSource, RequirementsSpecification};
use uv_scripts::{Pep723Error, Pep723Script};
use uv_warnings::warn_user_once;
use uv_workspace::{DiscoveryOptions, VirtualProject, Workspace, WorkspaceError};
use crate::commands::pip::loggers::{
DefaultInstallLogger, DefaultResolveLogger, SummaryInstallLogger, SummaryResolveLogger,
};
use crate::commands::pip::operations;
use crate::commands::pip::operations::Modifications;
use crate::commands::project::environment::CachedEnvironment;
use crate::commands::project::{ProjectError, WorkspacePython};
use crate::commands::reporters::PythonDownloadReporter;
use crate::commands::{project, ExitStatus, SharedState};
use crate::printer::Printer;
use crate::settings::ResolverInstallerSettings;
/// Run a command.
#[allow(clippy::fn_params_excessive_bools)]
pub(crate) async fn run(
script: Option<Pep723Script>,
command: ExternalCommand,
requirements: Vec<RequirementsSource>,
show_resolution: bool,
locked: bool,
frozen: bool,
isolated: bool,
package: Option<PackageName>,
no_project: bool,
extras: ExtrasSpecification,
dev: bool,
python: Option<String>,
settings: ResolverInstallerSettings,
python_preference: PythonPreference,
python_downloads: PythonDownloads,
connectivity: Connectivity,
concurrency: Concurrency,
native_tls: bool,
cache: &Cache,
printer: Printer,
) -> anyhow::Result<ExitStatus> {
// These cases seem quite complex because (in theory) they should change the "current package".
// Let's ban them entirely for now.
for source in &requirements {
match source {
RequirementsSource::PyprojectToml(_) => {
bail!("Adding requirements from a `pyproject.toml` is not supported in `uv run`");
}
RequirementsSource::SetupPy(_) => {
bail!("Adding requirements from a `setup.py` is not supported in `uv run`");
}
RequirementsSource::SetupCfg(_) => {
bail!("Adding requirements from a `setup.cfg` is not supported in `uv run`");
}
RequirementsSource::RequirementsTxt(path) => {
if path == Path::new("-") {
bail!("Reading requirements from stdin is not supported in `uv run`");
}
}
_ => {}
}
}
// Parse the input command.
let command = RunCommand::from(&command);
// Initialize any shared state.
let state = SharedState::default();
// Initialize any output reporters.
let download_reporter = PythonDownloadReporter::single(printer);
// Determine whether the command to execute is a PEP 723 script.
let temp_dir;
let script_interpreter = if let Some(script) = script {
writeln!(
printer.stderr(),
"Reading inline script metadata from: {}",
script.path.user_display().cyan()
)?;
// (1) Explicit request from user
let python_request = if let Some(request) = python.as_deref() {
Some(PythonRequest::parse(request))
// (2) Request from `.python-version`
} else if let Some(request) = request_from_version_file(&CWD).await? {
Some(request)
// (3) `Requires-Python` in `pyproject.toml`
} else {
script.metadata.requires_python.map(|requires_python| {
PythonRequest::Version(VersionRequest::Range(requires_python))
})
};
let client_builder = BaseClientBuilder::new()
.connectivity(connectivity)
.native_tls(native_tls);
let interpreter = PythonInstallation::find_or_download(
python_request,
EnvironmentPreference::Any,
python_preference,
python_downloads,
&client_builder,
cache,
Some(&download_reporter),
)
.await?
.into_interpreter();
// Install the script requirements, if necessary. Otherwise, use an isolated environment.
if let Some(dependencies) = script.metadata.dependencies {
// // Collect any `tool.uv.sources` from the script.
let empty = BTreeMap::default();
let script_sources = script
.metadata
.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.sources.as_ref())
.unwrap_or(&empty);
let script_dir = script.path.parent().expect("script path has no parent");
let requirements = dependencies
.into_iter()
.map(|requirement| {
LoweredRequirement::from_non_workspace_requirement(
requirement,
script_dir,
script_sources,
)
.map(LoweredRequirement::into_inner)
})
.collect::<Result<_, _>>()?;
let spec = RequirementsSpecification::from_requirements(requirements);
let result = CachedEnvironment::get_or_create(
spec,
interpreter,
&settings,
&state,
if show_resolution {
Box::new(DefaultResolveLogger)
} else {
Box::new(SummaryResolveLogger)
},
if show_resolution {
Box::new(DefaultInstallLogger)
} else {
Box::new(SummaryInstallLogger)
},
connectivity,
concurrency,
native_tls,
cache,
printer,
)
.await;
let environment = match result {
Ok(resolution) => resolution,
Err(ProjectError::Operation(operations::Error::Resolve(
uv_resolver::ResolveError::NoSolution(err),
))) => {
let report = miette::Report::msg(format!("{err}"))
.context(err.header().with_context("script"));
eprint!("{report:?}");
return Ok(ExitStatus::Failure);
}
Err(err) => return Err(err.into()),
};
Some(environment.into_interpreter())
} else {
// Create a virtual environment.
temp_dir = cache.environment()?;
let environment = uv_virtualenv::create_venv(
temp_dir.path(),
interpreter,
uv_virtualenv::Prompt::None,
false,
false,
false,
)?;
Some(environment.into_interpreter())
}
} else {
None
};
// Discover and sync the base environment.
let temp_dir;
let base_interpreter = if let Some(script_interpreter) = script_interpreter {
// If we found a PEP 723 script and the user provided a project-only setting, warn.
if no_project {
debug!(
"`--no-project` is a no-op for Python scripts with inline metadata; ignoring..."
);
}
if !extras.is_empty() {
warn_user_once!("Extras are not supported for Python scripts with inline metadata");
}
if !dev {
warn_user_once!("`--no-dev` is not supported for Python scripts with inline metadata");
}
if package.is_some() {
warn_user_once!(
"`--package` is a no-op for Python scripts with inline metadata, which always run in isolation"
);
}
if locked {
warn_user_once!(
"`--locked` is a no-op for Python scripts with inline metadata, which always run in isolation"
);
}
if frozen {
warn_user_once!(
"`--frozen` is a no-op for Python scripts with inline metadata, which always run in isolation"
);
}
if isolated {
warn_user_once!(
"`--isolated` is a no-op for Python scripts with inline metadata, which always run in isolation"
);
}
script_interpreter
} else {
let project = if let Some(package) = package {
// We need a workspace, but we don't need to have a current package, we can be e.g. in
// the root of a virtual workspace and then switch into the selected package.
Some(VirtualProject::Project(
Workspace::discover(&CWD, &DiscoveryOptions::default())
.await?
.with_current_project(package.clone())
.with_context(|| format!("Package `{package}` not found in workspace"))?,
))
} else {
match VirtualProject::discover(&CWD, &DiscoveryOptions::default()).await {
Ok(project) => Some(project),
Err(WorkspaceError::MissingPyprojectToml) => None,
Err(WorkspaceError::NonWorkspace(_)) => None,
Err(err) => return Err(err.into()),
}
};
let project = if no_project {
// If the user runs with `--no-project` and we can't find a project, warn.
if project.is_none() {
debug!("`--no-project` was provided, but no project was found; ignoring...");
}
// If the user ran with `--no-project` and provided a project-only setting, warn.
if !extras.is_empty() {
warn_user_once!("Extras have no effect when used alongside `--no-project`");
}
if !dev {
warn_user_once!("`--no-dev` has no effect when used alongside `--no-project`");
}
if locked {
warn_user_once!("`--locked` has no effect when used alongside `--no-project`");
}
if frozen {
warn_user_once!("`--frozen` has no effect when used alongside `--no-project`");
}
None
} else {
// If we can't find a project and the user provided a project-only setting, warn.
if project.is_none() {
if !extras.is_empty() {
warn_user_once!("Extras have no effect when used outside of a project");
}
if !dev {
warn_user_once!("`--no-dev` has no effect when used outside of a project");
}
if locked {
warn_user_once!("`--locked` has no effect when used outside of a project");
}
if frozen {
warn_user_once!("`--frozen` has no effect when used outside of a project");
}
}
project
};
let interpreter = if let Some(project) = project {
if let Some(project_name) = project.project_name() {
debug!(
"Discovered project `{project_name}` at: {}",
project.workspace().install_path().display()
);
} else {
debug!(
"Discovered virtual workspace at: {}",
project.workspace().install_path().display()
);
}
let venv = if isolated {
debug!("Creating isolated virtual environment");
// If we're isolating the environment, use an ephemeral virtual environment as the
// base environment for the project.
let interpreter = {
let client_builder = BaseClientBuilder::new()
.connectivity(connectivity)
.native_tls(native_tls);
// Resolve the Python request and requirement for the workspace.
let WorkspacePython { python_request, .. } = WorkspacePython::from_request(
python.as_deref().map(PythonRequest::parse),
project.workspace(),
)
.await?;
PythonInstallation::find_or_download(
python_request,
EnvironmentPreference::Any,
python_preference,
python_downloads,
&client_builder,
cache,
Some(&download_reporter),
)
.await?
.into_interpreter()
};
// Create a virtual environment
temp_dir = cache.environment()?;
uv_virtualenv::create_venv(
temp_dir.path(),
interpreter,
uv_virtualenv::Prompt::None,
false,
false,
false,
)?
} else {
// If we're not isolating the environment, reuse the base environment for the
// project.
project::get_or_init_environment(
project.workspace(),
python.as_deref().map(PythonRequest::parse),
python_preference,
python_downloads,
connectivity,
native_tls,
cache,
printer,
)
.await?
};
let result = match project::lock::do_safe_lock(
locked,
frozen,
project.workspace(),
venv.interpreter(),
settings.as_ref().into(),
if show_resolution {
Box::new(DefaultResolveLogger)
} else {
Box::new(SummaryResolveLogger)
},
connectivity,
concurrency,
native_tls,
cache,
printer,
)
.await
{
Ok(result) => result,
Err(ProjectError::Operation(operations::Error::Resolve(
uv_resolver::ResolveError::NoSolution(err),
))) => {
let report = miette::Report::msg(format!("{err}")).context(err.header());
anstream::eprint!("{report:?}");
return Ok(ExitStatus::Failure);
}
Err(err) => return Err(err.into()),
};
project::sync::do_sync(
&project,
&venv,
result.lock(),
&extras,
dev,
Modifications::Sufficient,
settings.as_ref().into(),
&state,
if show_resolution {
Box::new(DefaultInstallLogger)
} else {
Box::new(SummaryInstallLogger)
},
connectivity,
concurrency,
native_tls,
cache,
printer,
)
.await?;
venv.into_interpreter()
} else {
debug!("No project found; searching for Python interpreter");
let interpreter = {
let client_builder = BaseClientBuilder::new()
.connectivity(connectivity)
.native_tls(native_tls);
let python = PythonInstallation::find_or_download(
python.as_deref().map(PythonRequest::parse),
// No opt-in is required for system environments, since we are not mutating it.
EnvironmentPreference::Any,
python_preference,
python_downloads,
&client_builder,
cache,
Some(&download_reporter),
)
.await?;
python.into_interpreter()
};
if isolated {
debug!("Creating isolated virtual environment");
// If we're isolating the environment, use an ephemeral virtual environment.
temp_dir = cache.environment()?;
let venv = uv_virtualenv::create_venv(
temp_dir.path(),
interpreter,
uv_virtualenv::Prompt::None,
false,
false,
false,
)?;
venv.into_interpreter()
} else {
interpreter
}
};
interpreter
};
debug!(
"Using Python {} interpreter at: {}",
base_interpreter.python_version(),
base_interpreter.sys_executable().display()
);
// Read the requirements.
let spec = if requirements.is_empty() {
None
} else {
let client_builder = BaseClientBuilder::new()
.connectivity(connectivity)
.native_tls(native_tls);
let spec =
RequirementsSpecification::from_simple_sources(&requirements, &client_builder).await?;
Some(spec)
};
// If necessary, create an environment for the ephemeral requirements or command.
let temp_dir;
let ephemeral_env = if can_skip_ephemeral(spec.as_ref(), &base_interpreter, &settings) {
None
} else {
debug!("Creating ephemeral environment");
Some(match spec.filter(|spec| !spec.is_empty()) {
None => {
// Create a virtual environment
temp_dir = cache.environment()?;
uv_virtualenv::create_venv(
temp_dir.path(),
base_interpreter.clone(),
uv_virtualenv::Prompt::None,
false,
false,
false,
)?
}
Some(spec) => {
debug!("Syncing ephemeral requirements");
let result = CachedEnvironment::get_or_create(
spec,
base_interpreter.clone(),
&settings,
&state,
if show_resolution {
Box::new(DefaultResolveLogger)
} else {
Box::new(SummaryResolveLogger)
},
if show_resolution {
Box::new(DefaultInstallLogger)
} else {
Box::new(SummaryInstallLogger)
},
connectivity,
concurrency,
native_tls,
cache,
printer,
)
.await;
let environment = match result {
Ok(resolution) => resolution,
Err(ProjectError::Operation(operations::Error::Resolve(
uv_resolver::ResolveError::NoSolution(err),
))) => {
let report = miette::Report::msg(format!("{err}"))
.context(err.header().with_context("`--with`"));
eprint!("{report:?}");
return Ok(ExitStatus::Failure);
}
Err(ProjectError::Operation(operations::Error::Named(err))) => {
let err = miette::Report::msg(format!("{err}"))
.context("Invalid `--with` requirement");
eprint!("{err:?}");
return Ok(ExitStatus::Failure);
}
Err(err) => {
return Err(err.into());
}
};
environment.into()
}
})
};
// If we're running in an ephemeral environment, add a `sitecustomize.py` to enable loading of
// the base environment's site packages. Setting `PYTHONPATH` is insufficient, as it doesn't
// resolve `.pth` files in the base environment.
if let Some(ephemeral_env) = ephemeral_env.as_ref() {
let ephemeral_site_packages = ephemeral_env
.site_packages()
.next()
.ok_or_else(|| anyhow!("Ephemeral environment has no site packages directory"))?;
let base_site_packages = base_interpreter
.site_packages()
.next()
.ok_or_else(|| anyhow!("Base environment has no site packages directory"))?;
fs_err::write(
ephemeral_site_packages.join("sitecustomize.py"),
format!(
"import site; site.addsitedir(\"{}\")",
base_site_packages.escape_for_python()
),
)?;
}
debug!("Running `{command}`");
let mut process = Command::from(&command);
// Construct the `PATH` environment variable.
let new_path = std::env::join_paths(
ephemeral_env
.as_ref()
.map(PythonEnvironment::scripts)
.into_iter()
.chain(std::iter::once(base_interpreter.scripts()))
.map(PathBuf::from)
.chain(
std::env::var_os("PATH")
.as_ref()
.iter()
.flat_map(std::env::split_paths),
),
)?;
process.env("PATH", new_path);
// Spawn and wait for completion
// Standard input, output, and error streams are all inherited
// TODO(zanieb): Throw a nicer error message if the command is not found
let mut handle = process.spawn().with_context(|| {
format!(
"Failed to spawn: `{}`",
command.executable().to_string_lossy()
)
})?;
// Ignore signals in the parent process, deferring them to the child. This is safe as long as
// the command is the last thing that runs in this process; otherwise, we'd need to restore the
// signal handlers after the command completes.
let _handler = tokio::spawn(async { while tokio::signal::ctrl_c().await.is_ok() {} });
let status = handle.wait().await.context("Child process disappeared")?;
// Exit based on the result of the command
// TODO(zanieb): Do we want to exit with the code of the child process? Probably.
if status.success() {
Ok(ExitStatus::Success)
} else {
Ok(ExitStatus::Failure)
}
}
/// Read a [`Pep723Script`] from the given command.
pub(crate) async fn parse_script(
command: &ExternalCommand,
) -> Result<Option<Pep723Script>, Pep723Error> {
// Parse the input command.
let command = RunCommand::from(command);
let RunCommand::Python(target, _) = &command else {
return Ok(None);
};
// Read the PEP 723 `script` metadata from the target script.
Pep723Script::read(&target).await
}
/// Returns `true` if we can skip creating an additional ephemeral environment in `uv run`.
fn can_skip_ephemeral(
spec: Option<&RequirementsSpecification>,
base_interpreter: &Interpreter,
settings: &ResolverInstallerSettings,
) -> bool {
// No additional requirements.
let Some(spec) = spec.as_ref() else {
return true;
};
let Ok(site_packages) = SitePackages::from_interpreter(base_interpreter) else {
return false;
};
if !(settings.reinstall.is_none() && settings.reinstall.is_none()) {
return false;
}
match site_packages.satisfies(&spec.requirements, &spec.constraints) {
// If the requirements are already satisfied, we're done.
Ok(SatisfiesResult::Fresh {
recursive_requirements,
}) => {
debug!(
"Base environment satisfies requirements: {}",
recursive_requirements
.iter()
.map(|entry| entry.requirement.to_string())
.sorted()
.join(" | ")
);
true
}
Ok(SatisfiesResult::Unsatisfied(requirement)) => {
debug!(
"At least one requirement is not satisfied in the base environment: {requirement}"
);
false
}
Err(err) => {
debug!("Failed to check requirements against base environment: {err}");
false
}
}
}
#[derive(Debug)]
enum RunCommand {
/// Execute a `python` script.
Python(PathBuf, Vec<OsString>),
/// Execute an external command.
External(OsString, Vec<OsString>),
/// Execute an empty command (in practice, `python` with no arguments).
Empty,
}
impl RunCommand {
/// Return the name of the target executable.
fn executable(&self) -> Cow<'_, OsString> {
match self {
Self::Python(_, _) | Self::Empty => Cow::Owned(OsString::from("python")),
Self::External(executable, _) => Cow::Borrowed(executable),
}
}
}
impl std::fmt::Display for RunCommand {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Python(target, args) => {
write!(f, "python {}", target.display())?;
for arg in args {
write!(f, " {}", arg.to_string_lossy())?;
}
Ok(())
}
Self::External(executable, args) => {
write!(f, "{}", executable.to_string_lossy())?;
for arg in args {
write!(f, " {}", arg.to_string_lossy())?;
}
Ok(())
}
Self::Empty => {
write!(f, "python")?;
Ok(())
}
}
}
}
impl From<&ExternalCommand> for RunCommand {
fn from(command: &ExternalCommand) -> Self {
let (target, args) = command.split();
let Some(target) = target else {
return Self::Empty;
};
let target_path = PathBuf::from(&target);
if target_path
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("py"))
&& target_path.exists()
{
Self::Python(target_path, args.to_vec())
} else {
Self::External(
target.clone(),
args.iter().map(std::clone::Clone::clone).collect(),
)
}
}
}
impl From<&RunCommand> for Command {
fn from(command: &RunCommand) -> Self {
match command {
RunCommand::Python(target, args) => {
let mut process = Command::new("python");
process.arg(target);
process.args(args);
process
}
RunCommand::External(executable, args) => {
let mut process = Command::new(executable);
process.args(args);
process
}
RunCommand::Empty => Command::new("python"),
}
}
}