forked from prefix-dev/pixi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsource.rs
546 lines (492 loc) · 18.9 KB
/
source.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
use std::fmt;
use pixi_consts::{consts, consts::PYPROJECT_PIXI_PREFIX};
use pixi_spec::PixiSpec;
use rattler_conda_types::{PackageName, Platform};
use toml_edit::{value, Array, Item, Table, Value};
use crate::toml::TomlDocument;
use crate::{
manifests::project::TableName, pypi::PyPiPackageName, FeatureName, PyPiRequirement,
PypiDependencyLocation, SpecType, Task, TomlError,
};
/// Discriminates between a 'pixi.toml' and a 'pyproject.toml' manifest.
#[derive(Debug, Clone)]
pub enum ManifestSource {
PyProjectToml(TomlDocument),
PixiToml(TomlDocument),
}
impl fmt::Display for ManifestSource {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ManifestSource::PyProjectToml(document) => write!(f, "{}", document),
ManifestSource::PixiToml(document) => write!(f, "{}", document),
}
}
}
impl ManifestSource {
/// Returns a new empty pixi manifest.
#[cfg(test)]
fn empty_pixi() -> Self {
ManifestSource::PixiToml(TomlDocument::default())
}
/// Returns a new empty pyproject manifest.
#[cfg(test)]
fn empty_pyproject() -> Self {
ManifestSource::PyProjectToml(TomlDocument::default())
}
/// Returns the file name of the manifest
#[cfg(test)]
fn file_name(&self) -> &'static str {
match self {
ManifestSource::PyProjectToml(_) => "pyproject.toml",
ManifestSource::PixiToml(_) => "pixi.toml",
}
}
fn table_prefix(&self) -> Option<&'static str> {
match self {
ManifestSource::PyProjectToml(_) => Some(PYPROJECT_PIXI_PREFIX),
ManifestSource::PixiToml(_) => None,
}
}
fn manifest_mut(&mut self) -> &mut TomlDocument {
match self {
ManifestSource::PyProjectToml(document) => document,
ManifestSource::PixiToml(document) => document,
}
}
fn manifest(&self) -> &TomlDocument {
match self {
ManifestSource::PyProjectToml(document) => document,
ManifestSource::PixiToml(document) => document,
}
}
/// Returns a mutable reference to the specified array either in project or
/// feature.
pub fn get_array_mut(
&mut self,
array_name: &str,
feature_name: &FeatureName,
) -> Result<&mut Array, TomlError> {
let table = match feature_name {
FeatureName::Default => Some("project"),
FeatureName::Named(_) => None,
};
let table_name = TableName::new()
.with_prefix(self.table_prefix())
.with_feature_name(Some(feature_name))
.with_table(table);
self.manifest_mut()
.get_or_insert_toml_array_mut(table_name.to_string().as_str(), array_name)
}
fn as_table_mut(&mut self) -> &mut Table {
match self {
ManifestSource::PyProjectToml(document) => document.as_table_mut(),
ManifestSource::PixiToml(document) => document.as_table_mut(),
}
}
/// Removes a pypi dependency from the TOML manifest from native pyproject
/// arrays and/or pixi tables as required.
///
/// If will be a no-op if the dependency is not found.
pub fn remove_pypi_dependency(
&mut self,
dep: &PyPiPackageName,
platform: Option<Platform>,
feature_name: &FeatureName,
) -> Result<(), TomlError> {
// For 'pyproject.toml' manifest, try and remove the dependency from native
// arrays
let remove_requirement =
|source: &mut ManifestSource, table, array_name| -> Result<(), TomlError> {
let array = source
.manifest_mut()
.get_mut_toml_array(table, array_name)?;
if let Some(array) = array {
array.retain(|x| {
let req: pep508_rs::Requirement = x
.as_str()
.unwrap_or("")
.parse()
.expect("should be a valid pep508 dependency");
let name = PyPiPackageName::from_normalized(req.name);
name != *dep
});
if array.is_empty() {
source
.manifest_mut()
.get_or_insert_nested_table(table)?
.remove(array_name);
}
}
Ok(())
};
match self {
ManifestSource::PyProjectToml(_) if feature_name.is_default() => {
remove_requirement(self, "project", "dependencies")?;
}
ManifestSource::PyProjectToml(_) => {
let name = feature_name.to_string();
remove_requirement(self, "project.optional-dependencies", &name)?;
remove_requirement(self, "dependency-groups", &name)?;
}
_ => (),
};
// For both 'pyproject.toml' and 'pixi.toml' manifest,
// try and remove the dependency from pixi native tables
let table_name = TableName::new()
.with_prefix(self.table_prefix())
.with_feature_name(Some(feature_name))
.with_platform(platform.as_ref())
.with_table(Some(consts::PYPI_DEPENDENCIES));
self.manifest_mut()
.get_or_insert_nested_table(table_name.to_string().as_str())
.map(|t| t.remove(dep.as_source()))?;
Ok(())
}
/// Removes a conda or pypi dependency from the TOML manifest's pixi table
/// for either a 'pyproject.toml' and 'pixi.toml'
///
/// If will be a no-op if the dependency is not found
pub fn remove_dependency(
&mut self,
dep: &PackageName,
spec_type: SpecType,
platform: Option<Platform>,
feature_name: &FeatureName,
) -> Result<(), TomlError> {
let table_name = TableName::new()
.with_prefix(self.table_prefix())
.with_feature_name(Some(feature_name))
.with_platform(platform.as_ref())
.with_table(Some(spec_type.name()));
self.manifest_mut()
.get_or_insert_nested_table(table_name.to_string().as_str())
.map(|t| t.remove(dep.as_source()))?;
Ok(())
}
/// Adds a conda dependency to the TOML manifest
///
/// If a dependency with the same name already exists, it will be replaced.
pub fn add_dependency(
&mut self,
name: &PackageName,
spec: &PixiSpec,
spec_type: SpecType,
platform: Option<Platform>,
feature_name: &FeatureName,
) -> Result<(), TomlError> {
let dependency_table = TableName::new()
.with_prefix(self.table_prefix())
.with_platform(platform.as_ref())
.with_feature_name(Some(feature_name))
.with_table(Some(spec_type.name()));
self.manifest_mut()
.get_or_insert_nested_table(dependency_table.to_string().as_str())
.map(|t| t.insert(name.as_normalized(), Item::Value(spec.to_toml_value())))?;
Ok(())
}
/// Adds a pypi dependency to the TOML manifest
///
/// If a pypi dependency with the same name already exists, it will be
/// replaced.
pub fn add_pypi_dependency(
&mut self,
requirement: &pep508_rs::Requirement,
platform: Option<Platform>,
feature_name: &FeatureName,
editable: Option<bool>,
location: &Option<PypiDependencyLocation>,
) -> Result<(), TomlError> {
// Pypi dependencies can be stored in different places in pyproject.toml
// manifests so we remove any potential dependency of the same name
// before adding it back
if matches!(self, ManifestSource::PyProjectToml(_)) {
self.remove_pypi_dependency(
&PyPiPackageName::from_normalized(requirement.name.clone()),
platform,
feature_name,
)?;
}
// The '[pypi-dependencies]' or '[tool.pixi.pypi-dependencies]' table is
// selected
// - For 'pixi.toml' manifests where it is the only choice
// - When explicitly requested
// - When a specific platform is requested, as markers are not supported (https://github.com/prefix-dev/pixi/issues/2149)
// - When an editable install is requested
if matches!(self, ManifestSource::PixiToml(_))
|| matches!(location, Some(PypiDependencyLocation::PixiPypiDependencies))
|| platform.is_some()
|| editable.is_some_and(|e| e)
{
let mut pypi_requirement =
PyPiRequirement::try_from(requirement.clone()).map_err(Box::new)?;
if let Some(editable) = editable {
pypi_requirement.set_editable(editable);
}
let dependency_table = TableName::new()
.with_prefix(self.table_prefix())
.with_platform(platform.as_ref())
.with_feature_name(Some(feature_name))
.with_table(Some(consts::PYPI_DEPENDENCIES));
self.manifest_mut()
.get_or_insert_nested_table(dependency_table.to_string().as_str())?
.insert(
requirement.name.as_ref(),
Item::Value(pypi_requirement.into()),
);
return Ok(());
}
// Otherwise:
// - the [project.dependencies] array is selected for the default feature
// - the [dependency-groups.feature_name] array is selected unless
// - optional-dependencies is explicitly requested as location
let add_requirement =
|source: &mut ManifestSource, table, array| -> Result<(), TomlError> {
source
.manifest_mut()
.get_or_insert_toml_array_mut(table, array)?
.push(requirement.to_string());
Ok(())
};
if feature_name.is_default()
|| matches!(location, Some(PypiDependencyLocation::Dependencies))
{
add_requirement(self, "project", "dependencies")?
} else if matches!(location, Some(PypiDependencyLocation::OptionalDependencies)) {
add_requirement(
self,
"project.optional-dependencies",
&feature_name.to_string(),
)?
} else {
add_requirement(self, "dependency-groups", &feature_name.to_string())?
}
Ok(())
}
/// Determines the location of a PyPi dependency within the manifest.
///
/// This method checks various sections of the manifest to locate the specified
/// PyPi dependency. It searches in the following order:
/// 1. `pypi-dependencies` table in the manifest.
/// 2. `project.dependencies` array in the manifest.
/// 3. `project.optional-dependencies` array in the manifest.
/// 4. `dependency-groups` array in the manifest.
///
/// # Arguments
///
/// * `dep` - The name of the PyPi package to locate.
/// * `platform` - An optional platform specification.
/// * `feature_name` - The name of the feature to which the dependency belongs.
///
/// # Returns
///
/// An `Option` containing the `PypiDependencyLocation` if the dependency is found,
/// or `None` if it is not found in any of the checked sections.
pub fn pypi_dependency_location(
&self,
package_name: &PyPiPackageName,
platform: Option<Platform>,
feature_name: &FeatureName,
) -> Option<PypiDependencyLocation> {
// For both 'pyproject.toml' and 'pixi.toml' manifest,
// try and to get `pypi-dependency`
let table_name = TableName::new()
.with_prefix(self.table_prefix())
.with_feature_name(Some(feature_name))
.with_platform(platform.as_ref())
.with_table(Some(consts::PYPI_DEPENDENCIES));
let pypi_dependency_table = self
.manifest()
.get_nested_table(table_name.to_string().as_str())
.ok();
if pypi_dependency_table
.and_then(|table| table.get(package_name.as_source()))
.is_some()
{
return Some(PypiDependencyLocation::PixiPypiDependencies);
}
if self
.manifest()
.get_toml_array("project", "dependencies")
.is_ok()
{
return Some(PypiDependencyLocation::Dependencies);
}
let name = feature_name.to_string();
if self
.manifest()
.get_toml_array("project.optional-dependencies", &name)
.is_ok()
{
return Some(PypiDependencyLocation::OptionalDependencies);
}
if self
.manifest()
.get_toml_array("dependency-groups", &name)
.is_ok()
{
return Some(PypiDependencyLocation::DependencyGroups);
}
None
}
/// Removes a task from the TOML manifest
pub fn remove_task(
&mut self,
name: &str,
platform: Option<Platform>,
feature_name: &FeatureName,
) -> Result<(), TomlError> {
// Get the task table either from the target platform or the default tasks.
// If it does not exist in TOML, consider this ok as we want to remove it
// anyways
let task_table = TableName::new()
.with_prefix(self.table_prefix())
.with_platform(platform.as_ref())
.with_feature_name(Some(feature_name))
.with_table(Some("tasks"));
self.manifest_mut()
.get_or_insert_nested_table(task_table.to_string().as_str())?
.remove(name);
Ok(())
}
/// Adds a task to the TOML manifest
pub fn add_task(
&mut self,
name: &str,
task: Task,
platform: Option<Platform>,
feature_name: &FeatureName,
) -> Result<(), TomlError> {
// Get the task table either from the target platform or the default tasks.
let task_table = TableName::new()
.with_prefix(self.table_prefix())
.with_platform(platform.as_ref())
.with_feature_name(Some(feature_name))
.with_table(Some("tasks"));
self.manifest_mut()
.get_or_insert_nested_table(task_table.to_string().as_str())?
.insert(name, task.into());
Ok(())
}
/// Adds an environment to the manifest
pub fn add_environment(
&mut self,
name: impl Into<String>,
features: Option<Vec<String>>,
solve_group: Option<String>,
no_default_features: bool,
) -> Result<(), TomlError> {
// Construct the TOML item
let item = if solve_group.is_some() || no_default_features {
let mut table = toml_edit::InlineTable::new();
if let Some(features) = features {
table.insert("features", Array::from_iter(features).into());
}
if let Some(solve_group) = solve_group {
table.insert("solve-group", solve_group.into());
}
if no_default_features {
table.insert("no-default-feature", true.into());
}
Item::Value(table.into())
} else {
Item::Value(Value::Array(Array::from_iter(
features.into_iter().flatten(),
)))
};
let env_table = TableName::new()
.with_prefix(self.table_prefix())
.with_feature_name(Some(&FeatureName::Default))
.with_table(Some("environments"));
// Get the environment table
self.manifest_mut()
.get_or_insert_nested_table(env_table.to_string().as_str())?
.insert(&name.into(), item);
Ok(())
}
/// Removes an environment from the manifest. Returns `true` if the
/// environment was removed.
pub fn remove_environment(&mut self, name: &str) -> Result<bool, TomlError> {
let env_table = TableName::new()
.with_prefix(self.table_prefix())
.with_feature_name(Some(&FeatureName::Default))
.with_table(Some("environments"));
Ok(self
.manifest_mut()
.get_or_insert_nested_table(env_table.to_string().as_str())?
.remove(name)
.is_some())
}
/// Sets the description of the project
pub fn set_description(&mut self, description: &str) {
self.as_table_mut()["project"]["description"] = value(description);
}
/// Sets the version of the project
pub fn set_version(&mut self, version: &str) {
self.as_table_mut()["project"]["version"] = value(version);
}
}
#[cfg(test)]
mod test {
use super::*;
use insta::assert_snapshot;
use rstest::rstest;
#[rstest]
#[case::pixi_toml(ManifestSource::empty_pixi())]
#[case::pyproject_toml(ManifestSource::empty_pyproject())]
fn test_add_environment(#[case] mut source: ManifestSource) {
source
.add_environment("foo", Some(vec![]), None, false)
.unwrap();
source
.add_environment("bar", Some(vec![String::from("default")]), None, false)
.unwrap();
source
.add_environment(
"baz",
Some(vec![String::from("default")]),
Some(String::from("group1")),
false,
)
.unwrap();
source
.add_environment(
"foobar",
Some(vec![String::from("default")]),
Some(String::from("group1")),
true,
)
.unwrap();
source
.add_environment("barfoo", Some(vec![String::from("default")]), None, true)
.unwrap();
// Overwrite
source
.add_environment("bar", Some(vec![String::from("not-default")]), None, false)
.unwrap();
assert_snapshot!(
format!("test_add_environment_{}", source.file_name()),
source.to_string()
);
}
#[rstest]
#[case::pixi_toml(ManifestSource::empty_pixi())]
#[case::pyproject_toml(ManifestSource::empty_pyproject())]
fn test_remove_environment(#[case] mut source: ManifestSource) {
source
.add_environment("foo", Some(vec![String::from("default")]), None, false)
.unwrap();
source
.add_environment("bar", Some(vec![String::from("default")]), None, false)
.unwrap();
assert!(!source.remove_environment("default").unwrap());
source
.add_environment("default", Some(vec![String::from("default")]), None, false)
.unwrap();
assert!(source.remove_environment("default").unwrap());
assert!(source.remove_environment("foo").unwrap());
assert_snapshot!(
format!("test_remove_environment_{}", source.file_name()),
source.to_string()
);
}
}