-
Notifications
You must be signed in to change notification settings - Fork 493
Expand file tree
/
Copy pathmain.rs
More file actions
1346 lines (1201 loc) · 43.6 KB
/
main.rs
File metadata and controls
1346 lines (1201 loc) · 43.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
mod build_script;
mod config;
mod metadata;
mod pypi_mapping;
use build_script::{BuildPlatform, BuildScriptContext, Installer};
use config::PythonBackendConfig;
use fs_err as fs;
use miette::IntoDiagnostic;
use pixi_build_backend::variants::NormalizedKey;
use pixi_build_backend::{
Variable,
generated_recipe::{GenerateRecipe, GeneratedRecipe, PythonParams},
intermediate_backend::IntermediateBackendInstantiator,
traits::ProjectModel,
};
use pyproject_toml::PyProjectToml;
use rattler_conda_types::{ChannelUrl, PackageName, Platform, Version, package::EntryPoint};
use recipe_stage0::matchspec::PackageDependency;
use recipe_stage0::recipe::{Item, NoArchKind, Python, Script, Value};
use std::collections::HashSet;
use std::{
collections::{BTreeMap, BTreeSet},
path::{Path, PathBuf},
str::FromStr,
sync::Arc,
};
use crate::metadata::{PyprojectManifestMode, PyprojectMetadataProvider};
use crate::pypi_mapping::{
detect_compilers_from_build_requirements, filter_mapped_pypi_deps,
map_requirements_with_channels,
};
/// Compute the `python-abi3` version spec from an optional `requires-python`
/// specifier string.
///
/// Extracts the lower bound (first `>=` specifier) and pins it to a single
/// minor version:
/// - `">=3.9"` → `"3.9.*"`
/// - `">=3.9.3"` → `"3.9.*"`
/// - `">=3.11,<4"` → `"3.11.*"`
/// - `None` → `"3.8.*"` (default)
fn python_abi3_spec_from_requires_python(requires_python: Option<&str>) -> miette::Result<String> {
let lower_bound = requires_python
.and_then(|s| {
let specifiers = pep440_rs::VersionSpecifiers::from_str(s).ok()?;
specifiers
.iter()
.find(|spec| *spec.operator() == pep440_rs::Operator::GreaterThanEqual)
.map(|spec| {
let pep_version = spec.version();
Version::from_str(&pep_version.to_string())
.expect("pep440 version should be a valid conda version")
})
})
.unwrap_or_else(|| Version::from_str("3.8").expect("valid version"));
let segment_count = std::cmp::min(lower_bound.segment_count(), 2);
let major_minor = lower_bound
.with_segments(..segment_count)
.ok_or_else(|| miette::miette!("failed to truncate version to major.minor"))?;
Ok(format!("{major_minor}.*"))
}
fn requirement_contains_package(
requirements: &[Item<PackageDependency>],
package_name: &str,
) -> bool {
requirements.iter().any(|item| match item {
Item::Value(Value::Concrete(dep)) => dep.package_name().as_normalized() == package_name,
Item::Value(Value::Template(spec)) => spec.split_whitespace().next() == Some(package_name),
Item::Conditional(cond) => cond
.then
.0
.iter()
.chain(cond.else_value.0.iter())
.any(|dep| dep.package_name().as_normalized() == package_name),
})
}
#[derive(Default, Clone)]
pub struct PythonGenerator {}
impl PythonGenerator {
/// Read the entry points from the pyproject.toml and return them as a list.
///
/// If the manifest is not a pyproject.toml file no entry-points are added.
pub(crate) fn entry_points(pyproject_manifest: Option<PyProjectToml>) -> Vec<EntryPoint> {
let scripts = pyproject_manifest
.as_ref()
.and_then(|p| p.project.as_ref())
.and_then(|p| p.scripts.as_ref());
scripts
.into_iter()
.flatten()
.flat_map(|(name, entry_point)| {
EntryPoint::from_str(&format!("{name} = {entry_point}"))
})
.collect()
}
}
#[async_trait::async_trait]
impl GenerateRecipe for PythonGenerator {
type Config = PythonBackendConfig;
async fn generate_recipe(
&self,
model: &pixi_build_types::ProjectModel,
config: &Self::Config,
manifest_path: PathBuf,
host_platform: Platform,
python_params: Option<PythonParams>,
variants: &HashSet<NormalizedKey>,
channels: Vec<ChannelUrl>,
cache_dir: Option<PathBuf>,
) -> miette::Result<GeneratedRecipe> {
let params = python_params.unwrap_or_default();
// Determine the manifest root, because `manifest_path` can be
// either a direct file path or a directory path.
let manifest_root = if manifest_path.is_file() {
manifest_path
.parent()
.ok_or_else(|| {
miette::Error::msg(format!(
"Manifest path {} is a file but has no parent directory.",
manifest_path.display()
))
})?
.to_path_buf()
} else {
manifest_path.clone()
};
let mode = if config
.ignore_pyproject_manifest
.is_some_and(|ignore| ignore)
{
PyprojectManifestMode::Ignore
} else {
PyprojectManifestMode::Read
};
let mut pyproject_metadata_provider = PyprojectMetadataProvider::new(&manifest_root, mode);
let mut generated_recipe =
GeneratedRecipe::from_model(model.clone(), &mut pyproject_metadata_provider)
.into_diagnostic()?;
let requirements = &mut generated_recipe.recipe.requirements;
// Get the platform-specific dependencies from the project model.
// This properly handles target selectors like [target.linux-64] by using
// the ProjectModel trait's platform-aware API instead of trying to evaluate
// rattler-build selectors with simple string comparison.
let model_dependencies = model.dependencies(Some(host_platform));
// Ensure the python build tools are added to the `host` requirements.
// Please note: this is a subtle difference for python, where the build tools
// are added to the `host` requirements, while for cmake/rust they are
// added to the `build` requirements.
// We only check build and host dependencies for the installer.
let installer =
Installer::determine_installer_from_names(model_dependencies.build_and_host_names());
let installer_name = installer.package_name().to_string();
let installer_pkg = pixi_build_types::SourcePackageName::from(installer_name.as_str());
// add installer in the host requirements
if !model_dependencies.host.contains_key(&installer_pkg) {
requirements
.host
.push(installer_name.parse().into_diagnostic()?);
}
// Get Python requirement spec
let python_requirement_str = match pyproject_metadata_provider.requires_python() {
Ok(Some(requires_python)) => format!("python {requires_python}"),
_ => "python".to_string(),
};
// Add python to host and run requirements, if not already set in the package manifest
let python_pkg = pixi_build_types::SourcePackageName::from("python");
let python_requirement: Item<PackageDependency> =
python_requirement_str.parse().into_diagnostic()?;
if !model_dependencies.host.contains_key(&python_pkg) {
requirements.host.push(python_requirement.clone());
}
if !model_dependencies.run.contains_key(&python_pkg) {
requirements.run.push(python_requirement);
}
// Detect compilers from build-system.requires (e.g., maturin -> rust)
// This needs to happen early so we can determine the correct platform for mapping
let auto_detected_compilers = pyproject_metadata_provider
.build_system_requires()?
.map(|reqs| detect_compilers_from_build_requirements(reqs))
.unwrap_or_default();
// Merge explicit config compilers with auto-detected ones
let mut compilers = config.compilers.clone().unwrap_or_default();
for compiler in auto_detected_compilers {
if !compilers.contains(&compiler) {
compilers.push(compiler);
}
}
// Determine whether the package should be built as a noarch package.
// This needs to be determined early so we can use the correct platform for PyPI mapping.
let has_compilers = !compilers.is_empty();
let is_noarch = if config.noarch == Some(true) {
// The user explicitly requested a noarch package.
true
} else if config.noarch == Some(false) {
// The user explicitly requested a non-noarch package.
false
} else if has_compilers {
// No specific user request, but we have compilers, not a noarch package.
false
} else {
// Otherwise, default to a noarch package.
// This is the default behavior for pure Python packages.
true
};
// Validate abi3 + noarch conflict
if config.abi3 == Some(true) && is_noarch {
miette::bail!(
"abi3 = true is incompatible with noarch packages. \
The stable ABI is only meaningful for packages with compiled extensions."
);
}
// ABI3 packages should not inherit CPython ABI pins from `host: python`.
if config.abi3 == Some(true) {
if !requirement_contains_package(&requirements.host, "python-abi3") {
let requires_python_str =
pyproject_metadata_provider.requires_python().ok().flatten();
let abi3_spec =
python_abi3_spec_from_requires_python(requires_python_str.as_deref())?;
let python_abi3_req: Item<PackageDependency> = format!("python-abi3 {abi3_spec}")
.parse()
.into_diagnostic()?;
requirements.host.push(python_abi3_req);
}
let python_package = PackageName::from_str("python").into_diagnostic()?;
if !requirements
.ignore_run_exports
.from_package
.contains(&python_package)
{
requirements
.ignore_run_exports
.from_package
.push(python_package);
}
}
// Use NoArch platform for mapping if this is a noarch package
let mapping_platform = if is_noarch {
Platform::NoArch
} else {
host_platform
};
// Map PyPI dependencies from pyproject.toml to conda dependencies
if !config.ignore_pypi_mapping() {
if let Some(pypi_deps) = pyproject_metadata_provider.project_dependencies()? {
let mapped_deps = map_requirements_with_channels(
pypi_deps,
&channels,
&cache_dir,
"project",
mapping_platform,
)
.await;
let skip_packages: HashSet<pixi_build_types::SourcePackageName> =
model_dependencies
.run
.keys()
.map(|k| (*k).clone())
.collect();
for match_spec in filter_mapped_pypi_deps(&mapped_deps, &skip_packages) {
requirements
.run
.push(match_spec.to_string().parse().into_diagnostic()?);
}
}
// Map build-system.requires from pyproject.toml to conda host dependencies
if let Some(build_system_deps) = pyproject_metadata_provider.build_system_requires()? {
let mapped_deps = map_requirements_with_channels(
build_system_deps,
&channels,
&cache_dir,
"build-system",
mapping_platform,
)
.await;
let skip_packages: HashSet<pixi_build_types::SourcePackageName> =
model_dependencies
.host
.keys()
.map(|k| (*k).clone())
.collect();
for match_spec in filter_mapped_pypi_deps(&mapped_deps, &skip_packages) {
requirements
.host
.push(match_spec.to_string().parse().into_diagnostic()?);
}
}
}
pixi_build_backend::compilers::add_compilers_to_requirements(
&compilers,
&mut requirements.build,
&model_dependencies,
&host_platform,
);
pixi_build_backend::compilers::add_stdlib_to_requirements(
&compilers,
&mut requirements.build,
variants,
);
let build_platform = Platform::current();
// TODO: remove this env var override as soon as we have profiles
let editable = std::env::var("BUILD_EDITABLE_PYTHON")
.map(|val| val == "true")
.unwrap_or(params.editable);
let build_script = BuildScriptContext {
installer,
build_platform: if build_platform.is_windows() {
BuildPlatform::Windows
} else {
BuildPlatform::Unix
},
editable,
extra_args: config.extra_args.clone(),
manifest_root: manifest_root.clone(),
}
.render();
// Convert the is_noarch boolean to the NoArchKind enum
let noarch_kind = if is_noarch {
Some(NoArchKind::Python)
} else {
None
};
// read pyproject.toml content if it exists
let pyproject_manifest_path = manifest_root.join("pyproject.toml");
let pyproject_manifest = if pyproject_manifest_path.exists() {
let contents = fs::read_to_string(&pyproject_manifest_path).into_diagnostic()?;
generated_recipe.build_input_globs =
BTreeSet::from([pyproject_manifest_path.to_string_lossy().to_string()]);
Some(toml::from_str(&contents).into_diagnostic()?)
} else {
None
};
// Construct python specific settings
let python = Python {
entry_points: PythonGenerator::entry_points(pyproject_manifest),
version_independent: config.abi3 == Some(true),
};
generated_recipe.recipe.build.python = python;
generated_recipe.recipe.build.noarch = noarch_kind;
generated_recipe.recipe.build.script = Script {
content: build_script,
env: config.env.clone(),
..Script::default()
};
// Add the metadata input globs from the MetadataProvider
generated_recipe
.metadata_input_globs
.extend(pyproject_metadata_provider.input_globs());
// Log any warnings collected during metadata extraction
for warning in pyproject_metadata_provider.warnings() {
tracing::warn!("{}", warning);
}
Ok(generated_recipe)
}
/// Determines the build input globs for given python package
/// even this will be probably backend specific, e.g setuptools
/// has a different way of determining the input globs than hatch etc.
///
/// However, lets take everything in the directory as input for now
fn extract_input_globs_from_build(
&self,
config: &Self::Config,
_workdir: impl AsRef<Path>,
editable: bool,
) -> miette::Result<BTreeSet<String>> {
let base_globs = Vec::from([
// Project configuration
"setup.py",
"setup.cfg",
"pyproject.toml",
"requirements*.txt",
"Pipfile",
"Pipfile.lock",
"poetry.lock",
"tox.ini",
]);
let compiler_based_globs: Vec<&str> = config
.compilers
.iter()
.flatten()
.flat_map(|c| match c.as_str() {
"rust" => vec!["**/*.rs", "**/Cargo.toml"],
"cxx" => vec!["**/*.{cc,cxx,cpp,hpp,hxx}"],
"c" => vec!["**/*.{c,h}"],
_ => vec![],
})
.collect();
let python_globs = if editable {
Vec::new()
} else {
Vec::from(["**/*.py", "**/*.pyx"])
};
Ok(base_globs
.iter()
.chain(python_globs.iter())
.chain(compiler_based_globs.iter())
.map(|s| s.to_string())
.chain(config.extra_input_globs.clone())
.collect())
}
fn default_variants(
&self,
host_platform: Platform,
) -> miette::Result<BTreeMap<NormalizedKey, Vec<Variable>>> {
let mut variants = BTreeMap::new();
if host_platform.is_windows() {
// Default to the Visual Studio 2022 compiler on Windows
// Not 2019 due to Conda-forge switching and the mainstream support dropping in 2024.
// rattler-build will default to vs2017 which for most github runners is too
// old.
variants.insert(NormalizedKey::from("c_compiler"), vec!["vs2022".into()]);
variants.insert(NormalizedKey::from("cxx_compiler"), vec!["vs2022".into()]);
}
Ok(variants)
}
}
#[tokio::main]
pub async fn main() {
if let Err(err) = pixi_build_backend::cli::main(|log| {
IntermediateBackendInstantiator::<PythonGenerator>::new(log, Arc::default())
})
.await
{
eprintln!("{err:?}");
std::process::exit(1);
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use indexmap::IndexMap;
use pixi_build_backend::utils::test::intermediate_conda_outputs;
use pixi_build_types::VariantValue;
use recipe_stage0::recipe::{Item, Value};
use tokio::fs;
use super::*;
#[test]
fn test_input_globs_includes_extra_globs() {
let config = PythonBackendConfig {
extra_input_globs: vec!["custom/*.py".to_string()],
..Default::default()
};
let generator = PythonGenerator::default();
let result = generator.extract_input_globs_from_build(&config, PathBuf::new(), false);
insta::assert_debug_snapshot!(result);
}
#[test]
fn test_input_globs_includes_extra_globs_editable() {
let config = PythonBackendConfig {
extra_input_globs: vec!["custom/*.py".to_string()],
..Default::default()
};
let generator = PythonGenerator::default();
let result = generator.extract_input_globs_from_build(&config, PathBuf::new(), true);
insta::assert_debug_snapshot!(result);
}
#[macro_export]
macro_rules! project_fixture {
($($json:tt)+) => {
serde_json::from_value::<pixi_build_types::ProjectModel>(
serde_json::json!($($json)+)
).expect("Failed to create TestProjectModel from JSON fixture.")
};
}
#[tokio::test]
async fn test_intermediate_conda_outputs_snapshot() {
let project_model = project_fixture!({
"name": "foobar",
"version": "0.1.0",
"targets": {
"defaultTarget": {
"buildDependencies": {
"boltons": {
"binary": {
"version": "*"
}
}
}
},
}
});
let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
fs::write(
temp_dir.path().join("pyproject.toml"),
r#"[project]
name = "foobar"
version = "0.1.0"
"#,
)
.await
.expect("Failed to write pyproject.toml");
fs::write(
temp_dir.path().join("pixi.toml"),
r#"[project]
name = "foobar"
version = "0.1.0"
"#,
)
.await
.expect("Failed to write pixi.toml");
let variant_configuration = BTreeMap::from([(
"boltons".to_string(),
Vec::from([VariantValue::from("==1.0.0")]),
)]);
let result = intermediate_conda_outputs::<PythonGenerator>(
Some(project_model),
Some(temp_dir.path().to_path_buf()),
Platform::Linux64,
Some(variant_configuration),
None,
)
.await;
assert_eq!(
result.outputs[0].metadata.variant["boltons"],
VariantValue::from("==1.0.0")
);
if let Some(tp) = result.outputs[0].metadata.variant.get("target_platform") {
assert_eq!(tp, &VariantValue::from("noarch"));
}
}
#[tokio::test]
async fn test_variant_files_are_applied() {
let project_model = project_fixture!({
"name": "foobar",
"version": "0.1.0",
"targets": {
"defaultTarget": {
"buildDependencies": {
"boltons": {
"binary": {
"version": "*"
}
}
}
},
}
});
let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
fs::write(
temp_dir.path().join("pyproject.toml"),
r#"[project]
name = "foobar"
version = "0.1.0"
"#,
)
.await
.expect("Failed to write pyproject.toml");
fs::write(
temp_dir.path().join("pixi.toml"),
r#"[project]
name = "foobar"
version = "0.1.0"
"#,
)
.await
.expect("Failed to write pixi.toml");
let variant_file = temp_dir.path().join("variants.yaml");
fs::write(
&variant_file,
r#"boltons:
- "==2.0.0"
"#,
)
.await
.expect("Failed to write variants file");
let result = intermediate_conda_outputs::<PythonGenerator>(
Some(project_model),
Some(temp_dir.path().to_path_buf()),
Platform::Linux64,
None,
Some(vec![variant_file]),
)
.await;
assert_eq!(
result.outputs[0].metadata.variant["boltons"],
VariantValue::from("==2.0.0")
);
if let Some(tp) = result.outputs[0].metadata.variant.get("target_platform") {
assert_eq!(tp, &VariantValue::from("noarch"));
}
}
#[tokio::test]
async fn test_pip_is_in_host_requirements() {
let project_model = project_fixture!({
"name": "foobar",
"version": "0.1.0",
"targets": {
"defaultTarget": {
"runDependencies": {
"boltons": {
"binary": {
"version": "*"
}
}
}
},
}
});
let generated_recipe = PythonGenerator::default()
.generate_recipe(
&project_model,
&PythonBackendConfig::default_with_ignore_pyproject_manifest(),
PathBuf::from("."),
Platform::Linux64,
None,
&HashSet::new(),
vec![],
None,
)
.await
.expect("Failed to generate recipe");
insta::assert_yaml_snapshot!(generated_recipe.recipe, {
".source[0].path" => "[ ... path ... ]",
".build.script" => "[ ... script ... ]",
});
}
#[tokio::test]
async fn test_python_is_not_added_if_already_present() {
let project_model = project_fixture!({
"name": "foobar",
"version": "0.1.0",
"targets": {
"defaultTarget": {
"runDependencies": {
"boltons": {
"binary": {
"version": "*"
}
}
},
"hostDependencies": {
"python": {
"binary": {
"version": "*"
}
}
}
},
}
});
let generated_recipe = PythonGenerator::default()
.generate_recipe(
&project_model,
&PythonBackendConfig::default_with_ignore_pyproject_manifest(),
PathBuf::from("."),
Platform::Linux64,
None,
&HashSet::new(),
vec![],
None,
)
.await
.expect("Failed to generate recipe");
insta::assert_yaml_snapshot!(generated_recipe.recipe, {
".source[0].path" => "[ ... path ... ]",
".build.script" => "[ ... script ... ]",
});
}
#[tokio::test]
async fn test_env_vars_are_set() {
let project_model = project_fixture!({
"name": "foobar",
"version": "0.1.0",
"targets": {
"defaultTarget": {
"runDependencies": {
"boltons": {
"binary": {
"version": "*"
}
}
}
},
}
});
let env = IndexMap::from([("foo".to_string(), "bar".to_string())]);
let generated_recipe = PythonGenerator::default()
.generate_recipe(
&project_model,
&PythonBackendConfig {
env: env.clone(),
ignore_pyproject_manifest: Some(true),
..Default::default()
},
PathBuf::from("."),
Platform::Linux64,
None,
&HashSet::new(),
vec![],
None,
)
.await
.expect("Failed to generate recipe");
insta::assert_yaml_snapshot!(generated_recipe.recipe.build.script,
{
".content" => "[ ... script ... ]",
});
}
#[tokio::test]
async fn test_multiple_compilers_configuration() {
let project_model = project_fixture!({
"name": "foobar",
"version": "0.1.0",
"targets": {
"defaultTarget": {
"runDependencies": {
"boltons": {
"binary": {
"version": "*"
}
}
}
},
}
});
let generated_recipe = PythonGenerator::default()
.generate_recipe(
&project_model,
&PythonBackendConfig {
compilers: Some(vec!["c".to_string(), "cxx".to_string(), "rust".to_string()]),
ignore_pyproject_manifest: Some(true),
..Default::default()
},
PathBuf::from("."),
Platform::Linux64,
None,
&HashSet::new(),
vec![],
None,
)
.await
.expect("Failed to generate recipe");
// Check that we have exactly the expected compilers
let build_reqs = &generated_recipe.recipe.requirements.build;
let compiler_templates: Vec<String> = build_reqs
.iter()
.filter_map(|item| match item {
Item::Value(Value::Template(s)) if s.contains("compiler") => Some(s.clone()),
_ => None,
})
.collect();
// Should have exactly three compilers
assert_eq!(
compiler_templates.len(),
3,
"Should have exactly three compilers"
);
// Check we have the expected compilers
assert!(
compiler_templates.contains(&"${{ compiler('c') }}".to_string()),
"C compiler should be in build requirements"
);
assert!(
compiler_templates.contains(&"${{ compiler('cxx') }}".to_string()),
"C++ compiler should be in build requirements"
);
assert!(
compiler_templates.contains(&"${{ compiler('rust') }}".to_string()),
"Rust compiler should be in build requirements"
);
}
#[tokio::test]
async fn test_default_no_compilers_when_not_specified() {
let project_model = project_fixture!({
"name": "foobar",
"version": "0.1.0",
"targets": {
"defaultTarget": {
"runDependencies": {
"boltons": {
"binary": {
"version": "*"
}
}
}
},
}
});
let generated_recipe = PythonGenerator::default()
.generate_recipe(
&project_model,
&PythonBackendConfig {
compilers: None,
ignore_pyproject_manifest: Some(true),
..Default::default()
},
PathBuf::from("."),
Platform::Linux64,
None,
&HashSet::new(),
vec![],
None,
)
.await
.expect("Failed to generate recipe");
// Check that no compilers are added by default
let build_reqs = &generated_recipe.recipe.requirements.build;
let compiler_templates: Vec<String> = build_reqs
.iter()
.filter_map(|item| match item {
Item::Value(Value::Template(s)) if s.contains("compiler") => Some(s.clone()),
_ => None,
})
.collect();
// Should have no compilers by default for Python packages
assert_eq!(
compiler_templates.len(),
0,
"Should have no compilers by default for pure Python packages"
);
}
// Helper function to create a minimal project fixture
fn minimal_project() -> pixi_build_types::ProjectModel {
project_fixture!({
"name": "foobar",
"version": "0.1.0",
"targets": {
"defaultTarget": {}
}
})
}
// Helper function to generate recipe with given config
async fn generate_test_recipe(
config: &PythonBackendConfig,
) -> Result<GeneratedRecipe, Box<dyn std::error::Error>> {
Ok(PythonGenerator::default()
.generate_recipe(
&minimal_project(),
config,
PathBuf::from("."),
Platform::Linux64,
None,
&std::collections::HashSet::<pixi_build_backend::variants::NormalizedKey>::new(),
vec![],
None,
)
.await?)
}
#[tokio::test]
async fn test_noarch_defaults_to_true_when_no_compilers() {
let recipe = generate_test_recipe(&PythonBackendConfig {
ignore_pyproject_manifest: Some(true),
..Default::default()
})
.await
.expect("Failed to generate recipe");
assert!(
matches!(recipe.recipe.build.noarch, Some(NoArchKind::Python)),
"noarch should default to true when no compilers specified"
);
}
#[tokio::test]
async fn test_noarch_defaults_to_false_when_compilers_present() {
let config = PythonBackendConfig {
compilers: Some(vec!["c".to_string()]),
ignore_pyproject_manifest: Some(true),
..Default::default()
};
let recipe = generate_test_recipe(&config)
.await
.expect("Failed to generate recipe");
assert!(
recipe.recipe.build.noarch.is_none(),
"noarch should default to false when compilers are present"
);
}
#[tokio::test]
async fn test_noarch_explicit_true_overrides_compilers() {
let config = PythonBackendConfig {
noarch: Some(true),
compilers: Some(vec!["c".to_string()]),
ignore_pyproject_manifest: Some(true),
..Default::default()
};
let recipe = generate_test_recipe(&config)
.await
.expect("Failed to generate recipe");
assert!(
matches!(recipe.recipe.build.noarch, Some(NoArchKind::Python)),
"explicit noarch=true should override compiler presence"
);
}
#[tokio::test]
async fn test_noarch_explicit_false_overrides_no_compilers() {
let config = PythonBackendConfig {
noarch: Some(false),
compilers: None,
ignore_pyproject_manifest: Some(true),
..Default::default()
};
let recipe = generate_test_recipe(&config)
.await
.expect("Failed to generate recipe");
assert!(