-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathlib.rs
4236 lines (3744 loc) · 153 KB
/
lib.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
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::ffi::OsString;
use std::ops::Deref;
use std::path::PathBuf;
use std::str::FromStr;
use anyhow::{anyhow, Result};
use clap::builder::styling::{AnsiColor, Effects, Style};
use clap::builder::Styles;
use clap::{Args, Parser, Subcommand};
use distribution_types::{FlatIndexLocation, IndexUrl};
use pep508_rs::Requirement;
use pypi_types::VerbatimParsedUrl;
use uv_cache::CacheArgs;
use uv_configuration::{
ConfigSettingEntry, ExportFormat, IndexStrategy, KeyringProviderType, PackageNameSpecifier,
TargetTriple, TrustedHost,
};
use uv_normalize::{ExtraName, PackageName};
use uv_python::{PythonDownloads, PythonPreference, PythonVersion};
use uv_resolver::{AnnotationStyle, ExcludeNewer, PrereleaseMode, ResolutionMode};
pub mod compat;
pub mod options;
pub mod version;
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
pub enum VersionFormat {
/// Display the version as plain text.
Text,
/// Display the version as JSON.
Json,
}
#[derive(Debug, Default, Clone, clap::ValueEnum)]
pub enum ListFormat {
/// Display the list of packages in a human-readable table.
#[default]
Columns,
/// Display the list of packages in a `pip freeze`-like format, with one package per line
/// alongside its version.
Freeze,
/// Display the list of packages in a machine-readable JSON format.
Json,
}
fn extra_name_with_clap_error(arg: &str) -> Result<ExtraName> {
ExtraName::from_str(arg).map_err(|_err| {
anyhow!(
"Extra names must start and end with a letter or digit and may only \
contain -, _, ., and alphanumeric characters"
)
})
}
// Configures Clap v3-style help menu colors
const STYLES: Styles = Styles::styled()
.header(AnsiColor::Green.on_default().effects(Effects::BOLD))
.usage(AnsiColor::Green.on_default().effects(Effects::BOLD))
.literal(AnsiColor::Cyan.on_default().effects(Effects::BOLD))
.placeholder(AnsiColor::Cyan.on_default());
#[derive(Parser)]
#[command(name = "uv", author, long_version = crate::version::version())]
#[command(about = "An extremely fast Python package manager.")]
#[command(propagate_version = true)]
#[command(
after_help = "Use `uv help` for more details.",
after_long_help = "",
disable_help_flag = true,
disable_help_subcommand = true,
disable_version_flag = true
)]
#[command(styles=STYLES)]
#[allow(clippy::struct_excessive_bools)]
pub struct Cli {
#[command(subcommand)]
pub command: Box<Commands>,
#[command(flatten)]
pub cache_args: Box<CacheArgs>,
#[command(flatten)]
pub global_args: Box<GlobalArgs>,
/// The path to a `uv.toml` file to use for configuration.
///
/// While uv configuration can be included in a `pyproject.toml` file, it is
/// not allowed in this context.
#[arg(
global = true,
long,
env = "UV_CONFIG_FILE",
help_heading = "Global options"
)]
pub config_file: Option<PathBuf>,
/// Avoid discovering configuration files (`pyproject.toml`, `uv.toml`).
///
/// Normally, configuration files are discovered in the current directory,
/// parent directories, or user configuration directories.
#[arg(global = true, long, env = "UV_NO_CONFIG", value_parser = clap::builder::BoolishValueParser::new(), help_heading = "Global options")]
pub no_config: bool,
/// Display the concise help for this command.
#[arg(global = true, short, long, action = clap::ArgAction::HelpShort, help_heading = "Global options")]
help: Option<bool>,
/// Display the uv version.
#[arg(global = true, short = 'V', long, action = clap::ArgAction::Version, help_heading = "Global options")]
version: Option<bool>,
}
#[derive(Parser, Debug, Clone)]
#[command(next_help_heading = "Global options", next_display_order = 1000)]
#[allow(clippy::struct_excessive_bools)]
pub struct GlobalArgs {
/// Whether to prefer uv-managed or system Python installations.
///
/// By default, uv prefers using Python versions it manages. However, it
/// will use system Python installations if a uv-managed Python is not
/// installed. This option allows prioritizing or ignoring system Python
/// installations.
#[arg(
global = true,
long,
help_heading = "Python options",
display_order = 700,
env = "UV_PYTHON_PREFERENCE"
)]
pub python_preference: Option<PythonPreference>,
#[allow(clippy::doc_markdown)]
/// Allow automatically downloading Python when required. [env: "UV_PYTHON_DOWNLOADS=auto"]
#[arg(global = true, long, help_heading = "Python options", hide = true)]
pub allow_python_downloads: bool,
#[allow(clippy::doc_markdown)]
/// Disable automatic downloads of Python. [env: "UV_PYTHON_DOWNLOADS=never"]
#[arg(global = true, long, help_heading = "Python options")]
pub no_python_downloads: bool,
/// Deprecated version of [`Self::python_downloads`].
#[arg(global = true, long, hide = true)]
pub python_fetch: Option<PythonDownloads>,
/// Do not print any output.
#[arg(global = true, long, short, conflicts_with = "verbose")]
pub quiet: bool,
/// Use verbose output.
///
/// You can configure fine-grained logging using the `RUST_LOG` environment variable.
/// (<https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives>)
#[arg(global = true, action = clap::ArgAction::Count, long, short, conflicts_with = "quiet")]
pub verbose: u8,
/// Disable colors.
///
/// Provided for compatibility with `pip`, use `--color` instead.
#[arg(global = true, long, hide = true, conflicts_with = "color")]
pub no_color: bool,
/// Control colors in output.
#[arg(
global = true,
long,
value_enum,
default_value = "auto",
conflicts_with = "no_color",
value_name = "COLOR_CHOICE"
)]
pub color: ColorChoice,
/// Whether to load TLS certificates from the platform's native certificate store.
///
/// By default, uv loads certificates from the bundled `webpki-roots` crate. The
/// `webpki-roots` are a reliable set of trust roots from Mozilla, and including them in uv
/// improves portability and performance (especially on macOS).
///
/// However, in some cases, you may want to use the platform's native certificate store,
/// especially if you're relying on a corporate trust root (e.g., for a mandatory proxy) that's
/// included in your system's certificate store.
#[arg(global = true, long, env = "UV_NATIVE_TLS", value_parser = clap::builder::BoolishValueParser::new(), overrides_with("no_native_tls"))]
pub native_tls: bool,
#[arg(global = true, long, overrides_with("native_tls"), hide = true)]
pub no_native_tls: bool,
/// Disable network access.
///
/// When disabled, uv will only use locally cached data and locally available files.
#[arg(global = true, long, overrides_with("no_offline"))]
pub offline: bool,
#[arg(global = true, long, overrides_with("offline"), hide = true)]
pub no_offline: bool,
/// Whether to enable experimental, preview features.
///
/// Preview features may change without warning.
#[arg(global = true, long, hide = true, env = "UV_PREVIEW", value_parser = clap::builder::BoolishValueParser::new(), overrides_with("no_preview"))]
pub preview: bool,
#[arg(global = true, long, overrides_with("preview"), hide = true)]
pub no_preview: bool,
/// Avoid discovering a `pyproject.toml` or `uv.toml` file.
///
/// Normally, configuration files are discovered in the current directory,
/// parent directories, or user configuration directories.
///
/// This option is deprecated in favor of `--no-config`.
#[arg(global = true, long, hide = true)]
pub isolated: bool,
/// Show the resolved settings for the current command.
///
/// This option is used for debugging and development purposes.
#[arg(global = true, long, hide = true)]
pub show_settings: bool,
/// Hide all progress outputs.
///
/// For example, spinners or progress bars.
#[arg(global = true, long)]
pub no_progress: bool,
/// Change to the given directory prior to running the command.
#[arg(global = true, long, hide = true)]
pub directory: Option<PathBuf>,
}
#[derive(Debug, Copy, Clone, clap::ValueEnum)]
pub enum ColorChoice {
/// Enables colored output only when the output is going to a terminal or TTY with support.
Auto,
/// Enables colored output regardless of the detected environment.
Always,
/// Disables colored output.
Never,
}
impl From<ColorChoice> for anstream::ColorChoice {
fn from(value: ColorChoice) -> Self {
match value {
ColorChoice::Auto => Self::Auto,
ColorChoice::Always => Self::Always,
ColorChoice::Never => Self::Never,
}
}
}
#[derive(Subcommand)]
#[allow(clippy::large_enum_variant)]
pub enum Commands {
/// Manage Python projects.
#[command(flatten)]
Project(Box<ProjectCommand>),
/// Run and install commands provided by Python packages.
#[command(
after_help = "Use `uv help tool` for more details.",
after_long_help = ""
)]
Tool(ToolNamespace),
/// Manage Python versions and installations
///
/// Generally, uv first searches for Python in a virtual environment, either active or in a
/// `.venv` directory in the current working directory or any parent directory. If a virtual
/// environment is not required, uv will then search for a Python interpreter. Python
/// interpreters are found by searching for Python executables in the `PATH` environment
/// variable.
///
/// On Windows, the `py` launcher is also invoked to find Python executables.
///
/// By default, uv will download Python if a version cannot be found. This behavior can be
/// disabled with the `--no-python-downloads` flag or the `python-downloads` setting.
///
/// The `--python` option allows requesting a different interpreter.
///
/// The following Python version request formats are supported:
///
/// - `<version>` e.g. `3`, `3.12`, `3.12.3`
/// - `<version-specifier>` e.g. `>=3.12,<3.13`
/// - `<implementation>` e.g. `cpython` or `cp`
/// - `<implementation>@<version>` e.g. `cpython@3.12`
/// - `<implementation><version>` e.g. `cpython3.12` or `cp312`
/// - `<implementation><version-specifier>` e.g. `cpython>=3.12,<3.13`
/// - `<implementation>-<version>-<os>-<arch>-<libc>` e.g. `cpython-3.12.3-macos-aarch64-none`
///
/// Additionally, a specific system Python interpreter can often be requested with:
///
/// - `<executable-path>` e.g. `/opt/homebrew/bin/python3`
/// - `<executable-name>` e.g. `mypython3`
/// - `<install-dir>` e.g. `/some/environment/`
///
/// When the `--python` option is used, normal discovery rules apply but discovered interpreters
/// are checked for compatibility with the request, e.g., if `pypy` is requested, uv will first
/// check if the virtual environment contains a PyPy interpreter then check if each executable
/// in the path is a PyPy interpreter.
///
/// uv supports discovering CPython, PyPy, and GraalPy interpreters. Unsupported interpreters
/// will be skipped during discovery. If an unsupported interpreter implementation is requested,
/// uv will exit with an error.
#[clap(verbatim_doc_comment)]
#[command(
after_help = "Use `uv help python` for more details.",
after_long_help = ""
)]
Python(PythonNamespace),
/// Manage Python packages with a pip-compatible interface.
#[command(
after_help = "Use `uv help pip` for more details.",
after_long_help = ""
)]
Pip(PipNamespace),
/// Create a virtual environment.
///
/// By default, creates a virtual environment named `.venv` in the working
/// directory. An alternative path may be provided positionally.
///
/// If in a project, the default environment name can be changed with
/// the `UV_PROJECT_ENVIRONMENT` environment variable; this only applies
/// when run from the project root directory.
///
/// If a virtual environment exists at the target path, it will be removed
/// and a new, empty virtual environment will be created.
///
/// When using uv, the virtual environment does not need to be activated. uv
/// will find a virtual environment (named `.venv`) in the working directory
/// or any parent directories.
#[command(
alias = "virtualenv",
alias = "v",
after_help = "Use `uv help venv` for more details.",
after_long_help = ""
)]
Venv(VenvArgs),
/// Build Python packages into source distributions and wheels.
///
/// `uv build` accepts a path to a directory or source distribution,
/// which defaults to the current working directory.
///
/// By default, if passed a directory, `uv build` will build a source
/// distribution ("sdist") from the source directory, and a binary
/// distribution ("wheel") from the source distribution.
///
/// `uv build --sdist` can be used to build only the source distribution,
/// `uv build --wheel` can be used to build only the binary distribution,
/// and `uv build --sdist --wheel` can be used to build both distributions
/// from source.
///
/// If passed a source distribution, `uv build --wheel` will build a wheel
/// from the source distribution.
#[command(
after_help = "Use `uv help build` for more details.",
after_long_help = ""
)]
Build(BuildArgs),
/// Manage uv's cache.
#[command(
after_help = "Use `uv help cache` for more details.",
after_long_help = ""
)]
Cache(CacheNamespace),
/// Manage the uv executable.
#[command(name = "self")]
#[cfg(feature = "self-update")]
Self_(SelfNamespace),
/// Clear the cache, removing all entries or those linked to specific packages.
#[command(hide = true)]
Clean(CleanArgs),
/// Display uv's version
Version {
#[arg(long, value_enum, default_value = "text")]
output_format: VersionFormat,
},
/// Generate shell completion
#[command(alias = "--generate-shell-completion", hide = true)]
GenerateShellCompletion(GenerateShellCompletionArgs),
/// Display documentation for a command.
// To avoid showing the global options when displaying help for the help command, we are
// responsible for maintaining the options using the `after_help`.
#[command(help_template = "\
{about-with-newline}
{usage-heading} {usage}{after-help}
",
after_help = format!("\
{heading}Options:{heading:#}
{option}--no-pager{option:#} Disable pager when printing help
",
heading = Style::new().bold().underline(),
option = Style::new().bold(),
),
)]
Help(HelpArgs),
}
#[derive(Args, Debug)]
pub struct HelpArgs {
/// Disable pager when printing help
#[arg(long)]
pub no_pager: bool,
pub command: Option<Vec<String>>,
}
#[derive(Args)]
#[cfg(feature = "self-update")]
pub struct SelfNamespace {
#[command(subcommand)]
pub command: SelfCommand,
}
#[derive(Subcommand)]
#[cfg(feature = "self-update")]
pub enum SelfCommand {
/// Update uv.
Update(SelfUpdateArgs),
}
#[derive(Args, Debug)]
#[cfg(feature = "self-update")]
pub struct SelfUpdateArgs {
/// Update to the specified version. If not provided, uv will update to the latest version.
pub target_version: Option<String>,
}
#[derive(Args)]
#[allow(clippy::struct_excessive_bools)]
pub struct CacheNamespace {
#[command(subcommand)]
pub command: CacheCommand,
}
#[derive(Subcommand)]
pub enum CacheCommand {
/// Clear the cache, removing all entries or those linked to specific packages.
Clean(CleanArgs),
/// Prune all unreachable objects from the cache.
Prune(PruneArgs),
/// Show the cache directory.
///
///
/// By default, the cache is stored in `$XDG_CACHE_HOME/uv` or `$HOME/.cache/uv` on Unix and
/// `%LOCALAPPDATA%\uv\cache` on Windows.
///
/// When `--no-cache` is used, the cache is stored in a temporary directory and discarded when
/// the process exits.
///
/// An alternative cache directory may be specified via the `cache-dir` setting, the
/// `--cache-dir` option, or the `$UV_CACHE_DIR` environment variable.
///
/// Note that it is important for performance for the cache directory to be located on the same
/// file system as the Python environment uv is operating on.
Dir,
}
#[derive(Args, Debug)]
#[allow(clippy::struct_excessive_bools)]
pub struct CleanArgs {
/// The packages to remove from the cache.
pub package: Vec<PackageName>,
}
#[derive(Args, Debug)]
#[allow(clippy::struct_excessive_bools)]
pub struct PruneArgs {
/// Optimize the cache for persistence in a continuous integration environment, like GitHub
/// Actions.
///
/// By default, uv caches both the wheels that it builds from source and the pre-built wheels
/// that it downloads directly, to enable high-performance package installation. In some
/// scenarios, though, persisting pre-built wheels may be undesirable. For example, in GitHub
/// Actions, it's faster to omit pre-built wheels from the cache and instead have re-download
/// them on each run. However, it typically _is_ faster to cache wheels that are built from
/// source, since the wheel building process can be expensive, especially for extension
/// modules.
///
/// In `--ci` mode, uv will prune any pre-built wheels from the cache, but retain any wheels
/// that were built from source.
#[arg(long)]
pub ci: bool,
}
#[derive(Args)]
#[allow(clippy::struct_excessive_bools)]
pub struct PipNamespace {
#[command(subcommand)]
pub command: PipCommand,
}
#[derive(Subcommand)]
pub enum PipCommand {
/// Compile a `requirements.in` file to a `requirements.txt` file.
#[command(
after_help = "Use `uv help pip compile` for more details.",
after_long_help = ""
)]
Compile(PipCompileArgs),
/// Sync an environment with a `requirements.txt` file.
#[command(
after_help = "Use `uv help pip sync` for more details.",
after_long_help = ""
)]
Sync(Box<PipSyncArgs>),
/// Install packages into an environment.
#[command(
after_help = "Use `uv help pip install` for more details.",
after_long_help = ""
)]
Install(PipInstallArgs),
/// Uninstall packages from an environment.
#[command(
after_help = "Use `uv help pip uninstall` for more details.",
after_long_help = ""
)]
Uninstall(PipUninstallArgs),
/// List, in requirements format, packages installed in an environment.
#[command(
after_help = "Use `uv help pip freeze` for more details.",
after_long_help = ""
)]
Freeze(PipFreezeArgs),
/// List, in tabular format, packages installed in an environment.
#[command(
after_help = "Use `uv help pip list` for more details.",
after_long_help = ""
)]
List(PipListArgs),
/// Show information about one or more installed packages.
#[command(
after_help = "Use `uv help pip show` for more details.",
after_long_help = ""
)]
Show(PipShowArgs),
/// Display the dependency tree for an environment.
#[command(
after_help = "Use `uv help pip tree` for more details.",
after_long_help = ""
)]
Tree(PipTreeArgs),
/// Verify installed packages have compatible dependencies.
#[command(
after_help = "Use `uv help pip check` for more details.",
after_long_help = ""
)]
Check(PipCheckArgs),
}
#[derive(Subcommand)]
pub enum ProjectCommand {
/// Run a command or script.
///
/// Ensures that the command runs in a Python environment.
///
/// When used with a file ending in `.py`, the file will be treated as a
/// script and run with a Python interpreter, i.e., `uv run file.py` is
/// equivalent to `uv run python file.py`. If the script contains inline
/// dependency metadata, it will be installed into an isolated, ephemeral
/// environment. When used with `-`, the input will be read from stdin,
/// and treated as a Python script.
///
/// When used in a project, the project environment will be created and
/// updated before invoking the command.
///
/// When used outside a project, if a virtual environment can be found in
/// the current directory or a parent directory, the command will be run in
/// that environment. Otherwise, the command will be run in the environment
/// of the discovered interpreter.
///
/// Arguments following the command (or script) are not interpreted as
/// arguments to uv. All options to uv must be provided before the command,
/// e.g., `uv run --verbose foo`. A `--` can be used to separate the command
/// from uv options for clarity, e.g., `uv run --python 3.12 -- python`.
#[command(
after_help = "Use `uv help run` for more details.",
after_long_help = ""
)]
Run(RunArgs),
/// Create a new project.
///
/// Follows the `pyproject.toml` specification.
///
/// If a `pyproject.toml` already exists at the target, uv will exit with an
/// error.
///
/// If a `pyproject.toml` is found in any of the parent directories of the
/// target path, the project will be added as a workspace member of
/// the parent.
///
/// Some project state is not created until needed, e.g., the project
/// virtual environment (`.venv`) and lockfile (`uv.lock`) are lazily
/// created during the first sync.
Init(InitArgs),
/// Add dependencies to the project.
///
/// Dependencies are added to the project's `pyproject.toml` file.
///
/// If a given dependency exists already, it will be updated to the new version specifier unless
/// it includes markers that differ from the existing specifier in which case another entry for
/// the dependency will be added.
///
/// If no constraint or URL is provided for a dependency, a lower bound is added equal to the
/// latest compatible version of the package, e.g., `>=1.2.3`, unless `--frozen` is provided, in
/// which case no resolution is performed.
///
/// The lockfile and project environment will be updated to reflect the added dependencies. To
/// skip updating the lockfile, use `--frozen`. To skip updating the environment, use
/// `--no-sync`.
///
/// If any of the requested dependencies cannot be found, uv will exit with an error, unless the
/// `--frozen` flag is provided, in which case uv will add the dependencies verbatim without
/// checking that they exist or are compatible with the project.
///
/// uv will search for a project in the current directory or any parent directory. If a project
/// cannot be found, uv will exit with an error.
#[command(
after_help = "Use `uv help add` for more details.",
after_long_help = ""
)]
Add(AddArgs),
/// Remove dependencies from the project.
///
/// Dependencies are removed from the project's `pyproject.toml` file.
///
/// If multiple entries exist for a given dependency, i.e., each with different markers, all of
/// the entries will be removed.
///
/// The lockfile and project environment will be updated to reflect the
/// removed dependencies. To skip updating the lockfile, use `--frozen`. To
/// skip updating the environment, use `--no-sync`.
///
/// If any of the requested dependencies are not present in the project, uv
/// will exit with an error.
///
/// If a package has been manually installed in the environment, i.e., with
/// `uv pip install`, it will not be removed by `uv remove`.
///
/// uv will search for a project in the current directory or any parent
/// directory. If a project cannot be found, uv will exit with an error.
#[command(
after_help = "Use `uv help remove` for more details.",
after_long_help = ""
)]
Remove(RemoveArgs),
/// Update the project's environment.
///
/// Syncing ensures that all project dependencies are installed and up-to-date with the
/// lockfile.
///
/// By default, an exact sync is performed: uv removes packages that are not declared as
/// dependencies of the project. Use the `--inexact` flag to keep extraneous packages. Note that
/// if an extraneous package conflicts with a project dependency, it will still be removed.
/// Additionally, if `--no-build-isolation` is used, uv will not remove extraneous packages to
/// avoid removing possible build dependencies.
///
/// If the project virtual environment (`.venv`) does not exist, it will be created.
///
/// The project is re-locked before syncing unless the `--locked` or `--frozen` flag is
/// provided.
///
/// uv will search for a project in the current directory or any parent directory. If a project
/// cannot be found, uv will exit with an error.
///
/// Note that, when installing from a lockfile, uv will not provide warnings for yanked package
/// versions.
#[command(
after_help = "Use `uv help sync` for more details.",
after_long_help = ""
)]
Sync(SyncArgs),
/// Update the project's lockfile.
///
/// If the project lockfile (`uv.lock`) does not exist, it will be created.
/// If a lockfile is present, its contents will be used as preferences for
/// the resolution.
///
/// If there are no changes to the project's dependencies, locking will have
/// no effect unless the `--upgrade` flag is provided.
#[command(
after_help = "Use `uv help lock` for more details.",
after_long_help = ""
)]
Lock(LockArgs),
/// Export the project's lockfile to an alternate format.
///
/// At present, only `requirements-txt` is supported.
///
/// The project is re-locked before exporting unless the `--locked` or `--frozen` flag is
/// provided.
///
/// uv will search for a project in the current directory or any parent directory. If a project
/// cannot be found, uv will exit with an error.
///
/// If operating in a workspace, the root will be exported by default; however, a specific
/// member can be selected using the `--package` option.
#[command(
after_help = "Use `uv help export` for more details.",
after_long_help = ""
)]
Export(ExportArgs),
/// Display the project's dependency tree.
Tree(TreeArgs),
}
/// A re-implementation of `Option`, used to avoid Clap's automatic `Option` flattening in
/// [`parse_index_url`].
#[derive(Debug, Clone)]
pub enum Maybe<T> {
Some(T),
None,
}
impl<T> Maybe<T> {
pub fn into_option(self) -> Option<T> {
match self {
Maybe::Some(value) => Some(value),
Maybe::None => None,
}
}
}
/// Parse a string into an [`IndexUrl`], mapping the empty string to `None`.
fn parse_index_url(input: &str) -> Result<Maybe<IndexUrl>, String> {
if input.is_empty() {
Ok(Maybe::None)
} else {
match IndexUrl::from_str(input) {
Ok(url) => Ok(Maybe::Some(url)),
Err(err) => Err(err.to_string()),
}
}
}
/// Parse a string into an [`Url`], mapping the empty string to `None`.
fn parse_insecure_host(input: &str) -> Result<Maybe<TrustedHost>, String> {
if input.is_empty() {
Ok(Maybe::None)
} else {
match TrustedHost::from_str(input) {
Ok(host) => Ok(Maybe::Some(host)),
Err(err) => Err(err.to_string()),
}
}
}
/// Parse a string into a [`PathBuf`]. The string can represent a file, either as a path or a
/// `file://` URL.
fn parse_file_path(input: &str) -> Result<PathBuf, String> {
if input.starts_with("file://") {
let url = match url::Url::from_str(input) {
Ok(url) => url,
Err(err) => return Err(err.to_string()),
};
url.to_file_path()
.map_err(|()| "invalid file URL".to_string())
} else {
Ok(PathBuf::from(input))
}
}
/// Parse a string into a [`PathBuf`], mapping the empty string to `None`.
fn parse_maybe_file_path(input: &str) -> Result<Maybe<PathBuf>, String> {
if input.is_empty() {
Ok(Maybe::None)
} else {
parse_file_path(input).map(Maybe::Some)
}
}
#[derive(Args)]
#[allow(clippy::struct_excessive_bools)]
pub struct PipCompileArgs {
/// Include all packages listed in the given `requirements.in` files.
///
/// If a `pyproject.toml`, `setup.py`, or `setup.cfg` file is provided, uv will extract the
/// requirements for the relevant project.
///
/// If `-` is provided, then requirements will be read from stdin.
///
/// The order of the requirements files and the requirements in them is used to determine
/// priority during resolution.
#[arg(required(true), value_parser = parse_file_path)]
pub src_file: Vec<PathBuf>,
/// Constrain versions using the given requirements files.
///
/// Constraints files are `requirements.txt`-like files that only control the _version_ of a
/// requirement that's installed. However, including a package in a constraints file will _not_
/// trigger the installation of that package.
///
/// This is equivalent to pip's `--constraint` option.
#[arg(long, short, env = "UV_CONSTRAINT", value_delimiter = ' ', value_parser = parse_maybe_file_path)]
pub constraint: Vec<Maybe<PathBuf>>,
/// Override versions using the given requirements files.
///
/// Overrides files are `requirements.txt`-like files that force a specific version of a
/// requirement to be installed, regardless of the requirements declared by any constituent
/// package, and regardless of whether this would be considered an invalid resolution.
///
/// While constraints are _additive_, in that they're combined with the requirements of the
/// constituent packages, overrides are _absolute_, in that they completely replace the
/// requirements of the constituent packages.
#[arg(long, env = "UV_OVERRIDE", value_delimiter = ' ', value_parser = parse_maybe_file_path)]
pub r#override: Vec<Maybe<PathBuf>>,
/// Constrain build dependencies using the given requirements files when building source
/// distributions.
///
/// Constraints files are `requirements.txt`-like files that only control the _version_ of a
/// requirement that's installed. However, including a package in a constraints file will _not_
/// trigger the installation of that package.
#[arg(long, short, env = "UV_BUILD_CONSTRAINT", value_delimiter = ' ', value_parser = parse_maybe_file_path)]
pub build_constraint: Vec<Maybe<PathBuf>>,
/// Include optional dependencies from the extra group name; may be provided more than once.
///
/// Only applies to `pyproject.toml`, `setup.py`, and `setup.cfg` sources.
#[arg(long, conflicts_with = "all_extras", value_parser = extra_name_with_clap_error)]
pub extra: Option<Vec<ExtraName>>,
/// Include all optional dependencies.
///
/// Only applies to `pyproject.toml`, `setup.py`, and `setup.cfg` sources.
#[arg(long, conflicts_with = "extra")]
pub all_extras: bool,
#[arg(long, overrides_with("all_extras"), hide = true)]
pub no_all_extras: bool,
#[command(flatten)]
pub resolver: ResolverArgs,
#[command(flatten)]
pub refresh: RefreshArgs,
/// Ignore package dependencies, instead only add those packages explicitly listed
/// on the command line to the resulting the requirements file.
#[arg(long)]
pub no_deps: bool,
#[arg(long, overrides_with("no_deps"), hide = true)]
pub deps: bool,
/// Write the compiled requirements to the given `requirements.txt` file.
///
/// If the file already exists, the existing versions will be preferred when resolving
/// dependencies, unless `--upgrade` is also specified.
#[arg(long, short)]
pub output_file: Option<PathBuf>,
/// Include extras in the output file.
///
/// By default, uv strips extras, as any packages pulled in by the extras are already included
/// as dependencies in the output file directly. Further, output files generated with
/// `--no-strip-extras` cannot be used as constraints files in `install` and `sync` invocations.
#[arg(long, overrides_with("strip_extras"))]
pub no_strip_extras: bool,
#[arg(long, overrides_with("no_strip_extras"), hide = true)]
pub strip_extras: bool,
/// Include environment markers in the output file.
///
/// By default, uv strips environment markers, as the resolution generated by `compile` is
/// only guaranteed to be correct for the target environment.
#[arg(long, overrides_with("strip_markers"))]
pub no_strip_markers: bool,
#[arg(long, overrides_with("no_strip_markers"), hide = true)]
pub strip_markers: bool,
/// Exclude comment annotations indicating the source of each package.
#[arg(long, overrides_with("annotate"))]
pub no_annotate: bool,
#[arg(long, overrides_with("no_annotate"), hide = true)]
pub annotate: bool,
/// Exclude the comment header at the top of the generated output file.
#[arg(long, overrides_with("header"))]
pub no_header: bool,
#[arg(long, overrides_with("no_header"), hide = true)]
pub header: bool,
/// The style of the annotation comments included in the output file, used to indicate the
/// source of each package.
///
/// Defaults to `split`.
#[arg(long, value_enum)]
pub annotation_style: Option<AnnotationStyle>,
/// The header comment to include at the top of the output file generated by `uv pip compile`.
///
/// Used to reflect custom build scripts and commands that wrap `uv pip compile`.
#[arg(long, env = "UV_CUSTOM_COMPILE_COMMAND")]
pub custom_compile_command: Option<String>,
/// The Python interpreter to use during resolution.
///
/// A Python interpreter is required for building source distributions to
/// determine package metadata when there are not wheels.
///
/// The interpreter is also used to determine the default minimum Python
/// version, unless `--python-version` is provided.
///
/// See `uv help python` for details on Python discovery and supported
/// request formats.
#[arg(long, verbatim_doc_comment, help_heading = "Python options")]
pub python: Option<String>,
/// Install packages into the system Python environment.
///
/// By default, uv uses the virtual environment in the current working directory or any parent
/// directory, falling back to searching for a Python executable in `PATH`. The `--system`
/// option instructs uv to avoid using a virtual environment Python and restrict its search to
/// the system path.
#[arg(
long,
env = "UV_SYSTEM_PYTHON",
value_parser = clap::builder::BoolishValueParser::new(),
overrides_with("no_system")
)]
pub system: bool,
#[arg(long, overrides_with("system"), hide = true)]
pub no_system: bool,
/// Include distribution hashes in the output file.
#[arg(long, overrides_with("no_generate_hashes"))]
pub generate_hashes: bool,
#[arg(long, overrides_with("generate_hashes"), hide = true)]
pub no_generate_hashes: bool,
/// Don't build source distributions.
///
/// When enabled, resolving will not run arbitrary Python code. The cached wheels of
/// already-built source distributions will be reused, but operations that require building
/// distributions will exit with an error.
///
/// Alias for `--only-binary :all:`.
#[arg(
long,
conflicts_with = "no_binary",
conflicts_with = "only_binary",
overrides_with("build")
)]
pub no_build: bool,
#[arg(
long,
conflicts_with = "no_binary",
conflicts_with = "only_binary",
overrides_with("no_build"),
hide = true
)]
pub build: bool,
/// Don't install pre-built wheels.
///
/// The given packages will be built and installed from source. The resolver will still use
/// pre-built wheels to extract package metadata, if available.
///
/// Multiple packages may be provided. Disable binaries for all packages with `:all:`.
/// Clear previously specified packages with `:none:`.
#[arg(long, conflicts_with = "no_build")]
pub no_binary: Option<Vec<PackageNameSpecifier>>,
/// Only use pre-built wheels; don't build source distributions.
///
/// When enabled, resolving will not run code from the given packages. The cached wheels of already-built
/// source distributions will be reused, but operations that require building distributions will
/// exit with an error.
///
/// Multiple packages may be provided. Disable binaries for all packages with `:all:`.
/// Clear previously specified packages with `:none:`.
#[arg(long, conflicts_with = "no_build")]
pub only_binary: Option<Vec<PackageNameSpecifier>>,
/// The Python version to use for resolution.
///
/// For example, `3.8` or `3.8.17`.
///
/// Defaults to the version of the Python interpreter used for resolution.
///
/// Defines the minimum Python version that must be supported by the
/// resolved requirements.
///
/// If a patch version is omitted, the minimum patch version is assumed. For
/// example, `3.8` is mapped to `3.8.0`.
#[arg(long, short, help_heading = "Python options")]
pub python_version: Option<PythonVersion>,