-
Notifications
You must be signed in to change notification settings - Fork 425
/
utils.py
2224 lines (1896 loc) · 72.5 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2014 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from collections import OrderedDict, defaultdict
import contextlib
import fnmatch
from functools import lru_cache
import hashlib
from itertools import filterfalse
import json
from locale import getpreferredencoding
import libarchive
import logging
import logging.config
import mmap
import os
from os.path import (
dirname,
getmtime,
getsize,
isdir,
join,
isfile,
abspath,
islink,
expanduser,
expandvars,
)
import re
import stat
import subprocess
import sys
import shutil
import tarfile
import tempfile
from threading import Thread
import time
from pathlib import Path
try:
from json.decoder import JSONDecodeError
except ImportError:
JSONDecodeError = ValueError
import yaml
import filelock
import conda_package_handling.api
try:
from conda.base.constants import (
CONDA_PACKAGE_EXTENSIONS,
CONDA_PACKAGE_EXTENSION_V1,
CONDA_PACKAGE_EXTENSION_V2,
)
except Exception:
from conda.base.constants import (
CONDA_TARBALL_EXTENSION as CONDA_PACKAGE_EXTENSION_V1,
)
CONDA_PACKAGE_EXTENSION_V2 = ".conda"
CONDA_PACKAGE_EXTENSIONS = (CONDA_PACKAGE_EXTENSION_V2, CONDA_PACKAGE_EXTENSION_V1)
from conda.api import PackageCacheData # noqa
from .conda_interface import (
hashsum_file,
md5_file,
unix_path_to_win,
win_path_to_unix,
) # noqa
from .conda_interface import root_dir, pkgs_dirs # noqa
from .conda_interface import StringIO # noqa
from .conda_interface import VersionOrder, MatchSpec # noqa
from .conda_interface import cc_conda_build # noqa
from .conda_interface import Dist # noqa
from .conda_interface import context # noqa
from .conda_interface import (
download,
TemporaryDirectory,
get_conda_channel,
CondaHTTPError,
) # noqa
# NOQA because it is not used in this file.
from conda_build.conda_interface import rm_rf as _rm_rf # noqa
from conda_build.exceptions import BuildLockError # noqa
from conda_build.os_utils import external # noqa
import urllib.parse as urlparse
import urllib.request as urllib
from glob import glob as glob_glob
# stdlib glob is less feature-rich but considerably faster than glob2
def glob(pathname, recursive=True):
return glob_glob(pathname, recursive=recursive)
# NOQA because it is not used in this file.
from contextlib import ExitStack # NOQA
PermissionError = PermissionError # NOQA
FileNotFoundError = FileNotFoundError
on_win = sys.platform == "win32"
codec = getpreferredencoding() or "utf-8"
on_win = sys.platform == "win32"
root_script_dir = os.path.join(root_dir, "Scripts" if on_win else "bin")
mmap_MAP_PRIVATE = 0 if on_win else mmap.MAP_PRIVATE
mmap_PROT_READ = 0 if on_win else mmap.PROT_READ
mmap_PROT_WRITE = 0 if on_win else mmap.PROT_WRITE
DEFAULT_SUBDIRS = {
"linux-64",
"linux-32",
"linux-s390x",
"linux-ppc64",
"linux-ppc64le",
"linux-armv6l",
"linux-armv7l",
"linux-aarch64",
"win-64",
"win-32",
"win-arm64",
"osx-64",
"osx-arm64",
"zos-z",
"noarch",
}
RUN_EXPORTS_TYPES = {
"weak",
"strong",
"noarch",
"weak_constrains",
"strong_constrains",
}
PY_TMPL = r"""
# -*- coding: utf-8 -*-
import re
import sys
from %(module)s import %(import_name)s
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(%(func)s())
"""
# filenames accepted as recipe meta files
VALID_METAS = ("meta.yaml", "meta.yml", "conda.yaml", "conda.yml")
try:
from os import scandir, walk # NOQA
except ImportError:
from scandir import walk
@lru_cache(maxsize=None)
def stat_file(path):
return os.stat(path)
def directory_size_slow(path):
total_size = 0
seen = set()
for root, _, files in walk(path):
for f in files:
try:
stat = stat_file(os.path.join(root, f))
except OSError:
continue
if stat.st_ino in seen:
continue
seen.add(stat.st_ino)
total_size += stat.st_size
return total_size
def directory_size(path):
""" """
try:
if on_win:
command = 'dir /s "{}"' # Windows path can have spaces
out = subprocess.check_output(command.format(path), shell=True)
else:
command = "du -s {}"
out = subprocess.check_output(
command.format(path).split(), stderr=subprocess.PIPE
)
if hasattr(out, "decode"):
try:
out = out.decode(errors="ignore")
# This isn't important anyway so give up. Don't try search on bytes.
except (UnicodeDecodeError, IndexError):
if on_win:
return 0
else:
pass
if on_win:
# Windows can give long output, we need only 2nd to last line
out = out.strip().rsplit("\r\n", 2)[-2]
pattern = r"\s([\d\W]+).+" # Language and punctuation neutral
out = re.search(pattern, out.strip()).group(1).strip()
out = out.replace(",", "").replace(".", "").replace(" ", "")
else:
out = out.split()[0]
except subprocess.CalledProcessError:
out = directory_size_slow(path)
try:
return int(out) # size in bytes
except ValueError:
return 0
class DummyPsutilProcess:
def children(self, *args, **kwargs):
return []
def _setup_rewrite_pipe(env):
"""Rewrite values of env variables back to $ENV in stdout
Takes output on the pipe and finds any env value
and rewrites it as the env key
Useful for replacing "~/conda/conda-bld/pkg_<date>/_h_place..." with "$PREFIX"
Returns an FD to be passed to Popen(stdout=...)
"""
# replacements is the env dict reversed,
# ordered by the length of the value so that longer replacements
# always occur first in case of common prefixes
replacements = OrderedDict()
for k, v in sorted(env.items(), key=lambda kv: len(kv[1]), reverse=True):
replacements[v] = k
r_fd, w_fd = os.pipe()
r = os.fdopen(r_fd, "rt")
if sys.platform == "win32":
replacement_t = "%{}%"
else:
replacement_t = "${}"
def rewriter():
while True:
try:
line = r.readline()
if not line:
# reading done
r.close()
os.close(w_fd)
return
for s, key in replacements.items():
line = line.replace(s, replacement_t.format(key))
sys.stdout.write(line)
except UnicodeDecodeError:
try:
txt = os.read(r, 10000)
sys.stdout.write(txt or "")
except TypeError:
pass
t = Thread(target=rewriter)
t.daemon = True
t.start()
return w_fd
class PopenWrapper:
# Small wrapper around subprocess.Popen to allow memory usage monitoring
# copied from ProtoCI, https://github.com/ContinuumIO/ProtoCI/blob/59159bc2c9f991fbfa5e398b6bb066d7417583ec/protoci/build2.py#L20 # NOQA
def __init__(self, *args, **kwargs):
self.elapsed = None
self.rss = 0
self.vms = 0
self.returncode = None
self.disk = 0
self.processes = 1
self.out, self.err = self._execute(*args, **kwargs)
def _execute(self, *args, **kwargs):
try:
import psutil
psutil_exceptions = (
psutil.NoSuchProcess,
psutil.AccessDenied,
psutil.NoSuchProcess,
)
except ImportError as e:
psutil = None
psutil_exceptions = (OSError, ValueError)
log = get_logger(__name__)
log.warn(f"psutil import failed. Error was {e}")
log.warn(
"only disk usage and time statistics will be available. Install psutil to "
"get CPU time and memory usage statistics."
)
# The polling interval (in seconds)
time_int = kwargs.pop("time_int", 2)
disk_usage_dir = kwargs.get("cwd", sys.prefix)
# Create a process of this (the parent) process
parent = psutil.Process(os.getpid()) if psutil else DummyPsutilProcess()
cpu_usage = defaultdict(dict)
# Using the convenience Popen class provided by psutil
start_time = time.time()
_popen = (
psutil.Popen(*args, **kwargs)
if psutil
else subprocess.Popen(*args, **kwargs)
)
try:
while self.returncode is None:
# We need to get all of the children of our process since our
# process spawns other processes. Collect all of the child
# processes
rss = 0
vms = 0
processes = 0
# We use the parent process to get mem usage of all spawned processes
for child in parent.children(recursive=True):
child_cpu_usage = cpu_usage.get(child.pid, {})
try:
mem = child.memory_info()
rss += mem.rss
vms += mem.rss
# listing child times are only available on linux, so we don't use them.
# we are instead looping over children and getting each individually.
# https://psutil.readthedocs.io/en/latest/#psutil.Process.cpu_times
cpu_stats = child.cpu_times()
child_cpu_usage["sys"] = cpu_stats.system
child_cpu_usage["user"] = cpu_stats.user
cpu_usage[child.pid] = child_cpu_usage
except psutil_exceptions:
# process already died. Just ignore it.
continue
processes += 1
# Sum the memory usage of all the children together (2D columnwise sum)
self.rss = max(rss, self.rss)
self.vms = max(vms, self.vms)
self.cpu_sys = sum(child["sys"] for child in cpu_usage.values())
self.cpu_user = sum(child["user"] for child in cpu_usage.values())
self.processes = max(processes, self.processes)
# Get disk usage
self.disk = max(directory_size(disk_usage_dir), self.disk)
time.sleep(time_int)
self.elapsed = time.time() - start_time
self.returncode = _popen.poll()
except KeyboardInterrupt:
_popen.kill()
raise
self.disk = max(directory_size(disk_usage_dir), self.disk)
self.elapsed = time.time() - start_time
return _popen.stdout, _popen.stderr
def __repr__(self):
return str(
{
"elapsed": self.elapsed,
"rss": self.rss,
"vms": self.vms,
"disk": self.disk,
"processes": self.processes,
"cpu_user": self.cpu_user,
"cpu_sys": self.cpu_sys,
"returncode": self.returncode,
}
)
def _func_defaulting_env_to_os_environ(func, *popenargs, **kwargs):
if "env" not in kwargs:
kwargs = kwargs.copy()
env_copy = os.environ.copy()
kwargs.update({"env": env_copy})
kwargs["env"] = {str(key): str(value) for key, value in kwargs["env"].items()}
_args = []
if "stdin" not in kwargs:
kwargs["stdin"] = subprocess.PIPE
for arg in popenargs:
# arguments to subprocess need to be bytestrings
if sys.version_info.major < 3 and hasattr(arg, "encode"):
arg = arg.encode(codec)
elif sys.version_info.major >= 3 and hasattr(arg, "decode"):
arg = arg.decode(codec)
_args.append(str(arg))
stats = kwargs.get("stats")
if "stats" in kwargs:
del kwargs["stats"]
rewrite_stdout_env = kwargs.pop("rewrite_stdout_env", None)
if rewrite_stdout_env:
kwargs["stdout"] = _setup_rewrite_pipe(rewrite_stdout_env)
out = None
if stats is not None:
proc = PopenWrapper(_args, **kwargs)
if func == "output":
out = proc.out.read()
if proc.returncode != 0:
raise subprocess.CalledProcessError(proc.returncode, _args)
stats.update(
{
"elapsed": proc.elapsed,
"disk": proc.disk,
"processes": proc.processes,
"cpu_user": proc.cpu_user,
"cpu_sys": proc.cpu_sys,
"rss": proc.rss,
"vms": proc.vms,
}
)
else:
if func == "call":
subprocess.check_call(_args, **kwargs)
else:
if "stdout" in kwargs:
del kwargs["stdout"]
out = subprocess.check_output(_args, **kwargs)
return out
def check_call_env(popenargs, **kwargs):
return _func_defaulting_env_to_os_environ("call", *popenargs, **kwargs)
def check_output_env(popenargs, **kwargs):
return _func_defaulting_env_to_os_environ(
"output", stdout=subprocess.PIPE, *popenargs, **kwargs
).rstrip()
def bytes2human(n):
# http://code.activestate.com/recipes/578019
# >>> bytes2human(10000)
# '9.8K'
# >>> bytes2human(100001221)
# '95.4M'
symbols = ("K", "M", "G", "T", "P", "E", "Z", "Y")
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return f"{value:.1f}{s}"
return "%sB" % n
def seconds2human(s):
m, s = divmod(s, 60)
h, m = divmod(int(m), 60)
return f"{h:d}:{m:02d}:{s:04.1f}"
def get_recipe_abspath(recipe):
"""resolve recipe dir as absolute path. If recipe is a tarball rather than a folder,
extract it and return the extracted directory.
Returns the absolute path, and a boolean flag that is true if a tarball has been extracted
and needs cleanup.
"""
if isfile(recipe):
if recipe.lower().endswith(decompressible_exts) or recipe.lower().endswith(
CONDA_PACKAGE_EXTENSIONS
):
recipe_dir = tempfile.mkdtemp()
if recipe.lower().endswith(CONDA_PACKAGE_EXTENSIONS):
import conda_package_handling.api
conda_package_handling.api.extract(recipe, recipe_dir)
else:
tar_xf(recipe, recipe_dir)
# At some stage the old build system started to tar up recipes.
recipe_tarfile = os.path.join(recipe_dir, "info", "recipe.tar")
if isfile(recipe_tarfile):
tar_xf(recipe_tarfile, os.path.join(recipe_dir, "info"))
need_cleanup = True
else:
print("Ignoring non-recipe: %s" % recipe)
return (None, None)
else:
recipe_dir = abspath(os.path.join(os.getcwd(), recipe))
need_cleanup = False
if not os.path.exists(recipe_dir):
raise ValueError(f"Package or recipe at path {recipe_dir} does not exist")
return recipe_dir, need_cleanup
@contextlib.contextmanager
def try_acquire_locks(locks, timeout):
"""Try to acquire all locks.
If any lock can't be immediately acquired, free all locks.
If the timeout is reached withou acquiring all locks, free all locks and raise.
http://stackoverflow.com/questions/9814008/multiple-mutex-locking-strategies-and-why-libraries-dont-use-address-comparison
"""
t = time.time()
while time.time() - t < timeout:
# Continuously try to acquire all locks.
# By passing a short timeout to each individual lock, we give other
# processes that might be trying to acquire the same locks (and may
# already hold some of them) a chance to the remaining locks - and
# hopefully subsequently release them.
try:
for lock in locks:
lock.acquire(timeout=0.1)
except filelock.Timeout:
# If we failed to acquire a lock, it is important to release all
# locks we may have already acquired, to avoid wedging multiple
# processes that try to acquire the same set of locks.
# That is, we want to avoid a situation where processes 1 and 2 try
# to acquire locks A and B, and proc 1 holds lock A while proc 2
# holds lock B.
for lock in locks:
lock.release()
else:
break
else:
# If we reach this point, we weren't able to acquire all locks within
# the specified timeout. We shouldn't be holding any locks anymore at
# this point, so we just raise an exception.
raise BuildLockError("Failed to acquire all locks")
try:
yield
finally:
for lock in locks:
lock.release()
# with each of these, we are copying less metadata. This seems to be necessary
# to cope with some shared filesystems with some virtual machine setups.
# See https://github.com/conda/conda-build/issues/1426
def _copy_with_shell_fallback(src, dst):
is_copied = False
for func in (shutil.copy2, shutil.copy, shutil.copyfile):
try:
func(src, dst)
is_copied = True
break
except (OSError, PermissionError):
continue
if not is_copied:
try:
subprocess.check_call(
f"cp -a {src} {dst}",
shell=True,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
)
except subprocess.CalledProcessError as e:
if not os.path.isfile(dst):
raise OSError(f"Failed to copy {src} to {dst}. Error was: {e}")
def get_prefix_replacement_paths(src, dst):
ssplit = src.split(os.path.sep)
dsplit = dst.split(os.path.sep)
while ssplit and ssplit[-1] == dsplit[-1]:
del ssplit[-1]
del dsplit[-1]
return os.path.join(*ssplit), os.path.join(*dsplit)
def copy_into(
src, dst, timeout=900, symlinks=False, lock=None, locking=True, clobber=False
):
"""Copy all the files and directories in src to the directory dst"""
log = get_logger(__name__)
if symlinks and islink(src):
try:
os.makedirs(os.path.dirname(dst))
except OSError:
pass
if os.path.lexists(dst):
os.remove(dst)
src_base, dst_base = get_prefix_replacement_paths(src, dst)
src_target = os.readlink(src)
src_replaced = src_target.replace(src_base, dst_base)
os.symlink(src_replaced, dst)
try:
st = os.lstat(src)
mode = stat.S_IMODE(st.st_mode)
os.lchmod(dst, mode)
except:
pass # lchmod not available
elif isdir(src):
merge_tree(
src,
dst,
symlinks,
timeout=timeout,
lock=lock,
locking=locking,
clobber=clobber,
)
else:
if isdir(dst):
dst_fn = os.path.join(dst, os.path.basename(src))
else:
dst_fn = dst
if os.path.isabs(src):
src_folder = os.path.dirname(src)
else:
if os.path.sep in dst_fn:
src_folder = os.path.dirname(dst_fn)
if not os.path.isdir(src_folder):
os.makedirs(src_folder)
else:
src_folder = os.getcwd()
if os.path.islink(src) and not os.path.exists(os.path.realpath(src)):
log.warn("path %s is a broken symlink - ignoring copy", src)
return
if not lock and locking:
lock = get_lock(src_folder, timeout=timeout)
locks = [lock] if locking else []
with try_acquire_locks(locks, timeout):
# if intermediate folders not not exist create them
dst_folder = os.path.dirname(dst)
if dst_folder and not os.path.exists(dst_folder):
try:
os.makedirs(dst_folder)
except OSError:
pass
try:
_copy_with_shell_fallback(src, dst_fn)
except shutil.Error:
log.debug(
"skipping %s - already exists in %s", os.path.basename(src), dst
)
def move_with_fallback(src, dst):
try:
shutil.move(src, dst)
except PermissionError:
try:
copy_into(src, dst)
os.unlink(src)
except PermissionError:
log = get_logger(__name__)
log.debug(
f"Failed to copy/remove path from {src} to {dst} due to permission error"
)
# http://stackoverflow.com/a/22331852/1170370
def copytree(src, dst, symlinks=False, ignore=None, dry_run=False):
if not os.path.exists(dst):
os.makedirs(dst)
shutil.copystat(src, dst)
lst = os.listdir(src)
if ignore:
excl = ignore(src, lst)
lst = [x for x in lst if x not in excl]
# do not copy lock files
if ".conda_lock" in lst:
lst.remove(".conda_lock")
dst_lst = [os.path.join(dst, item) for item in lst]
if not dry_run:
for idx, item in enumerate(lst):
s = os.path.join(src, item)
d = dst_lst[idx]
if symlinks and os.path.islink(s):
if os.path.lexists(d):
os.remove(d)
os.symlink(os.readlink(s), d)
try:
st = os.lstat(s)
mode = stat.S_IMODE(st.st_mode)
os.lchmod(d, mode)
except:
pass # lchmod not available
elif os.path.isdir(s):
copytree(s, d, symlinks, ignore)
else:
_copy_with_shell_fallback(s, d)
return dst_lst
def merge_tree(
src, dst, symlinks=False, timeout=900, lock=None, locking=True, clobber=False
):
"""
Merge src into dst recursively by copying all files from src into dst.
Return a list of all files copied.
Like copytree(src, dst), but raises an error if merging the two trees
would overwrite any files.
"""
dst = os.path.normpath(os.path.normcase(dst))
src = os.path.normpath(os.path.normcase(src))
assert not dst.startswith(src), (
"Can't merge/copy source into subdirectory of itself. "
"Please create separate spaces for these things.\n"
" src: {}\n"
" dst: {}".format(src, dst)
)
new_files = copytree(src, dst, symlinks=symlinks, dry_run=True)
existing = [f for f in new_files if isfile(f)]
if existing and not clobber:
raise OSError(
"Can't merge {} into {}: file exists: " "{}".format(src, dst, existing[0])
)
locks = []
if locking:
if not lock:
lock = get_lock(src, timeout=timeout)
locks = [lock]
with try_acquire_locks(locks, timeout):
copytree(src, dst, symlinks=symlinks)
# purpose here is that we want *one* lock per location on disk. It can be locked or unlocked
# at any time, but the lock within this process should all be tied to the same tracking
# mechanism.
_lock_folders = (
os.path.join(root_dir, "locks"),
os.path.expanduser(os.path.join("~", ".conda_build_locks")),
)
def get_lock(folder, timeout=900):
fl = None
try:
location = os.path.abspath(os.path.normpath(folder))
except OSError:
location = folder
b_location = location
if hasattr(b_location, "encode"):
b_location = b_location.encode()
# Hash the entire filename to avoid collisions.
lock_filename = hashlib.sha256(b_location).hexdigest()
if hasattr(lock_filename, "decode"):
lock_filename = lock_filename.decode()
for locks_dir in _lock_folders:
try:
if not os.path.isdir(locks_dir):
os.makedirs(locks_dir)
lock_file = os.path.join(locks_dir, lock_filename)
with open(lock_file, "w") as f:
f.write("")
fl = filelock.FileLock(lock_file, timeout)
break
except OSError:
continue
else:
raise RuntimeError(
"Could not write locks folder to either system location ({})"
"or user location ({}). Aborting.".format(*_lock_folders)
)
return fl
def get_conda_operation_locks(locking=True, bldpkgs_dirs=None, timeout=900):
locks = []
bldpkgs_dirs = ensure_list(bldpkgs_dirs)
# locks enabled by default
if locking:
_pkgs_dirs = pkgs_dirs[:1]
locked_folders = _pkgs_dirs + list(bldpkgs_dirs)
for folder in locked_folders:
if not os.path.isdir(folder):
os.makedirs(folder)
lock = get_lock(folder, timeout=timeout)
locks.append(lock)
# lock used to generally indicate a conda operation occurring
locks.append(get_lock("conda-operation", timeout=timeout))
return locks
def relative(f, d="lib"):
assert not f.startswith("/"), f
assert not d.startswith("/"), d
d = d.strip("/").split("/")
if d == ["."]:
d = []
f = dirname(f).split("/")
if f == [""]:
f = []
while d and f and d[0] == f[0]:
d.pop(0)
f.pop(0)
return "/".join((([".."] * len(f)) if f else ["."]) + d)
# This is the lowest common denominator of the formats supported by our libarchive/python-libarchive-c
# packages across all platforms
decompressible_exts = (
".7z",
".tar",
".tar.bz2",
".tar.gz",
".tar.lzma",
".tar.xz",
".tar.z",
".tar.zst",
".tgz",
".whl",
".zip",
".rpm",
".deb",
)
def _tar_xf_fallback(tarball, dir_path, mode="r:*"):
if tarball.lower().endswith(".tar.z"):
uncompress = external.find_executable("uncompress")
if not uncompress:
uncompress = external.find_executable("gunzip")
if not uncompress:
sys.exit(
"""\
uncompress (or gunzip) is required to unarchive .z source files.
"""
)
check_call_env([uncompress, "-f", tarball])
tarball = tarball[:-2]
t = tarfile.open(tarball, mode)
members = t.getmembers()
for i, member in enumerate(members, 0):
if os.path.isabs(member.name):
member.name = os.path.relpath(member.name, "/")
cwd = os.path.realpath(os.getcwd())
if not os.path.realpath(member.name).startswith(cwd):
member.name = member.name.replace("../", "")
if not os.path.realpath(member.name).startswith(cwd):
sys.exit("tarball contains unsafe path: " + member.name + " cwd is: " + cwd)
members[i] = member
t.extractall(path=dir_path)
t.close()
def tar_xf_file(tarball, entries):
from conda_build.utils import ensure_list
entries = ensure_list(entries)
if not os.path.isabs(tarball):
tarball = os.path.join(os.getcwd(), tarball)
result = None
n_found = 0
with libarchive.file_reader(tarball) as archive:
for entry in archive:
if entry.name in entries:
n_found += 1
for block in entry.get_blocks():
if result is None:
result = bytes(block)
else:
result += block
break
if n_found != len(entries):
raise KeyError()
return result
def tar_xf_getnames(tarball):
if not os.path.isabs(tarball):
tarball = os.path.join(os.getcwd(), tarball)
result = []
with libarchive.file_reader(tarball) as archive:
for entry in archive:
result.append(entry.name)
return result
def tar_xf(tarball, dir_path):
flags = (
libarchive.extract.EXTRACT_TIME
| libarchive.extract.EXTRACT_PERM
| libarchive.extract.EXTRACT_SECURE_NODOTDOT
| libarchive.extract.EXTRACT_SECURE_SYMLINKS
| libarchive.extract.EXTRACT_SECURE_NOABSOLUTEPATHS
)
if not os.path.isabs(tarball):
tarball = os.path.join(os.getcwd(), tarball)
try:
with tmp_chdir(os.path.realpath(dir_path)):
libarchive.extract_file(tarball, flags)
except libarchive.exception.ArchiveError:
# try again, maybe we are on Windows and the archive contains symlinks
# https://github.com/conda/conda-build/issues/3351
# https://github.com/libarchive/libarchive/pull/1030
if tarball.lower().endswith(
(".tar", ".tar.gz", ".tgz", ".tar.bz2", ".tar.z", ".tar.xz")
):
_tar_xf_fallback(tarball, dir_path)
else:
raise
def file_info(path):
return {
"size": getsize(path),
"md5": md5_file(path),
"sha256": hashsum_file(path, "sha256"),
"mtime": getmtime(path),
}
def comma_join(items):
"""
Like ', '.join(items) but with and
Examples:
>>> comma_join(['a'])
'a'
>>> comma_join(['a', 'b'])
'a and b'
>>> comma_join(['a', 'b', 'c'])
'a, b, and c'
"""
return (
" and ".join(items)
if len(items) <= 2
else ", ".join(items[:-1]) + ", and " + items[-1]
)
def safe_print_unicode(*args, **kwargs):
"""
prints unicode strings to stdout using configurable `errors` handler for
encoding errors
:param args: unicode strings to print to stdout
:param sep: separator (defaults to ' ')
:param end: ending character (defaults to '\n')
:param errors: error handler for encoding errors (defaults to 'replace')
"""
sep = kwargs.pop("sep", " ")
end = kwargs.pop("end", "\n")
errors = kwargs.pop("errors", "replace")
func = sys.stdout.buffer.write
line = sep.join(args) + end
encoding = sys.stdout.encoding or "utf8"
func(line.encode(encoding, errors))
def rec_glob(path, patterns, ignores=None):
"""
Recursively searches path for filename patterns.
:param path: path within to search for files
:param patterns: list of filename patterns to search for
:param ignore: list of directory patterns to ignore in search
:return: list of paths in path satisfying patterns/ignore
"""
patterns = ensure_list(patterns)
ignores = ensure_list(ignores)
for path, dirs, files in walk(path):
# remove directories to ignore
for ignore in ignores:
for d in fnmatch.filter(dirs, ignore):
dirs.remove(d)