-
-
Notifications
You must be signed in to change notification settings - Fork 185
/
configure_feedstock.py
2611 lines (2266 loc) · 91.4 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 glob
from itertools import product, chain
import logging
import os
from os import fspath
import re
import sys
import subprocess
import textwrap
import time
import yaml
import warnings
from collections import OrderedDict, namedtuple, Counter
import copy
import hashlib
import requests
from pathlib import Path, PurePath
# 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.utils
import conda_build.variants
import conda_build.conda_interface
import conda_build.render
from conda.models.match_spec import MatchSpec
from copy import deepcopy
from conda_build import __version__ as conda_build_version
from jinja2 import Environment, FileSystemLoader
from conda_smithy.feedstock_io import (
set_exe_file,
write_file,
remove_file,
copy_file,
remove_file_or_dir,
)
from conda_smithy.utils import (
get_feedstock_name_from_meta,
get_feedstock_about_from_meta,
)
from . import __version__
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",
]
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)
)
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(f"srch:{srch}")
logger.debug(f"ignore:{ignore}")
if srch.intersection(ignore):
logger.info(f"{rel} rendering is skipped")
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 _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"])
all_variants.update(
conda_build.utils.HashableDict(v) for v in meta.config.variants
)
all_variants.add(conda_build.utils.HashableDict(meta.config.variant))
if not meta.noarch:
is_noarch = False
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")
# 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(
list_of_metas[0].config.input_variants
)
)
squished_used_variants = (
conda_build.variants.list_of_dicts_to_dict_of_lists(list(all_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)
# 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)
used_key_values = {
key: squished_input_variants[key]
for key in all_used_vars
if key in squished_input_variants
}
for k, v in squished_used_variants.items():
if k in all_used_vars:
input_variant = squished_input_variants.get(k)
if input_variant and isinstance(input_variant, (tuple, list)):
# Ensure we retain the input order to avoid mismatched entries
# with the preserve_top_level_loops overrides below.
# NOTE: "pin_run_as_build" (dict of dict) order is not handled.
# "tuple" below only used for uniform list/tuple/str comparison.
v_set = set(map(tuple, v))
v = type(input_variant)(
v_i for v_i in input_variant if tuple(v_i) in v_set
)
used_key_values[k] = v
for k in preserve_top_level_loops:
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 = {
conda_build.utils.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("top_level_loop_vars {}".format(top_level_loop_vars))
logger.debug("used_key_values {}".format(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 _santize_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 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,
)
# 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 = "{}-{}".format(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)
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 .variant_algebra import parse_variant, variant_add
migration_variants = [
(fn, parse_variant(open(fn, "r").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(
f"Applying migrations: {','.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 _render_ci_provider(
provider_name,
jinja_env,
forge_config,
forge_dir,
platforms,
archs,
fast_finish_text,
platform_target_path,
platform_template_file,
platform_specific_setup,
keep_noarchs=None,
extra_platform_files={},
upload_packages=[],
return_metadata=False,
):
if keep_noarchs is None:
keep_noarchs = [False] * len(platforms)
metas_list_of_lists = []
enable_platform = [False] * len(platforms)
for i, (platform, arch, keep_noarch) in enumerate(
zip(platforms, archs, keep_noarchs)
):
os.environ["CONFIG_VERSION"] = forge_config["config_version"]
os.environ["BUILD_PLATFORM"] = forge_config["build_platform"][
f"{platform}_{arch}"
].replace("_", "-")
# set the environment variable for OS version
if platform == "linux":
ver = forge_config["os_version"][f"{platform}_{arch}"]
if ver:
os.environ["DEFAULT_LINUX_VERSION"] = ver
# detect if `compiler('cuda')` is used in meta.yaml,
# and set appropriate environment variable
with open(
os.path.join(forge_dir, forge_config["recipe_dir"], "meta.yaml")
) as f:
meta_lines = f.readlines()
# looking for `compiler('cuda')` with both quote variants;
# do not match if there is a `#` somewhere before on the line
pat = re.compile(r"^[^\#]*compiler\((\"cuda\"|\'cuda\')\).*")
for ml in meta_lines:
if pat.match(ml):
os.environ["CF_CUDA_ENABLED"] = "True"
config = conda_build.config.get_or_merge_config(
None,
exclusive_config_file=forge_config["exclusive_config_file"],
platform=platform,
arch=arch,
)
# Get the combined variants from normal variant locations prior to running migrations
(
combined_variant_spec,
_,
) = conda_build.variants.get_package_combined_spec(
os.path.join(forge_dir, forge_config["recipe_dir"]), config=config
)
migrated_combined_variant_spec = migrate_combined_spec(
combined_variant_spec,
forge_dir,
config,
forge_config,
)
for channel_target in migrated_combined_variant_spec.get(
"channel_targets", []
):
if (
channel_target.startswith("conda-forge ")
and provider_name == "github_actions"
and not forge_config["github_actions"]["self_hosted"]
):
raise RuntimeError(
"Using github_actions as the CI provider inside "
"conda-forge github org is not allowed in order "
"to avoid a denial of service for other infrastructure."
)
# we skip travis builds for anything but aarch64, ppc64le and s390x
# due to their current open-source policies around usage
if (
channel_target.startswith("conda-forge ")
and provider_name == "travis"
and (
platform != "linux"
or arch not in ["aarch64", "ppc64le", "s390x"]
)
):
raise RuntimeError(
"Travis CI can only be used for 'linux_aarch64', "
"'linux_ppc64le' or 'linux_s390x' native builds"
", not '%s_%s', to avoid using open-source build minutes!"
% (platform, arch)
)
# AFAIK there is no way to get conda build to ignore the CBC yaml
# in the recipe. This one can mess up migrators applied with local
# CBC yaml files where variants in the migrators are not in the CBC.
# Thus we move it out of the way.
# TODO: upstream this as a flag in conda-build
try:
_recipe_cbc = os.path.join(
forge_dir,
forge_config["recipe_dir"],
"conda_build_config.yaml",
)
if os.path.exists(_recipe_cbc):
os.rename(_recipe_cbc, _recipe_cbc + ".conda.smithy.bak")
channel_sources = migrated_combined_variant_spec.get(
"channel_sources", [""]
)[0].split(",")
metas = conda_build.api.render(
os.path.join(forge_dir, forge_config["recipe_dir"]),
platform=platform,
arch=arch,
ignore_system_variants=True,
variants=migrated_combined_variant_spec,
permit_undefined_jinja=True,
finalize=False,
bypass_env_check=True,
channel_urls=channel_sources,
)
finally:
if os.path.exists(_recipe_cbc + ".conda.smithy.bak"):
os.rename(_recipe_cbc + ".conda.smithy.bak", _recipe_cbc)
# render returns some download & reparsing info that we don't care about
metas = [m for m, _, _ in metas]
if not keep_noarch:
to_delete = []
for idx, meta in enumerate(metas):
if meta.noarch:
# do not build noarch, including noarch: python, packages on Travis CI.
to_delete.append(idx)
for idx in reversed(to_delete):
del metas[idx]
for meta in metas:
if not meta.skip():
enable_platform[i] = True
metas_list_of_lists.append(metas)
if not any(enable_platform):
# There are no cases to build (not even a case without any special
# dependencies), so remove the run_docker_build.sh if it exists.
forge_config[provider_name]["enabled"] = False
target_fnames = [platform_target_path]
if extra_platform_files:
for val in extra_platform_files.values():
target_fnames.extend(val)
for each_target_fname in target_fnames:
remove_file(each_target_fname)
else:
forge_config[provider_name]["enabled"] = True
fancy_name = {
"linux_64": "Linux",
"osx_64": "OSX",
"win_64": "Windows",
"linux_aarch64": "Arm64",
"linux_ppc64le": "PowerPC64",
}
fancy_platforms = []
unfancy_platforms = set()
configs = []
for metas, platform, arch, enable, upload in zip(
metas_list_of_lists,
platforms,
archs,
enable_platform,
upload_packages,
):
if enable:
configs.extend(
dump_subspace_config_files(
metas, forge_dir, platform, arch, upload, forge_config
)
)
plat_arch = f"{platform}_{arch}"
forge_config[plat_arch]["enabled"] = True
fancy_platforms.append(fancy_name.get(plat_arch, plat_arch))
unfancy_platforms.add(plat_arch)
elif platform in extra_platform_files:
for each_target_fname in extra_platform_files[platform]:
remove_file(each_target_fname)
for key in extra_platform_files.keys():
if key != "common" and key not in platforms:
for each_target_fname in extra_platform_files[key]:
remove_file(each_target_fname)
forge_config[provider_name]["platforms"] = ",".join(fancy_platforms)
forge_config[provider_name]["all_platforms"] = list(unfancy_platforms)
# Copy the config now. Changes below shouldn't persist across CI.
forge_config = deepcopy(forge_config)
forge_config["configs"] = configs
forge_config["fast_finish"] = _get_fast_finish_script(
provider_name,
forge_dir=forge_dir,
forge_config=forge_config,
fast_finish_text=fast_finish_text,
)
# If the recipe has its own conda_forge_ci_setup package, then
# install that
if 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",
)
):
forge_config["local_ci_setup"] = True
else:
forge_config["local_ci_setup"] = False
# hook for extending with whatever platform specific junk we need.
# Function passed in as argument
build_platforms = OrderedDict()
for platform, arch, enable in zip(platforms, archs, enable_platform):
if enable:
build_platform = forge_config["build_platform"][
f"{platform}_{arch}"
].split("_")[0]
build_platforms[build_platform] = True
for platform in build_platforms.keys():
platform_specific_setup(
jinja_env=jinja_env,
forge_dir=forge_dir,
forge_config=forge_config,
platform=platform,
)
template = jinja_env.get_template(platform_template_file)
with write_file(platform_target_path) as fh:
fh.write(template.render(**forge_config))
# circleci needs a placeholder file of sorts - always write the output, even if no metas
if provider_name == "circle":
template = jinja_env.get_template(platform_template_file)
with write_file(platform_target_path) as fh:
fh.write(template.render(**forge_config))
# TODO: azure-pipelines might need the same as circle
if return_metadata:
return dict(
forge_config=forge_config,
metas_list_of_lists=metas_list_of_lists,
platforms=platforms,
archs=archs,
enable_platform=enable_platform,
provider_name=provider_name,
)
else:
return forge_config
def _get_build_setup_line(forge_dir, platform, forge_config):
# If the recipe supplies its own run_conda_forge_build_setup script_linux,
# we use it instead of the global one.
if platform == "linux":
cfbs_fpath = os.path.join(
forge_dir,
forge_config["recipe_dir"],
"run_conda_forge_build_setup_linux",
)
elif platform == "win":
cfbs_fpath = os.path.join(
forge_dir,
forge_config["recipe_dir"],
"run_conda_forge_build_setup_win.bat",
)
else:
cfbs_fpath = os.path.join(
forge_dir,
forge_config["recipe_dir"],
"run_conda_forge_build_setup_osx",
)
build_setup = ""
if os.path.exists(cfbs_fpath):
if platform == "linux":
build_setup += textwrap.dedent(
"""\
# Overriding global run_conda_forge_build_setup_linux with local copy.
source ${RECIPE_ROOT}/run_conda_forge_build_setup_linux
"""
)
elif platform == "win":
build_setup += textwrap.dedent(
"""\
:: Overriding global run_conda_forge_build_setup_win with local copy.
CALL {recipe_dir}\\run_conda_forge_build_setup_win
""".format(
recipe_dir=forge_config["recipe_dir"]
)
)
else:
build_setup += textwrap.dedent(
"""\
# Overriding global run_conda_forge_build_setup_osx with local copy.
source {recipe_dir}/run_conda_forge_build_setup_osx
""".format(
recipe_dir=forge_config["recipe_dir"]
)
)
else:
if platform == "win":
build_setup += textwrap.dedent(
"""\
CALL run_conda_forge_build_setup
"""
)
else:
build_setup += textwrap.dedent(
"""\
source run_conda_forge_build_setup
"""
)
return build_setup
def _circle_specific_setup(jinja_env, forge_config, forge_dir, platform):
if platform == "linux":
yum_build_setup = generate_yum_requirements(forge_config, forge_dir)
if yum_build_setup:
forge_config["yum_build_setup"] = yum_build_setup
forge_config["build_setup"] = _get_build_setup_line(
forge_dir, platform, forge_config
)
template_files = [".circleci/fast_finish_ci_pr_build.sh"]
if platform == "linux":
template_files.append(".scripts/run_docker_build.sh")
template_files.append(".scripts/build_steps.sh")
else:
template_files.append(".scripts/run_osx_build.sh")
_render_template_exe_files(
forge_config=forge_config,
jinja_env=jinja_env,
template_files=template_files,