-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathpyproject_mut.rs
1358 lines (1216 loc) · 47.1 KB
/
pyproject_mut.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::cmp::Ordering;
use std::path::Path;
use std::str::FromStr;
use std::{fmt, mem};
use itertools::Itertools;
use thiserror::Error;
use toml_edit::{
Array, ArrayOfTables, DocumentMut, Formatted, Item, RawString, Table, TomlError, Value,
};
use url::Url;
use uv_cache_key::CanonicalUrl;
use uv_distribution_types::Index;
use uv_fs::PortablePath;
use uv_normalize::GroupName;
use uv_pep440::{Version, VersionSpecifier, VersionSpecifiers};
use uv_pep508::{ExtraName, MarkerTree, PackageName, Requirement, VersionOrUrl};
use crate::pyproject::{DependencyType, Source};
/// Raw and mutable representation of a `pyproject.toml`.
///
/// This is useful for operations that require editing an existing `pyproject.toml` while
/// preserving comments and other structure, such as `uv add` and `uv remove`.
pub struct PyProjectTomlMut {
doc: DocumentMut,
target: DependencyTarget,
}
#[derive(Error, Debug)]
pub enum Error {
#[error("Failed to parse `pyproject.toml`")]
Parse(#[from] Box<TomlError>),
#[error("Failed to serialize `pyproject.toml`")]
Serialize(#[from] Box<toml::ser::Error>),
#[error("Failed to deserialize `pyproject.toml`")]
Deserialize(#[from] Box<toml::de::Error>),
#[error("Dependencies in `pyproject.toml` are malformed")]
MalformedDependencies,
#[error("Sources in `pyproject.toml` are malformed")]
MalformedSources,
#[error("Workspace in `pyproject.toml` is malformed")]
MalformedWorkspace,
#[error("Expected a dependency at index {0}")]
MissingDependency(usize),
#[error("Cannot perform ambiguous update; found multiple entries with matching package names")]
Ambiguous,
}
/// The result of editing an array in a TOML document.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ArrayEdit {
/// An existing entry (at the given index) was updated.
Update(usize),
/// A new entry was added at the given index (typically, the end of the array).
Add(usize),
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum CommentType {
/// A comment that appears on its own line.
OwnLine,
/// A comment that appears at the end of a line.
EndOfLine,
}
#[derive(Debug, Clone)]
struct Comment {
text: String,
comment_type: CommentType,
}
impl ArrayEdit {
pub fn index(&self) -> usize {
match self {
Self::Update(i) | Self::Add(i) => *i,
}
}
}
/// Specifies whether dependencies are added to a script file or a `pyproject.toml` file.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum DependencyTarget {
/// A PEP 723 script, with inline metadata.
Script,
/// A project with a `pyproject.toml`.
PyProjectToml,
}
impl PyProjectTomlMut {
/// Initialize a [`PyProjectTomlMut`] from a [`str`].
pub fn from_toml(raw: &str, target: DependencyTarget) -> Result<Self, Error> {
Ok(Self {
doc: raw.parse().map_err(Box::new)?,
target,
})
}
/// Adds a project to the workspace.
pub fn add_workspace(&mut self, path: impl AsRef<Path>) -> Result<(), Error> {
// Get or create `tool.uv.workspace.members`.
let members = self
.doc
.entry("tool")
.or_insert(implicit())
.as_table_mut()
.ok_or(Error::MalformedWorkspace)?
.entry("uv")
.or_insert(implicit())
.as_table_mut()
.ok_or(Error::MalformedWorkspace)?
.entry("workspace")
.or_insert(Item::Table(Table::new()))
.as_table_mut()
.ok_or(Error::MalformedWorkspace)?
.entry("members")
.or_insert(Item::Value(Value::Array(Array::new())))
.as_array_mut()
.ok_or(Error::MalformedWorkspace)?;
// Add the path to the workspace.
members.push(PortablePath::from(path.as_ref()).to_string());
Ok(())
}
/// Retrieves a mutable reference to the `project` [`Table`] of the TOML document, creating the
/// table if necessary.
///
/// For a script, this returns the root table.
fn project(&mut self) -> Result<&mut Table, Error> {
let doc = match self.target {
DependencyTarget::Script => self.doc.as_table_mut(),
DependencyTarget::PyProjectToml => self
.doc
.entry("project")
.or_insert(Item::Table(Table::new()))
.as_table_mut()
.ok_or(Error::MalformedDependencies)?,
};
Ok(doc)
}
/// Retrieves an optional mutable reference to the `project` [`Table`], returning `None` if it
/// doesn't exist.
///
/// For a script, this returns the root table.
fn project_mut(&mut self) -> Result<Option<&mut Table>, Error> {
let doc = match self.target {
DependencyTarget::Script => Some(self.doc.as_table_mut()),
DependencyTarget::PyProjectToml => self
.doc
.get_mut("project")
.map(|project| project.as_table_mut().ok_or(Error::MalformedSources))
.transpose()?,
};
Ok(doc)
}
/// Adds a dependency to `project.dependencies`.
///
/// Returns `true` if the dependency was added, `false` if it was updated.
pub fn add_dependency(
&mut self,
req: &Requirement,
source: Option<&Source>,
) -> Result<ArrayEdit, Error> {
// Get or create `project.dependencies`.
let dependencies = self
.project()?
.entry("dependencies")
.or_insert(Item::Value(Value::Array(Array::new())))
.as_array_mut()
.ok_or(Error::MalformedDependencies)?;
let name = req.name.clone();
let edit = add_dependency(req, dependencies, source.is_some())?;
if let Some(source) = source {
self.add_source(&name, source)?;
}
Ok(edit)
}
/// Adds a development dependency to `tool.uv.dev-dependencies`.
///
/// Returns `true` if the dependency was added, `false` if it was updated.
pub fn add_dev_dependency(
&mut self,
req: &Requirement,
source: Option<&Source>,
) -> Result<ArrayEdit, Error> {
// Get or create `tool.uv.dev-dependencies`.
let dev_dependencies = self
.doc
.entry("tool")
.or_insert(implicit())
.as_table_mut()
.ok_or(Error::MalformedSources)?
.entry("uv")
.or_insert(Item::Table(Table::new()))
.as_table_mut()
.ok_or(Error::MalformedSources)?
.entry("dev-dependencies")
.or_insert(Item::Value(Value::Array(Array::new())))
.as_array_mut()
.ok_or(Error::MalformedDependencies)?;
let name = req.name.clone();
let edit = add_dependency(req, dev_dependencies, source.is_some())?;
if let Some(source) = source {
self.add_source(&name, source)?;
}
Ok(edit)
}
/// Add an [`Index`] to `tool.uv.index`.
pub fn add_index(&mut self, index: &Index) -> Result<(), Error> {
let existing = self
.doc
.entry("tool")
.or_insert(implicit())
.as_table_mut()
.ok_or(Error::MalformedSources)?
.entry("uv")
.or_insert(implicit())
.as_table_mut()
.ok_or(Error::MalformedSources)?
.entry("index")
.or_insert(Item::ArrayOfTables(ArrayOfTables::new()))
.as_array_of_tables_mut()
.ok_or(Error::MalformedSources)?;
// If there's already an index with the same name or URL, update it (and move it to the top).
let mut table = existing
.iter()
.find(|table| {
// If the index has the same name, reuse it.
if let Some(index) = index.name.as_deref() {
if table
.get("name")
.and_then(|name| name.as_str())
.is_some_and(|name| name == index)
{
return true;
}
}
// If the index is the default, and there's another default index, reuse it.
if index.default
&& table
.get("default")
.is_some_and(|default| default.as_bool() == Some(true))
{
return true;
}
// If there's another index with the same URL, reuse it.
if table
.get("url")
.and_then(|item| item.as_str())
.and_then(|url| Url::parse(url).ok())
.is_some_and(|url| {
CanonicalUrl::new(&url) == CanonicalUrl::new(index.url.url())
})
{
return true;
}
false
})
.cloned()
.unwrap_or_default();
// If necessary, update the name.
if let Some(index) = index.name.as_deref() {
if table
.get("name")
.and_then(|name| name.as_str())
.is_none_or(|name| name != index)
{
let mut formatted = Formatted::new(index.to_string());
if let Some(value) = table.get("name").and_then(Item::as_value) {
if let Some(prefix) = value.decor().prefix() {
formatted.decor_mut().set_prefix(prefix.clone());
}
if let Some(suffix) = value.decor().suffix() {
formatted.decor_mut().set_suffix(suffix.clone());
}
}
table.insert("name", Value::String(formatted).into());
}
}
// If necessary, update the URL.
if table
.get("url")
.and_then(|item| item.as_str())
.and_then(|url| Url::parse(url).ok())
.is_none_or(|url| CanonicalUrl::new(&url) != CanonicalUrl::new(index.url.url()))
{
let mut formatted = Formatted::new(index.url.redacted().to_string());
if let Some(value) = table.get("url").and_then(Item::as_value) {
if let Some(prefix) = value.decor().prefix() {
formatted.decor_mut().set_prefix(prefix.clone());
}
if let Some(suffix) = value.decor().suffix() {
formatted.decor_mut().set_suffix(suffix.clone());
}
}
table.insert("url", Value::String(formatted).into());
}
// If necessary, update the default.
if index.default {
if !table
.get("default")
.and_then(Item::as_bool)
.is_some_and(|default| default)
{
let mut formatted = Formatted::new(true);
if let Some(value) = table.get("default").and_then(Item::as_value) {
if let Some(prefix) = value.decor().prefix() {
formatted.decor_mut().set_prefix(prefix.clone());
}
if let Some(suffix) = value.decor().suffix() {
formatted.decor_mut().set_suffix(suffix.clone());
}
}
table.insert("default", Value::Boolean(formatted).into());
}
}
// Remove any replaced tables.
existing.retain(|table| {
// If the index has the same name, skip it.
if let Some(index) = index.name.as_deref() {
if table
.get("name")
.and_then(|name| name.as_str())
.is_some_and(|name| name == index)
{
return false;
}
}
// If there's another default index, skip it.
if index.default
&& table
.get("default")
.is_some_and(|default| default.as_bool() == Some(true))
{
return false;
}
// If there's another index with the same URL, skip it.
if table
.get("url")
.and_then(|item| item.as_str())
.and_then(|url| Url::parse(url).ok())
.is_some_and(|url| CanonicalUrl::new(&url) == CanonicalUrl::new(index.url.url()))
{
return false;
}
true
});
// Set the position to the minimum, if it's not already the first element.
if let Some(min) = existing.iter().filter_map(Table::position).min() {
table.set_position(min);
// Increment the position of all existing elements.
for table in existing.iter_mut() {
if let Some(position) = table.position() {
table.set_position(position + 1);
}
}
}
// Push the item to the table.
existing.push(table);
Ok(())
}
/// Adds a dependency to `project.optional-dependencies`.
///
/// Returns `true` if the dependency was added, `false` if it was updated.
pub fn add_optional_dependency(
&mut self,
group: &ExtraName,
req: &Requirement,
source: Option<&Source>,
) -> Result<ArrayEdit, Error> {
// Get or create `project.optional-dependencies`.
let optional_dependencies = self
.project()?
.entry("optional-dependencies")
.or_insert(Item::Table(Table::new()))
.as_table_like_mut()
.ok_or(Error::MalformedDependencies)?;
let group = optional_dependencies
.entry(group.as_ref())
.or_insert(Item::Value(Value::Array(Array::new())))
.as_array_mut()
.ok_or(Error::MalformedDependencies)?;
let name = req.name.clone();
let added = add_dependency(req, group, source.is_some())?;
// If `project.optional-dependencies` is an inline table, reformat it.
//
// Reformatting can drop comments between keys, but you can't put comments
// between items in an inline table anyway.
if let Some(optional_dependencies) = self
.project()?
.get_mut("optional-dependencies")
.and_then(Item::as_inline_table_mut)
{
optional_dependencies.fmt();
}
if let Some(source) = source {
self.add_source(&name, source)?;
}
Ok(added)
}
/// Adds a dependency to `dependency-groups`.
///
/// Returns `true` if the dependency was added, `false` if it was updated.
pub fn add_dependency_group_requirement(
&mut self,
group: &GroupName,
req: &Requirement,
source: Option<&Source>,
) -> Result<ArrayEdit, Error> {
// Get or create `dependency-groups`.
let dependency_groups = self
.doc
.entry("dependency-groups")
.or_insert(Item::Table(Table::new()))
.as_table_like_mut()
.ok_or(Error::MalformedDependencies)?;
let group = dependency_groups
.entry(group.as_ref())
.or_insert(Item::Value(Value::Array(Array::new())))
.as_array_mut()
.ok_or(Error::MalformedDependencies)?;
let name = req.name.clone();
let added = add_dependency(req, group, source.is_some())?;
// If `dependency-groups` is an inline table, reformat it.
//
// Reformatting can drop comments between keys, but you can't put comments
// between items in an inline table anyway.
if let Some(dependency_groups) = self
.doc
.get_mut("dependency-groups")
.and_then(Item::as_inline_table_mut)
{
dependency_groups.fmt();
}
if let Some(source) = source {
self.add_source(&name, source)?;
}
Ok(added)
}
/// Set the minimum version for an existing dependency in `project.dependencies`.
pub fn set_dependency_minimum_version(
&mut self,
index: usize,
version: Version,
) -> Result<(), Error> {
// Get or create `project.dependencies`.
let dependencies = self
.project()?
.entry("dependencies")
.or_insert(Item::Value(Value::Array(Array::new())))
.as_array_mut()
.ok_or(Error::MalformedDependencies)?;
let Some(req) = dependencies.get(index) else {
return Err(Error::MissingDependency(index));
};
let mut req = req
.as_str()
.and_then(try_parse_requirement)
.ok_or(Error::MalformedDependencies)?;
req.version_or_url = Some(VersionOrUrl::VersionSpecifier(VersionSpecifiers::from(
VersionSpecifier::greater_than_equal_version(version),
)));
dependencies.replace(index, req.to_string());
Ok(())
}
/// Set the minimum version for an existing dependency in `tool.uv.dev-dependencies`.
pub fn set_dev_dependency_minimum_version(
&mut self,
index: usize,
version: Version,
) -> Result<(), Error> {
// Get or create `tool.uv.dev-dependencies`.
let dev_dependencies = self
.doc
.entry("tool")
.or_insert(implicit())
.as_table_mut()
.ok_or(Error::MalformedSources)?
.entry("uv")
.or_insert(Item::Table(Table::new()))
.as_table_mut()
.ok_or(Error::MalformedSources)?
.entry("dev-dependencies")
.or_insert(Item::Value(Value::Array(Array::new())))
.as_array_mut()
.ok_or(Error::MalformedDependencies)?;
let Some(req) = dev_dependencies.get(index) else {
return Err(Error::MissingDependency(index));
};
let mut req = req
.as_str()
.and_then(try_parse_requirement)
.ok_or(Error::MalformedDependencies)?;
req.version_or_url = Some(VersionOrUrl::VersionSpecifier(VersionSpecifiers::from(
VersionSpecifier::greater_than_equal_version(version),
)));
dev_dependencies.replace(index, req.to_string());
Ok(())
}
/// Set the minimum version for an existing dependency in `project.optional-dependencies`.
pub fn set_optional_dependency_minimum_version(
&mut self,
group: &ExtraName,
index: usize,
version: Version,
) -> Result<(), Error> {
// Get or create `project.optional-dependencies`.
let optional_dependencies = self
.project()?
.entry("optional-dependencies")
.or_insert(Item::Table(Table::new()))
.as_table_like_mut()
.ok_or(Error::MalformedDependencies)?;
let group = optional_dependencies
.entry(group.as_ref())
.or_insert(Item::Value(Value::Array(Array::new())))
.as_array_mut()
.ok_or(Error::MalformedDependencies)?;
let Some(req) = group.get(index) else {
return Err(Error::MissingDependency(index));
};
let mut req = req
.as_str()
.and_then(try_parse_requirement)
.ok_or(Error::MalformedDependencies)?;
req.version_or_url = Some(VersionOrUrl::VersionSpecifier(VersionSpecifiers::from(
VersionSpecifier::greater_than_equal_version(version),
)));
group.replace(index, req.to_string());
Ok(())
}
/// Set the minimum version for an existing dependency in `dependency-groups`.
pub fn set_dependency_group_requirement_minimum_version(
&mut self,
group: &GroupName,
index: usize,
version: Version,
) -> Result<(), Error> {
// Get or create `dependency-groups`.
let dependency_groups = self
.doc
.entry("dependency-groups")
.or_insert(Item::Table(Table::new()))
.as_table_like_mut()
.ok_or(Error::MalformedDependencies)?;
let group = dependency_groups
.entry(group.as_ref())
.or_insert(Item::Value(Value::Array(Array::new())))
.as_array_mut()
.ok_or(Error::MalformedDependencies)?;
let Some(req) = group.get(index) else {
return Err(Error::MissingDependency(index));
};
let mut req = req
.as_str()
.and_then(try_parse_requirement)
.ok_or(Error::MalformedDependencies)?;
req.version_or_url = Some(VersionOrUrl::VersionSpecifier(VersionSpecifiers::from(
VersionSpecifier::greater_than_equal_version(version),
)));
group.replace(index, req.to_string());
Ok(())
}
/// Adds a source to `tool.uv.sources`.
fn add_source(&mut self, name: &PackageName, source: &Source) -> Result<(), Error> {
// Get or create `tool.uv.sources`.
let sources = self
.doc
.entry("tool")
.or_insert(implicit())
.as_table_mut()
.ok_or(Error::MalformedSources)?
.entry("uv")
.or_insert(implicit())
.as_table_mut()
.ok_or(Error::MalformedSources)?
.entry("sources")
.or_insert(Item::Table(Table::new()))
.as_table_mut()
.ok_or(Error::MalformedSources)?;
if let Some(key) = find_source(name, sources) {
sources.remove(&key);
}
add_source(name, source, sources)?;
Ok(())
}
/// Removes all occurrences of dependencies with the given name.
pub fn remove_dependency(&mut self, name: &PackageName) -> Result<Vec<Requirement>, Error> {
// Try to get `project.dependencies`.
let Some(dependencies) = self
.project_mut()?
.and_then(|project| project.get_mut("dependencies"))
.map(|dependencies| {
dependencies
.as_array_mut()
.ok_or(Error::MalformedDependencies)
})
.transpose()?
else {
return Ok(Vec::new());
};
let requirements = remove_dependency(name, dependencies);
self.remove_source(name)?;
Ok(requirements)
}
/// Removes all occurrences of development dependencies with the given name.
pub fn remove_dev_dependency(&mut self, name: &PackageName) -> Result<Vec<Requirement>, Error> {
// Try to get `tool.uv.dev-dependencies`.
let Some(dev_dependencies) = self
.doc
.get_mut("tool")
.map(|tool| tool.as_table_mut().ok_or(Error::MalformedDependencies))
.transpose()?
.and_then(|tool| tool.get_mut("uv"))
.map(|tool_uv| tool_uv.as_table_mut().ok_or(Error::MalformedDependencies))
.transpose()?
.and_then(|tool_uv| tool_uv.get_mut("dev-dependencies"))
.map(|dependencies| {
dependencies
.as_array_mut()
.ok_or(Error::MalformedDependencies)
})
.transpose()?
else {
return Ok(Vec::new());
};
let requirements = remove_dependency(name, dev_dependencies);
self.remove_source(name)?;
Ok(requirements)
}
/// Removes all occurrences of optional dependencies in the group with the given name.
pub fn remove_optional_dependency(
&mut self,
name: &PackageName,
group: &ExtraName,
) -> Result<Vec<Requirement>, Error> {
// Try to get `project.optional-dependencies.<group>`.
let Some(optional_dependencies) = self
.project_mut()?
.and_then(|project| project.get_mut("optional-dependencies"))
.map(|extras| {
extras
.as_table_like_mut()
.ok_or(Error::MalformedDependencies)
})
.transpose()?
.and_then(|extras| extras.get_mut(group.as_ref()))
.map(|dependencies| {
dependencies
.as_array_mut()
.ok_or(Error::MalformedDependencies)
})
.transpose()?
else {
return Ok(Vec::new());
};
let requirements = remove_dependency(name, optional_dependencies);
self.remove_source(name)?;
Ok(requirements)
}
/// Removes all occurrences of the dependency in the group with the given name.
pub fn remove_dependency_group_requirement(
&mut self,
name: &PackageName,
group: &GroupName,
) -> Result<Vec<Requirement>, Error> {
// Try to get `project.optional-dependencies.<group>`.
let Some(group_dependencies) = self
.doc
.get_mut("dependency-groups")
.map(|groups| {
groups
.as_table_like_mut()
.ok_or(Error::MalformedDependencies)
})
.transpose()?
.and_then(|groups| groups.get_mut(group.as_ref()))
.map(|dependencies| {
dependencies
.as_array_mut()
.ok_or(Error::MalformedDependencies)
})
.transpose()?
else {
return Ok(Vec::new());
};
let requirements = remove_dependency(name, group_dependencies);
self.remove_source(name)?;
Ok(requirements)
}
/// Remove a matching source from `tool.uv.sources`, if it exists.
fn remove_source(&mut self, name: &PackageName) -> Result<(), Error> {
// If the dependency is still in use, don't remove the source.
if !self.find_dependency(name, None).is_empty() {
return Ok(());
}
if let Some(sources) = self
.doc
.get_mut("tool")
.map(|tool| tool.as_table_mut().ok_or(Error::MalformedSources))
.transpose()?
.and_then(|tool| tool.get_mut("uv"))
.map(|tool_uv| tool_uv.as_table_mut().ok_or(Error::MalformedSources))
.transpose()?
.and_then(|tool_uv| tool_uv.get_mut("sources"))
.map(|sources| sources.as_table_mut().ok_or(Error::MalformedSources))
.transpose()?
{
if let Some(key) = find_source(name, sources) {
sources.remove(&key);
// Remove the `tool.uv.sources` table if it is empty.
if sources.is_empty() {
self.doc
.entry("tool")
.or_insert(implicit())
.as_table_mut()
.ok_or(Error::MalformedSources)?
.entry("uv")
.or_insert(implicit())
.as_table_mut()
.ok_or(Error::MalformedSources)?
.remove("sources");
}
}
}
Ok(())
}
/// Returns `true` if the `tool.uv.dev-dependencies` table is present.
pub fn has_dev_dependencies(&self) -> bool {
self.doc
.get("tool")
.and_then(Item::as_table)
.and_then(|tool| tool.get("uv"))
.and_then(Item::as_table)
.and_then(|uv| uv.get("dev-dependencies"))
.is_some()
}
/// Returns `true` if the `dependency-groups` table is present and contains the given group.
pub fn has_dependency_group(&self, group: &GroupName) -> bool {
self.doc
.get("dependency-groups")
.and_then(Item::as_table)
.and_then(|groups| groups.get(group.as_ref()))
.is_some()
}
/// Returns all the places in this `pyproject.toml` that contain a dependency with the given
/// name.
///
/// This method searches `project.dependencies`, `tool.uv.dev-dependencies`, and
/// `tool.uv.optional-dependencies`.
pub fn find_dependency(
&self,
name: &PackageName,
marker: Option<&MarkerTree>,
) -> Vec<DependencyType> {
let mut types = Vec::new();
if let Some(project) = self.doc.get("project").and_then(Item::as_table) {
// Check `project.dependencies`.
if let Some(dependencies) = project.get("dependencies").and_then(Item::as_array) {
if !find_dependencies(name, marker, dependencies).is_empty() {
types.push(DependencyType::Production);
}
}
// Check `project.optional-dependencies`.
if let Some(extras) = project
.get("optional-dependencies")
.and_then(Item::as_table)
{
for (extra, dependencies) in extras {
let Some(dependencies) = dependencies.as_array() else {
continue;
};
let Ok(extra) = ExtraName::new(extra.to_string()) else {
continue;
};
if !find_dependencies(name, marker, dependencies).is_empty() {
types.push(DependencyType::Optional(extra));
}
}
}
}
// Check `dependency-groups`.
if let Some(groups) = self.doc.get("dependency-groups").and_then(Item::as_table) {
for (group, dependencies) in groups {
let Some(dependencies) = dependencies.as_array() else {
continue;
};
let Ok(group) = GroupName::new(group.to_string()) else {
continue;
};
if !find_dependencies(name, marker, dependencies).is_empty() {
types.push(DependencyType::Group(group));
}
}
}
// Check `tool.uv.dev-dependencies`.
if let Some(dev_dependencies) = self
.doc
.get("tool")
.and_then(Item::as_table)
.and_then(|tool| tool.get("uv"))
.and_then(Item::as_table)
.and_then(|uv| uv.get("dev-dependencies"))
.and_then(Item::as_array)
{
if !find_dependencies(name, marker, dev_dependencies).is_empty() {
types.push(DependencyType::Dev);
}
}
types
}
}
/// Returns an implicit table.
fn implicit() -> Item {
let mut table = Table::new();
table.set_implicit(true);
Item::Table(table)
}
/// Adds a dependency to the given `deps` array.
///
/// Returns `true` if the dependency was added, `false` if it was updated.
pub fn add_dependency(
req: &Requirement,
deps: &mut Array,
has_source: bool,
) -> Result<ArrayEdit, Error> {
let mut to_replace = find_dependencies(&req.name, Some(&req.marker), deps);
match to_replace.as_slice() {
[] => {
#[derive(Debug, Copy, Clone)]
enum Sort {
/// The list is sorted in a case-insensitive manner.
CaseInsensitive,
/// The list is sorted in a case-sensitive manner.
CaseSensitive,
/// The list is unsorted.
Unsorted,
}
/// Compare two [`Value`] requirements case-insensitively.
fn case_insensitive(a: &Value, b: &Value) -> Ordering {
a.as_str()
.map(str::to_lowercase)
.as_deref()
.map(split_specifiers)
.cmp(
&b.as_str()
.map(str::to_lowercase)
.as_deref()
.map(split_specifiers),
)
}
/// Compare two [`Value`] requirements case-sensitively.
fn case_sensitive(a: &Value, b: &Value) -> Ordering {
a.as_str()
.map(split_specifiers)
.cmp(&b.as_str().map(split_specifiers))
}
// Determine if the dependency list is sorted prior to
// adding the new dependency; the new dependency list
// will be sorted only when the original list is sorted
// so that user's custom dependency ordering is preserved.
//
// Additionally, if the table is invalid (i.e. contains non-string values)
// we still treat it as unsorted for the sake of simplicity.
//
// We account for both case-sensitive and case-insensitive sorting.
let sort = deps
.iter()
.all(Value::is_str)
.then(|| {
if deps.iter().tuple_windows().all(|(a, b)| {
matches!(case_insensitive(a, b), Ordering::Less | Ordering::Equal)
}) {
Some(Sort::CaseInsensitive)
} else if deps.iter().tuple_windows().all(|(a, b)| {
matches!(case_sensitive(a, b), Ordering::Less | Ordering::Equal)
}) {
Some(Sort::CaseSensitive)
} else {
None
}
})
.flatten()
.unwrap_or(Sort::Unsorted);
let req_string = req.to_string();
let index = match sort {
Sort::CaseInsensitive => deps.iter().position(|d| {
case_insensitive(d, &Value::from(req_string.as_str())) == Ordering::Greater
}),
Sort::CaseSensitive => deps.iter().position(|d| {
case_sensitive(d, &Value::from(req_string.as_str())) == Ordering::Greater
}),
Sort::Unsorted => None,
};
let index = index.unwrap_or(deps.len());
let mut value = Value::from(req_string.as_str());
let decor = value.decor_mut();
// If we're adding to the end of the list, treat trailing comments as leading comments
// on the added dependency.
//
// For example, given:
// ```toml
// dependencies = [