Debian Codegraph @

src/conda_package_handling/api.py

raw
1 from __future__ import annotations
2
3 import functools as _functools
4 import os as _os
5 import warnings as _warnings
6 from glob import glob as _glob
7
8 # expose these two exceptions as part of the API. Everything else should feed into these.
9 from .exceptions import ConversionError, InvalidArchiveError # NOQA
10 from .interface import AbstractBaseFormat
11 from .tarball import CondaTarBZ2 as _CondaTarBZ2
12 from .utils import ensure_list, is_info_member_path
13 from .utils import get_executor as _get_executor
14
15 SUPPORTED_EXTENSIONS: dict[str, type[AbstractBaseFormat]] = {".tar.bz2": _CondaTarBZ2}
16
17 libarchive_enabled = False #: Old API meaning "can extract .conda" (now without libarchive)
18
19 try:
20 from .conda_fmt import (
21 ZSTD_COMPRESS_LEVEL,
22 ZSTD_COMPRESS_THREADS,
23 _translate_zstd_level_threads,
24 )
25 from .conda_fmt import CondaFormat_v2 as _CondaFormat_v2
26
27 SUPPORTED_EXTENSIONS[".conda"] = _CondaFormat_v2
28
29 libarchive_enabled = True
30
31 except ImportError:
32 _warnings.warn("Install backports.zstd or use Python 3.14+ for .conda support")
33
34 THREADSAFE_EXTRACT = True #: Not present in conda-package-handling<2.0.
35
36
37 def _collect_paths(prefix):
38 dir_paths, file_paths = [], []
39 for dp, dn, filenames in _os.walk(prefix):
40 for f in filenames:
41 file_paths.append(_os.path.relpath(_os.path.join(dp, f), prefix))
42 dir_paths.extend(_os.path.relpath(_os.path.join(dp, _), prefix) for _ in dn)
43 file_list = file_paths + [
44 dp for dp in dir_paths if not any(f.startswith(dp + _os.sep) for f in file_paths)
45 ]
46 return file_list
47
48
49 def get_default_extracted_folder(in_file, abspath=True):
50 dirname = None
51 for ext in SUPPORTED_EXTENSIONS:
52 if in_file.endswith(ext):
53 dirname = in_file[: -len(ext)]
54 if dirname and not abspath:
55 dirname = _os.path.basename(dirname)
56 return dirname
57
58
59 def extract(fn, dest_dir=None, components=None, prefix=None):
60 if dest_dir:
61 if _os.path.isabs(dest_dir) and prefix:
62 raise ValueError(
63 "dest_dir and prefix both provided as abs paths. If providing both, "
64 "prefix can be abspath, but dest dir must be relative (relative to "
65 "prefix)"
66 )
67 if not _os.path.isabs(dest_dir):
68 dest_dir = _os.path.normpath(_os.path.join(prefix or _os.getcwd(), dest_dir))
69 else:
70 dest_dir = _os.path.join(
71 prefix or _os.path.dirname(fn),
72 get_default_extracted_folder(fn, abspath=False),
73 )
74
75 if not _os.path.isdir(dest_dir):
76 _os.makedirs(dest_dir)
77
78 for format in SUPPORTED_EXTENSIONS.values():
79 if format.supported(fn):
80 format.extract(fn, dest_dir, components=components)
81 break
82 else:
83 raise ValueError(
84 f"Didn't recognize extension for file '{fn}'. Supported extensions are: "
85 f"{list(SUPPORTED_EXTENSIONS.keys())}"
86 )
87
88
89 def create(prefix, file_list, out_fn, out_folder=None, **kw):
90 if not out_folder:
91 out_folder = _os.getcwd()
92
93 # simplify arguments to format.create()
94 if _os.path.isabs(out_fn):
95 out_folder = _os.path.dirname(out_fn)
96 out_fn = _os.path.basename(out_fn)
97
98 if file_list is None:
99 file_list = _collect_paths(prefix)
100 elif isinstance(file_list, str):
101 try:
102 with open(file_list) as f:
103 data = f.readlines()
104 file_list = [_.strip() for _ in data]
105 except:
106 raise
107
108 out = None
109 for format in SUPPORTED_EXTENSIONS.values():
110 if format.supported(out_fn):
111 try:
112 out = format.create(prefix, file_list, out_fn, out_folder, **kw)
113 break
114 except BaseException as err:
115 # don't leave broken files around
116 abs_out_fn = _os.path.join(out_folder, out_fn)
117 if _os.path.isfile(abs_out_fn):
118 _os.unlink(abs_out_fn)
119 raise err
120 else:
121 raise ValueError(
122 f"Didn't recognize extension for file '{out_fn}'. Supported extensions are: "
123 f"{list(SUPPORTED_EXTENSIONS.keys())}"
124 )
125
126 return out
127
128
129 def _convert(
130 fn,
131 out_ext,
132 out_folder,
133 force=False,
134 zstd_compress_level=None,
135 zstd_compress_threads=None,
136 **kw,
137 ):
138 # allow package to work in degraded mode when zstd is not available
139 import conda_package_streaming.transmute
140
141 basename = get_default_extracted_folder(fn, abspath=False)
142 from .validate import validate_converted_files_match_streaming
143
144 if not basename:
145 return (
146 fn,
147 "",
148 f"Input file {fn} doesn't have a supported extension ({SUPPORTED_EXTENSIONS}), "
149 "skipping it",
150 )
151 out_fn = str(_os.path.join(out_folder, basename + out_ext))
152 errors = ""
153 if not _os.path.lexists(out_fn) or force:
154 if force and _os.path.lexists(out_fn):
155 _os.unlink(out_fn)
156
157 if out_ext == ".conda":
158 zstd_compress_level, zstd_compress_threads = _translate_zstd_level_threads( # type: ignore
159 zstd_compress_level, zstd_compress_threads
160 )
161 transmute = _functools.partial(
162 conda_package_streaming.transmute.transmute,
163 fn,
164 out_folder,
165 is_info=is_info_member_path,
166 compression_level=zstd_compress_level,
167 compression_threads=zstd_compress_threads,
168 )
169
170 else:
171 transmute = _functools.partial(
172 conda_package_streaming.transmute.transmute_tar_bz2, fn, out_folder
173 )
174
175 try:
176 transmute()
177 result = validate_converted_files_match_streaming(out_fn, fn)
178 _, missing_files, mismatching_sizes = result
179 if missing_files or mismatching_sizes:
180 errors = str(ConversionError(missing_files, mismatching_sizes))
181 except BaseException as e:
182 # don't leave partial package around
183 if _os.path.isfile(out_fn):
184 _os.unlink(out_fn)
185 if not isinstance(e, Exception):
186 raise
187 errors = str(e)
188
189 return fn, out_fn, errors
190
191
192 def transmute(in_file, out_ext, out_folder=None, processes=1, **kw):
193 if not out_folder:
194 out_folder = _os.path.dirname(in_file) or _os.getcwd()
195
196 flist = set(_glob(in_file))
197 for in_ext in SUPPORTED_EXTENSIONS:
198 if in_file.endswith(in_ext):
199 replacement = in_file[: -len(in_ext)] + out_ext
200 flist = flist - set(_glob(replacement))
201 break
202
203 failed_files = {}
204 with _get_executor(processes) as executor:
205 convert_f = _functools.partial(_convert, out_ext=out_ext, out_folder=out_folder, **kw)
206 for fn, out_fn, errors in executor.map(convert_f, flist):
207 if errors:
208 failed_files[fn] = errors
209 try:
210 _os.unlink(out_fn)
211 except FileNotFoundError:
212 pass
213 return failed_files
214
215
216 def get_pkg_details(in_file):
217 """For the new pkg format, we return the size and hashes of the inner pkg part of the file"""
218 for format in SUPPORTED_EXTENSIONS.values():
219 if format.supported(in_file):
220 return format.get_pkg_details(in_file)
221 raise ValueError(f"Don't know what to do with file {in_file}")
222
223
224 def list_contents(in_file, verbose=False, components=None):
225 components = ensure_list(components or ("info", "pkg"))
226 for format in SUPPORTED_EXTENSIONS.values():
227 if format.supported(in_file):
228 return format.list_contents(in_file, verbose=verbose, components=components)
229 raise ValueError(f"Don't know what to do with file {in_file}")