-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathpyproject.rs
More file actions
1897 lines (1759 loc) · 67.6 KB
/
pyproject.rs
File metadata and controls
1897 lines (1759 loc) · 67.6 KB
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
//! Reads the following fields from `pyproject.toml`:
//!
//! * `project.{dependencies,optional-dependencies}`
//! * `tool.uv.sources`
//! * `tool.uv.workspace`
//!
//! Then lowers them into a dependency specification.
#[cfg(feature = "schemars")]
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt::Formatter;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use glob::Pattern;
use owo_colors::OwoColorize;
use rustc_hash::{FxBuildHasher, FxHashSet};
use serde::de::SeqAccess;
use serde::{Deserialize, Deserializer, Serialize};
use thiserror::Error;
use tracing::instrument;
use uv_build_backend::BuildBackendSettings;
use uv_configuration::GitLfsSetting;
use uv_distribution_types::{Index, IndexName, RequirementSource};
use uv_fs::{PortablePathBuf, try_relative_to_if};
use uv_git_types::GitReference;
use uv_macros::OptionsMetadata;
use uv_normalize::{DefaultGroups, ExtraName, GroupName, PackageName};
use uv_options_metadata::{OptionSet, OptionsMetadata, Visit};
use uv_pep440::{Version, VersionSpecifiers};
use uv_pep508::MarkerTree;
use uv_pypi_types::{
Conflicts, DependencyGroups, SchemaConflicts, SupportedEnvironments, VerbatimParsedUrl,
};
use uv_redacted::DisplaySafeUrl;
#[derive(Error, Debug)]
pub enum PyprojectTomlError {
#[error(transparent)]
Toml(#[from] toml::de::Error),
#[error(
"`pyproject.toml` is using the `[project]` table, but the required `project.name` field is not set"
)]
MissingName,
#[error(
"`pyproject.toml` is using the `[project]` table, but the required `project.version` field is neither set nor present in the `project.dynamic` list"
)]
MissingVersion,
}
/// Helper function to deserialize a map while ensuring all keys are unique.
fn deserialize_unique_map<'de, D, K, V, F>(
deserializer: D,
error_msg: F,
) -> Result<BTreeMap<K, V>, D::Error>
where
D: Deserializer<'de>,
K: Deserialize<'de> + Ord + std::fmt::Display,
V: Deserialize<'de>,
F: FnOnce(&K) -> String,
{
struct Visitor<K, V, F>(F, std::marker::PhantomData<(K, V)>);
impl<'de, K, V, F> serde::de::Visitor<'de> for Visitor<K, V, F>
where
K: Deserialize<'de> + Ord + std::fmt::Display,
V: Deserialize<'de>,
F: FnOnce(&K) -> String,
{
type Value = BTreeMap<K, V>;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a map with unique keys")
}
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: serde::de::MapAccess<'de>,
{
use std::collections::btree_map::Entry;
let mut map = BTreeMap::new();
while let Some((key, value)) = access.next_entry::<K, V>()? {
match map.entry(key) {
Entry::Occupied(entry) => {
return Err(serde::de::Error::custom((self.0)(entry.key())));
}
Entry::Vacant(entry) => {
entry.insert(value);
}
}
}
Ok(map)
}
}
deserializer.deserialize_map(Visitor(error_msg, std::marker::PhantomData))
}
/// A `pyproject.toml` as specified in PEP 517.
#[derive(Deserialize, Debug, Clone)]
#[cfg_attr(test, derive(Serialize))]
#[serde(rename_all = "kebab-case")]
pub struct PyProjectToml {
/// PEP 621-compliant project metadata.
pub project: Option<Project>,
/// Tool-specific metadata.
pub tool: Option<Tool>,
/// Non-project dependency groups, as defined in PEP 735.
pub dependency_groups: Option<DependencyGroups>,
/// The raw unserialized document.
#[serde(skip)]
pub raw: String,
/// Used to determine whether a `build-system` section is present.
#[serde(default, skip_serializing)]
pub build_system: Option<serde::de::IgnoredAny>,
}
impl PyProjectToml {
/// Parse a `PyProjectToml` from a raw TOML string.
#[instrument("toml::from_str workspace", skip_all, fields(path = %_path.as_ref().display()))]
pub fn from_string(raw: String, _path: impl AsRef<Path>) -> Result<Self, PyprojectTomlError> {
let pyproject = toml::from_str(&raw).map_err(PyprojectTomlError::Toml)?;
Ok(Self { raw, ..pyproject })
}
/// Returns `true` if the project should be considered a Python package, as opposed to a
/// non-package ("virtual") project.
pub fn is_package(&self, require_build_system: bool) -> bool {
// If `tool.uv.package` is set, defer to that explicit setting.
if let Some(is_package) = self.tool_uv_package() {
return is_package;
}
// Otherwise, a project is assumed to be a package if `build-system` is present.
self.build_system.is_some() || !require_build_system
}
/// Returns the value of `tool.uv.package` if set.
fn tool_uv_package(&self) -> Option<bool> {
self.tool
.as_ref()
.and_then(|tool| tool.uv.as_ref())
.and_then(|uv| uv.package)
}
/// Returns `true` if the project uses a dynamic version.
pub fn is_dynamic(&self) -> bool {
self.project
.as_ref()
.is_some_and(|project| project.version.is_none())
}
/// Returns whether the project manifest contains any script table.
pub fn has_scripts(&self) -> bool {
if let Some(ref project) = self.project {
project.gui_scripts.is_some() || project.scripts.is_some()
} else {
false
}
}
/// Returns the set of conflicts for the project.
pub fn conflicts(&self) -> Conflicts {
let empty = Conflicts::empty();
let Some(project) = self.project.as_ref() else {
return empty;
};
let Some(tool) = self.tool.as_ref() else {
return empty;
};
let Some(tooluv) = tool.uv.as_ref() else {
return empty;
};
let Some(conflicting) = tooluv.conflicts.as_ref() else {
return empty;
};
conflicting.to_conflicts_with_package_name(&project.name)
}
}
// Ignore raw document in comparison.
impl PartialEq for PyProjectToml {
fn eq(&self, other: &Self) -> bool {
self.project.eq(&other.project) && self.tool.eq(&other.tool)
}
}
impl Eq for PyProjectToml {}
impl AsRef<[u8]> for PyProjectToml {
fn as_ref(&self) -> &[u8] {
self.raw.as_bytes()
}
}
/// PEP 621 project metadata (`project`).
///
/// See <https://packaging.python.org/en/latest/specifications/pyproject-toml>.
#[derive(Deserialize, Debug, Clone, PartialEq)]
#[cfg_attr(test, derive(Serialize))]
#[serde(rename_all = "kebab-case", try_from = "ProjectWire")]
pub struct Project {
/// The name of the project
pub name: PackageName,
/// The version of the project
pub version: Option<Version>,
/// The Python versions this project is compatible with.
pub requires_python: Option<VersionSpecifiers>,
/// The dependencies of the project.
pub dependencies: Option<Vec<String>>,
/// The optional dependencies of the project.
pub optional_dependencies: Option<BTreeMap<ExtraName, Vec<String>>>,
/// Used to determine whether a `gui-scripts` section is present.
#[serde(default, skip_serializing)]
pub(crate) gui_scripts: Option<serde::de::IgnoredAny>,
/// Used to determine whether a `scripts` section is present.
#[serde(default, skip_serializing)]
pub(crate) scripts: Option<serde::de::IgnoredAny>,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "kebab-case")]
struct ProjectWire {
name: Option<PackageName>,
version: Option<Version>,
dynamic: Option<Vec<String>>,
requires_python: Option<VersionSpecifiers>,
dependencies: Option<Vec<String>>,
optional_dependencies: Option<BTreeMap<ExtraName, Vec<String>>>,
gui_scripts: Option<serde::de::IgnoredAny>,
scripts: Option<serde::de::IgnoredAny>,
}
impl TryFrom<ProjectWire> for Project {
type Error = PyprojectTomlError;
fn try_from(value: ProjectWire) -> Result<Self, Self::Error> {
// If `[project.name]` is not present, show a dedicated error message.
let name = value.name.ok_or(PyprojectTomlError::MissingName)?;
// If `[project.version]` is not present (or listed in `[project.dynamic]`), show a dedicated error message.
if value.version.is_none()
&& !value
.dynamic
.as_ref()
.is_some_and(|dynamic| dynamic.iter().any(|field| field == "version"))
{
return Err(PyprojectTomlError::MissingVersion);
}
Ok(Self {
name,
version: value.version,
requires_python: value.requires_python,
dependencies: value.dependencies,
optional_dependencies: value.optional_dependencies,
gui_scripts: value.gui_scripts,
scripts: value.scripts,
})
}
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(test, derive(Serialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct Tool {
pub uv: Option<ToolUv>,
}
/// Validates the `tool.uv.index` field.
///
/// This custom deserializer function checks for:
/// - Duplicate index names
/// - Multiple indexes marked as default
fn deserialize_index_vec<'de, D>(deserializer: D) -> Result<Option<Vec<Index>>, D::Error>
where
D: Deserializer<'de>,
{
let indexes = Option::<Vec<Index>>::deserialize(deserializer)?;
if let Some(indexes) = indexes.as_ref() {
let mut seen_names = FxHashSet::with_capacity_and_hasher(indexes.len(), FxBuildHasher);
let mut seen_default = false;
for index in indexes {
if let Some(name) = index.name.as_ref() {
if !seen_names.insert(name) {
return Err(serde::de::Error::custom(format!(
"duplicate index name `{name}`"
)));
}
}
if index.default {
if seen_default {
return Err(serde::de::Error::custom(
"found multiple indexes with `default = true`; only one index may be marked as default",
));
}
seen_default = true;
}
}
}
Ok(indexes)
}
// NOTE(charlie): When adding fields to this struct, mark them as ignored on `Options` in
// `crates/uv-settings/src/settings.rs`.
#[derive(Deserialize, OptionsMetadata, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(test, derive(Serialize))]
#[serde(rename_all = "kebab-case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ToolUv {
/// The sources to use when resolving dependencies.
///
/// `tool.uv.sources` enriches the dependency metadata with additional sources, incorporated
/// during development. A dependency source can be a Git repository, a URL, a local path, or an
/// alternative registry.
///
/// See [Dependencies](../concepts/projects/dependencies.md) for more.
#[option(
default = "{}",
value_type = "dict",
example = r#"
[tool.uv.sources]
httpx = { git = "https://github.com/encode/httpx", tag = "0.27.0" }
pytest = { url = "https://files.pythonhosted.org/packages/6b/77/7440a06a8ead44c7757a64362dd22df5760f9b12dc5f11b6188cd2fc27a0/pytest-8.3.3-py3-none-any.whl" }
pydantic = { path = "/path/to/pydantic", editable = true }
"#
)]
pub sources: Option<ToolUvSources>,
/// The indexes to use when resolving dependencies.
///
/// Accepts either a repository compliant with [PEP 503](https://peps.python.org/pep-0503/)
/// (the simple repository API), or a local directory laid out in the same format.
///
/// Indexes are considered in the order in which they're defined, such that the first-defined
/// index has the highest priority. Further, the indexes provided by this setting are given
/// higher priority than any indexes specified via [`index_url`](#index-url) or
/// [`extra_index_url`](#extra-index-url). uv will only consider the first index that contains
/// a given package, unless an alternative [index strategy](#index-strategy) is specified.
///
/// If an index is marked as `explicit = true`, it will be used exclusively for the
/// dependencies that select it explicitly via `[tool.uv.sources]`, as in:
///
/// ```toml
/// [[tool.uv.index]]
/// name = "pytorch"
/// url = "https://download.pytorch.org/whl/cu121"
/// explicit = true
///
/// [tool.uv.sources]
/// torch = { index = "pytorch" }
/// ```
///
/// If an index is marked as `default = true`, it will be moved to the end of the prioritized list, such that it is
/// given the lowest priority when resolving packages. Additionally, marking an index as default will disable the
/// PyPI default index.
#[option(
default = "[]",
value_type = "dict",
example = r#"
[[tool.uv.index]]
name = "pytorch"
url = "https://download.pytorch.org/whl/cu121"
"#
)]
#[serde(deserialize_with = "deserialize_index_vec", default)]
pub index: Option<Vec<Index>>,
/// The workspace definition for the project, if any.
#[option_group]
pub workspace: Option<ToolUvWorkspace>,
/// Whether the project is managed by uv. If `false`, uv will ignore the project when
/// `uv run` is invoked.
#[option(
default = r#"true"#,
value_type = "bool",
example = r#"
managed = false
"#
)]
pub managed: Option<bool>,
/// Whether the project should be considered a Python package, or a non-package ("virtual")
/// project.
///
/// Packages are built and installed into the virtual environment in editable mode and thus
/// require a build backend, while virtual projects are _not_ built or installed; instead, only
/// their dependencies are included in the virtual environment.
///
/// Creating a package requires that a `build-system` is present in the `pyproject.toml`, and
/// that the project adheres to a structure that adheres to the build backend's expectations
/// (e.g., a `src` layout).
#[option(
default = r#"true"#,
value_type = "bool",
example = r#"
package = false
"#
)]
pub package: Option<bool>,
/// The list of `dependency-groups` to install by default.
///
/// Can also be the literal `"all"` to default enable all groups.
#[option(
default = r#"["dev"]"#,
value_type = r#"str | list[str]"#,
example = r#"
default-groups = ["docs"]
"#
)]
pub default_groups: Option<DefaultGroups>,
/// Additional settings for `dependency-groups`.
///
/// Currently this can only be used to add `requires-python` constraints
/// to dependency groups (typically to inform uv that your dev tooling
/// has a higher python requirement than your actual project).
///
/// This cannot be used to define dependency groups, use the top-level
/// `[dependency-groups]` table for that.
#[option(
default = "[]",
value_type = "dict",
example = r#"
[tool.uv.dependency-groups]
my-group = {requires-python = ">=3.12"}
"#
)]
pub dependency_groups: Option<ToolUvDependencyGroups>,
/// The project's development dependencies.
///
/// Development dependencies will be installed by default in `uv run` and `uv sync`, but will
/// not appear in the project's published metadata.
///
/// Use of this field is not recommend anymore. Instead, use the `dependency-groups.dev` field
/// which is a standardized way to declare development dependencies. The contents of
/// `tool.uv.dev-dependencies` and `dependency-groups.dev` are combined to determine the final
/// requirements of the `dev` dependency group.
#[cfg_attr(
feature = "schemars",
schemars(
with = "Option<Vec<String>>",
description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
)
)]
#[option(
default = "[]",
value_type = "list[str]",
example = r#"
dev-dependencies = ["ruff==0.5.0"]
"#
)]
pub dev_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
/// Overrides to apply when resolving the project's dependencies.
///
/// Overrides are used to force selection of a specific version of a package, regardless of the
/// version requested by any other package, and regardless of whether choosing that version
/// would typically constitute 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 any constituent packages.
///
/// Including a package as an override will _not_ trigger installation of the package on its
/// own; instead, the package must be requested elsewhere in the project's first-party or
/// transitive dependencies.
///
/// !!! note
/// In `uv lock`, `uv sync`, and `uv run`, uv will only read `override-dependencies` from
/// the `pyproject.toml` at the workspace root, and will ignore any declarations in other
/// workspace members or `uv.toml` files.
#[cfg_attr(
feature = "schemars",
schemars(
with = "Option<Vec<String>>",
description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
)
)]
#[option(
default = "[]",
value_type = "list[str]",
example = r#"
# Always install Werkzeug 2.3.0, regardless of whether transitive dependencies request
# a different version.
override-dependencies = ["werkzeug==2.3.0"]
"#
)]
pub override_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
/// Dependencies to exclude when resolving the project's dependencies.
///
/// Excludes are used to prevent a package from being selected during resolution,
/// regardless of whether it's requested by any other package. When a package is excluded,
/// it will be omitted from the dependency list entirely.
///
/// Including a package as an exclusion will prevent it from being installed, even if
/// it's requested by transitive dependencies. This can be useful for removing optional
/// dependencies or working around packages with broken dependencies.
///
/// !!! note
/// In `uv lock`, `uv sync`, and `uv run`, uv will only read `exclude-dependencies` from
/// the `pyproject.toml` at the workspace root, and will ignore any declarations in other
/// workspace members or `uv.toml` files.
#[cfg_attr(
feature = "schemars",
schemars(
with = "Option<Vec<String>>",
description = "Package names to exclude, e.g., `werkzeug`, `numpy`."
)
)]
#[option(
default = "[]",
value_type = "list[str]",
example = r#"
# Exclude Werkzeug from being installed, even if transitive dependencies request it.
exclude-dependencies = ["werkzeug"]
"#
)]
pub exclude_dependencies: Option<Vec<PackageName>>,
/// Constraints to apply when resolving the project's dependencies.
///
/// Constraints are used to restrict the versions of dependencies that are selected during
/// resolution.
///
/// Including a package as a constraint will _not_ trigger installation of the package on its
/// own; instead, the package must be requested elsewhere in the project's first-party or
/// transitive dependencies.
///
/// !!! note
/// In `uv lock`, `uv sync`, and `uv run`, uv will only read `constraint-dependencies` from
/// the `pyproject.toml` at the workspace root, and will ignore any declarations in other
/// workspace members or `uv.toml` files.
#[cfg_attr(
feature = "schemars",
schemars(
with = "Option<Vec<String>>",
description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
)
)]
#[option(
default = "[]",
value_type = "list[str]",
example = r#"
# Ensure that the grpcio version is always less than 1.65, if it's requested by a
# direct or transitive dependency.
constraint-dependencies = ["grpcio<1.65"]
"#
)]
pub constraint_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
/// Constraints to apply when solving build dependencies.
///
/// Build constraints are used to restrict the versions of build dependencies that are selected
/// when building a package during resolution or installation.
///
/// Including a package as a constraint will _not_ trigger installation of the package during
/// a build; instead, the package must be requested elsewhere in the project's build dependency
/// graph.
///
/// !!! note
/// In `uv lock`, `uv sync`, and `uv run`, uv will only read `build-constraint-dependencies` from
/// the `pyproject.toml` at the workspace root, and will ignore any declarations in other
/// workspace members or `uv.toml` files.
#[cfg_attr(
feature = "schemars",
schemars(
with = "Option<Vec<String>>",
description = "PEP 508-style requirements, e.g., `ruff==0.5.0`, or `ruff @ https://...`."
)
)]
#[option(
default = "[]",
value_type = "list[str]",
example = r#"
# Ensure that the setuptools v60.0.0 is used whenever a package has a build dependency
# on setuptools.
build-constraint-dependencies = ["setuptools==60.0.0"]
"#
)]
pub build_constraint_dependencies: Option<Vec<uv_pep508::Requirement<VerbatimParsedUrl>>>,
/// A list of supported environments against which to resolve dependencies.
///
/// By default, uv will resolve for all possible environments during a `uv lock` operation.
/// However, you can restrict the set of supported environments to improve performance and avoid
/// unsatisfiable branches in the solution space.
///
/// These environments will also be respected when `uv pip compile` is invoked with the
/// `--universal` flag.
#[cfg_attr(
feature = "schemars",
schemars(
with = "Option<Vec<String>>",
description = "A list of environment markers, e.g., `python_version >= '3.6'`."
)
)]
#[option(
default = "[]",
value_type = "str | list[str]",
example = r#"
# Resolve for macOS, but not for Linux or Windows.
environments = ["sys_platform == 'darwin'"]
"#
)]
pub environments: Option<SupportedEnvironments>,
/// A list of required platforms, for packages that lack source distributions.
///
/// When a package does not have a source distribution, it's availability will be limited to
/// the platforms supported by its built distributions (wheels). For example, if a package only
/// publishes wheels for Linux, then it won't be installable on macOS or Windows.
///
/// By default, uv requires each package to include at least one wheel that is compatible with
/// the designated Python version. The `required-environments` setting can be used to ensure that
/// the resulting resolution contains wheels for specific platforms, or fails if no such wheels
/// are available.
///
/// While the `environments` setting _limits_ the set of environments that uv will consider when
/// resolving dependencies, `required-environments` _expands_ the set of platforms that uv _must_
/// support when resolving dependencies.
///
/// For example, `environments = ["sys_platform == 'darwin'"]` would limit uv to solving for
/// macOS (and ignoring Linux and Windows). On the other hand, `required-environments = ["sys_platform == 'darwin'"]`
/// would _require_ that any package without a source distribution include a wheel for macOS in
/// order to be installable.
#[cfg_attr(
feature = "schemars",
schemars(
with = "Option<Vec<String>>",
description = "A list of environment markers, e.g., `sys_platform == 'darwin'."
)
)]
#[option(
default = "[]",
value_type = "str | list[str]",
example = r#"
# Require that the package is available on the following platforms:
required-environments = [
# macOS on Apple Silicon (ARM)
"sys_platform == 'darwin' and platform_machine == 'arm64'",
# Linux on x86_64 (Intel/AMD)
"sys_platform == 'linux' and platform_machine == 'x86_64'",
# Windows on x86_64 (Intel/AMD)
"sys_platform == 'win32' and platform_machine == 'AMD64'",
]
"#
)]
pub required_environments: Option<SupportedEnvironments>,
/// Declare collections of extras or dependency groups that are conflicting
/// (i.e., mutually exclusive).
///
/// It's useful to declare conflicts when two or more extras have mutually
/// incompatible dependencies. For example, extra `foo` might depend
/// on `numpy==2.0.0` while extra `bar` depends on `numpy==2.1.0`. While these
/// dependencies conflict, it may be the case that users are not expected to
/// activate both `foo` and `bar` at the same time, making it possible to
/// generate a universal resolution for the project despite the incompatibility.
///
/// By making such conflicts explicit, uv can generate a universal resolution
/// for a project, taking into account that certain combinations of extras and
/// groups are mutually exclusive. In exchange, installation will fail if a
/// user attempts to activate both conflicting extras.
#[cfg_attr(
feature = "schemars",
schemars(description = "A list of sets of conflicting groups or extras.")
)]
#[option(
default = r#"[]"#,
value_type = "list[list[dict]]",
example = r#"
# Require that `package[extra1]` and `package[extra2]` are resolved
# in different forks so that they cannot conflict with one another.
conflicts = [
[
{ extra = "extra1" },
{ extra = "extra2" },
]
]
# Require that the dependency groups `group1` and `group2`
# are resolved in different forks so that they cannot conflict
# with one another.
conflicts = [
[
{ group = "group1" },
{ group = "group2" },
]
]
"#
)]
pub conflicts: Option<SchemaConflicts>,
// Only exists on this type for schema and docs generation, the build backend settings are
// never merged in a workspace and read separately by the backend code.
/// Configuration for the uv build backend.
///
/// Note that those settings only apply when using the `uv_build` backend, other build backends
/// (such as hatchling) have their own configuration.
#[option_group]
pub build_backend: Option<BuildBackendSettingsSchema>,
}
#[derive(Default, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(test, derive(Serialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ToolUvSources(BTreeMap<PackageName, Sources>);
impl ToolUvSources {
/// Returns the underlying `BTreeMap` of package names to sources.
pub fn inner(&self) -> &BTreeMap<PackageName, Sources> {
&self.0
}
/// Convert the [`ToolUvSources`] into its inner `BTreeMap`.
#[must_use]
pub fn into_inner(self) -> BTreeMap<PackageName, Sources> {
self.0
}
}
/// Ensure that all keys in the TOML table are unique.
impl<'de> serde::de::Deserialize<'de> for ToolUvSources {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserialize_unique_map(deserializer, |key: &PackageName| {
format!("duplicate sources for package `{key}`")
})
.map(ToolUvSources)
}
}
#[derive(Default, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(test, derive(Serialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ToolUvDependencyGroups(BTreeMap<GroupName, DependencyGroupSettings>);
impl ToolUvDependencyGroups {
/// Returns the underlying `BTreeMap` of group names to settings.
pub fn inner(&self) -> &BTreeMap<GroupName, DependencyGroupSettings> {
&self.0
}
/// Convert the [`ToolUvDependencyGroups`] into its inner `BTreeMap`.
#[must_use]
pub fn into_inner(self) -> BTreeMap<GroupName, DependencyGroupSettings> {
self.0
}
}
/// Ensure that all keys in the TOML table are unique.
impl<'de> serde::de::Deserialize<'de> for ToolUvDependencyGroups {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserialize_unique_map(deserializer, |key: &GroupName| {
format!("duplicate settings for dependency group `{key}`")
})
.map(ToolUvDependencyGroups)
}
}
#[derive(Deserialize, Default, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(test, derive(Serialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case")]
pub struct DependencyGroupSettings {
/// Version of python to require when installing this group
#[cfg_attr(feature = "schemars", schemars(with = "Option<String>"))]
pub requires_python: Option<VersionSpecifiers>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged, rename_all = "kebab-case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum ExtraBuildDependencyWire {
Unannotated(uv_pep508::Requirement<VerbatimParsedUrl>),
#[serde(rename_all = "kebab-case")]
Annotated {
requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
match_runtime: bool,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
deny_unknown_fields,
from = "ExtraBuildDependencyWire",
into = "ExtraBuildDependencyWire"
)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ExtraBuildDependency {
pub requirement: uv_pep508::Requirement<VerbatimParsedUrl>,
pub match_runtime: bool,
}
impl From<ExtraBuildDependency> for uv_pep508::Requirement<VerbatimParsedUrl> {
fn from(value: ExtraBuildDependency) -> Self {
value.requirement
}
}
impl From<ExtraBuildDependencyWire> for ExtraBuildDependency {
fn from(wire: ExtraBuildDependencyWire) -> Self {
match wire {
ExtraBuildDependencyWire::Unannotated(requirement) => Self {
requirement,
match_runtime: false,
},
ExtraBuildDependencyWire::Annotated {
requirement,
match_runtime,
} => Self {
requirement,
match_runtime,
},
}
}
}
impl From<ExtraBuildDependency> for ExtraBuildDependencyWire {
fn from(item: ExtraBuildDependency) -> Self {
Self::Annotated {
requirement: item.requirement,
match_runtime: item.match_runtime,
}
}
}
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ExtraBuildDependencies(BTreeMap<PackageName, Vec<ExtraBuildDependency>>);
impl std::ops::Deref for ExtraBuildDependencies {
type Target = BTreeMap<PackageName, Vec<ExtraBuildDependency>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for ExtraBuildDependencies {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl IntoIterator for ExtraBuildDependencies {
type Item = (PackageName, Vec<ExtraBuildDependency>);
type IntoIter = std::collections::btree_map::IntoIter<PackageName, Vec<ExtraBuildDependency>>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl FromIterator<(PackageName, Vec<ExtraBuildDependency>)> for ExtraBuildDependencies {
fn from_iter<T: IntoIterator<Item = (PackageName, Vec<ExtraBuildDependency>)>>(
iter: T,
) -> Self {
Self(iter.into_iter().collect())
}
}
/// Ensure that all keys in the TOML table are unique.
impl<'de> serde::de::Deserialize<'de> for ExtraBuildDependencies {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserialize_unique_map(deserializer, |key: &PackageName| {
format!("duplicate extra-build-dependencies for `{key}`")
})
.map(ExtraBuildDependencies)
}
}
#[derive(Deserialize, OptionsMetadata, Default, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(test, derive(Serialize))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct ToolUvWorkspace {
/// Packages to include as workspace members.
///
/// Supports both globs and explicit paths.
///
/// For more information on the glob syntax, refer to the [`glob` documentation](https://docs.rs/glob/latest/glob/struct.Pattern.html).
#[option(
default = "[]",
value_type = "list[str]",
example = r#"
members = ["member1", "path/to/member2", "libs/*"]
"#
)]
pub members: Option<Vec<SerdePattern>>,
/// Packages to exclude as workspace members. If a package matches both `members` and
/// `exclude`, it will be excluded.
///
/// Supports both globs and explicit paths.
///
/// For more information on the glob syntax, refer to the [`glob` documentation](https://docs.rs/glob/latest/glob/struct.Pattern.html).
#[option(
default = "[]",
value_type = "list[str]",
example = r#"
exclude = ["member1", "path/to/member2", "libs/*"]
"#
)]
pub exclude: Option<Vec<SerdePattern>>,
}
/// (De)serialize globs as strings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SerdePattern(Pattern);
impl serde::ser::Serialize for SerdePattern {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
self.0.as_str().serialize(serializer)
}
}
impl<'de> serde::Deserialize<'de> for SerdePattern {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct Visitor;
impl serde::de::Visitor<'_> for Visitor {
type Value = SerdePattern;
fn expecting(&self, f: &mut Formatter) -> std::fmt::Result {
f.write_str("a string")
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
Pattern::from_str(v)
.map(SerdePattern)
.map_err(serde::de::Error::custom)
}
}
deserializer.deserialize_str(Visitor)
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for SerdePattern {
fn schema_name() -> Cow<'static, str> {
Cow::Borrowed("SerdePattern")
}
fn json_schema(generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema {
<String as schemars::JsonSchema>::json_schema(generator)
}
}
impl Deref for SerdePattern {
type Target = Pattern;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "kebab-case", try_from = "SourcesWire")]
pub struct Sources(#[cfg_attr(feature = "schemars", schemars(with = "SourcesWire"))] Vec<Source>);
impl Sources {
/// Return an [`Iterator`] over the sources.
///
/// If the iterator contains multiple entries, they will always use disjoint markers.
///
/// The iterator will contain at most one registry source.
pub fn iter(&self) -> impl Iterator<Item = &Source> {
self.0.iter()
}
/// Returns `true` if the sources list is empty.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Returns the number of sources in the list.
pub fn len(&self) -> usize {