omdev 0.0.0.dev7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. omdev/__about__.py +35 -0
  2. omdev/__init__.py +0 -0
  3. omdev/amalg/__init__.py +0 -0
  4. omdev/amalg/__main__.py +4 -0
  5. omdev/amalg/amalg.py +513 -0
  6. omdev/classdot.py +61 -0
  7. omdev/cmake.py +164 -0
  8. omdev/exts/__init__.py +0 -0
  9. omdev/exts/_distutils/__init__.py +10 -0
  10. omdev/exts/_distutils/build_ext.py +367 -0
  11. omdev/exts/_distutils/compilers/__init__.py +3 -0
  12. omdev/exts/_distutils/compilers/ccompiler.py +1032 -0
  13. omdev/exts/_distutils/compilers/options.py +80 -0
  14. omdev/exts/_distutils/compilers/unixccompiler.py +385 -0
  15. omdev/exts/_distutils/dir_util.py +76 -0
  16. omdev/exts/_distutils/errors.py +62 -0
  17. omdev/exts/_distutils/extension.py +107 -0
  18. omdev/exts/_distutils/file_util.py +216 -0
  19. omdev/exts/_distutils/modified.py +47 -0
  20. omdev/exts/_distutils/spawn.py +103 -0
  21. omdev/exts/_distutils/sysconfig.py +349 -0
  22. omdev/exts/_distutils/util.py +201 -0
  23. omdev/exts/_distutils/version.py +308 -0
  24. omdev/exts/build.py +43 -0
  25. omdev/exts/cmake.py +195 -0
  26. omdev/exts/importhook.py +88 -0
  27. omdev/exts/scan.py +74 -0
  28. omdev/interp/__init__.py +1 -0
  29. omdev/interp/__main__.py +4 -0
  30. omdev/interp/cli.py +63 -0
  31. omdev/interp/inspect.py +105 -0
  32. omdev/interp/providers.py +67 -0
  33. omdev/interp/pyenv.py +353 -0
  34. omdev/interp/resolvers.py +76 -0
  35. omdev/interp/standalone.py +187 -0
  36. omdev/interp/system.py +125 -0
  37. omdev/interp/types.py +92 -0
  38. omdev/mypy/__init__.py +0 -0
  39. omdev/mypy/debug.py +86 -0
  40. omdev/pyproject/__init__.py +1 -0
  41. omdev/pyproject/__main__.py +4 -0
  42. omdev/pyproject/cli.py +319 -0
  43. omdev/pyproject/configs.py +97 -0
  44. omdev/pyproject/ext.py +107 -0
  45. omdev/pyproject/pkg.py +196 -0
  46. omdev/scripts/__init__.py +0 -0
  47. omdev/scripts/execrss.py +19 -0
  48. omdev/scripts/findimports.py +62 -0
  49. omdev/scripts/findmagic.py +70 -0
  50. omdev/scripts/interp.py +2118 -0
  51. omdev/scripts/pyproject.py +3584 -0
  52. omdev/scripts/traceimport.py +502 -0
  53. omdev/tokens.py +42 -0
  54. omdev/toml/__init__.py +1 -0
  55. omdev/toml/parser.py +823 -0
  56. omdev/toml/writer.py +104 -0
  57. omdev/tools/__init__.py +0 -0
  58. omdev/tools/dockertools.py +81 -0
  59. omdev/tools/sqlrepl.py +193 -0
  60. omdev/versioning/__init__.py +1 -0
  61. omdev/versioning/specifiers.py +531 -0
  62. omdev/versioning/versions.py +416 -0
  63. omdev-0.0.0.dev7.dist-info/LICENSE +21 -0
  64. omdev-0.0.0.dev7.dist-info/METADATA +24 -0
  65. omdev-0.0.0.dev7.dist-info/RECORD +67 -0
  66. omdev-0.0.0.dev7.dist-info/WHEEL +5 -0
  67. omdev-0.0.0.dev7.dist-info/top_level.txt +1 -0
@@ -0,0 +1,80 @@
1
+ import os
2
+ import typing as ta
3
+
4
+ from ..util import always_iterable
5
+
6
+
7
+ Macro: ta.TypeAlias = tuple[str, str | None] | tuple[str]
8
+
9
+
10
+ def gen_preprocess_options(
11
+ macros: list[Macro],
12
+ include_dirs: list[str],
13
+ ) -> list[str]:
14
+ """
15
+ Generate C pre-processor options (-D, -U, -I) as used by at least two types of compilers: the typical Unix compiler
16
+ and Visual C++. 'macros' is the usual thing, a list of 1- or 2-tuples, where (name,) means undefine (-U) macro
17
+ 'name', and (name,value) means define (-D) macro 'name' to 'value'. 'include_dirs' is just a list of directory
18
+ names to be added to the header file search path (-I). Returns a list of command-line options suitable for either
19
+ Unix compilers or Visual C++.
20
+ """
21
+ # it would be nice (mainly aesthetic, and so we don't generate stupid-looking command lines) to go over 'macros' and
22
+ # eliminate redundant definitions/undefinitions (ie. ensure that only the latest mention of a particular macro winds
23
+ # up on the command line). I don't think it's essential, though, since most (all?) Unix C compilers only pay
24
+ # attention to the latest -D or -U mention of a macro on their command line. Similar situation for 'include_dirs'.
25
+ # I'm punting on both for now. Anyways, weeding out redundancies like this should probably be the province of
26
+ # CCompiler, since the data structures used are inherited from it and therefore common to all CCompiler classes.
27
+ pp_opts: list[str] = []
28
+ for macro in macros:
29
+ if not (isinstance(macro, tuple) and 1 <= len(macro) <= 2):
30
+ raise TypeError(f"bad macro definition '{macro}': each element of 'macros' list must be a 1- or 2-tuple")
31
+
32
+ if len(macro) == 1: # undefine this macro
33
+ pp_opts.append(f'-U{macro[0]}')
34
+ elif len(macro) == 2:
35
+ if macro[1] is None: # define with no explicit value
36
+ pp_opts.append(f'-D{macro[0]}')
37
+ else:
38
+ # *don't* need to be clever about quoting the macro value here, because we're going to avoid the shell
39
+ # at all costs when we spawn the command!
40
+ pp_opts.append('-D{}={}'.format(*macro))
41
+
42
+ for dir in include_dirs: # noqa
43
+ pp_opts.append(f'-I{dir}')
44
+ return pp_opts
45
+
46
+
47
+ def gen_lib_options(
48
+ compiler,
49
+ library_dirs: list[str],
50
+ runtime_library_dirs: list[str],
51
+ libraries: list[str],
52
+ ) -> list[str]:
53
+ """
54
+ Generate linker options for searching library directories and linking with specific libraries. 'libraries' and
55
+ 'library_dirs' are, respectively, lists of library names (not filenames!) and search directories. Returns a list of
56
+ command-line options suitable for use with some compiler (depending on the two format strings passed in).
57
+ """
58
+ lib_opts = []
59
+
60
+ for dir in library_dirs: # noqa
61
+ lib_opts.append(compiler.library_dir_option(dir))
62
+
63
+ for dir in runtime_library_dirs: # noqa
64
+ lib_opts.extend(always_iterable(compiler.runtime_library_dir_option(dir)))
65
+
66
+ # it's important that we *not* remove redundant library mentions! sometimes you really do have to say "-lfoo -lbar
67
+ # -lfoo" in order to resolve all symbols. I just hope we never have to say "-lfoo obj.o -lbar" to get things to
68
+ # work -- that's certainly a possibility, but a pretty nasty way to arrange your C code.
69
+
70
+ for lib in libraries:
71
+ (lib_dir, lib_name) = os.path.split(lib)
72
+ if lib_dir:
73
+ lib_file = compiler.find_library_file([lib_dir], lib_name)
74
+ if lib_file:
75
+ lib_opts.append(lib_file)
76
+ else:
77
+ compiler.warn(f"no library file corresponding to '{lib}' found (skipping)")
78
+ else:
79
+ lib_opts.append(compiler.library_option(lib))
80
+ return lib_opts
@@ -0,0 +1,385 @@
1
+ """
2
+ Contains the UnixCCompiler class, a subclass of CCompiler that handles
3
+ the "typical" Unix-style command-line C compiler:
4
+ * macros defined with -Dname[=value]
5
+ * macros undefined with -Uname
6
+ * include search directories specified with -Idir
7
+ * libraries specified with -lllib
8
+ * library search directories specified with -Ldir
9
+ * compile handled by 'cc' (or similar) executable with -c option: compiles .c to .o
10
+ * link static library handled by 'ar' command (possibly with 'ranlib')
11
+ * link shared library handled by 'cc -shared'
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import importlib
16
+ import itertools
17
+ import logging
18
+ import os
19
+ import re
20
+ import shlex
21
+ import sys
22
+ import typing as ta
23
+
24
+ from .. import sysconfig
25
+ from ..errors import CompileError
26
+ from ..errors import DistutilsExecError
27
+ from ..errors import LibError
28
+ from ..errors import LinkError
29
+ from ..modified import newer
30
+ from .ccompiler import CCompiler
31
+ from .options import gen_lib_options
32
+ from .options import gen_preprocess_options
33
+
34
+
35
+ log = logging.getLogger(__name__)
36
+
37
+
38
+ def bypass_compiler_fixup(cmd, args):
39
+ return cmd
40
+
41
+
42
+ if sys.platform == 'darwin':
43
+ compiler_fixup = importlib.import_module('_osx_support').compiler_fixup
44
+ else:
45
+ compiler_fixup = bypass_compiler_fixup
46
+
47
+
48
+ # Things not currently handled:
49
+ # * optimization/debug/warning flags; we just use whatever's in Python's Makefile and live with it. Is this adequate?
50
+ # If not, we might have to have a bunch of subclasses GNUCCompiler, SGICCompiler, SunCCompiler, and I suspect down
51
+ # that road lies madness.
52
+ # * even if we don't know a warning flag from an optimization flag, we need some way for outsiders to feed
53
+ # preprocessor/compiler/linker flags in to us -- eg. a sysadmin might want to mandate certain flags via a site
54
+ # config file, or a user might want to set something for compiling this module distribution only via the setup.py
55
+ # command line, whatever. As long as these options come from something on the current system, they can be as
56
+ # system-dependent as they like, and we should just happily stuff them into the preprocessor/compiler/linker options
57
+ # and carry on.
58
+
59
+
60
+ def _split_env(cmd: list[str]) -> tuple[list[str], list[str]]:
61
+ """
62
+ For macOS, split command into 'env' portion (if any) and the rest of the linker command.
63
+
64
+ >>> _split_env(['a', 'b', 'c'])
65
+ ([], ['a', 'b', 'c'])
66
+ >>> _split_env(['/usr/bin/env', 'A=3', 'gcc'])
67
+ (['/usr/bin/env', 'A=3'], ['gcc'])
68
+ """
69
+ pivot = 0
70
+ if os.path.basename(cmd[0]) == 'env':
71
+ pivot = 1
72
+ while '=' in cmd[pivot]:
73
+ pivot += 1
74
+ return cmd[:pivot], cmd[pivot:]
75
+
76
+
77
+ def _split_aix(cmd: list[str]) -> tuple[list[str], list[str]]:
78
+ """
79
+ AIX platforms prefix the compiler with the ld_so_aix
80
+ script, so split that from the linker command.
81
+
82
+ >>> _split_aix(['a', 'b', 'c'])
83
+ ([], ['a', 'b', 'c'])
84
+ >>> _split_aix(['/bin/foo/ld_so_aix', 'gcc'])
85
+ (['/bin/foo/ld_so_aix'], ['gcc'])
86
+ """
87
+ pivot = os.path.basename(cmd[0]) == 'ld_so_aix'
88
+ return cmd[:pivot], cmd[pivot:]
89
+
90
+
91
+ def _linker_params(linker_cmd: list[str], compiler_cmd: list[str]) -> list[str]:
92
+ """
93
+ The linker command usually begins with the compiler command (possibly multiple elements), followed by zero or more
94
+ params for shared library building.
95
+
96
+ If the LDSHARED env variable overrides the linker command, however, the commands may not match.
97
+
98
+ Return the best guess of the linker parameters by stripping the linker command. If the compiler command does not
99
+ match the linker command, assume the linker command is just the first element.
100
+
101
+ >>> _linker_params('gcc foo bar'.split(), ['gcc'])
102
+ ['foo', 'bar']
103
+ >>> _linker_params('gcc foo bar'.split(), ['other'])
104
+ ['foo', 'bar']
105
+ >>> _linker_params('ccache gcc foo bar'.split(), 'ccache gcc'.split())
106
+ ['foo', 'bar']
107
+ >>> _linker_params(['gcc'], ['gcc'])
108
+ []
109
+ """
110
+ c_len = len(compiler_cmd)
111
+ pivot = c_len if linker_cmd[:c_len] == compiler_cmd else 1
112
+ return linker_cmd[pivot:]
113
+
114
+
115
+ def consolidate_linker_args(args: list[str]) -> str | list[str]:
116
+ """
117
+ Ensure the return value is a string for backward compatibility.
118
+
119
+ Retain until at least 2024-04-31. See pypa/distutils#246
120
+ """
121
+
122
+ if not all(arg.startswith('-Wl,') for arg in args):
123
+ return args
124
+ return '-Wl,' + ','.join(arg.removeprefix('-Wl,') for arg in args)
125
+
126
+
127
+ class UnixCCompiler(CCompiler):
128
+ compiler_type = 'unix'
129
+
130
+ # These are used by CCompiler in two places: the constructor sets instance attributes 'preprocessor', 'compiler',
131
+ # etc. from them, and 'set_executable()' allows any of these to be set. The defaults here are pretty generic; they
132
+ # will probably have to be set by an outsider (eg. using information discovered by the sysconfig about building
133
+ # Python extensions).
134
+ executables = { # noqa
135
+ 'preprocessor': None,
136
+ 'compiler': ['cc'],
137
+ 'compiler_so': ['cc'],
138
+ 'compiler_cxx': ['cc'],
139
+ 'linker_so': ['cc', '-shared'],
140
+ 'linker_exe': ['cc'],
141
+ 'archiver': ['ar', '-cr'],
142
+ 'ranlib': None,
143
+ }
144
+
145
+ if sys.platform[:6] == 'darwin':
146
+ executables['ranlib'] = ['ranlib']
147
+
148
+ # Needed for the filename generation methods provided by the base class, CCompiler. NB. whoever instantiates/uses a
149
+ # particular UnixCCompiler instance should set 'shared_lib_ext' -- we set a reasonable common default here, but it's
150
+ # not necessarily used on all Unices!
151
+
152
+ src_extensions: ta.ClassVar[list[str]] = ['.c', '.C', '.cc', '.cxx', '.cpp', '.m']
153
+ obj_extension = '.o'
154
+ static_lib_extension = '.a'
155
+ shared_lib_extension = '.so'
156
+ dylib_lib_extension = '.dylib'
157
+ xcode_stub_lib_extension = '.tbd'
158
+ static_lib_format = shared_lib_format = dylib_lib_format = 'lib%s%s'
159
+ xcode_stub_lib_format = dylib_lib_format
160
+
161
+ def preprocess(
162
+ self,
163
+ source,
164
+ output_file=None,
165
+ macros=None,
166
+ include_dirs=None,
167
+ extra_preargs=None,
168
+ extra_postargs=None,
169
+ ):
170
+ fixed_args = self._fix_compile_args(None, macros, include_dirs)
171
+ ignore, macros, include_dirs = fixed_args
172
+ pp_opts = gen_preprocess_options(macros, include_dirs)
173
+ pp_args = self.preprocessor + pp_opts
174
+ if output_file:
175
+ pp_args.extend(['-o', output_file])
176
+ if extra_preargs:
177
+ pp_args[:0] = extra_preargs
178
+ if extra_postargs:
179
+ pp_args.extend(extra_postargs)
180
+ pp_args.append(source)
181
+
182
+ # reasons to preprocess:
183
+ # - force is indicated
184
+ # - output is directed to stdout
185
+ # - source file is newer than the target
186
+ preprocess = self.force or output_file is None or newer(source, output_file)
187
+ if not preprocess:
188
+ return
189
+
190
+ if output_file:
191
+ self.mkpath(os.path.dirname(output_file))
192
+
193
+ try:
194
+ self.spawn(pp_args)
195
+ except DistutilsExecError as msg:
196
+ raise CompileError(msg) from None
197
+
198
+ def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
199
+ compiler_so = compiler_fixup(self.compiler_so, cc_args + extra_postargs)
200
+ try:
201
+ self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs)
202
+ except DistutilsExecError as msg:
203
+ raise CompileError(msg) from None
204
+
205
+ def create_static_lib(
206
+ self,
207
+ objects,
208
+ output_libname,
209
+ output_dir=None,
210
+ debug=0,
211
+ target_lang=None,
212
+ ):
213
+ objects, output_dir = self._fix_object_args(objects, output_dir)
214
+
215
+ output_filename = self.library_filename(output_libname, output_dir=output_dir)
216
+
217
+ if self._need_link(objects, output_filename):
218
+ self.mkpath(os.path.dirname(output_filename))
219
+ self.spawn([*self.archiver, output_filename, *objects, *self.objects])
220
+
221
+ # Not many Unices required ranlib anymore -- SunOS 4.x is, I think the only major Unix that does. Maybe we
222
+ # need some platform intelligence here to skip ranlib if it's not needed -- or maybe Python's configure
223
+ # script took care of it for us, hence the check for leading colon.
224
+ if self.ranlib:
225
+ try:
226
+ self.spawn([*self.ranlib, output_filename])
227
+ except DistutilsExecError as msg:
228
+ raise LibError(msg) from None
229
+ else:
230
+ log.debug('skipping %s (up-to-date)', output_filename)
231
+
232
+ def link(
233
+ self,
234
+ target_desc,
235
+ objects,
236
+ output_filename,
237
+ output_dir=None,
238
+ libraries=None,
239
+ library_dirs=None,
240
+ runtime_library_dirs=None,
241
+ export_symbols=None,
242
+ debug=0,
243
+ extra_preargs=None,
244
+ extra_postargs=None,
245
+ build_temp=None,
246
+ target_lang=None,
247
+ ):
248
+ objects, output_dir = self._fix_object_args(objects, output_dir)
249
+ fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)
250
+ libraries, library_dirs, runtime_library_dirs = fixed_args
251
+
252
+ lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)
253
+ if not isinstance(output_dir, (str, type(None))):
254
+ raise TypeError("'output_dir' must be a string or None")
255
+ if output_dir is not None:
256
+ output_filename = os.path.join(output_dir, output_filename)
257
+
258
+ if self._need_link(objects, output_filename):
259
+ ld_args = objects + self.objects + lib_opts + ['-o', output_filename]
260
+ if debug:
261
+ ld_args[:0] = ['-g']
262
+ if extra_preargs:
263
+ ld_args[:0] = extra_preargs
264
+ if extra_postargs:
265
+ ld_args.extend(extra_postargs)
266
+ self.mkpath(os.path.dirname(output_filename))
267
+ try:
268
+ # Select a linker based on context: linker_exe when building an executable or linker_so (with shared
269
+ # options) when building a shared library.
270
+ building_exe = target_desc == CCompiler.EXECUTABLE
271
+ linker = (self.linker_exe if building_exe else self.linker_so)[:]
272
+
273
+ if target_lang == 'c++' and self.compiler_cxx:
274
+ env, linker_ne = _split_env(linker)
275
+ aix, linker_na = _split_aix(linker_ne)
276
+ _, compiler_cxx_ne = _split_env(self.compiler_cxx)
277
+ _, linker_exe_ne = _split_env(self.linker_exe)
278
+
279
+ params = _linker_params(linker_na, linker_exe_ne)
280
+ linker = env + aix + compiler_cxx_ne + params
281
+
282
+ linker = compiler_fixup(linker, ld_args)
283
+
284
+ self.spawn(linker + ld_args)
285
+ except DistutilsExecError as msg:
286
+ raise LinkError(msg) from None
287
+ else:
288
+ log.debug('skipping %s (up-to-date)', output_filename)
289
+
290
+ # -- Miscellaneous methods -----------------------------------------
291
+ # These are all used by the 'gen_lib_options() function, in ccompiler.py.
292
+
293
+ def library_dir_option(self, dir): # noqa
294
+ return '-L' + dir
295
+
296
+ def _is_gcc(self):
297
+ cc_var = sysconfig.get_config_var('CC')
298
+ compiler = os.path.basename(shlex.split(cc_var)[0])
299
+ return 'gcc' in compiler or 'g++' in compiler
300
+
301
+ def runtime_library_dir_option(self, dir: str) -> str | list[str]: # noqa
302
+ # Hackish, at the very least. See Python bug #445902: https://bugs.python.org/issue445902 Linkers on different
303
+ # platforms need different options to specify that directories need to be added to the list of directories
304
+ # searched for dependencies when a dynamic library is sought. GCC on GNU systems (Linux, FreeBSD, ...) has to
305
+ # be told to pass the -R option through to the linker, whereas other compilers and gcc on other systems just
306
+ # know this. Other compilers may need something slightly different. At this time, there's no way to determine
307
+ # this information from the configuration data stored in the Python installation, so we use this hack.
308
+ if sys.platform[:6] == 'darwin':
309
+ from ..util import get_macosx_target_ver
310
+ from ..util import split_version
311
+
312
+ macosx_target_ver = get_macosx_target_ver()
313
+ if macosx_target_ver and split_version(macosx_target_ver) >= [10, 5]:
314
+ return '-Wl,-rpath,' + dir
315
+ else: # no support for -rpath on earlier macOS versions
316
+ return '-L' + dir
317
+ elif sys.platform[:7] == 'freebsd':
318
+ return '-Wl,-rpath=' + dir
319
+ elif sys.platform[:5] == 'hp-ux':
320
+ return [
321
+ '-Wl,+s' if self._is_gcc() else '+s',
322
+ '-L' + dir,
323
+ ]
324
+
325
+ # For all compilers, `-Wl` is the presumed way to pass a compiler option to the linker
326
+ if sysconfig.get_config_var('GNULD') == 'yes':
327
+ return consolidate_linker_args([
328
+ # Force RUNPATH instead of RPATH
329
+ '-Wl,--enable-new-dtags',
330
+ '-Wl,-rpath,' + dir,
331
+ ])
332
+ else:
333
+ return '-Wl,-R' + dir
334
+
335
+ def library_option(self, lib):
336
+ return '-l' + lib
337
+
338
+ @staticmethod
339
+ def _library_root(dir): # noqa
340
+ """
341
+ macOS users can specify an alternate SDK using'-isysroot'. Calculate the SDK root if it is specified.
342
+
343
+ Note that, as of Xcode 7, Apple SDKs may contain textual stub libraries with .tbd extensions rather than the
344
+ normal .dylib shared libraries installed in /. The Apple compiler tool chain handles this transparently but it
345
+ can cause problems for programs that are being built with an SDK and searching for specific libraries. Callers
346
+ of find_library_file need to keep in mind that the base filename of the returned SDK library file might have a
347
+ different extension from that of the library file installed on the running system, for example:
348
+ /Applications/Xcode.app/Contents/Developer/Platforms/
349
+ MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/
350
+ usr/lib/libedit.tbd
351
+ vs
352
+ /usr/lib/libedit.dylib
353
+ """
354
+ cflags = sysconfig.get_config_var('CFLAGS')
355
+ match = re.search(r'-isysroot\s*(\S+)', cflags)
356
+
357
+ apply_root = (
358
+ sys.platform == 'darwin'
359
+ and match
360
+ and (
361
+ dir.startswith('/System/')
362
+ or (dir.startswith('/usr/') and not dir.startswith('/usr/local/'))
363
+ )
364
+ )
365
+
366
+ return os.path.join(match.group(1), dir[1:]) if match and apply_root else dir
367
+
368
+ def find_library_file(self, dirs, lib, debug=0):
369
+ """
370
+ Second-guess the linker with not much hard data to go on: GCC seems to prefer the shared library, so assume that
371
+ *all* Unix C compilers do, ignoring even GCC's "-static" option.
372
+ """
373
+ lib_names = (
374
+ self.library_filename(lib, lib_type=ty)
375
+ for ty in 'dylib xcode_stub shared static'.split()
376
+ )
377
+
378
+ roots = map(self._library_root, dirs)
379
+
380
+ searched = itertools.starmap(os.path.join, itertools.product(roots, lib_names))
381
+
382
+ found = filter(os.path.exists, searched)
383
+
384
+ # Return None if it could not be found in any dir.
385
+ return next(found, None)
@@ -0,0 +1,76 @@
1
+ """Utility functions for manipulating directories and directory trees."""
2
+ import errno
3
+ import logging
4
+ import os
5
+
6
+ from .errors import DistutilsFileError
7
+ from .errors import DistutilsInternalError
8
+
9
+
10
+ log = logging.getLogger(__name__)
11
+
12
+
13
+ # cache for by mkpath() -- in addition to cheapening redundant calls, eliminates redundant "creating /foo/bar/baz"
14
+ # messages in dry-run mode
15
+ _path_created: dict[str, int] = {}
16
+
17
+
18
+ def mkpath(name, mode=0o777, verbose=1, dry_run=False) -> list[str]: # noqa: C901
19
+ """Create a directory and any missing ancestor directories.
20
+
21
+ If the directory already exists (or if 'name' is the empty string, which means the current directory, which of
22
+ course exists), then do nothing. Raise DistutilsFileError if unable to create some directory along the way (eg. some
23
+ sub-path exists, but is a file rather than a directory). If 'verbose' is true, print a one-line summary of each
24
+ mkdir to stdout. Return the list of directories actually created.
25
+
26
+ os.makedirs is not used because:
27
+
28
+ a) It's new to Python 1.5.2, and
29
+ b) it blows up if the directory already exists (in which case it should silently succeed).
30
+ """
31
+
32
+ # Detect a common bug -- name is None
33
+ if not isinstance(name, str):
34
+ raise DistutilsInternalError(f"mkpath: 'name' must be a string (got {name!r})")
35
+
36
+ # what's the better way to handle verbosity? print as we create each directory in the path (the current behaviour),
37
+ # or only announce the creation of the whole path? (quite easy to do the latter since we're not using a recursive
38
+ # algorithm)
39
+
40
+ name = os.path.normpath(name)
41
+ created_dirs: list[str] = []
42
+ if os.path.isdir(name) or name == '':
43
+ return created_dirs
44
+ if _path_created.get(os.path.abspath(name)):
45
+ return created_dirs
46
+
47
+ (head, tail) = os.path.split(name)
48
+ tails = [tail] # stack of lone dirs to create
49
+
50
+ while head and tail and not os.path.isdir(head):
51
+ (head, tail) = os.path.split(head)
52
+ tails.insert(0, tail) # push next higher dir onto stack
53
+
54
+ # now 'head' contains the deepest directory that already exists (that is, the child of 'head' in 'name' is the
55
+ # highest directory that does *not* exist)
56
+ for d in tails:
57
+ # print "head = %s, d = %s: " % (head, d),
58
+ head = os.path.join(head, d)
59
+ abs_head = os.path.abspath(head)
60
+
61
+ if _path_created.get(abs_head):
62
+ continue
63
+
64
+ if verbose >= 1:
65
+ log.info('creating %s', head)
66
+
67
+ if not dry_run:
68
+ try:
69
+ os.mkdir(head, mode)
70
+ except OSError as exc:
71
+ if not (exc.errno == errno.EEXIST and os.path.isdir(head)):
72
+ raise DistutilsFileError(f"could not create '{head}': {exc.args[-1]}") from None
73
+ created_dirs.append(head)
74
+
75
+ _path_created[abs_head] = 1
76
+ return created_dirs
@@ -0,0 +1,62 @@
1
+ """
2
+ Provides exceptions used by the Distutils modules. Note that Distutils modules may raise standard exceptions; in
3
+ particular, SystemExit is usually raised for errors that are obviously the end-user's fault (eg. bad command-line
4
+ arguments).
5
+
6
+ This module is safe to use in "from ... import *" mode; it only exports symbols whose names start with "Distutils" and
7
+ end with "Error".
8
+ """
9
+
10
+
11
+ class DistutilsError(Exception):
12
+ """The root of all Distutils evil."""
13
+
14
+
15
+ class DistutilsModuleError(DistutilsError):
16
+ """
17
+ Unable to load an expected module, or to find an expected class within some module (in particular, command modules
18
+ and classes).
19
+ """
20
+
21
+
22
+ class DistutilsFileError(DistutilsError):
23
+ """
24
+ Any problems in the filesystem: expected file not found, etc. Typically this is for problems that we detect before
25
+ OSError could be raised.
26
+ """
27
+
28
+
29
+ class DistutilsPlatformError(DistutilsError):
30
+ """
31
+ We don't know how to do something on the current platform (but we do know how to do it on some platform) -- eg.
32
+ trying to compile C files on a platform not supported by a CCompiler subclass.
33
+ """
34
+
35
+
36
+ class DistutilsExecError(DistutilsError):
37
+ """Any problems executing an external program (such as the C compiler, when compiling C files)."""
38
+
39
+
40
+ class DistutilsInternalError(DistutilsError):
41
+ """Internal inconsistencies or impossibilities (obviously, this should never be seen if the code is working!)."""
42
+
43
+
44
+ # Exception classes used by the CCompiler implementation classes
45
+ class CCompilerError(Exception):
46
+ """Some compile/link operation failed."""
47
+
48
+
49
+ class CompileError(CCompilerError):
50
+ """Failure to compile one or more C/C++ source files."""
51
+
52
+
53
+ class LibError(CCompilerError):
54
+ """Failure to create a static library from one or more C/C++ object files."""
55
+
56
+
57
+ class LinkError(CCompilerError):
58
+ """Failure to link one or more C/C++ object files into an executable or shared library file."""
59
+
60
+
61
+ class UnknownFileError(CCompilerError):
62
+ """Attempt to process an unknown file type."""