-
Notifications
You must be signed in to change notification settings - Fork 427
/
environ.py
1479 lines (1294 loc) · 52.1 KB
/
environ.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 contextlib
import json
import logging
import multiprocessing
import os
import platform
import re
import subprocess
import sys
import warnings
from collections import defaultdict
from functools import lru_cache
from glob import glob
from logging import getLogger
from os.path import join, normpath
from typing import TYPE_CHECKING
from conda.base.constants import (
CONDA_PACKAGE_EXTENSIONS,
DEFAULTS_CHANNEL_NAME,
UNKNOWN_CHANNEL,
)
from conda.base.context import context, reset_context
from conda.common.io import env_vars
from conda.core.index import LAST_CHANNEL_URLS
from conda.core.link import PrefixSetup, UnlinkLinkTransaction
from conda.core.package_cache_data import PackageCacheData
from conda.core.prefix_data import PrefixData
from conda.exceptions import (
CondaError,
LinkError,
LockError,
NoPackagesFoundError,
PaddingError,
UnsatisfiableError,
)
from conda.models.channel import prioritize_channels
from conda.models.match_spec import MatchSpec
from . import utils
from .conda_interface import (
Channel,
PackageRecord,
ProgressiveFetchExtract,
TemporaryDirectory,
)
from .deprecations import deprecated
from .exceptions import BuildLockError, DependencyNeedsBuildingError
from .features import feature_list
from .index import get_build_index
from .os_utils import external
from .utils import (
ensure_list,
env_var,
on_mac,
on_win,
package_record_to_requirement,
prepend_bin_path,
)
from .variants import get_default_variant
if TYPE_CHECKING:
from pathlib import Path
from typing import Any, Iterable, TypedDict
from .config import Config
from .metadata import MetaData
class InstallActionsType(TypedDict):
PREFIX: str | os.PathLike | Path
LINK: list[PackageRecord]
log = getLogger(__name__)
deprecated.constant("24.3", "24.5", "PREFIX_ACTION", _PREFIX_ACTION := "PREFIX")
deprecated.constant("24.3", "24.5", "LINK_ACTION", _LINK_ACTION := "LINK")
# these are things that we provide env vars for more explicitly. This list disables the
# pass-through of variant values to env vars for these keys.
LANGUAGES = ("PERL", "LUA", "R", "NUMPY", "PYTHON")
R_PACKAGES = ("r-base", "mro-base", "r-impl")
def get_perl_ver(config):
return ".".join(
config.variant.get("perl", get_default_variant(config)["perl"]).split(".")[:2]
)
def get_lua_ver(config):
return ".".join(
config.variant.get("lua", get_default_variant(config)["lua"]).split(".")[:2]
)
def get_py_ver(config):
py = config.variant.get("python", get_default_variant(config)["python"])
if not hasattr(py, "split"):
py = py[0]
return ".".join(py.split(".")[:2])
def get_r_ver(config):
return ".".join(
config.variant.get("r_base", get_default_variant(config)["r_base"]).split(".")[
:3
]
)
def get_npy_ver(config):
conda_npy = "".join(
str(config.variant.get("numpy") or get_default_variant(config)["numpy"]).split(
"."
)
)
# Convert int -> string, e.g.
# 17 -> '1.7'
# 110 -> '1.10'
return conda_npy[0] + "." + conda_npy[1:]
def get_lua_include_dir(config):
return join(config.host_prefix, "include")
@lru_cache(maxsize=None)
def verify_git_repo(
git_exe, git_dir, git_url, git_commits_since_tag, debug=False, expected_rev="HEAD"
):
env = os.environ.copy()
log = utils.get_logger(__name__)
stderr = None if debug else subprocess.DEVNULL
if not expected_rev:
return False
OK = True
env["GIT_DIR"] = git_dir
try:
# Verify current commit (minus our locally applied patches) matches expected commit
current_commit = utils.check_output_env(
[
git_exe,
"log",
"-n1",
"--format=%H",
"HEAD" + "^" * git_commits_since_tag,
],
env=env,
stderr=stderr,
)
current_commit = current_commit.decode("utf-8")
expected_tag_commit = utils.check_output_env(
[git_exe, "log", "-n1", "--format=%H", expected_rev], env=env, stderr=stderr
)
expected_tag_commit = expected_tag_commit.decode("utf-8")
if current_commit != expected_tag_commit:
return False
# Verify correct remote url. Need to find the git cache directory,
# and check the remote from there.
cache_details = utils.check_output_env(
[git_exe, "remote", "-v"], env=env, stderr=stderr
)
cache_details = cache_details.decode("utf-8")
cache_dir = cache_details.split("\n")[0].split()[1]
if not isinstance(cache_dir, str):
# On Windows, subprocess env can't handle unicode.
cache_dir = cache_dir.encode(sys.getfilesystemencoding() or "utf-8")
try:
remote_details = utils.check_output_env(
[git_exe, "--git-dir", cache_dir, "remote", "-v"],
env=env,
stderr=stderr,
)
except subprocess.CalledProcessError:
if on_win and cache_dir.startswith("/"):
cache_dir = utils.convert_unix_path_to_win(cache_dir)
remote_details = utils.check_output_env(
[git_exe, "--git-dir", cache_dir, "remote", "-v"],
env=env,
stderr=stderr,
)
remote_details = remote_details.decode("utf-8")
remote_url = remote_details.split("\n")[0].split()[1]
# on windows, remote URL comes back to us as cygwin or msys format. Python doesn't
# know how to normalize it. Need to convert it to a windows path.
if on_win and remote_url.startswith("/"):
remote_url = utils.convert_unix_path_to_win(git_url)
if os.path.exists(remote_url):
# Local filepaths are allowed, but make sure we normalize them
remote_url = normpath(remote_url)
# If the current source directory in conda-bld/work doesn't match the user's
# metadata git_url or git_rev, then we aren't looking at the right source.
if not os.path.isdir(remote_url) and remote_url.lower() != git_url.lower():
log.debug("remote does not match git_url")
log.debug("Remote: " + remote_url.lower())
log.debug("git_url: " + git_url.lower())
OK = False
except subprocess.CalledProcessError as error:
log.debug("Error obtaining git information in verify_git_repo. Error was: ")
log.debug(str(error))
OK = False
return OK
GIT_DESCRIBE_REGEX = re.compile(
r"(?:[_-a-zA-Z]*)"
r"(?P<version>[a-zA-Z0-9.]+)"
r"(?:-(?P<post>\d+)-g(?P<hash>[0-9a-f]{7,}))$"
)
def get_version_from_git_tag(tag):
"""Return a PEP440-compliant version derived from the git status.
If that fails for any reason, return the changeset hash.
"""
m = GIT_DESCRIBE_REGEX.match(tag)
if m is None:
return None
version, post_commit, hash = m.groups()
return version if post_commit == "0" else f"{version}.post{post_commit}+{hash}"
def get_git_info(git_exe, repo, debug):
"""
Given a repo to a git repo, return a dictionary of:
GIT_DESCRIBE_TAG
GIT_DESCRIBE_TAG_PEP440
GIT_DESCRIBE_NUMBER
GIT_DESCRIBE_HASH
GIT_FULL_HASH
GIT_BUILD_STR
from the output of git describe.
:return:
"""
d = {}
log = utils.get_logger(__name__)
stderr = None if debug else subprocess.DEVNULL
# grab information from describe
env = os.environ.copy()
env["GIT_DIR"] = repo
keys = ["GIT_DESCRIBE_TAG", "GIT_DESCRIBE_NUMBER", "GIT_DESCRIBE_HASH"]
try:
output = utils.check_output_env(
[git_exe, "describe", "--tags", "--long", "HEAD"],
env=env,
cwd=os.path.dirname(repo),
stderr=stderr,
).splitlines()[0]
output = output.decode("utf-8")
parts = output.rsplit("-", 2)
if len(parts) == 3:
d.update(dict(zip(keys, parts)))
d["GIT_DESCRIBE_TAG_PEP440"] = str(get_version_from_git_tag(output))
except subprocess.CalledProcessError:
msg = (
"Failed to obtain git tag information.\n"
"Consider using annotated tags if you are not already "
"as they are more reliable when used with git describe."
)
log.debug(msg)
# If there was no tag reachable from HEAD, the above failed and the short hash is not set.
# Try to get the short hash from describing with all refs (not just the tags).
if "GIT_DESCRIBE_HASH" not in d:
try:
output = utils.check_output_env(
[git_exe, "describe", "--all", "--long", "HEAD"],
env=env,
cwd=os.path.dirname(repo),
stderr=stderr,
).splitlines()[0]
output = output.decode("utf-8")
parts = output.rsplit("-", 2)
if len(parts) == 3:
# Don't save GIT_DESCRIBE_TAG and GIT_DESCRIBE_NUMBER because git (probably)
# described a branch. We just want to save the short hash.
d["GIT_DESCRIBE_HASH"] = parts[-1]
except subprocess.CalledProcessError as error:
log.debug("Error obtaining git commit information. Error was: ")
log.debug(str(error))
try:
# get the _full_ hash of the current HEAD
output = utils.check_output_env(
[git_exe, "rev-parse", "HEAD"],
env=env,
cwd=os.path.dirname(repo),
stderr=stderr,
).splitlines()[0]
output = output.decode("utf-8")
d["GIT_FULL_HASH"] = output
except subprocess.CalledProcessError as error:
log.debug("Error obtaining git commit information. Error was: ")
log.debug(str(error))
# set up the build string
if "GIT_DESCRIBE_NUMBER" in d and "GIT_DESCRIBE_HASH" in d:
d["GIT_BUILD_STR"] = "{}_{}".format(
d["GIT_DESCRIBE_NUMBER"], d["GIT_DESCRIBE_HASH"]
)
# issues on Windows with the next line of the command prompt being recorded here.
assert not any("\n" in value for value in d.values())
return d
def get_hg_build_info(repo):
env = os.environ.copy()
env["HG_DIR"] = repo
env = {str(key): str(value) for key, value in env.items()}
d = {}
cmd = [
"hg",
"log",
"--template",
"{rev}|{node|short}|{latesttag}|{latesttagdistance}|{branch}",
"--rev",
".",
]
output = utils.check_output_env(cmd, env=env, cwd=os.path.dirname(repo))
output = output.decode("utf-8")
rev, short_id, tag, distance, branch = output.split("|")
if tag != "null":
d["HG_LATEST_TAG"] = tag
if branch == "":
branch = "default"
d["HG_BRANCH"] = branch
d["HG_NUM_ID"] = rev
d["HG_LATEST_TAG_DISTANCE"] = distance
d["HG_SHORT_ID"] = short_id
d["HG_BUILD_STR"] = "{}_{}".format(d["HG_NUM_ID"], d["HG_SHORT_ID"])
return d
def get_dict(
m,
prefix=None,
for_env=True,
skip_build_id=False,
escape_backslash=False,
variant=None,
):
if not prefix:
prefix = m.config.host_prefix
m.config._merge_build_host = m.build_is_host
# conda-build specific vars
d = conda_build_vars(prefix, m.config)
# languages
d.update(python_vars(m, prefix, escape_backslash))
d.update(perl_vars(m, prefix, escape_backslash))
d.update(lua_vars(m, prefix, escape_backslash))
d.update(r_vars(m, prefix, escape_backslash))
if m:
d.update(meta_vars(m, skip_build_id=skip_build_id))
# system
d.update(os_vars(m, prefix))
# features
d.update({feat.upper(): str(int(value)) for feat, value in feature_list})
variant = variant or m.config.variant
for k, v in variant.items():
if not for_env or (k.upper() not in d and k.upper() not in LANGUAGES):
d[k] = v
return d
def conda_build_vars(prefix, config):
src_dir = (
config.test_dir if os.path.basename(prefix)[:2] == "_t" else config.work_dir
)
return {
"CONDA_BUILD": "1",
"PYTHONNOUSERSITE": "1",
"CONDA_DEFAULT_ENV": config.host_prefix,
"ARCH": str(config.host_arch),
# This is the one that is most important for where people put artifacts that get bundled.
# It is fed from our function argument, and can be any of:
# 1. Build prefix - when host requirements are not explicitly set,
# then prefix = build prefix = host prefix
# 2. Host prefix - when host requirements are explicitly set, prefix = host prefix
# 3. Test prefix - during test runs, this points at the test prefix
"PREFIX": prefix,
# This is for things that are specifically build tools. Things that run on the build
# platform, but probably should not be linked against, since they may not run on the
# destination host platform
# It can be equivalent to config.host_prefix if the host section is not explicitly set.
"BUILD_PREFIX": config.build_prefix,
"SYS_PREFIX": sys.prefix,
"SYS_PYTHON": sys.executable,
"SUBDIR": config.host_subdir,
"build_platform": config.build_subdir,
"SRC_DIR": src_dir,
"HTTPS_PROXY": os.getenv("HTTPS_PROXY", ""),
"HTTP_PROXY": os.getenv("HTTP_PROXY", ""),
"REQUESTS_CA_BUNDLE": os.getenv("REQUESTS_CA_BUNDLE", ""),
"DIRTY": "1" if config.dirty else "",
"ROOT": context.root_dir,
}
def python_vars(metadata, prefix, escape_backslash):
py_ver = get_py_ver(metadata.config)
stdlib_dir = utils.get_stdlib_dir(prefix, py_ver)
sp_dir = utils.get_site_packages(prefix, py_ver)
if utils.on_win and escape_backslash:
stdlib_dir = stdlib_dir.replace("\\", "\\\\")
sp_dir = sp_dir.replace("\\", "\\\\")
vars_ = {
"CONDA_PY": "".join(py_ver.split(".")[:2]),
"PY3K": str(int(int(py_ver[0]) >= 3)),
"PY_VER": py_ver,
"STDLIB_DIR": stdlib_dir,
"SP_DIR": sp_dir,
}
build_or_host = "host" if metadata.is_cross else "build"
deps = [str(ms.name) for ms in metadata.ms_depends(build_or_host)]
if "python" in deps or metadata.name() == "python":
python_bin = metadata.config.python_bin(prefix, metadata.config.host_subdir)
if utils.on_win and escape_backslash:
python_bin = python_bin.replace("\\", "\\\\")
vars_.update(
{
# host prefix is always fine, because it is the same as build when is_cross is False
"PYTHON": python_bin,
}
)
np_ver = metadata.config.variant.get(
"numpy", get_default_variant(metadata.config)["numpy"]
)
vars_["NPY_VER"] = ".".join(np_ver.split(".")[:2])
vars_["CONDA_NPY"] = "".join(np_ver.split(".")[:2])
vars_["NPY_DISTUTILS_APPEND_FLAGS"] = "1"
return vars_
def perl_vars(metadata, prefix, escape_backslash):
vars_ = {
"PERL_VER": get_perl_ver(metadata.config),
"CONDA_PERL": get_perl_ver(metadata.config),
}
build_or_host = "host" if metadata.is_cross else "build"
deps = [str(ms.name) for ms in metadata.ms_depends(build_or_host)]
if "perl" in deps or metadata.name() == "perl":
perl_bin = metadata.config.perl_bin(prefix, metadata.config.host_subdir)
if utils.on_win and escape_backslash:
perl_bin = perl_bin.replace("\\", "\\\\")
vars_.update(
{
# host prefix is always fine, because it is the same as build when is_cross is False
"PERL": perl_bin,
}
)
return vars_
def lua_vars(metadata, prefix, escape_backslash):
vars_ = {
"LUA_VER": get_lua_ver(metadata.config),
"CONDA_LUA": get_lua_ver(metadata.config),
}
build_or_host = "host" if metadata.is_cross else "build"
deps = [str(ms.name) for ms in metadata.ms_depends(build_or_host)]
if "lua" in deps:
lua_bin = metadata.config.lua_bin(prefix, metadata.config.host_subdir)
lua_include_dir = get_lua_include_dir(metadata.config)
if utils.on_win and escape_backslash:
lua_bin = lua_bin.replace("\\", "\\\\")
lua_include_dir = lua_include_dir.replace("\\", "\\\\")
vars_.update(
{
"LUA": lua_bin,
"LUA_INCLUDE_DIR": lua_include_dir,
}
)
return vars_
def r_vars(metadata, prefix, escape_backslash):
vars_ = {
"R_VER": get_r_ver(metadata.config),
"CONDA_R": get_r_ver(metadata.config),
}
build_or_host = "host" if metadata.is_cross else "build"
deps = [str(ms.name) for ms in metadata.ms_depends(build_or_host)]
if any(r_pkg in deps for r_pkg in R_PACKAGES) or metadata.name() in R_PACKAGES:
r_bin = metadata.config.r_bin(prefix, metadata.config.host_subdir)
# set R_USER explicitly to prevent crosstalk with existing R_LIBS_USER packages
r_user = join(prefix, "Libs", "R")
if utils.on_win and escape_backslash:
r_bin = r_bin.replace("\\", "\\\\")
vars_.update(
{
"R": r_bin,
"R_USER": r_user,
}
)
return vars_
def meta_vars(meta: MetaData, skip_build_id=False):
d = {}
for var_name in ensure_list(meta.get_value("build/script_env", [])):
if "=" in var_name:
var_name, value = var_name.split("=", 1)
else:
value = os.getenv(var_name)
if value is None:
warnings.warn(
"The environment variable '%s' specified in script_env is undefined."
% var_name,
UserWarning,
)
else:
d[var_name] = value
warnings.warn(
f"The environment variable '{var_name}' is being passed through with value "
f"'{'<hidden>' if meta.config.suppress_variables else value}'. "
"If you are splitting build and test phases with --no-test, please ensure "
"that this value is also set similarly at test time.",
UserWarning,
)
folder = meta.get_value("source/0/folder", "")
repo_dir = join(meta.config.work_dir, folder)
git_dir = join(repo_dir, ".git")
hg_dir = join(repo_dir, ".hg")
if not isinstance(git_dir, str):
# On Windows, subprocess env can't handle unicode.
git_dir = git_dir.encode(sys.getfilesystemencoding() or "utf-8")
git_exe = external.find_executable("git", meta.config.build_prefix)
if git_exe and os.path.exists(git_dir):
# We set all 'source' metavars using the FIRST source entry in meta.yaml.
git_url = meta.get_value("source/0/git_url")
if os.path.exists(git_url):
if on_win:
git_url = utils.convert_unix_path_to_win(git_url)
# If git_url is a relative path instead of a url, convert it to an abspath
git_url = normpath(join(meta.path, git_url))
_x = False
if git_url:
_x = verify_git_repo(
git_exe,
git_dir,
git_url,
meta.config.git_commits_since_tag,
meta.config.debug,
meta.get_value("source/0/git_rev", "HEAD"),
)
if _x or meta.get_value("source/0/path"):
d.update(get_git_info(git_exe, git_dir, meta.config.debug))
elif external.find_executable("hg", meta.config.build_prefix) and os.path.exists(
hg_dir
):
d.update(get_hg_build_info(hg_dir))
d["PKG_NAME"] = meta.name()
d["PKG_VERSION"] = meta.version()
d["PKG_BUILDNUM"] = str(meta.build_number())
if meta.final and not skip_build_id:
d["PKG_BUILD_STRING"] = meta.build_id()
d["PKG_HASH"] = meta.hash_dependencies()
else:
d["PKG_BUILD_STRING"] = "placeholder"
d["PKG_HASH"] = "1234567"
d["RECIPE_DIR"] = meta.path
return d
@lru_cache(maxsize=None)
def get_cpu_count():
if on_mac:
# multiprocessing.cpu_count() is not reliable on OSX
# See issue #645 on github.com/conda/conda-build
out, _ = subprocess.Popen(
"sysctl -n hw.logicalcpu", shell=True, stdout=subprocess.PIPE
).communicate()
return out.decode("utf-8").strip()
else:
try:
return str(multiprocessing.cpu_count())
except NotImplementedError:
return "1"
def get_shlib_ext(host_platform):
# Return the shared library extension.
if host_platform.startswith("win"):
return ".dll"
elif host_platform in ["osx", "darwin"]:
return ".dylib"
elif host_platform.startswith("linux") or host_platform.endswith("-wasm32"):
return ".so"
elif host_platform == "noarch":
# noarch packages should not contain shared libraries, use the system
# platform if this is requested
return get_shlib_ext(sys.platform)
else:
raise NotImplementedError(host_platform)
def windows_vars(m, get_default, prefix):
"""This is setting variables on a dict that is part of the get_default function"""
# We have gone for the clang values here.
win_arch = "i386" if str(m.config.host_arch) == "32" else "amd64"
win_msvc = "19.0.0"
library_prefix = join(prefix, "Library")
drive, tail = m.config.host_prefix.split(":")
get_default("SCRIPTS", join(prefix, "Scripts"))
get_default("LIBRARY_PREFIX", library_prefix)
get_default("LIBRARY_BIN", join(library_prefix, "bin"))
get_default("LIBRARY_INC", join(library_prefix, "include"))
get_default("LIBRARY_LIB", join(library_prefix, "lib"))
get_default(
"CYGWIN_PREFIX", "".join(("/cygdrive/", drive.lower(), tail.replace("\\", "/")))
)
# see https://en.wikipedia.org/wiki/Environment_variable#Default_values
get_default("ALLUSERSPROFILE")
get_default("APPDATA")
get_default("CommonProgramFiles")
get_default("CommonProgramFiles(x86)")
get_default("CommonProgramW6432")
get_default("COMPUTERNAME")
get_default("ComSpec")
get_default("HOMEDRIVE")
get_default("HOMEPATH")
get_default("LOCALAPPDATA")
get_default("LOGONSERVER")
get_default("NUMBER_OF_PROCESSORS")
get_default("PATHEXT")
get_default("ProgramData")
get_default("ProgramFiles")
get_default("ProgramFiles(x86)")
get_default("ProgramW6432")
get_default("PROMPT")
get_default("PSModulePath")
get_default("PUBLIC")
get_default("SystemDrive")
get_default("SystemRoot")
get_default("TEMP")
get_default("TMP")
get_default("USERDOMAIN")
get_default("USERNAME")
get_default("USERPROFILE")
get_default("windir")
# CPU data, see https://github.com/conda/conda-build/issues/2064
get_default("PROCESSOR_ARCHITEW6432")
get_default("PROCESSOR_ARCHITECTURE")
get_default("PROCESSOR_IDENTIFIER")
get_default("BUILD", win_arch + "-pc-windows-" + win_msvc)
for k in os.environ.keys():
if re.match("VS[0-9]{2,3}COMNTOOLS", k):
get_default(k)
elif re.match("VS[0-9]{4}INSTALLDIR", k):
get_default(k)
def unix_vars(m, get_default, prefix):
"""This is setting variables on a dict that is part of the get_default function"""
get_default("HOME", "UNKNOWN")
get_default("PKG_CONFIG_PATH", join(prefix, "lib", "pkgconfig"))
get_default("CMAKE_GENERATOR", "Unix Makefiles")
get_default("SSL_CERT_FILE")
def osx_vars(m, get_default, prefix):
"""This is setting variables on a dict that is part of the get_default function"""
if str(m.config.host_arch) == "32":
OSX_ARCH = "i386"
MACOSX_DEPLOYMENT_TARGET = 10.9
elif str(m.config.host_arch) == "arm64":
OSX_ARCH = "arm64"
MACOSX_DEPLOYMENT_TARGET = 11.0
else:
OSX_ARCH = "x86_64"
MACOSX_DEPLOYMENT_TARGET = 10.9
if str(m.config.arch) == "32":
BUILD = "i386-apple-darwin13.4.0"
elif str(m.config.arch) == "arm64":
BUILD = "arm64-apple-darwin20.0.0"
else:
BUILD = "x86_64-apple-darwin13.4.0"
# 10.7 install_name_tool -delete_rpath causes broken dylibs, I will revisit this ASAP.
# rpath = ' -Wl,-rpath,%(PREFIX)s/lib' % d # SIP workaround, DYLD_* no longer works.
# d['LDFLAGS'] = ldflags + rpath + ' -arch %(OSX_ARCH)s' % d
get_default("OSX_ARCH", OSX_ARCH)
get_default("MACOSX_DEPLOYMENT_TARGET", MACOSX_DEPLOYMENT_TARGET)
get_default("BUILD", BUILD)
@lru_cache(maxsize=None)
def _machine_and_architecture():
return platform.machine(), platform.architecture()
def linux_vars(m, get_default, prefix):
"""This is setting variables on a dict that is part of the get_default function"""
platform_machine, platform_architecture = _machine_and_architecture()
build_arch = platform_machine
# Python reports x86_64 when running a i686 Python binary on a 64-bit CPU
# unless run through linux32. Issue a warning when we detect this.
if build_arch == "x86_64" and platform_architecture[0] == "32bit":
print("Warning: You are running 32-bit Python on a 64-bit linux installation")
print(" but have not launched it via linux32. Various qeuries *will*")
print(" give unexpected results (uname -m, platform.machine() etc)")
build_arch = "i686"
# the GNU triplet is powerpc, not ppc. This matters.
if build_arch.startswith("ppc"):
build_arch = build_arch.replace("ppc", "powerpc")
if (
build_arch.startswith("powerpc")
or build_arch.startswith("aarch64")
or build_arch.startswith("s390x")
):
build_distro = "cos7"
else:
build_distro = "cos6"
# There is also QEMU_SET_ENV, but that needs to be
# filtered so it only contains the result of `linux_vars`
# which, before this change was empty, and after it only
# contains other QEMU env vars.
get_default("CFLAGS")
get_default("CXXFLAGS")
get_default("LDFLAGS")
get_default("QEMU_LD_PREFIX")
get_default("QEMU_UNAME")
get_default("DEJAGNU")
get_default("DISPLAY")
get_default("LD_RUN_PATH", prefix + "/lib")
get_default("BUILD", build_arch + "-conda_" + build_distro + "-linux-gnu")
def set_from_os_or_variant(out_dict, key, variant, default):
value = os.getenv(key)
if not value:
value = variant.get(key, default)
if value:
out_dict[key] = value
def system_vars(env_dict, m, prefix):
warnings.warn(
"`conda_build.environ.system_vars` is pending deprecation and will be removed in a "
"future release. Please use `conda_build.environ.os_vars` instead.",
PendingDeprecationWarning,
)
return os_vars(m, prefix)
def os_vars(m, prefix):
d = dict()
# note the dictionary is passed in here - variables are set in that dict if they are non-null
get_default = lambda key, default="": set_from_os_or_variant(
d, key, m.config.variant, default
)
get_default("CPU_COUNT", get_cpu_count())
get_default("LANG")
get_default("LC_ALL")
get_default("MAKEFLAGS")
d["SHLIB_EXT"] = get_shlib_ext(m.config.host_platform)
d["PATH"] = os.environ.copy()["PATH"]
if not m.config.activate:
d = prepend_bin_path(d, m.config.host_prefix)
if on_win:
windows_vars(m, get_default, prefix)
else:
unix_vars(m, get_default, prefix)
if m.config.host_platform == "osx":
osx_vars(m, get_default, prefix)
elif m.config.host_platform == "linux":
linux_vars(m, get_default, prefix)
return d
@deprecated("24.3", "24.5")
class InvalidEnvironment(Exception):
pass
# Stripped-down Environment class from conda-tools ( https://github.com/groutr/conda-tools )
# Vendored here to avoid the whole dependency for just this bit.
@deprecated("24.3", "24.5")
def _load_json(path):
with open(path) as fin:
x = json.load(fin)
return x
@deprecated("24.3", "24.5")
def _load_all_json(path):
"""
Load all json files in a directory. Return dictionary with filenames mapped to json
dictionaries.
"""
root, _, files = next(utils.walk(path))
result = {}
for f in files:
if f.endswith(".json"):
result[f] = _load_json(join(root, f))
return result
@deprecated("24.3", "24.5", addendum="Use `conda.core.prefix_data.PrefixData` instead.")
class Environment:
def __init__(self, path):
"""
Initialize an Environment object.
To reflect changes in the underlying environment, a new Environment object should be
created.
"""
self.path = path
self._meta = join(path, "conda-meta")
if os.path.isdir(path) and os.path.isdir(self._meta):
self._packages = {}
else:
raise InvalidEnvironment(f"Unable to load environment {path}")
def _read_package_json(self):
if not self._packages:
self._packages = _load_all_json(self._meta)
def package_specs(self):
"""
List all package specs in the environment.
"""
self._read_package_json()
json_objs = self._packages.values()
specs = []
for i in json_objs:
p, v, b = i["name"], i["version"], i["build"]
specs.append(f"{p} {v} {b}")
return specs
cached_precs: dict[
tuple[tuple[str | MatchSpec, ...], Any, Any, Any, bool], list[PackageRecord]
] = {}
deprecated.constant("24.3", "24.5", "cached_actions", cached_precs)
last_index_ts = 0
# NOTE: The function has to retain the "get_install_actions" name for now since
# conda_libmamba_solver.solver.LibMambaSolver._called_from_conda_build
# checks for this name in the call stack explicitly.
def get_install_actions(
prefix: str | os.PathLike | Path,
specs: Iterable[str | MatchSpec],
env, # unused
retries: int = 0,
subdir=None,
verbose: bool = True,
debug: bool = False,
locking: bool = True,
bldpkgs_dirs=None,
timeout=900,
disable_pip: bool = False,
max_env_retry: int = 3,
output_folder=None,
channel_urls=None,
) -> list[PackageRecord]:
global cached_precs
global last_index_ts
log = utils.get_logger(__name__)
conda_log_level = logging.WARN
specs = list(specs)
if specs:
specs.extend(context.create_default_packages)
if verbose or debug:
capture = contextlib.nullcontext
if debug:
conda_log_level = logging.DEBUG
else:
capture = utils.capture
for feature, value in feature_list:
if value:
specs.append("%s@" % feature)
bldpkgs_dirs = ensure_list(bldpkgs_dirs)
index, index_ts, _ = get_build_index(
subdir,
list(bldpkgs_dirs)[0],
output_folder=output_folder,
channel_urls=channel_urls,
debug=debug,
verbose=verbose,
locking=locking,
timeout=timeout,
)
specs = tuple(
utils.ensure_valid_spec(spec) for spec in specs if not str(spec).endswith("@")
)
precs: list[PackageRecord] = []
if (
specs,
env,
subdir,
channel_urls,
disable_pip,
) in cached_precs and last_index_ts >= index_ts:
precs = cached_precs[(specs, env, subdir, channel_urls, disable_pip)].copy()
elif specs:
# this is hiding output like:
# Fetching package metadata ...........
# Solving package specifications: ..........
with utils.LoggingContext(conda_log_level):
with capture():
try:
precs = _install_actions(prefix, index, specs)["LINK"]
except (NoPackagesFoundError, UnsatisfiableError) as exc:
raise DependencyNeedsBuildingError(exc, subdir=subdir)
except (
SystemExit,
PaddingError,
LinkError,
DependencyNeedsBuildingError,
CondaError,
AssertionError,
BuildLockError,
) as exc:
if "lock" in str(exc):
log.warn(
"failed to get package records, retrying. exception was: %s",
str(exc),
)
elif (
"requires a minimum conda version" in str(exc)
or "link a source that does not" in str(exc)
or isinstance(exc, AssertionError)
):
locks = utils.get_conda_operation_locks(
locking, bldpkgs_dirs, timeout
)
with utils.try_acquire_locks(locks, timeout=timeout):
pkg_dir = str(exc)
folder = 0
while (
os.path.dirname(pkg_dir) not in context.pkgs_dirs
and folder < 20
):
pkg_dir = os.path.dirname(pkg_dir)
folder += 1
log.warn(
"I think conda ended up with a partial extraction for %s. "
"Removing the folder and retrying",
pkg_dir,