-
-
Notifications
You must be signed in to change notification settings - Fork 198
/
Copy pathconfigure_feedstock.py
2954 lines (2539 loc) · 104 KB
/
configure_feedstock.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 copy
import glob
import hashlib
import logging
import os
import pprint
import re
import subprocess
import sys
import textwrap
import time
import warnings
from collections import Counter, OrderedDict, namedtuple
from copy import deepcopy
from functools import lru_cache
from itertools import chain, product
from os import fspath
from pathlib import Path, PurePath
import requests
import yaml
# The `requests` lib uses `simplejson` instead of `json` when available.
# In consequence the same JSON library must be used or the `JSONDecodeError`
# used when catching an exception won't be the same as the one raised
# by `requests`.
try:
import simplejson as json
except ImportError:
import json
import conda_build.api
import conda_build.render
import conda_build.utils
import conda_build.variants
from conda.exceptions import InvalidVersionSpec
from conda.models.match_spec import MatchSpec
from conda.models.version import VersionOrder
from conda_build import __version__ as conda_build_version
from conda_build.metadata import get_selectors
from jinja2 import FileSystemLoader
from jinja2.sandbox import SandboxedEnvironment
from rattler_build_conda_compat.loader import parse_recipe_config_file
from rattler_build_conda_compat.render import render as rattler_render
from conda_smithy import __version__
from conda_smithy.feedstock_io import (
copy_file,
remove_file,
remove_file_or_dir,
set_exe_file,
write_file,
)
from conda_smithy.utils import (
RATTLER_BUILD,
HashableDict,
get_feedstock_about_from_meta,
get_feedstock_name_from_meta,
)
from conda_smithy.validate_schema import (
CONDA_FORGE_YAML_DEFAULTS_FILE,
validate_json_schema,
)
conda_forge_content = os.path.abspath(os.path.dirname(__file__))
logger = logging.getLogger(__name__)
# feedstocks listed here are allowed to use GHA on
# conda-forge
# this should solve issues where other CI proviers have too many
# jobs and we need to change something via CI
SERVICE_FEEDSTOCKS = [
"conda-forge-pinning-feedstock",
"conda-forge-repodata-patches-feedstock",
"conda-smithy-feedstock",
"conda-forge-ci-setup-feedstock",
# these are parts of the bot or used by it
"conda-forge-tick",
"conda-forge-feedstock-check-solvable-feedstock",
"conda-forge-metadata-feedstock",
"conda-forge-feedstock-ops-feedstock",
# this one is used for testing
"cf-autotick-bot-test-package-feedstock",
]
if "CONDA_SMITHY_SERVICE_FEEDSTOCKS" in os.environ:
SERVICE_FEEDSTOCKS += os.environ["CONDA_SMITHY_SERVICE_FEEDSTOCKS"].split(
","
)
# Cache lifetime in seconds, default 15min
CONDA_FORGE_PINNING_LIFETIME = int(
os.environ.get("CONDA_FORGE_PINNING_LIFETIME", 15 * 60)
)
# use lru_cache to avoid repeating warnings endlessly;
# this keeps track of 10 different messages and then warns again
@lru_cache(10)
def warn_once(msg: str):
logger.warning(msg)
def package_key(config, used_loop_vars, subdir):
# get the build string from whatever conda-build makes of the configuration
key = "".join(
[
k + str(config[k][0])
for k in sorted(list(used_loop_vars))
if k != "target_platform"
]
)
return key.replace("*", "_").replace(" ", "_")
def _ignore_match(ignore, rel):
"""Return true if rel or any of it's PurePath().parents are in ignore
i.e. putting .github in skip_render will prevent rendering of anything
named .github in the toplevel of the feedstock and anything below that as well
"""
srch = {rel}
srch.update(map(fspath, PurePath(rel).parents))
logger.debug("srch:%s", srch)
logger.debug("ignore:%s", ignore)
if srch.intersection(ignore):
logger.info("%s rendering is skipped", rel)
return True
else:
return False
def copytree(src, dst, ignore=(), root_dst=None):
"""This emulates shutil.copytree, but does so with our git file tracking, so that the new files
are added to the repo"""
if root_dst is None:
root_dst = dst
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
rel = os.path.relpath(d, root_dst)
if _ignore_match(ignore, rel):
continue
elif os.path.isdir(s):
if not os.path.exists(d):
os.makedirs(d)
copytree(s, d, ignore, root_dst=root_dst)
else:
copy_file(s, d)
def merge_list_of_dicts(list_of_dicts):
squished_dict = OrderedDict()
for idict in list_of_dicts:
for key, val in idict.items():
if key not in squished_dict:
squished_dict[key] = []
squished_dict[key].extend(val)
return squished_dict
def argsort(seq):
return sorted(range(len(seq)), key=seq.__getitem__)
def sort_config(config, zip_key_groups):
groups = copy.deepcopy(zip_key_groups)
for i, group in enumerate(groups):
groups[i] = [pkg for pkg in group if pkg in config.keys()]
groups = [group for group in groups if group]
sorting_order = {}
for group in groups:
if not group:
continue
list_of_values = []
for idx in range(len(config[group[0]])):
values = []
for key in group:
values.append(config[key][idx])
list_of_values.append(tuple(values))
order = argsort(list_of_values)
for key in group:
sorting_order[key] = order
for key, value in config.items():
if isinstance(value, (list, set, tuple)):
val = list(value)
if key in sorting_order:
config[key] = [val[i] for i in sorting_order[key]]
else:
config[key] = sorted(val)
if key == "pin_run_as_build":
p = OrderedDict()
for pkg in sorted(list(value.keys())):
pkg_pins = value[pkg]
d = OrderedDict()
for pin in list(reversed(sorted(pkg_pins.keys()))):
d[pin] = pkg_pins[pin]
p[pkg] = d
config[key] = p
def break_up_top_level_values(top_level_keys, squished_variants):
"""top-level values make up CI configurations. We need to break them up
into individual files."""
accounted_for_keys = set()
# handle grouping from zip_keys for everything in conform_dict
zip_key_groups = []
if "zip_keys" in squished_variants:
zip_key_groups = squished_variants["zip_keys"]
if zip_key_groups and not isinstance(zip_key_groups[0], list):
zip_key_groups = [zip_key_groups]
zipped_configs = []
top_level_dimensions = []
for key in top_level_keys:
if key in accounted_for_keys:
# remove the used variables from the collection of all variables - we have them in the
# other collections now
continue
if any(key in group for group in zip_key_groups):
for group in zip_key_groups:
if key in group:
accounted_for_keys.update(set(group))
# create a list of dicts that represent the different permutations that are
# zipped together. Each dict in this list will be a different top-level
# config in its own file
zipped_config = []
top_level_config_dict = OrderedDict()
for idx, variant_key in enumerate(squished_variants[key]):
top_level_config = []
for k in group:
if k in top_level_keys:
top_level_config.append(
squished_variants[k][idx]
)
top_level_config = tuple(top_level_config)
if top_level_config not in top_level_config_dict:
top_level_config_dict[top_level_config] = []
top_level_config_dict[top_level_config].append(
{k: [squished_variants[k][idx]] for k in group}
)
# merge dicts with the same `key` if `key` is repeated in the group.
for _, variant_key_val in top_level_config_dict.items():
squished_dict = merge_list_of_dicts(variant_key_val)
zipped_config.append(squished_dict)
zipped_configs.append(zipped_config)
for k in group:
del squished_variants[k]
break
else:
# dimension slice is just this one variable, all other dimensions keep their variability
top_level_dimensions.append(
[{key: [val]} for val in squished_variants[key]]
)
del squished_variants[key]
configs = []
dimensions = []
# sort values so that the diff doesn't show randomly changing order
if "zip_keys" in squished_variants:
zip_key_groups = squished_variants["zip_keys"]
sort_config(squished_variants, zip_key_groups)
for zipped_config in zipped_configs:
for config in zipped_config:
sort_config(config, zip_key_groups)
if top_level_dimensions:
dimensions.extend(top_level_dimensions)
if zipped_configs:
dimensions.extend(zipped_configs)
if squished_variants:
dimensions.append([squished_variants])
for permutation in product(*dimensions):
config = dict()
for perm in permutation:
config.update(perm)
configs.append(config)
return configs
def _package_var_name(pkg):
return pkg.replace("-", "_")
def _trim_unused_zip_keys(all_used_vars):
"""Remove unused keys in zip_keys sets, so that they don't cause unnecessary missing value
errors"""
groups = all_used_vars.get("zip_keys", [])
if groups and not any(isinstance(groups[0], obj) for obj in (list, tuple)):
groups = [groups]
used_groups = []
for group in groups:
used_keys_in_group = [k for k in group if k in all_used_vars]
if len(used_keys_in_group) > 1:
used_groups.append(used_keys_in_group)
if used_groups:
all_used_vars["zip_keys"] = used_groups
elif "zip_keys" in all_used_vars:
del all_used_vars["zip_keys"]
def _trim_unused_pin_run_as_build(all_used_vars):
"""Remove unused keys in pin_run_as_build sets"""
pkgs = all_used_vars.get("pin_run_as_build", {})
used_pkgs = {}
if pkgs:
for key in pkgs.keys():
if _package_var_name(key) in all_used_vars:
used_pkgs[key] = pkgs[key]
if used_pkgs:
all_used_vars["pin_run_as_build"] = used_pkgs
elif "pin_run_as_build" in all_used_vars:
del all_used_vars["pin_run_as_build"]
def _get_used_key_values_by_input_order(
squished_input_variants,
squished_used_variants,
all_used_vars,
):
used_key_values = {
key: squished_input_variants[key]
for key in all_used_vars
if key in squished_input_variants
}
logger.debug("initial used_key_values %s", pprint.pformat(used_key_values))
# we want remove any used key values not in used variants and make sure they follow the
# input order
# zipped keys are a special case since they are ordered by the list of tuple of zipped
# key values
# so we do the zipped keys first and then do the rest
zipped_tuples = {}
zipped_keys = set()
for keyset in squished_input_variants["zip_keys"]:
zipped_tuples[tuple(keyset)] = list(
zip(*[squished_input_variants[k] for k in keyset])
)
zipped_keys |= set(keyset)
logger.debug("zipped_keys %s", pprint.pformat(zipped_keys))
logger.debug("zipped_tuples %s", pprint.pformat(zipped_tuples))
for keyset, tuples in zipped_tuples.items():
# for each set of zipped keys from squished_input_variants,
# we trim them down to what is in squished_used_variants
used_keyset = []
used_keyset_inds = []
for k in keyset:
if k in squished_used_variants:
used_keyset.append(k)
used_keyset_inds.append(keyset.index(k))
used_keyset = tuple(used_keyset)
used_keyset_inds = tuple(used_keyset_inds)
# if we find nothing, keep going
if not used_keyset:
continue
# this trims the zipped tuples down to the used keys
used_tuples = tuple(
[
tuple(
[
tup[used_keyset_ind]
for used_keyset_ind in used_keyset_inds
]
)
for tup in tuples
]
)
logger.debug("used_keyset %s", pprint.pformat(used_keyset))
logger.debug("used_keyset_inds %s", pprint.pformat(used_keyset_inds))
logger.debug("used_tuples %s", pprint.pformat(used_tuples))
# this is the set of tuples that we want to keep, but need to be reordered
used_tuples_to_be_reordered = set(
list(zip(*[squished_used_variants[k] for k in used_keyset]))
)
logger.debug(
"used_tuples_to_be_reordered %s",
pprint.pformat(used_tuples_to_be_reordered),
)
# we double check the logic above by looking to ensure everything in
# the squished_used_variants
# is in the squished_input_variants
used_tuples_set = set(used_tuples)
logger.debug(
"are all used tuples in input tuples? %s",
all(
used_tuple in used_tuples_set
for used_tuple in used_tuples_to_be_reordered
),
)
# now we do the final rdering
final_used_tuples = tuple(
[tup for tup in used_tuples if tup in used_tuples_to_be_reordered]
)
logger.debug("final_used_tuples %s", pprint.pformat(final_used_tuples))
# now we reconstruct the list of values per key and replace in used_key_values
# we keep only keys in all_used_vars
for i, k in enumerate(used_keyset):
if k in all_used_vars:
used_key_values[k] = [tup[i] for tup in final_used_tuples]
# finally, we handle the rest of the keys that are not zipped
for k, v in squished_used_variants.items():
if k in all_used_vars and k not in zipped_keys:
used_key_values[k] = v
logger.debug(
"post input reorder used_key_values %s",
pprint.pformat(used_key_values),
)
return used_key_values, zipped_keys
def _merge_deployment_target(container_of_dicts, has_macdt):
"""
For a collection of variant dictionaries, merge deployment target specs.
- The "old" way is MACOSX_DEPLOYMENT_TARGET, the new way is c_stdlib_version;
For now, take the maximum to populate both.
- In any case, populate MACOSX_DEPLOYMENT_TARGET, as that is the key picked
up by https://github.com/conda-forge/conda-forge-ci-setup-feedstock
- If MACOSX_SDK_VERSION is lower than the merged value from the previous step,
update it to match the merged value.
"""
result = []
for var_dict in container_of_dicts:
# cases where no updates are necessary
if not var_dict.get("target_platform", "dummy").startswith("osx"):
result.append(var_dict)
continue
if "c_stdlib_version" not in var_dict:
result.append(var_dict)
continue
# case where we need to do processing
v_stdlib = var_dict["c_stdlib_version"]
macdt = var_dict.get("MACOSX_DEPLOYMENT_TARGET", v_stdlib)
sdk = var_dict.get("MACOSX_SDK_VERSION", v_stdlib)
# error out if someone puts in a range of versions; we need a single version
try:
stdlib_lt_macdt = VersionOrder(v_stdlib) < VersionOrder(macdt)
sdk_lt_stdlib = VersionOrder(sdk) < VersionOrder(v_stdlib)
sdk_lt_macdt = VersionOrder(sdk) < VersionOrder(macdt)
except InvalidVersionSpec:
raise ValueError(
"all of c_stdlib_version/MACOSX_DEPLOYMENT_TARGET/"
"MACOSX_SDK_VERSION need to be a single version, "
"not a version range!"
)
if v_stdlib != macdt:
# determine maximum version and use it to populate both
v_stdlib = macdt if stdlib_lt_macdt else v_stdlib
msg = (
"Conflicting specification for minimum macOS deployment target!\n"
"If your conda_build_config.yaml sets `MACOSX_DEPLOYMENT_TARGET`, "
"please change the name of that key to `c_stdlib_version`!\n"
f"Using {v_stdlib}=max(c_stdlib_version, MACOSX_DEPLOYMENT_TARGET)."
)
# we don't want to warn for recipes that do not use MACOSX_DEPLOYMENT_TARGET
# in the local CBC, but only inherit it from the global pinning
if has_macdt:
warn_once(msg)
if sdk_lt_stdlib or sdk_lt_macdt:
sdk_lt_merged = VersionOrder(sdk) < VersionOrder(v_stdlib)
sdk = v_stdlib if sdk_lt_merged else sdk
msg = (
"Conflicting specification for minimum macOS SDK version!\n"
"If your conda_build_config.yaml sets `MACOSX_SDK_VERSION`, "
"it must be larger or equal than `c_stdlib_version` "
"(which is also influenced by the global pinning)!\n"
f"Using {sdk}=max(c_stdlib_version, MACOSX_SDK_VERSION)."
)
warn_once(msg)
# we set MACOSX_DEPLOYMENT_TARGET to match c_stdlib_version,
# for ease of use in conda-forge-ci-setup;
# use new dictionary to avoid mutating existing var_dict in place
new_dict = HashableDict(
{
**var_dict,
"c_stdlib_version": v_stdlib,
"MACOSX_DEPLOYMENT_TARGET": v_stdlib,
"MACOSX_SDK_VERSION": sdk,
}
)
result.append(new_dict)
# ensure we keep type of wrapper container (set stays set, etc.)
return type(container_of_dicts)(result)
def _collapse_subpackage_variants(
list_of_metas, root_path, platform, arch, forge_config
):
"""Collapse all subpackage node variants into one aggregate collection of used variables
We get one node per output, but a given recipe can have multiple outputs. Each output
can have its own used_vars, and we must unify all of the used variables for all of the
outputs"""
# things we consider "top-level" are things that we loop over with CI jobs. We don't loop over
# outputs with CI jobs.
top_level_loop_vars = set()
all_used_vars = set()
all_variants = set()
is_noarch = True
for meta in list_of_metas:
all_used_vars.update(meta.get_used_vars())
# this is a hack to work around the fact that we specify mpi variants
# via an `mpi` variable in the CBC but we do not parse our recipes
# twice to ensure the pins given by the variant also show up in the
# smithy CI support scripts
# future MPI variants have to be added here
if "mpi" in all_used_vars:
all_used_vars.update(
["mpich", "openmpi", "msmpi", "mpi_serial", "impi"]
)
all_variants.update(HashableDict(v) for v in meta.config.variants)
all_variants.add(HashableDict(meta.config.variant))
if not meta.noarch:
is_noarch = False
# determine if MACOSX_DEPLOYMENT_TARGET appears in recipe-local CBC;
# all metas in list_of_metas come from same recipe, so path is identical
recipe_dir = list_of_metas[0].path
cbc_path = os.path.join(recipe_dir, "conda_build_config.yaml")
has_macdt = False
if os.path.exists(cbc_path):
with open(cbc_path) as f:
cbc_text = f.read()
if re.match(r"^\s*MACOSX_DEPLOYMENT_TARGET:", cbc_text):
has_macdt = True
# check if recipe contains `python_min`; add it to used_vars if so; we cannot use
# `m.get_recipe_text()`, because noarch outputs may have been skipped already
recipe_path = os.path.join(recipe_dir, "meta.yaml")
if not os.path.exists(recipe_path):
recipe_path = os.path.join(recipe_dir, "recipe.yaml")
# either v0 or v1 recipe must exist; no fall-back if missing
with open(recipe_path) as f:
meta_text = f.read()
pm_pat = re.compile(r".*\{\{ python_min \}\}")
if any(pm_pat.match(x) for x in meta_text.splitlines()):
all_used_vars.add("python_min")
# on osx, merge MACOSX_DEPLOYMENT_TARGET & c_stdlib_version to max of either; see #1884
all_variants = _merge_deployment_target(all_variants, has_macdt)
top_level_loop_vars = list_of_metas[0].get_used_loop_vars(
force_top_level=True
)
top_level_vars = list_of_metas[0].get_used_vars(force_top_level=True)
if "target_platform" in all_used_vars:
top_level_loop_vars.add("target_platform")
logger.debug("initial all_used_vars %s", pprint.pformat(all_used_vars))
# this is the initial collection of all variants before we discard any. "Squishing"
# them is necessary because the input form is already broken out into one matrix
# configuration per item, and we want a single dict, with each key representing many values
squished_input_variants = conda_build.variants.list_of_dicts_to_dict_of_lists(
# ensure we update the input_variants in the same way as all_variants
_merge_deployment_target(
list_of_metas[0].config.input_variants, has_macdt
)
)
squished_used_variants = (
conda_build.variants.list_of_dicts_to_dict_of_lists(list(all_variants))
)
logger.debug(
"squished_input_variants %s", pprint.pformat(squished_input_variants)
)
logger.debug(
"squished_used_variants %s", pprint.pformat(squished_used_variants)
)
# these are variables that only occur in the top level, and thus won't show up as loops in the
# above collection of all variants. We need to transfer them from the input_variants.
preserve_top_level_loops = set(top_level_loop_vars) - set(all_used_vars)
logger.debug("preserve_top_level_loops %s", preserve_top_level_loops)
# Add in some variables that should always be preserved
always_keep_keys = {
"zip_keys",
"pin_run_as_build",
"MACOSX_DEPLOYMENT_TARGET",
"MACOSX_SDK_VERSION",
"macos_min_version",
"macos_machine",
"channel_sources",
"channel_targets",
"docker_image",
"build_number_decrement",
# The following keys are required for some of our aarch64 builds
# Added in https://github.com/conda-forge/conda-forge-pinning-feedstock/pull/180
"cdt_arch",
"cdt_name",
"BUILD",
}
if not is_noarch:
always_keep_keys.add("target_platform")
if forge_config["github_actions"]["self_hosted"]:
always_keep_keys.add("github_actions_labels")
all_used_vars.update(always_keep_keys)
all_used_vars.update(top_level_vars)
logger.debug("final all_used_vars %s", pprint.pformat(all_used_vars))
logger.debug("top_level_vars %s", pprint.pformat(top_level_vars))
logger.debug("top_level_loop_vars %s", pprint.pformat(top_level_loop_vars))
used_key_values, used_zipped_vars = _get_used_key_values_by_input_order(
squished_input_variants,
squished_used_variants,
all_used_vars,
)
for k in preserve_top_level_loops:
# we do not stomp on keys in zips since their order matters
if k not in used_zipped_vars:
used_key_values[k] = squished_input_variants[k]
_trim_unused_zip_keys(used_key_values)
_trim_unused_pin_run_as_build(used_key_values)
# to deduplicate potentially zipped keys, we blow out the collection of variables, then
# do a set operation, then collapse it again
used_key_values = conda_build.variants.dict_of_lists_to_list_of_dicts(
used_key_values
)
used_key_values = {HashableDict(variant) for variant in used_key_values}
used_key_values = conda_build.variants.list_of_dicts_to_dict_of_lists(
list(used_key_values)
)
_trim_unused_zip_keys(used_key_values)
_trim_unused_pin_run_as_build(used_key_values)
logger.debug("final used_key_values %s", pprint.pformat(used_key_values))
return (
break_up_top_level_values(top_level_loop_vars, used_key_values),
top_level_loop_vars,
)
def _yaml_represent_ordereddict(yaml_representer, data):
# represent_dict processes dict-likes with a .sort() method or plain iterables of key-value
# pairs. Only for the latter it never sorts and retains the order of the OrderedDict.
return yaml.representer.SafeRepresenter.represent_dict(
yaml_representer, data.items()
)
def _has_local_ci_setup(forge_dir, forge_config):
# If the recipe has its own conda_forge_ci_setup package, then
# install that
return os.path.exists(
os.path.join(
forge_dir,
forge_config["recipe_dir"],
"conda_forge_ci_setup",
"__init__.py",
)
) and os.path.exists(
os.path.join(
forge_dir,
forge_config["recipe_dir"],
"setup.py",
)
)
def _sanitize_remote_ci_setup(remote_ci_setup):
remote_ci_setup_ = conda_build.utils.ensure_list(remote_ci_setup)
remote_ci_setup = []
for package in remote_ci_setup_:
if package.startswith(("'", '"')):
pass
elif ("<" in package) or (">" in package) or ("|" in package):
package = '"' + package + '"'
remote_ci_setup.append(package)
return remote_ci_setup
def _sanitize_build_tool_deps_as_dict(
forge_dir, forge_config
) -> dict[str, str]:
"""
Aggregates different sources of build tool dependencies in
mapping of package names to OR-merged version constraints.
"""
deps = [
*forge_config["conda_build_tool_deps"].split(),
*forge_config["remote_ci_setup"],
]
merged = {
spec.name: str(spec.version or "*")
for spec in MatchSpec.merge([dep.strip("\"'") for dep in deps])
}
if forge_config.get("local_ci_setup") or _has_local_ci_setup(
forge_dir, forge_config
):
# We need to conda uninstall conda-forge-ci-setup
# and then pip install on top
merged.setdefault("conda", "*")
merged.setdefault("pip", "*")
return merged
def finalize_config(config, platform, arch, forge_config):
"""For configs without essential parameters like docker_image
add fallback value.
"""
build_platform = forge_config["build_platform"][f"{platform}_{arch}"]
if build_platform.startswith("linux"):
if "docker_image" in config:
config["docker_image"] = [config["docker_image"][0]]
else:
config["docker_image"] = [forge_config["docker"]["fallback_image"]]
if "zip_keys" in config:
for ziplist in config["zip_keys"]:
if "docker_image" in ziplist:
for key in ziplist:
if key != "docker_image":
config[key] = [config[key][0]]
return config
def dump_subspace_config_files(
metas, root_path, platform, arch, upload, forge_config
):
"""With conda-build 3, it handles the build matrix. We take what it spits out, and write a
config.yaml file for each matrix entry that it spits out. References to a specific file
replace all of the old environment variables that specified a matrix entry.
"""
# identify how to break up the complete set of used variables. Anything considered
# "top-level" should be broken up into a separate CI job.
configs, top_level_loop_vars = _collapse_subpackage_variants(
metas,
root_path,
platform,
arch,
forge_config,
)
logger.debug(
"collapsed subspace config files: %s", pprint.pformat(configs)
)
# get rid of the special object notation in the yaml file for objects that we dump
yaml.add_representer(set, yaml.representer.SafeRepresenter.represent_list)
yaml.add_representer(
tuple, yaml.representer.SafeRepresenter.represent_list
)
yaml.add_representer(OrderedDict, _yaml_represent_ordereddict)
platform_arch = f"{platform}-{arch}"
result = []
for config in configs:
config_name = "{}_{}".format(
f"{platform}_{arch}",
package_key(config, top_level_loop_vars, metas[0].config.subdir),
)
short_config_name = config_name
if len(short_config_name) >= 49:
h = hashlib.sha256(config_name.encode("utf-8")).hexdigest()[:10]
short_config_name = config_name[:35] + "_h" + h
if len("conda-forge-build-done-" + config_name) >= 250:
# Shorten file name length to avoid hitting maximum filename limits.
config_name = short_config_name
out_folder = os.path.join(root_path, ".ci_support")
out_path = os.path.join(out_folder, config_name) + ".yaml"
if not os.path.isdir(out_folder):
os.makedirs(out_folder)
config = finalize_config(config, platform, arch, forge_config)
logger.debug("finalized config file: %s", pprint.pformat(config))
with write_file(out_path) as f:
yaml.dump(config, f, default_flow_style=False)
target_platform = config.get("target_platform", [platform_arch])[0]
result.append(
{
"config_name": config_name,
"platform": target_platform,
"upload": upload,
"config": config,
"short_config_name": short_config_name,
"build_platform": forge_config["build_platform"][
f"{platform}_{arch}"
].replace("_", "-"),
}
)
return sorted(result, key=lambda x: x["config_name"])
def _get_fast_finish_script(
provider_name, forge_config, forge_dir, fast_finish_text
):
get_fast_finish_script = ""
fast_finish_script = ""
tooling_branch = forge_config["github"]["tooling_branch_name"]
cfbs_fpath = os.path.join(
forge_dir, forge_config["recipe_dir"], "ff_ci_pr_build.py"
)
if provider_name == "appveyor":
if os.path.exists(cfbs_fpath):
fast_finish_script = "{recipe_dir}\\ff_ci_pr_build".format(
recipe_dir=forge_config["recipe_dir"]
)
else:
get_fast_finish_script = '''powershell -Command "(New-Object Net.WebClient).DownloadFile('https://raw.githubusercontent.com/conda-forge/conda-forge-ci-setup-feedstock/{branch}/recipe/conda_forge_ci_setup/ff_ci_pr_build.py', 'ff_ci_pr_build.py')"''' # NOQA
fast_finish_script += "ff_ci_pr_build"
fast_finish_text += "del {fast_finish_script}.py"
fast_finish_text = fast_finish_text.format(
get_fast_finish_script=get_fast_finish_script.format(
branch=tooling_branch
),
fast_finish_script=fast_finish_script,
)
fast_finish_text = fast_finish_text.strip()
fast_finish_text = fast_finish_text.replace("\n", "\n ")
else:
# If the recipe supplies its own ff_ci_pr_build.py script,
# we use it instead of the global one.
if os.path.exists(cfbs_fpath):
get_fast_finish_script += (
"cat {recipe_dir}/ff_ci_pr_build.py".format(
recipe_dir=forge_config["recipe_dir"]
)
)
else:
get_fast_finish_script += "curl https://raw.githubusercontent.com/conda-forge/conda-forge-ci-setup-feedstock/{branch}/recipe/conda_forge_ci_setup/ff_ci_pr_build.py" # NOQA
fast_finish_text = fast_finish_text.format(
get_fast_finish_script=get_fast_finish_script.format(
branch=tooling_branch
)
)
fast_finish_text = fast_finish_text.strip()
return fast_finish_text
def migrate_combined_spec(combined_spec, forge_dir, config, forge_config):
"""CFEP-9 variant migrations
Apply the list of migrations configurations to the build (in the correct sequence)
This will be used to change the variant within the list of MetaData instances,
and return the migrated variants.
This has to happend before the final variant files are computed.
The method for application is determined by the variant algebra as defined by CFEP-9
"""
combined_spec = combined_spec.copy()
if "migration_fns" not in forge_config:
migrations = set_migration_fns(forge_dir, forge_config)
migrations = forge_config["migration_fns"]
from conda_smithy.variant_algebra import parse_variant, variant_add
migration_variants = [
(fn, parse_variant(open(fn).read(), config=config))
for fn in migrations
]
migration_variants.sort(key=lambda fn_v: (fn_v[1]["migrator_ts"], fn_v[0]))
if len(migration_variants):
logger.info(
"Applying migrations: %s",
",".join(k for k, v in migration_variants),
)
for migrator_file, migration in migration_variants:
if "migrator_ts" in migration:
del migration["migrator_ts"]
if len(migration):
combined_spec = variant_add(combined_spec, migration)
return combined_spec
def _conda_build_api_render_for_smithy(
recipe_path,
config=None,
variants=None,
permit_unsatisfiable_variants=True,
finalize=True,
bypass_env_check=False,
**kwargs,
):
"""This function works just like conda_build.api.render, but it returns all of metadata objects
regardless of whether they produce a unique package hash / name.
When conda-build renders a recipe, it returns the metadata for each unique file generated. If a key
we use at the top-level in a multi-output recipe does not explicitly impact one of the recipe outputs
(i.e., an output's recipe doesn't use that key), then conda-build will not return all of the variants
for that key.
This behavior is not what we do in conda-forge (i.e., we want all variants that are not explicitly
skipped even if some of the keys in the variants are not explicitly used in an output).
The most robust way to handle this is to write a custom function that returns metadata for each of
the variants in the full exploded matrix that involve a key used by the recipe anywhere,
except the ones that the recipe skips.
"""
from conda.exceptions import NoPackagesFoundError
from conda_build.config import get_or_merge_config
from conda_build.exceptions import DependencyNeedsBuildingError
from conda_build.render import finalize_metadata, render_recipe
config = get_or_merge_config(config, **kwargs)
metadata_tuples = render_recipe(
recipe_path,
bypass_env_check=bypass_env_check,
no_download_source=config.no_download_source,
config=config,
variants=variants,
permit_unsatisfiable_variants=permit_unsatisfiable_variants,
)
output_metas = []
for meta, download, render_in_env in metadata_tuples:
if not meta.skip() or not config.trim_skip:
for od, om in meta.get_output_metadata_set(
permit_unsatisfiable_variants=permit_unsatisfiable_variants,
permit_undefined_jinja=not finalize,
bypass_env_check=bypass_env_check,
):
if not om.skip() or not config.trim_skip:
if "type" not in od or od["type"] == "conda":
if finalize and not om.final:
try:
om = finalize_metadata(
om,
permit_unsatisfiable_variants=permit_unsatisfiable_variants,
)
except (
DependencyNeedsBuildingError,
NoPackagesFoundError,
):
if not permit_unsatisfiable_variants:
raise
# remove outputs section from output objects for simplicity
if not om.path and (
outputs := om.get_section("outputs")
):
om.parent_outputs = outputs
del om.meta["outputs"]
output_metas.append((om, download, render_in_env))
else:
output_metas.append((om, download, render_in_env))
return output_metas
def _render_ci_provider(
provider_name,
jinja_env,
forge_config,
forge_dir,
platforms,