-
Notifications
You must be signed in to change notification settings - Fork 423
/
metadata.py
3007 lines (2678 loc) · 114 KB
/
metadata.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
# Copyright (C) 2014 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import copy
import hashlib
import json
import os
import re
import sys
import time
import warnings
from collections import OrderedDict
from functools import lru_cache
from os.path import isdir, isfile, join
from typing import TYPE_CHECKING, NamedTuple, overload
import yaml
from bs4 import UnicodeDammit
from conda.base.context import locate_prefix_by_name
from conda.gateways.disk.read import compute_sum
from conda.models.match_spec import MatchSpec
from frozendict import deepfreeze
from . import utils
from .config import Config, get_or_merge_config
from .deprecations import deprecated
from .exceptions import (
CondaBuildException,
CondaBuildUserError,
DependencyNeedsBuildingError,
RecipeError,
UnableToParse,
UnableToParseMissingJinja2,
)
from .features import feature_list
from .license_family import ensure_valid_license_family
from .utils import (
DEFAULT_SUBDIRS,
ensure_list,
expand_globs,
find_recipe,
get_installed_packages,
insert_variant_versions,
on_win,
)
from .variants import (
dict_of_lists_to_list_of_dicts,
find_used_variables_in_batch_script,
find_used_variables_in_shell_script,
find_used_variables_in_text,
get_default_variant,
get_vars,
list_of_dicts_to_dict_of_lists,
)
if TYPE_CHECKING:
from pathlib import Path
from typing import Any, Literal, Self
OutputDict = dict[str, Any]
OutputTuple = tuple[OutputDict, "MetaData"]
try:
import yaml
except ImportError:
sys.exit(
"Error: could not import yaml (required to read meta.yaml "
"files of conda recipes)"
)
try:
Loader = yaml.CLoader
except AttributeError:
Loader = yaml.Loader
class StringifyNumbersLoader(Loader):
@classmethod
def remove_implicit_resolver(cls, tag):
if "yaml_implicit_resolvers" not in cls.__dict__:
cls.yaml_implicit_resolvers = {
k: v[:] for k, v in cls.yaml_implicit_resolvers.items()
}
for ch in tuple(cls.yaml_implicit_resolvers):
resolvers = [(t, r) for t, r in cls.yaml_implicit_resolvers[ch] if t != tag]
if resolvers:
cls.yaml_implicit_resolvers[ch] = resolvers
else:
del cls.yaml_implicit_resolvers[ch]
@classmethod
def remove_constructor(cls, tag):
if "yaml_constructors" not in cls.__dict__:
cls.yaml_constructors = cls.yaml_constructors.copy()
if tag in cls.yaml_constructors:
del cls.yaml_constructors[tag]
StringifyNumbersLoader.remove_implicit_resolver("tag:yaml.org,2002:float")
StringifyNumbersLoader.remove_implicit_resolver("tag:yaml.org,2002:int")
StringifyNumbersLoader.remove_constructor("tag:yaml.org,2002:float")
StringifyNumbersLoader.remove_constructor("tag:yaml.org,2002:int")
# arches that don't follow exact names in the subdir need to be mapped here
ARCH_MAP = {"32": "x86", "64": "x86_64"}
NOARCH_TYPES = ("python", "generic", True)
# we originally matched outputs based on output name. Unfortunately, that
# doesn't work when outputs are templated - we want to match un-rendered
# text, but we have rendered names.
# We overcome that divide by finding the output index in a rendered set of
# outputs, so our names match, then we use that numeric index with this
# regex, which extract all outputs in order.
# Stop condition is one of 3 things:
# \w at the start of a line (next top-level section)
# \Z (end of file)
# next output, as delineated by "- name" or "- type"
output_re = re.compile(
r"^\ +-\ +(?:name|type):.+?(?=^\w|\Z|^\ +-\ +(?:name|type))", flags=re.M | re.S
)
numpy_xx_re = re.compile(
r"(numpy\s*x\.x)|pin_compatible\([\'\"]numpy.*max_pin=[\'\"]x\.x[\'\"]"
)
# TODO: there's probably a way to combine these, but I can't figure out how to many the x
# capturing group optional.
numpy_compatible_x_re = re.compile(
r"pin_\w+\([\'\"]numpy[\'\"].*((?<=x_pin=[\'\"])[x\.]*(?=[\'\"]))"
)
numpy_compatible_re = re.compile(r"pin_\w+\([\'\"]numpy[\'\"]")
# used to avoid recomputing/rescanning recipe contents for used variables
used_vars_cache = {}
def get_selectors(config: Config) -> dict[str, bool]:
"""Aggregates selectors for use in recipe templating.
Derives selectors from the config and variants to be injected
into the Jinja environment prior to templating.
Args:
config (Config): The config object
Returns:
dict[str, bool]: Dictionary of on/off selectors for Jinja
"""
# Remember to update the docs of any of this changes
plat = config.host_subdir
d = dict(
linux32=bool(plat == "linux-32"),
linux64=bool(plat == "linux-64"),
arm=plat.startswith("linux-arm"),
unix=plat.startswith(("linux-", "osx-", "emscripten-")),
win32=bool(plat == "win-32"),
win64=bool(plat == "win-64"),
os=os,
environ=os.environ,
nomkl=bool(int(os.environ.get("FEATURE_NOMKL", False))),
)
# Add the current platform to the list of subdirs to enable conda-build
# to bootstrap new platforms without a new conda release.
subdirs = list(DEFAULT_SUBDIRS) + [plat]
# filter out noarch and other weird subdirs
subdirs = [subdir for subdir in subdirs if "-" in subdir]
subdir_oses = {subdir.split("-")[0] for subdir in subdirs}
subdir_archs = {subdir.split("-")[1] for subdir in subdirs}
for subdir_os in subdir_oses:
d[subdir_os] = plat.startswith(f"{subdir_os}-")
for arch in subdir_archs:
arch_full = ARCH_MAP.get(arch, arch)
d[arch_full] = plat.endswith(f"-{arch}")
if arch == "32":
d["x86"] = plat.endswith(("-32", "-64"))
defaults = get_default_variant(config)
py = config.variant.get("python", defaults["python"])
# there are times when python comes in as a tuple
if not hasattr(py, "split"):
py = py[0]
# go from "3.6 *_cython" -> "36"
# or from "3.6.9" -> "36"
py_major, py_minor, *_ = py.split(" ")[0].split(".")
py = int(f"{py_major}{py_minor}")
d["build_platform"] = config.build_subdir
d.update(
dict(
py=py,
py3k=bool(py_major == "3"),
py2k=bool(py_major == "2"),
py26=bool(py == 26),
py27=bool(py == 27),
py33=bool(py == 33),
py34=bool(py == 34),
py35=bool(py == 35),
py36=bool(py == 36),
)
)
np = config.variant.get("numpy")
if not np:
np = defaults["numpy"]
if config.verbose:
utils.get_logger(__name__).warning(
"No numpy version specified in conda_build_config.yaml. "
"Falling back to default numpy value of {}".format(defaults["numpy"])
)
d["np"] = int("".join(np.split(".")[:2]))
pl = config.variant.get("perl", defaults["perl"])
d["pl"] = pl
lua = config.variant.get("lua", defaults["lua"])
d["lua"] = lua
d["luajit"] = bool(lua[0] == "2")
for feature, value in feature_list:
d[feature] = value
d.update(os.environ)
# here we try to do some type conversion for more intuitive usage. Otherwise,
# values like 35 are strings by default, making relational operations confusing.
# We also convert "True" and things like that to booleans.
for k, v in config.variant.items():
if k not in d:
try:
d[k] = int(v)
except (TypeError, ValueError):
if isinstance(v, str) and v.lower() in ("false", "true"):
v = v.lower() == "true"
d[k] = v
return d
def ns_cfg(config: Config) -> dict[str, bool]:
warnings.warn(
"`conda_build.metadata.ns_cfg` is pending deprecation and will be removed in a "
"future release. Please use `conda_build.metadata.get_selectors` instead.",
PendingDeprecationWarning,
)
return get_selectors(config)
# Selectors must be either:
# - at end of the line
# - embedded (anywhere) within a comment
#
# Notes:
# - [([^\[\]]+)\] means "find a pair of brackets containing any
# NON-bracket chars, and capture the contents"
# - (?(2)[^\(\)]*)$ means "allow trailing characters iff group 2 (#.*) was found."
# Skip markdown link syntax.
sel_pat = re.compile(r"(.+?)\s*(#.*)?\[([^\[\]]+)\](?(2)[^\(\)]*)$")
# this function extracts the variable name from a NameError exception, it has the form of:
# "NameError: name 'var' is not defined", where var is the variable that is not defined. This gets
# returned
def parseNameNotFound(error):
m = re.search("'(.+?)'", str(error))
if len(m.groups()) == 1:
return m.group(1)
else:
return ""
# We evaluate the selector and return True (keep this line) or False (drop this line)
# If we encounter a NameError (unknown variable in selector), then we replace it by False and
# re-run the evaluation
def eval_selector(selector_string, namespace, variants_in_place):
try:
# TODO: is there a way to do this without eval? Eval allows arbitrary
# code execution.
return eval(selector_string, namespace, {})
except NameError as e:
missing_var = parseNameNotFound(e)
if variants_in_place:
log = utils.get_logger(__name__)
log.debug(
"Treating unknown selector '" + missing_var + "' as if it was False."
)
next_string = selector_string.replace(missing_var, "False")
return eval_selector(next_string, namespace, variants_in_place)
@lru_cache(maxsize=None)
def _split_line_selector(text: str) -> tuple[tuple[str | None, str], ...]:
lines: list[tuple[str | None, str]] = []
for line in text.splitlines():
line = line.rstrip()
# skip comment lines, include a blank line as a placeholder
if line.lstrip().startswith("#"):
lines.append((None, ""))
continue
# include blank lines
if not line:
lines.append((None, ""))
continue
# user may have quoted entire line to make YAML happy
trailing_quote = ""
if line and line[-1] in ("'", '"'):
trailing_quote = line[-1]
# Checking for "[" and "]" before regex matching every line is a bit faster.
if (
("[" in line and "]" in line)
and (match := sel_pat.match(line))
and (selector := match.group(3))
):
# found a selector
lines.append((selector, (match.group(1) + trailing_quote).rstrip()))
else:
# no selector found
lines.append((None, line))
return tuple(lines)
def select_lines(text: str, namespace: dict[str, Any], variants_in_place: bool) -> str:
lines = []
selector_cache: dict[str, bool] = {}
for i, (selector, line) in enumerate(_split_line_selector(text)):
if not selector:
# no selector? include line as is
lines.append(line)
else:
# include lines with a selector that evaluates to True
try:
if selector_cache[selector]:
lines.append(line)
except KeyError:
# KeyError: cache miss
try:
value = bool(eval_selector(selector, namespace, variants_in_place))
selector_cache[selector] = value
if value:
lines.append(line)
except Exception as e:
raise CondaBuildUserError(
f"Invalid selector in meta.yaml line {i + 1}:\n"
f"offending selector:\n"
f" [{selector}]\n"
f"exception:\n"
f" {e.__class__.__name__}: {e}\n"
)
return "\n".join(lines) + "\n"
def yamlize(data):
try:
return yaml.load(data, Loader=StringifyNumbersLoader)
except yaml.error.YAMLError as e:
if "{{" in data:
try:
import jinja2
jinja2 # Avoid pyflakes failure: 'jinja2' imported but unused
except ImportError:
raise UnableToParseMissingJinja2(original=e)
print("Problematic recipe:", file=sys.stderr)
print(data, file=sys.stderr)
raise UnableToParse(original=e)
def ensure_valid_fields(meta):
pin_depends = meta.get("build", {}).get("pin_depends", "")
if pin_depends and pin_depends not in ("", "record", "strict"):
raise RuntimeError(
f"build/pin_depends must be 'record' or 'strict' - not '{pin_depends}'"
)
def _trim_None_strings(meta_dict):
log = utils.get_logger(__name__)
for key, value in meta_dict.items():
if hasattr(value, "keys"):
meta_dict[key] = _trim_None_strings(value)
elif value and hasattr(value, "__iter__") or isinstance(value, str):
if isinstance(value, str):
meta_dict[key] = None if "None" in value else value
else:
# support lists of dicts (homogeneous)
keep = []
if hasattr(next(iter(value)), "keys"):
for d in value:
trimmed_dict = _trim_None_strings(d)
if trimmed_dict:
keep.append(trimmed_dict)
# support lists of strings (homogeneous)
else:
keep = [i for i in value if i not in ("None", "NoneType")]
meta_dict[key] = keep
else:
log.debug(
f"found unrecognized data type in dictionary: {value}, type: {type(value)}"
)
return meta_dict
def ensure_valid_noarch_value(meta):
build_noarch = meta.get("build", {}).get("noarch")
if build_noarch and build_noarch not in NOARCH_TYPES:
raise CondaBuildException(f"Invalid value for noarch: {build_noarch}")
def _get_all_dependencies(metadata, envs=("host", "build", "run")):
reqs = []
for _env in envs:
reqs.extend(metadata.meta.get("requirements", {}).get(_env, []))
return reqs
def _check_circular_dependencies(
render_order: list[OutputTuple],
config: Config | None = None,
) -> None:
envs: tuple[str, ...]
if config and config.host_subdir != config.build_subdir:
# When cross compiling build dependencies are already built
# and cannot come from the recipe as subpackages
envs = ("host", "run")
else:
envs = ("build", "host", "run")
pairs: list[tuple[str, str]] = []
for idx, (_, metadata) in enumerate(render_order):
name = metadata.name()
for _, other_metadata in render_order[idx + 1 :]:
other_name = other_metadata.name()
if any(
name == dep.split(" ")[0]
for dep in _get_all_dependencies(other_metadata, envs=envs)
) and any(
other_name == dep.split(" ")[0]
for dep in _get_all_dependencies(metadata, envs=envs)
):
pairs.append((name, other_name))
if pairs:
error = "Circular dependencies in recipe: \n"
for pair in pairs:
error += " {} <-> {}\n".format(*pair)
raise RecipeError(error)
def _check_run_constrained(metadata_tuples):
errors = []
for _, metadata in metadata_tuples:
for dep in _get_all_dependencies(metadata, envs=("run_constrained",)):
if "{{" in dep:
# skip Jinja content; it might have not been rendered yet; we'll get it next call
continue
try:
MatchSpec(dep)
except ValueError as exc:
errors.append(
f"- Output '{metadata.name()}' has invalid run_constrained item: {dep}. "
f"Reason: {exc}"
)
if errors:
raise RecipeError("\n".join(["", *errors]))
def _variants_equal(metadata, output_metadata):
match = True
for key, val in metadata.config.variant.items():
if (
key in output_metadata.config.variant
and val != output_metadata.config.variant[key]
):
match = False
return match
def ensure_matching_hashes(output_metadata):
envs = "build", "host", "run"
problemos = []
for _, m in output_metadata.values():
for _, om in output_metadata.values():
if m != om:
run_exports = om.get_value("build/run_exports", [])
if hasattr(run_exports, "keys"):
run_exports_list = []
for export_type in utils.RUN_EXPORTS_TYPES:
run_exports_list = run_exports_list + run_exports.get(
export_type, []
)
run_exports = run_exports_list
deps = _get_all_dependencies(om, envs) + run_exports
for dep in deps:
if (
dep.startswith(m.name() + " ")
and len(dep.split(" ")) == 3
and dep.split(" ")[-1] != m.build_id()
and _variants_equal(m, om)
):
problemos.append((m.name(), m.build_id(), dep, om.name()))
if problemos:
error = ""
for prob in problemos:
error += "Mismatching package: {} (id {}); dep: {}; consumer package: {}\n".format(
*prob
)
raise RecipeError(
"Mismatching hashes in recipe. Exact pins in dependencies "
"that contribute to the hash often cause this. Can you "
"change one or more exact pins to version bound constraints?\n"
"Involved packages were:\n" + error
)
def parse(data, config, path=None):
data = select_lines(
data,
get_selectors(config),
variants_in_place=bool(config.variant),
)
res = yamlize(data)
# ensure the result is a dict
if res is None:
res = {}
for field in FIELDS:
if field not in res:
continue
# ensure that empty fields are dicts (otherwise selectors can cause invalid fields)
if not res[field]:
res[field] = {}
# source field may be either a dictionary, or a list of dictionaries
if field in OPTIONALLY_ITERABLE_FIELDS:
if not (
isinstance(res[field], dict)
or (hasattr(res[field], "__iter__") and not isinstance(res[field], str))
):
raise RuntimeError(
f"The {field} field should be a dict or list of dicts, not "
f"{res[field].__class__.__name__} in file {path}."
)
else:
if not isinstance(res[field], dict):
raise RuntimeError(
f"The {field} field should be a dict, not "
f"{res[field].__class__.__name__} in file {path}."
)
ensure_valid_fields(res)
ensure_valid_license_family(res)
ensure_valid_noarch_value(res)
return sanitize(res)
TRUES = {"y", "on", "true", "yes"}
FALSES = {"n", "no", "false", "off"}
# If you update this please update the example in
# conda-docs/docs/source/build.rst
FIELDS = {
"package": {
"name": None,
"version": str,
},
"source": {
"fn": None,
"url": None,
"md5": str,
"sha1": None,
"sha256": None,
"path": str,
"path_via_symlink": None,
"git_url": str,
"git_tag": str,
"git_branch": str,
"git_rev": str,
"git_depth": None,
"hg_url": None,
"hg_tag": None,
"svn_url": str,
"svn_rev": None,
"svn_ignore_externals": None,
"svn_username": None,
"svn_password": None,
"folder": None,
"no_hoist": None,
"patches": list,
},
"build": {
"number": None,
"string": str,
"entry_points": list,
"osx_is_app": bool,
"disable_pip": None,
"features": list,
"track_features": list,
"preserve_egg_dir": bool,
"no_link": None,
"binary_relocation": bool,
"script": list,
"noarch": str,
"noarch_python": bool,
"has_prefix_files": None,
"binary_has_prefix_files": None,
"ignore_prefix_files": None,
"detect_binary_files_with_prefix": bool,
"skip_compile_pyc": list,
"rpaths": None,
"rpaths_patcher": None,
"script_env": list,
"always_include_files": None,
"skip": bool,
"msvc_compiler": str,
"pin_depends": str, # still experimental
"include_recipe": None,
"preferred_env": str,
"preferred_env_executable_paths": list,
"run_exports": list,
"ignore_run_exports": list,
"ignore_run_exports_from": list,
"requires_features": dict,
"provides_features": dict,
"force_use_keys": list,
"force_ignore_keys": list,
"merge_build_host": None,
"pre-link": str,
"post-link": str,
"pre-unlink": str,
"missing_dso_whitelist": None,
"error_overdepending": None,
"error_overlinking": None,
"overlinking_ignore_patterns": [],
},
"outputs": {
"name": None,
"version": None,
"number": None,
"entry_points": None,
"script": None,
"script_interpreter": None,
"build": None,
"requirements": None,
"test": None,
"about": None,
"extra": None,
"files": None,
"type": None,
"run_exports": None,
"target": None,
},
"requirements": {
"build": list,
"host": list,
"run": list,
"conflicts": list,
"run_constrained": list,
},
"app": {
"entry": None,
"icon": None,
"summary": None,
"type": None,
"cli_opts": None,
"own_environment": bool,
},
"test": {
"requires": list,
"commands": list,
"files": list,
"imports": list,
"source_files": list,
"downstreams": list,
},
"about": {
"home": None,
# these are URLs
"dev_url": None,
"doc_url": None,
"doc_source_url": None,
"license_url": None,
# text
"license": None,
"summary": None,
"description": None,
"license_family": None,
# lists
"identifiers": list,
"tags": list,
"keywords": list,
# paths in source tree
"license_file": None,
"prelink_message": None,
"readme": None,
},
"extra": {},
}
# Fields that may either be a dictionary or a list of dictionaries.
OPTIONALLY_ITERABLE_FIELDS = ("source", "outputs")
def sanitize(meta):
"""
Sanitize the meta-data to remove aliases/handle deprecation
"""
sanitize_funs = {
"source": [_git_clean],
"package": [_str_version],
"build": [_str_version],
}
for section, funs in sanitize_funs.items():
if section in meta:
for func in funs:
section_data = meta[section]
# section is a dictionary
if hasattr(section_data, "keys"):
section_data = func(section_data)
# section is a list of dictionaries
else:
section_data = [func(_d) for _d in section_data]
meta[section] = section_data
return meta
def _git_clean(source_meta):
"""
Reduce the redundancy in git specification by removing git_tag and
git_branch.
If one is specified, copy to git_rev.
If more than one field is used to specified, exit
and complain.
"""
git_rev_tags_old = ("git_branch", "git_tag")
git_rev = "git_rev"
git_rev_tags = (git_rev,) + git_rev_tags_old
has_rev_tags = tuple(bool(source_meta.get(tag, "")) for tag in git_rev_tags)
keys = [key for key in (git_rev, "git_branch", "git_tag") if key in source_meta]
if not keys:
# git_branch, git_tag, nor git_rev specified, return as-is
return source_meta
elif len(keys) > 1:
raise CondaBuildUserError(f"Multiple git_revs: {', '.join(keys)}")
# make a copy of the input so we have no side-effects
ret_meta = source_meta.copy()
# loop over the old versions
for key, has in zip(git_rev_tags[1:], has_rev_tags[1:]):
# update if needed
if has:
ret_meta[git_rev_tags[0]] = ret_meta[key]
# and remove
ret_meta.pop(key, None)
return ret_meta
def _str_version(package_meta):
if "version" in package_meta:
package_meta["version"] = str(package_meta.get("version", ""))
if "msvc_compiler" in package_meta:
package_meta["msvc_compiler"] = str(package_meta.get("msvc_compiler", ""))
return package_meta
def check_bad_chrs(value: str, field: str) -> None:
bad_chrs = set("=@#$%^&*:;\"'\\|<>?/ ")
if field in ("package/version", "build/string"):
bad_chrs.add("-")
if field != "package/version":
bad_chrs.add("!")
if invalid := bad_chrs.intersection(value):
raise CondaBuildUserError(
f"Bad character(s) ({''.join(sorted(invalid))}) in {field}: {value}."
)
def get_package_version_pin(build_reqs, name):
version = ""
for spec in build_reqs:
if spec.split()[0] == name and len(spec.split()) > 1:
version = spec.split()[1]
return version
def build_string_from_metadata(metadata):
if metadata.meta.get("build", {}).get("string"):
build_str = metadata.get_value("build/string")
else:
res = []
build_or_host = "host" if metadata.is_cross else "build"
build_pkg_names = [ms.name for ms in metadata.ms_depends(build_or_host)]
build_deps = metadata.meta.get("requirements", {}).get(build_or_host, [])
# TODO: this is the bit that puts in strings like py27np111 in the filename. It would be
# nice to get rid of this, since the hash supercedes that functionally, but not clear
# whether anyone's tools depend on this file naming right now.
for s, names, places in (
("np", "numpy", 2),
("py", "python", 2),
("pl", "perl", 3),
("lua", "lua", 2),
("r", ("r", "r-base"), 2),
("mro", "mro-base", 3),
("mro", "mro-base_impl", 3),
):
for ms in metadata.ms_depends("run"):
for name in ensure_list(names):
if ms.name == name and name in build_pkg_names:
# only append numpy when it is actually pinned
if name == "numpy" and not metadata.numpy_xx:
continue
if metadata.noarch == name or (
metadata.get_value("build/noarch_python")
and name == "python"
):
res.append(s)
else:
pkg_names = list(ensure_list(names))
pkg_names.extend(
[
_n.replace("-", "_")
for _n in ensure_list(names)
if "-" in _n
]
)
for _n in pkg_names:
variant_version = get_package_version_pin(
build_deps, _n
) or metadata.config.variant.get(
_n.replace("-", "_"), ""
)
if variant_version:
break
entry = "".join([s] + variant_version.split(".")[:places])
if entry not in res:
res.append(entry)
features = ensure_list(metadata.get_value("build/features", []))
if res:
res.append("_")
if features:
res.extend(("_".join(features), "_"))
res.append(str(metadata.build_number()))
build_str = "".join(res)
return build_str
@deprecated(
"24.7", "24.9", addendum="Use `conda.base.context.locate_prefix_by_name` instead."
)
def _get_env_path(
env_name_or_path: str | os.PathLike | Path,
) -> str | os.PathLike | Path:
return (
env_name_or_path
if isdir(env_name_or_path)
else locate_prefix_by_name(env_name_or_path)
)
def _get_dependencies_from_environment(env_name_or_path):
path = _get_env_path(env_name_or_path)
# construct build requirements that replicate the given bootstrap environment
# and concatenate them to the build requirements from the recipe
bootstrap_metadata = get_installed_packages(path)
bootstrap_requirements = []
for package, data in bootstrap_metadata.items():
bootstrap_requirements.append(
"{} {} {}".format(package, data["version"], data["build"])
)
return {"requirements": {"build": bootstrap_requirements}}
def _toposort_outputs(output_tuples: list[OutputTuple]) -> list[OutputTuple]:
"""This function is used to work out the order to run the install scripts
for split packages based on any interdependencies. The result is just
a re-ordering of outputs such that we can run them in that order and
reset the initial set of files in the install prefix after each. This
will naturally lead to non-overlapping files in each package and also
the correct files being present during the install and test procedures,
provided they are run in this order."""
from conda.common.toposort import _toposort
# We only care about the conda packages built by this recipe. Non-conda
# packages get sorted to the end.
conda_outputs: dict[str, list[OutputTuple]] = {}
non_conda_outputs: list[OutputTuple] = []
for output_tuple in output_tuples:
output_d, _ = output_tuple
if output_d.get("type", "conda").startswith("conda"):
# conda packages must have a name
# the same package name may be seen multiple times (variants)
conda_outputs.setdefault(output_d["name"], []).append(output_tuple)
elif "name" in output_d:
non_conda_outputs.append(output_tuple)
else:
# TODO: is it even possible to get here? and if so should we silently ignore or error?
utils.get_logger(__name__).warning(
"Found an output without a name, skipping"
)
# Iterate over conda packages, creating a mapping of package names to their
# dependencies to be used in toposort
name_to_dependencies: dict[str, set[str]] = {}
for name, same_name_outputs in conda_outputs.items():
for output_d, output_metadata in same_name_outputs:
# dependencies for all of the variants
dependencies = (
*output_metadata.get_value("requirements/run", []),
*output_metadata.get_value("requirements/host", []),
*(
output_metadata.get_value("requirements/build", [])
if not output_metadata.is_cross
else []
),
)
name_to_dependencies.setdefault(name, set()).update(
dependency_name
for dependency in dependencies
if (dependency_name := dependency.split(" ")[0]) in conda_outputs
)
return [
*(
output
for name in _toposort(name_to_dependencies)
for output in conda_outputs[name]
),
*non_conda_outputs,
]
def get_output_dicts_from_metadata(
metadata: MetaData,
outputs: list[dict[str, Any]] | None = None,
) -> list[dict[str, Any]]:
outputs = outputs or metadata.get_section("outputs")
if not outputs:
outputs = [{"name": metadata.name()}]
else:
assert not hasattr(outputs, "keys"), (
"outputs specified as dictionary, but must be a "
"list of dictionaries. YAML syntax is: \n\n"
"outputs:\n - name: subpkg\n\n"
"(note the - before the inner dictionary)"
)
# make a metapackage for the top-level package if the top-level requirements
# mention a subpackage,
# but only if a matching output name is not explicitly provided
if metadata.uses_subpackage and not any(
metadata.name() == out.get("name", "") for out in outputs
):
outputs.append(OrderedDict(name=metadata.name()))
for out in outputs:
if (
out.get("name") == metadata.name()
and "package:" in metadata.get_recipe_text()
):
combine_top_level_metadata_with_output(metadata, out)
return outputs
def finalize_outputs_pass(
base_metadata,
render_order,
pass_no,
outputs=None,
permit_unsatisfiable_variants=False,
bypass_env_check=False,
):
from .render import finalize_metadata
outputs = OrderedDict()
# each of these outputs can have a different set of dependency versions from each other,
# but also from base_metadata
for output_d, metadata in render_order.values():
if metadata.skip():
continue
try:
log = utils.get_logger(__name__)
# We should reparse the top-level recipe to get all of our dependencies fixed up.
# we base things on base_metadata because it has the record of the full origin recipe
if base_metadata.config.verbose:
log.info(f"Attempting to finalize metadata for {metadata.name()}")
# Using base_metadata is important for keeping the reference to the parent recipe
om = base_metadata.copy()
# other_outputs is the context of what's available for
# pin_subpackage. It's stored on the metadata object here, but not
# on base_metadata, which om is a copy of. Before we do