Debian Codegraph @

src/conda_package_handling/utils.py

raw
1 import contextlib
2 import hashlib
3 import logging
4 import os
5 import re
6 import sys
7 from concurrent.futures import Executor, ProcessPoolExecutor, ThreadPoolExecutor
8
9 on_win = sys.platform == "win32"
10 log = logging.getLogger(__name__)
11
12
13 class DummyExecutor(Executor):
14 def map(self, func, *iterables):
15 for iterable in iterables:
16 for thing in iterable:
17 yield func(thing)
18
19
20 def get_executor(processes):
21 return DummyExecutor() if processes == 1 else ProcessPoolExecutor(max_workers=processes)
22
23
24 @contextlib.contextmanager
25 def tmp_chdir(dest):
26 curdir = os.getcwd()
27 try:
28 os.chdir(dest)
29 yield
30 finally:
31 os.chdir(curdir)
32
33
34 def ensure_list(arg):
35 if isinstance(arg, str) or not hasattr(arg, "__iter__"):
36 if arg is not None:
37 arg = [arg]
38 else:
39 arg = []
40 return arg
41
42
43 def filter_files(
44 files_list,
45 prefix,
46 filter_patterns=(
47 r"(.*[\\\\/])?\.git[\\\\/].*",
48 r"(.*[\\\\/])?\.git$",
49 r"(.*)?\.DS_Store.*",
50 r".*\.la$",
51 r"conda-meta.*",
52 ),
53 ):
54 """Remove things like the .git directory from the list of files to be copied"""
55 for pattern in filter_patterns:
56 r = re.compile(pattern)
57 files_list = set(files_list) - set(filter(r.match, files_list))
58 return [
59 f
60 for f in files_list
61 if
62 # `islink` prevents symlinks to directories from being removed
63 os.path.islink(os.path.join(prefix, f)) or not os.path.isdir(os.path.join(prefix, f))
64 ]
65
66
67 def is_info_member_path(path):
68 """Return True if ``path`` belongs in the ``info-*`` component (CEP 35)."""
69 return path == "info" or path.startswith(("info/", "info\\"))
70
71
72 def filter_info_files(files_list, prefix):
73 """Return packages files from files list that belong to the ``pkg-*`` component (CEP 35).
74
75 Returns files that go into the ``pkg-*`` component or in other words filter OUT
76 files that go into the ``info-*`` component.
77 """
78 return [f for f in filter_files(files_list, prefix) if not is_info_member_path(f)]
79
80
81 def _checksum(fd, algorithm, buffersize=65536):
82 hash_impl = hashlib.new(algorithm)
83 for block in iter(lambda: fd.read(buffersize), b""):
84 hash_impl.update(block)
85 return hash_impl.hexdigest()
86
87
88 def sha256_checksum(fd):
89 return _checksum(fd, "sha256")
90
91
92 def md5_checksum(fd):
93 return _checksum(fd, "md5")
94
95
96 def checksum(fn, algorithm, buffersize=1 << 18):
97 """
98 Calculate a checksum for a filename (not an open file).
99 """
100 with open(fn, "rb") as fd:
101 return _checksum(fd, algorithm, buffersize)
102
103
104 def checksums(fn, algorithms, buffersize=1 << 18):
105 """
106 Calculate multiple checksums for a filename in parallel.
107 """
108 with ThreadPoolExecutor(max_workers=len(algorithms)) as e:
109 # take care not to share hash_impl between threads
110 results = [e.submit(checksum, fn, algorithm, buffersize) for algorithm in algorithms]
111 return [result.result() for result in results]
112
113
114 def anonymize_tarinfo(tarinfo):
115 """
116 Remove user id, name from tarinfo.
117 """
118 # also remove timestamps?
119 tarinfo.uid = 0
120 tarinfo.uname = ""
121 tarinfo.gid = 0
122 tarinfo.gname = ""
123 return tarinfo