-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathutils.py
1260 lines (1038 loc) · 36.3 KB
/
utils.py
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
import contextlib
import copy
import datetime
import io
import itertools
import json
import logging
import os
import pprint
import re
import subprocess
import sys
import tempfile
import traceback
import typing
import warnings
from collections import defaultdict
from typing import Any, Dict, Iterable, Optional, Set, Tuple, cast
import jinja2
import jinja2.sandbox
import networkx as nx
import ruamel.yaml
from conda_forge_feedstock_ops.container_utils import (
get_default_log_level_args,
run_container_operation,
should_use_container,
)
from . import sensitive_env
from .lazy_json_backends import LazyJson
if typing.TYPE_CHECKING:
from mypy_extensions import TypedDict
from conda_forge_tick.migrators_types import RecipeTypedDict
logger = logging.getLogger(__name__)
T = typing.TypeVar("T")
TD = typing.TypeVar("TD", bound=dict, covariant=True)
PACKAGE_STUBS = [
"_compiler_stub",
"_stdlib_stub",
"subpackage_stub",
"compatible_pin_stub",
"cdt_stub",
]
class MockOS:
def __init__(self):
self.environ = defaultdict(str)
self.sep = "/"
CB_CONFIG = dict(
os=MockOS(),
environ=defaultdict(str),
compiler=lambda x: x + "_compiler_stub",
stdlib=lambda x: x + "_stdlib_stub",
pin_subpackage=lambda *args, **kwargs: args[0],
pin_compatible=lambda *args, **kwargs: args[0],
cdt=lambda *args, **kwargs: "cdt_stub",
cran_mirror="https://cran.r-project.org",
datetime=datetime,
load_file_regex=lambda *args, **kwargs: None,
)
def _munge_dict_repr(dct: Dict[Any, Any]) -> str:
from urllib.parse import quote_plus
return "__quote_plus__" + quote_plus(repr(dct)) + "__quote_plus__"
CB_CONFIG_PINNING = dict(
os=MockOS(),
environ=defaultdict(str),
compiler=lambda x: x + "_compiler_stub",
stdlib=lambda x: x + "_stdlib_stub",
# The `max_pin, ` stub is so we know when people used the functions
# to create the pins
pin_subpackage=lambda *args, **kwargs: _munge_dict_repr(
{"package_name": args[0], **kwargs},
),
pin_compatible=lambda *args, **kwargs: _munge_dict_repr(
{"package_name": args[0], **kwargs},
),
cdt=lambda *args, **kwargs: "cdt_stub",
cran_mirror="https://cran.r-project.org",
datetime=datetime,
load_file_regex=lambda *args, **kwargs: None,
)
DEFAULT_GRAPH_FILENAME = "graph.json"
DEFAULT_CONTAINER_TMPFS_SIZE_MB = 6000
def parse_munged_run_export(p: str) -> Dict:
from urllib.parse import unquote_plus
# get rid of comments
p = p.split("#")[0].strip()
# remove build string
p = p.rsplit("__quote_plus__", maxsplit=1)[0].strip()
# unquote
if p.startswith("__quote_plus__") or p.endswith("__quote_plus__"):
if p.startswith("__quote_plus__"):
p = p[len("__quote_plus__") :]
if p.endswith("__quote_plus__"):
p = p[: -len("__quote_plus__")]
p = unquote_plus(p)
return cast(Dict, yaml_safe_load(p))
REPRINTED_LINES = {}
@contextlib.contextmanager
def filter_reprinted_lines(key):
global REPRINTED_LINES
if key not in REPRINTED_LINES:
REPRINTED_LINES[key] = set()
stdout = io.StringIO()
stderr = io.StringIO()
try:
with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
yield
finally:
for line in stdout.getvalue().split("\n"):
if line not in REPRINTED_LINES[key]:
print(line, file=sys.stdout)
REPRINTED_LINES[key].add(line)
for line in stderr.getvalue().split("\n"):
if line not in REPRINTED_LINES[key]:
print(line, file=sys.stderr)
REPRINTED_LINES[key].add(line)
LOG_LINES_FOLDED = False
@contextlib.contextmanager
def fold_log_lines(title):
global LOG_LINES_FOLDED
try:
sys.stdout.flush()
sys.stderr.flush()
if os.environ.get("GITHUB_ACTIONS", "false") == "true" and not LOG_LINES_FOLDED:
LOG_LINES_FOLDED = True
print(f"::group::{title}", flush=True)
else:
print(">" * 80, flush=True)
print(">" * 80, flush=True)
print("> " + title, flush=True)
yield
finally:
sys.stdout.flush()
sys.stderr.flush()
if os.environ.get("GITHUB_ACTIONS", "false") == "true":
LOG_LINES_FOLDED = False
print("::endgroup::", flush=True)
def yaml_safe_load(stream):
"""Load a yaml doc safely"""
return ruamel.yaml.YAML(typ="safe", pure=True).load(stream)
def yaml_safe_dump(data, stream=None):
"""Dump a yaml object"""
yaml = ruamel.yaml.YAML(typ="safe", pure=True)
yaml.default_flow_style = False
return yaml.dump(data, stream=stream)
def _render_meta_yaml(text: str, for_pinning: bool = False, **kwargs) -> str:
"""Render the meta.yaml with Jinja2 variables.
Parameters
----------
text : str
The raw text in conda-forge feedstock meta.yaml file
Returns
-------
str
The text of the meta.yaml with Jinja2 variables replaced.
"""
cfg = dict(**kwargs)
env = jinja2.sandbox.SandboxedEnvironment(undefined=NullUndefined)
if for_pinning:
cfg.update(**CB_CONFIG_PINNING)
else:
cfg.update(**CB_CONFIG)
try:
return env.from_string(text).render(**cfg)
except Exception:
import traceback
logger.debug("render failure:\n%s", traceback.format_exc())
logger.debug("render template: %s", text)
logger.debug("render context:\n%s", pprint.pformat(cfg))
raise
def parse_recipe_yaml(
text: str,
for_pinning: bool = False,
platform_arch: str | None = None,
cbc_path: str | None = None,
use_container: bool | None = None,
) -> "RecipeTypedDict":
"""Parse the recipe.yaml.
Parameters
----------
text : str
The raw text in conda-forge feedstock recipe.yaml file
for_pinning : bool, optional
If True, render the recipe.yaml for pinning migrators, by default False.
platform_arch : str, optional
The platform and arch (e.g., 'linux-64', 'osx-arm64', 'win-64').
cbc_path : str, optional
The path to global pinning file.
log_debug : bool, optional
If True, print extra debugging info. Default is False.
use_container
Whether to use a container to run the parsing.
If None, the function will use a container if the environment
variable `CF_FEEDSTOCK_OPS_IN_CONTAINER` is 'false'. This feature can be
used to avoid container in container calls.
Returns
-------
dict :
The parsed YAML dict. If parsing fails, returns an empty dict. May raise
for some errors. Have fun.
"""
if should_use_container(use_container=use_container):
return parse_recipe_yaml_containerized(
text,
for_pinning=for_pinning,
platform_arch=platform_arch,
cbc_path=cbc_path,
)
else:
return parse_recipe_yaml_local(
text,
for_pinning=for_pinning,
platform_arch=platform_arch,
cbc_path=cbc_path,
)
def parse_recipe_yaml_containerized(
text: str,
for_pinning: bool = False,
platform_arch: str | None = None,
cbc_path: str | None = None,
) -> "RecipeTypedDict":
"""Parse the recipe.yaml.
**This function runs the parsing in a container.**
Parameters
----------
text : str
The raw text in conda-forge feedstock recipe.yaml file
for_pinning : bool, optional
If True, render the recipe.yaml for pinning migrators, by default False.
platform_arch : str, optional
The platform and arch (e.g., 'linux-64', 'osx-arm64', 'win-64').
cbc_path : str, optional
The path to global pinning file.
Returns
-------
dict :
The parsed YAML dict. If parsing fails, returns an empty dict. May raise
for some errors. Have fun.
"""
args = [
"conda-forge-tick-container",
"parse-recipe-yaml",
]
args += get_default_log_level_args(logger)
if platform_arch is not None:
args += ["--platform-arch", platform_arch]
if cbc_path is not None:
args += ["--cbc-path", cbc_path]
if for_pinning:
args += ["--for-pinning"]
return run_container_operation(
args,
input=text,
mount_readonly=True,
)
def parse_recipe_yaml_local(
text: str,
for_pinning: bool = False,
platform_arch: str | None = None,
cbc_path: str | None = None,
) -> "RecipeTypedDict":
"""Parse the recipe.yaml.
Parameters
----------
text : str
The raw text in conda-forge feedstock recipe.yaml file
for_pinning : bool, optional
If True, render the recipe.yaml for pinning migrators, by default False.
platform_arch : str, optional
The platform and arch (e.g., 'linux-64', 'osx-arm64', 'win-64').
cbc_path : str, optional
The path to global pinning file.
Returns
-------
dict :
The parsed YAML dict. If parsing fails, returns an empty dict. May raise
for some errors. Have fun.
"""
rendered_recipes = _render_recipe_yaml(
text, cbc_path=cbc_path, platform_arch=platform_arch
)
if for_pinning:
rendered_recipes = _process_recipe_for_pinning(rendered_recipes)
parsed_recipes = _parse_recipes(rendered_recipes)
return parsed_recipes
def replace_compiler_with_stub(text: str) -> str:
"""
Replace compiler function calls with a stub function call to match the conda-build
output.
Parameters
----------
text : str
Returns
-------
str
"""
pattern = r'\$\{\{\s*compiler\((["\'])(.*?)\1\)\s*\}\}'
text = re.sub(pattern, lambda m: f"{m.group(2)}_compiler_stub", text)
pattern = r'\$\{\{\s*stdlib\((["\'])(.*?)\1\)\s*\}\}'
text = re.sub(pattern, lambda m: f"{m.group(2)}_stdlib_stub", text)
return text
def _render_recipe_yaml(
text: str,
platform_arch: str | None = None,
cbc_path: str | None = None,
) -> list[dict[str, Any]]:
"""
Renders the given recipe YAML text using the `rattler-build` command-line tool.
Parameters
----------
text : str
The recipe YAML text to render.
platform : str, optional
The platform (e.g., 'linux', 'osx', 'win').
cbc_path : str, optional
The path to global pinning file.
Returns
-------
dict[str, Any]
The rendered recipe as a dictionary.
"""
variant_config_flags = [] if cbc_path is None else ["--variant-config", cbc_path]
build_platform_flags = (
[] if platform_arch is None else ["--build-platform", platform_arch]
)
prepared_text = replace_compiler_with_stub(text)
res = subprocess.run(
["rattler-build", "build", "--render-only"]
+ variant_config_flags
+ build_platform_flags,
stdout=subprocess.PIPE,
text=True,
input=prepared_text,
check=True,
)
return [output["recipe"] for output in json.loads(res.stdout)]
def _process_recipe_for_pinning(recipes: list[dict[str, Any]]) -> list[dict[str, Any]]:
def replace_name_key(d: dict[str, Any]) -> Any:
for key, value in d.items():
if isinstance(value, dict):
if key in ["pin_subpackage", "pin_compatible"] and "name" in value:
# Create a new dictionary with 'package_name' first
new_value = {"package_name": value.pop("name")}
new_value.update(value)
d[key] = {"name": _munge_dict_repr(new_value)}
else:
replace_name_key(value)
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
replace_name_key(item)
return d
return [replace_name_key(recipe) for recipe in recipes]
def _parse_recipes(
validated_recipes: list[dict[str, Any]],
) -> "RecipeTypedDict":
"""Parses validated recipes and transform them to fit `RecipeTypedDict`
Parameters
----------
validated_recipes : list[dict[str, Any]]
The recipes validated and rendered by `rattler-build`
Returns
-------
RecipeTypedDict
A dict conforming to conda-build's rendered output
"""
first = validated_recipes[0]
about = first["about"]
build = first["build"]
requirements = first["requirements"]
package = first["package"]
source = first.get("source")
about_data = (
None
if about is None
else {
"description": about.get("description"),
"dev_url": about.get("repository"),
"doc_url": about.get("documentation"),
"home": about.get("homepage"),
"license": about.get("license"),
"license_family": about.get("license"),
"license_file": about.get("license_file")[0],
"summary": about.get("summary"),
}
)
_parse_recipe_yaml_requirements(requirements)
build_data = (
None
if build is None or requirements is None
else {
"noarch": build.get("noarch"),
"number": str(build.get("number")),
"script": build.get("script"),
"run_exports": requirements.get("run_exports"),
}
)
package_data = (
None
if package is None
else {"name": package.get("name"), "version": package.get("version")}
)
if isinstance(source, list) and len(source) > 0:
source_data = {
"fn": source[0].get("file_name"),
"patches": source[0].get("patches"),
"sha256": source[0].get("sha256"),
"url": source[0].get("url"),
}
requirements_data = (
None
if requirements is None
else {
"build": requirements.get("build"),
"host": requirements.get("host"),
"run": requirements.get("run"),
}
)
output_data = []
for recipe in validated_recipes:
package_output = recipe.get("package")
requirements_output = recipe.get("requirements")
run_exports_output = (
None
if requirements_output is None
else requirements_output.get("run_exports")
)
requirements_output_data = (
None
if requirements_output is None
else {
"build": requirements_output.get("build", []),
"host": requirements_output.get("host", []),
"run": requirements_output.get("run", []),
}
)
build_output_data = (
None
if run_exports_output is None
else {
"strong": run_exports_output.get("strong", []),
"weak": run_exports_output.get("weak", []),
}
)
output_data.append(
{
"name": None if package_output is None else package_output.get("name"),
"requirements": requirements_output_data,
"build": build_output_data,
"tests": recipe.get("tests", []),
}
)
parsed_recipes = {
"about": about_data,
"build": build_data,
"package": package_data,
"requirements": requirements_data,
"source": source_data,
"outputs": output_data,
"extra": first.get("extra"),
}
return _remove_none_values(parsed_recipes)
def _parse_recipe_yaml_requirements(requirements) -> None:
"""Parse requirement section of render by rattler-build to fit `RecipeTypedDict`
When rendering the recipe by rattler build,
`requirements["run_exports"]["weak"]` gives a list looking like:
[
{
"pin_subpackage": {
"name": "slepc",
"lower_bound": "x.x.x.x.x.x",
"upper_bound": "x.x"
}
},
"numpy"
]
`run_exports["weak"]` of RecipeTypedDict looks like:
[
"slepc",
"numpy"
]
The same applies to "strong".
This function takes care of this transformation
requirements : dict
The requirements section of the recipe rendered by rattler-build.
This parameter will be modified by this function.
"""
if "run_exports" not in requirements:
return
run_exports = requirements["run_exports"]
for strength in ["strong", "weak"]:
original = run_exports.get(strength)
if isinstance(original, list):
result = []
for entry in original:
if isinstance(entry, str):
result.append(entry)
elif isinstance(entry, dict):
for key in ["pin_subpackage", "pin_compatible"]:
if key in entry and "name" in entry[key]:
result.append(entry[key]["name"])
run_exports[strength] = result
def _remove_none_values(d):
"""Recursively remove dictionary entries with None values."""
if not isinstance(d, dict):
return d
return {k: _remove_none_values(v) for k, v in d.items() if v is not None}
def parse_meta_yaml(
text: str,
for_pinning=False,
platform=None,
arch=None,
cbc_path=None,
orig_cbc_path=None,
log_debug=False,
use_container: bool | None = None,
) -> "RecipeTypedDict":
"""Parse the meta.yaml.
Parameters
----------
text : str
The raw text in conda-forge feedstock meta.yaml file
for_pinning : bool, optional
If True, render the meta.yaml for pinning migrators, by default False.
platform : str, optional
The platform (e.g., 'linux', 'osx', 'win').
arch : str, optional
The CPU architecture (e.g., '64', 'aarch64').
cbc_path : str, optional
The path to global pinning file.
orig_cbc_path : str, optional
If not None, the original conda build config file to put next to
the recipe while parsing.
log_debug : bool, optional
If True, print extra debugging info. Default is False.
use_container
Whether to use a container to run the parsing.
If None, the function will use a container if the environment
variable `CF_FEEDSTOCK_OPS_IN_CONTAINER` is 'false'. This feature can be
used to avoid container in container calls.
Returns
-------
dict :
The parsed YAML dict. If parsing fails, returns an empty dict. May raise
for some errors. Have fun.
"""
if should_use_container(use_container=use_container):
return parse_meta_yaml_containerized(
text,
for_pinning=for_pinning,
platform=platform,
arch=arch,
cbc_path=cbc_path,
orig_cbc_path=orig_cbc_path,
log_debug=log_debug,
)
else:
return parse_meta_yaml_local(
text,
for_pinning=for_pinning,
platform=platform,
arch=arch,
cbc_path=cbc_path,
orig_cbc_path=orig_cbc_path,
log_debug=log_debug,
)
def parse_meta_yaml_containerized(
text: str,
for_pinning=False,
platform=None,
arch=None,
cbc_path=None,
orig_cbc_path=None,
log_debug=False,
) -> "RecipeTypedDict":
"""Parse the meta.yaml.
**This function runs the parsing in a container.**
Parameters
----------
text : str
The raw text in conda-forge feedstock meta.yaml file
for_pinning : bool, optional
If True, render the meta.yaml for pinning migrators, by default False.
platform : str, optional
The platform (e.g., 'linux', 'osx', 'win').
arch : str, optional
The CPU architecture (e.g., '64', 'aarch64').
cbc_path : str, optional
The path to global pinning file.
orig_cbc_path : str, optional
If not None, the original conda build config file to put next to
the recipe while parsing.
log_debug : bool, optional
If True, print extra debugging info. Default is False.
Returns
-------
dict :
The parsed YAML dict. If parsing fails, returns an empty dict. May raise
for some errors. Have fun.
"""
args = [
"conda-forge-tick-container",
"parse-meta-yaml",
]
args += get_default_log_level_args(logger)
if platform is not None:
args += ["--platform", platform]
if arch is not None:
args += ["--arch", arch]
if log_debug:
args += ["--log-debug"]
if for_pinning:
args += ["--for-pinning"]
def _run(_args, _mount_dir):
return run_container_operation(
_args,
input=text,
mount_readonly=True,
mount_dir=_mount_dir,
)
if (cbc_path is not None and os.path.exists(cbc_path)) or (
orig_cbc_path is not None and os.path.exists(orig_cbc_path)
):
with tempfile.TemporaryDirectory() as tmpdir:
os.chmod(tmpdir, 0o755)
if cbc_path is not None and os.path.exists(cbc_path):
with open(os.path.join(tmpdir, "cbc_path.yaml"), "w") as fp:
with open(cbc_path) as fp_r:
fp.write(fp_r.read())
args += ["--cbc-path", "/cf_feedstock_ops_dir/cbc_path.yaml"]
if orig_cbc_path is not None and os.path.exists(orig_cbc_path):
with open(os.path.join(tmpdir, "orig_cbc_path.yaml"), "w") as fp:
with open(orig_cbc_path) as fp_r:
fp.write(fp_r.read())
args += ["--orig-cbc-path", "/cf_feedstock_ops_dir/orig_cbc_path.yaml"]
data = _run(args, tmpdir)
else:
data = _run(args, None)
return data
def parse_meta_yaml_local(
text: str,
for_pinning=False,
platform=None,
arch=None,
cbc_path=None,
orig_cbc_path=None,
log_debug=False,
) -> "RecipeTypedDict":
"""Parse the meta.yaml.
Parameters
----------
text : str
The raw text in conda-forge feedstock meta.yaml file
for_pinning : bool, optional
If True, render the meta.yaml for pinning migrators, by default False.
platform : str, optional
The platform (e.g., 'linux', 'osx', 'win').
arch : str, optional
The CPU architecture (e.g., '64', 'aarch64').
cbc_path : str, optional
The path to global pinning file.
orig_cbc_path : str, optional
If not None, the original conda build config file to put next to
the recipe while parsing.
log_debug : bool, optional
If True, print extra debugging info. Default is False.
Returns
-------
dict :
The parsed YAML dict. If parsing fails, returns an empty dict. May raise
for some errors. Have fun.
"""
def _run(*, use_orig_cbc_path):
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore",
message="The environment variable",
category=UserWarning,
module=r"conda_build\.environ",
)
class NumpyFilter(logging.Filter):
def filter(self, record):
if record.msg.startswith("No numpy version specified"):
return False
return True
np_filter = NumpyFilter()
try:
logging.getLogger("conda_build.metadata").addFilter(np_filter)
return _parse_meta_yaml_impl(
text,
for_pinning=for_pinning,
platform=platform,
arch=arch,
cbc_path=cbc_path,
log_debug=log_debug,
orig_cbc_path=(orig_cbc_path if use_orig_cbc_path else None),
)
finally:
logging.getLogger("conda_build.metadata").removeFilter(np_filter)
try:
return _run(use_orig_cbc_path=True)
except (SystemExit, Exception):
logger.debug("parsing w/ conda_build_config.yaml failed! " "trying without...")
try:
return _run(use_orig_cbc_path=False)
except (SystemExit, Exception) as e:
raise RuntimeError(
"conda build error: %s\n%s"
% (
repr(e),
traceback.format_exc(),
),
)
def _parse_meta_yaml_impl(
text: str,
for_pinning=False,
platform=None,
arch=None,
cbc_path=None,
log_debug=False,
orig_cbc_path=None,
) -> "RecipeTypedDict":
import conda_build.api
import conda_build.environ
from conda_build.config import Config
from conda_build.metadata import MetaData, parse
from conda_build.variants import explode_variants
if logger.getEffectiveLevel() <= logging.DEBUG:
log_debug = True
if cbc_path is not None and arch is not None and platform is not None:
with tempfile.TemporaryDirectory() as tmpdir:
with open(os.path.join(tmpdir, "meta.yaml"), "w") as fp:
fp.write(text)
if orig_cbc_path is not None and os.path.exists(orig_cbc_path):
with open(orig_cbc_path) as fp_r:
with open(
os.path.join(tmpdir, "conda_build_config.yaml"),
"w",
) as fp_w:
fp_w.write(fp_r.read())
def _run_parsing():
logger.debug(
"parsing for platform %s with cbc %s and arch %s"
% (
platform,
cbc_path,
arch,
),
)
config = conda_build.config.get_or_merge_config(
None,
platform=platform,
arch=arch,
variant_config_files=[
cbc_path,
],
)
_cbc, _ = conda_build.variants.get_package_combined_spec(
tmpdir,
config=config,
)
return config, _cbc
if not log_debug:
fout = io.StringIO()
ferr = io.StringIO()
# this code did use wulritzer.sys_pipes but that seemed
# to cause conda-build to hang
# versions:
# wurlitzer 3.0.2 py38h50d1736_1 conda-forge
# conda 4.11.0 py38h50d1736_0 conda-forge
# conda-build 3.21.7 py38h50d1736_0 conda-forge
with (
contextlib.redirect_stdout(
fout,
),
contextlib.redirect_stderr(ferr),
):
config, _cbc = _run_parsing()
else:
config, _cbc = _run_parsing()
cfg_as_dict = {}
for var in explode_variants(_cbc):
try:
m = MetaData(tmpdir, config=config, variant=var)
except SystemExit as e:
raise RuntimeError(repr(e))
cfg_as_dict.update(conda_build.environ.get_dict(m=m))
for key in cfg_as_dict:
try:
if cfg_as_dict[key].startswith("/"):
cfg_as_dict[key] = key
except Exception as e:
logger.debug(
"key-val not string: %s: %s", key, cfg_as_dict[key], exc_info=e
)
pass
cbc = Config(
platform=platform,
arch=arch,
variant=cfg_as_dict,
)
else:
with tempfile.TemporaryDirectory() as tmpdir:
with open(os.path.join(tmpdir, "meta.yaml"), "w") as fp:
fp.write(text)
_cfg = {}
if platform is not None:
_cfg["platform"] = platform
if arch is not None:
_cfg["arch"] = arch
cbc = Config(**_cfg)
try:
m = MetaData(tmpdir)
cfg_as_dict = conda_build.environ.get_dict(m=m)
except SystemExit as e:
raise RuntimeError(repr(e))
logger.debug("jinja2 environmment:\n%s", pprint.pformat(cfg_as_dict))
if for_pinning:
content = _render_meta_yaml(text, for_pinning=for_pinning, **cfg_as_dict)
else:
content = _render_meta_yaml(text, **cfg_as_dict)
try:
return parse(content, cbc)
except Exception:
import traceback
logger.debug("parse failure:\n%s", traceback.format_exc())
logger.debug("parse template: %s", text)
logger.debug("parse context:\n%s", pprint.pformat(cfg_as_dict))
raise
class UniversalSet(Set):
"""The universal set, or identity of the set intersection operation."""
def __and__(self, other: Set) -> Set:
return other
def __rand__(self, other: Set) -> Set:
return other
def __contains__(self, item: Any) -> bool:
return True
def __iter__(self) -> typing.Iterator[Any]:
return self
def __next__(self) -> typing.NoReturn:
raise StopIteration
def __len__(self) -> int:
return float("inf")
class NullUndefined(jinja2.Undefined):
def __unicode__(self) -> str: