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,308 @@
1
+ """
2
+ Provides classes to represent module version numbers (one class for each style of version numbering). There are
3
+ currently two such classes implemented: StrictVersion and LooseVersion.
4
+
5
+ Every version number class implements the following interface:
6
+ * the 'parse' method takes a string and parses it to some internal representation; if the string is an invalid version
7
+ number, 'parse' raises a ValueError exception
8
+ * the class constructor takes an optional string argument which, if supplied, is passed to 'parse'
9
+ * __str__ reconstructs the string that was passed to 'parse' (or an equivalent string -- ie. one that will generate an
10
+ equivalent version number instance)
11
+ * __repr__ generates Python code to recreate the version number instance
12
+ * _cmp compares the current instance with either another instance of the same class or a string (which will be parsed
13
+ to an instance of the same class, thus must follow the same rules)
14
+ """
15
+ import abc
16
+ import contextlib
17
+ import re
18
+ import warnings
19
+
20
+
21
+ @contextlib.contextmanager
22
+ def suppress_known_deprecation():
23
+ with warnings.catch_warnings(record=True) as ctx:
24
+ warnings.filterwarnings(
25
+ action='default',
26
+ category=DeprecationWarning,
27
+ message='distutils Version classes are deprecated.',
28
+ )
29
+ yield ctx
30
+
31
+
32
+ class Version(abc.ABC):
33
+ """
34
+ Abstract base class for version numbering classes. Just provides constructor (__init__) and reproducer (__repr__),
35
+ because those seem to be the same for all version numbering classes; and route rich comparisons to _cmp.
36
+ """
37
+
38
+ def __init__(self, vstring=None):
39
+ if vstring:
40
+ self.parse(vstring)
41
+ warnings.warn(
42
+ 'distutils Version classes are deprecated. Use packaging.version instead.',
43
+ DeprecationWarning,
44
+ stacklevel=2,
45
+ )
46
+
47
+ @abc.abstractmethod
48
+ def parse(self, vstring):
49
+ raise NotImplementedError
50
+
51
+ @abc.abstractmethod
52
+ def _cmp(self, other):
53
+ raise NotImplementedError
54
+
55
+ def __repr__(self):
56
+ return f"{self.__class__.__name__} ('{self!s}')"
57
+
58
+ def __eq__(self, other):
59
+ c = self._cmp(other)
60
+ if c is NotImplemented:
61
+ return c
62
+ return c == 0
63
+
64
+ def __lt__(self, other):
65
+ c = self._cmp(other)
66
+ if c is NotImplemented:
67
+ return c
68
+ return c < 0
69
+
70
+ def __le__(self, other):
71
+ c = self._cmp(other)
72
+ if c is NotImplemented:
73
+ return c
74
+ return c <= 0
75
+
76
+ def __gt__(self, other):
77
+ c = self._cmp(other)
78
+ if c is NotImplemented:
79
+ return c
80
+ return c > 0
81
+
82
+ def __ge__(self, other):
83
+ c = self._cmp(other)
84
+ if c is NotImplemented:
85
+ return c
86
+ return c >= 0
87
+
88
+
89
+ # Interface for version-number classes -- must be implemented by the following classes (the concrete ones -- Version
90
+ # should be treated as an abstract class).
91
+ # __init__ (string) - create and take same action as 'parse' (string parameter is optional)
92
+ # parse (string) - convert a string representation to whatever internal representation is appropriate for this
93
+ # style of version numbering
94
+ # __str__ (self) - convert back to a string; should be very similar (if not identical to) the string supplied to
95
+ # parse
96
+ # __repr__ (self) - generate Python code to recreate the instance
97
+ # _cmp (self, other) - compare two version numbers ('other' may be an unparsed version string, or another instance of
98
+ # your version class)
99
+
100
+
101
+ class StrictVersion(Version):
102
+ """
103
+ Version numbering for anal retentives and software idealists. Implements the standard interface for version number
104
+ classes as described above. A version number consists of two or three dot-separated numeric components, with an
105
+ optional "pre-release" tag on the end. The pre-release tag consists of the letter 'a' or 'b' followed by a number.
106
+ If the numeric components of two version numbers are equal, then one with a pre-release tag will always be deemed
107
+ earlier (lesser) than one without.
108
+
109
+ The following are valid version numbers (shown in the order that would be obtained by sorting according to the
110
+ supplied cmp function):
111
+
112
+ 0.4 0.4.0 (these two are equivalent)
113
+ 0.4.1
114
+ 0.5a1
115
+ 0.5b3
116
+ 0.5
117
+ 0.9.6
118
+ 1.0
119
+ 1.0.4a3
120
+ 1.0.4b1
121
+ 1.0.4
122
+
123
+ The following are examples of invalid version numbers:
124
+
125
+ 1
126
+ 2.7.2.2
127
+ 1.3.a4
128
+ 1.3pl1
129
+ 1.3c4
130
+
131
+ The rationale for this version numbering system will be explained in the distutils documentation.
132
+ """
133
+
134
+ version_re = re.compile(r'^(\d+) \. (\d+) (\. (\d+))? ([ab](\d+))?$', re.VERBOSE | re.ASCII)
135
+
136
+ version: tuple[int, ...]
137
+ prerelease: tuple[str, int] | None
138
+
139
+ def parse(self, vstring):
140
+ match = self.version_re.match(vstring)
141
+ if not match:
142
+ raise ValueError(f"invalid version number '{vstring}'")
143
+
144
+ (major, minor, patch, prerelease, prerelease_num) = match.group(1, 2, 4, 5, 6)
145
+
146
+ if patch:
147
+ self.version = tuple(map(int, [major, minor, patch]))
148
+ else:
149
+ self.version = (*map(int, [major, minor]), 0)
150
+
151
+ if prerelease:
152
+ self.prerelease = (prerelease[0], int(prerelease_num))
153
+ else:
154
+ self.prerelease = None
155
+
156
+ def __str__(self):
157
+ if self.version[2] == 0:
158
+ vstring = '.'.join(map(str, self.version[0:2]))
159
+ else:
160
+ vstring = '.'.join(map(str, self.version))
161
+
162
+ if self.prerelease:
163
+ vstring = vstring + self.prerelease[0] + str(self.prerelease[1])
164
+
165
+ return vstring
166
+
167
+ def _cmp(self, other):
168
+ if isinstance(other, str):
169
+ with suppress_known_deprecation():
170
+ other = StrictVersion(other)
171
+ elif not isinstance(other, StrictVersion):
172
+ return NotImplemented
173
+
174
+ if self.version == other.version:
175
+ # versions match; pre-release drives the comparison
176
+ return self._cmp_prerelease(other)
177
+
178
+ return -1 if self.version < other.version else 1
179
+
180
+ def _cmp_prerelease(self, other):
181
+ """
182
+ case 1: self has prerelease, other doesn't; other is greater
183
+ case 2: self doesn't have prerelease, other does: self is greater
184
+ case 3: both or neither have prerelease: compare them!
185
+ """
186
+ if self.prerelease and not other.prerelease:
187
+ return -1
188
+ elif not self.prerelease and other.prerelease:
189
+ return 1
190
+
191
+ if self.prerelease == other.prerelease:
192
+ return 0
193
+ elif self.prerelease < other.prerelease:
194
+ return -1
195
+ else:
196
+ return 1
197
+
198
+
199
+ # end class StrictVersion
200
+
201
+
202
+ # The rules according to Greg Stein:
203
+ # 1) a version number has 1 or more numbers separated by a period or by sequences of letters. If only periods, then
204
+ # these are compared left-to-right to determine an ordering.
205
+ # 2) sequences of letters are part of the tuple for comparison and are compared lexicographically
206
+ # 3) recognize the numeric components may have leading zeroes
207
+ #
208
+ # The LooseVersion class below implements these rules: a version number string is split up into a tuple of integer and
209
+ # string components, and comparison is a simple tuple comparison. This means that version numbers behave in a
210
+ # predictable and obvious way, but a way that might not necessarily be how people *want* version numbers to behave.
211
+ # There wouldn't be a problem if people could stick to purely numeric version numbers: just split on period and compare
212
+ # the numbers as tuples. However, people insist on putting letters into their version numbers; the most common purpose
213
+ # seems to be:
214
+ # - indicating a "pre-release" version ('alpha', 'beta', 'a', 'b', 'pre', 'p')
215
+ # - indicating a post-release patch ('p', 'pl', 'patch')
216
+ # but of course this can't cover all version number schemes, and there's no way to know what a programmer means without
217
+ # asking him.
218
+ #
219
+ # The problem is what to do with letters (and other non-numeric characters) in a version number. The current
220
+ # implementation does the obvious and predictable thing: keep them as strings and compare lexically within a tuple
221
+ # comparison. This has the desired effect if an appended letter sequence implies something "post-release": eg. "0.99" <
222
+ # "0.99pl14" < "1.0", and "5.001" < "5.001m" < "5.002".
223
+ #
224
+ # However, if letters in a version number imply a pre-release version, the "obvious" thing isn't correct. Eg. you would
225
+ # expect that "1.5.1" < "1.5.2a2" < "1.5.2", but under the tuple/lexical comparison implemented here, this just isn't
226
+ # so.
227
+ #
228
+ # Two possible solutions come to mind. The first is to tie the comparison algorithm to a particular set of semantic
229
+ # rules, as has been done in the StrictVersion class above. This works great as long as everyone can go along with
230
+ # bondage and discipline. Hopefully a (large) subset of Python module programmers will agree that the particular
231
+ # flavour of bondage and discipline provided by StrictVersion provides enough benefit to be worth using, and will submit
232
+ # their version numbering scheme to its domination. The free-thinking anarchists in the lot will never give in, though,
233
+ # and something needs to be done to accommodate them.
234
+ #
235
+ # Perhaps a "moderately strict" version class could be implemented that lets almost anything slide (syntactically), and
236
+ # makes some heuristic assumptions about non-digits in version number strings. This could sink into special-case-hell,
237
+ # though; if I was as talented and idiosyncratic as Larry Wall, I'd go ahead and implement a class that somehow knows
238
+ # that "1.2.1" < "1.2.2a2" < "1.2.2" < "1.2.2pl3", and is just as happy dealing with things like "2g6" and "1.13++". I
239
+ # don't think I'm smart enough to do it right though.
240
+ #
241
+ # In any case, I've coded the test suite for this module (see ../test/test_version.py) specifically to fail on things
242
+ # like comparing "1.2a2" and "1.2". That's not because the *code* is doing anything wrong, it's because the simple,
243
+ # obvious design doesn't match my complicated, hairy expectations for real-world version numbers. It would be a snap to
244
+ # fix the test suite to say, "Yep, LooseVersion does the Right Thing" (ie. the code matches the conception). But I'd
245
+ # rather have a conception that matches common notions about version numbers.
246
+
247
+
248
+ class LooseVersion(Version):
249
+ """
250
+ Version numbering for anarchists and software realists. Implements the standard interface for version number classes
251
+ as described above. A version number consists of a series of numbers, separated by either periods or strings of
252
+ letters. When comparing version numbers, the numeric components will be compared numerically, and the alphabetic
253
+ components lexically. The following are all valid version numbers, in no particular order:
254
+
255
+ 1.5.1
256
+ 1.5.2b2
257
+ 161
258
+ 3.10a
259
+ 8.02
260
+ 3.4j
261
+ 1996.07.12
262
+ 3.2.pl0
263
+ 3.1.1.6
264
+ 2g6
265
+ 11g
266
+ 0.960923
267
+ 2.2beta29
268
+ 1.13++
269
+ 5.5.kw
270
+ 2.0b1pl0
271
+
272
+ In fact, there is no such thing as an invalid version number under this scheme; the rules for comparison are simple
273
+ and predictable, but may not always give the results you want (for some definition of "want").
274
+ """
275
+
276
+ component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE)
277
+
278
+ def parse(self, vstring):
279
+ # I've given up on thinking I can reconstruct the version string from the parsed tuple -- so I just store the
280
+ # string here for use by __str__
281
+ self.vstring = vstring
282
+ components = [x for x in self.component_re.split(vstring) if x and x != '.']
283
+ for i, obj in enumerate(components):
284
+ with contextlib.suppress(ValueError):
285
+ components[i] = int(obj)
286
+
287
+ self.version = components
288
+
289
+ def __str__(self):
290
+ return self.vstring
291
+
292
+ def __repr__(self) -> str:
293
+ return f"LooseVersion ('{self!s}')"
294
+
295
+ def _cmp(self, other):
296
+ if isinstance(other, str):
297
+ other = LooseVersion(other)
298
+ elif not isinstance(other, LooseVersion):
299
+ return NotImplemented
300
+
301
+ if self.version == other.version:
302
+ return 0
303
+ if self.version < other.version:
304
+ return -1
305
+ if self.version > other.version:
306
+ return 1
307
+
308
+ return None
omdev/exts/build.py ADDED
@@ -0,0 +1,43 @@
1
+ import os.path
2
+ import sys
3
+ import sysconfig
4
+
5
+ from . import _distutils as du
6
+
7
+
8
+ def build_ext(
9
+ fullname: str,
10
+ src_path: str,
11
+ ) -> str:
12
+ extra_link_args: list[str] = []
13
+ if sys.platform == 'darwin':
14
+ extra_link_args.append('-Wl,-no_fixup_chains')
15
+
16
+ ext = du.Extension(
17
+ fullname,
18
+ sources=[src_path],
19
+ include_dirs=[os.path.dirname(src_path)],
20
+ extra_compile_args=[
21
+ *(['-std=c++20'] if any(src_path.endswith(sf) for sf in ('cc', 'cpp')) else []),
22
+ ],
23
+ extra_link_args=extra_link_args,
24
+ undef_macros=['BARF'],
25
+ )
26
+
27
+ cmd_obj = du.BuildExt(du.BuildExt.Options(
28
+ inplace=True,
29
+ debug=True,
30
+ ))
31
+ cmd_obj.build_extension(ext)
32
+
33
+ so_path = os.path.join(
34
+ os.path.dirname(src_path),
35
+ ''.join([
36
+ fullname.rpartition('.')[2],
37
+ '.',
38
+ sysconfig.get_config_var('SOABI'),
39
+ sysconfig.get_config_var('SHLIB_SUFFIX'),
40
+ ]),
41
+ )
42
+
43
+ return so_path
omdev/exts/cmake.py ADDED
@@ -0,0 +1,195 @@
1
+ """
2
+ TODO:
3
+ - symlink headers, included src files (hamt_impl, ...)
4
+ - point / copy output to dst dirs
5
+ - libs
6
+ - ..
7
+ - pybind
8
+ - catch2?
9
+ - json? https://github.com/nlohmann/json
10
+ - FindPackages? FetchContent? built_ext won't have that
11
+ - move omml git / data retriever stuff into omdev, get just the one header file from git via sha?
12
+
13
+ ==
14
+
15
+ Done:
16
+ - https://intellij-support.jetbrains.com/hc/en-us/community/posts/206608485-Multiple-Jetbrain-IDE-sharing-the-same-project-directory really?
17
+ - aight, generate a whole cmake subdir with symlinks to src files lol
18
+
19
+ """ # noqa
20
+ import io
21
+ import os.path
22
+ import shutil
23
+ import sys
24
+ import sysconfig
25
+
26
+ from omlish import check
27
+
28
+ from .. import cmake
29
+
30
+
31
+ def _main() -> None:
32
+ # py_root = '$ENV{HOME}/.pyenv/versions/3.11.8/'
33
+
34
+ prj_root = os.path.abspath(os.getcwd())
35
+ if not os.path.isfile(os.path.join(prj_root, 'pyproject.toml')):
36
+ raise Exception('Must be run in project root')
37
+
38
+ cmake_dir = os.path.join(prj_root, 'cmake')
39
+ if os.path.exists(cmake_dir):
40
+ for e in os.listdir(cmake_dir):
41
+ if e == '.idea':
42
+ continue
43
+ ep = os.path.join(cmake_dir, e)
44
+ if os.path.isfile(ep):
45
+ os.unlink(ep)
46
+ else:
47
+ shutil.rmtree(ep)
48
+ else:
49
+ os.mkdir(cmake_dir)
50
+
51
+ with open(os.path.join(cmake_dir, '.gitignore'), 'w') as f:
52
+ f.write('\n'.join(sorted(['/cmake-*', '/build'])))
53
+
54
+ if os.path.isdir(os.path.join(cmake_dir, '.idea')):
55
+ with open(os.path.join(cmake_dir, '.idea', '.name'), 'w') as f:
56
+ f.write('omlish')
57
+
58
+ venv_exe = sys.executable
59
+ venv_root = os.path.abspath(os.path.join(os.path.dirname(venv_exe), '..'))
60
+ real_exe = os.path.realpath(venv_exe)
61
+ py_root = os.path.abspath(os.path.join(os.path.dirname(real_exe), '..'))
62
+ py_sfx = '.'.join(map(str, sys.version_info[:2]))
63
+
64
+ out = io.StringIO()
65
+ gen = cmake.CmakeGen(out)
66
+
67
+ prj_name = 'omlish'
68
+ var_prefix = prj_name.upper()
69
+
70
+ gen.write(gen.preamble)
71
+ gen.write('')
72
+
73
+ gen.write(f'project({prj_name})')
74
+ gen.write('')
75
+
76
+ def sep_grps(*ls):
77
+ # itertools.interleave? or smth?
78
+ o = []
79
+ for i, l in enumerate(ls):
80
+ if not l:
81
+ continue
82
+ if i:
83
+ o.append('')
84
+ o.extend(check.not_isinstance(l, str))
85
+ return o
86
+
87
+ gen.write_var(cmake.Var(
88
+ f'{var_prefix}_INCLUDE_DIRECTORIES',
89
+ sep_grps(
90
+ [f'{venv_root}/include'],
91
+ [f'{py_root}/include/python{py_sfx}'],
92
+ [
93
+ # $ENV{HOME}/src/python/cpython
94
+ # $ENV{HOME}/src/python/cpython/include
95
+ ],
96
+ ),
97
+ ))
98
+
99
+ gen.write_var(cmake.Var(
100
+ f'{var_prefix}_COMPILE_OPTIONS',
101
+ sep_grps(
102
+ [
103
+ '-Wsign-compare',
104
+ '-Wunreachable-code',
105
+ '-DNDEBUG',
106
+ '-g',
107
+ '-fwrapv',
108
+ '-O3',
109
+ '-Wall',
110
+ ],
111
+ [
112
+ '-g',
113
+ '-c',
114
+ ],
115
+ ['-std=c++20'],
116
+ ),
117
+ ))
118
+
119
+ gen.write_var(cmake.Var(
120
+ f'{var_prefix}_LINK_DIRECTORIES',
121
+ sep_grps(
122
+ [f'{py_root}/lib'],
123
+ # ['$ENV{HOME}/src/python/cpython'],
124
+ ),
125
+ ))
126
+
127
+ gen.write_var(cmake.Var(
128
+ f'{var_prefix}_LINK_LIBRARIES',
129
+ sep_grps(
130
+ *([[
131
+ '-bundle',
132
+ '"-undefined dynamic_lookup"',
133
+ ]] if sys.platform == 'darwin' else []),
134
+ ),
135
+ ))
136
+
137
+ for ext_src in [
138
+ 'omdev/exts/_boilerplate.cc',
139
+ 'x/dev/c/junk.cc',
140
+ 'x/dev/c/_uuid.cc',
141
+ ]:
142
+ ext_name = ext_src.rpartition('.')[0].replace('/', '__')
143
+ so_name = ''.join([
144
+ os.path.basename(ext_src).split('.')[0],
145
+ '.',
146
+ sysconfig.get_config_var('SOABI'),
147
+ sysconfig.get_config_var('SHLIB_SUFFIX'),
148
+ ])
149
+
150
+ sl = os.path.join(cmake_dir, ext_src)
151
+ sal = os.path.abspath(sl)
152
+ sd = os.path.dirname(sal)
153
+ os.makedirs(sd, exist_ok=True)
154
+ rp = os.path.relpath(os.path.abspath(ext_src), sd)
155
+ os.symlink(rp, sal)
156
+
157
+ gen.write_target(cmake.ModuleLibrary(
158
+ ext_name,
159
+ src_files=[
160
+ sl,
161
+ ],
162
+ include_dirs=[
163
+ f'${{{var_prefix}_INCLUDE_DIRECTORIES}}',
164
+ ],
165
+ compile_opts=[
166
+ f'${{{var_prefix}_COMPILE_OPTIONS}}',
167
+ ],
168
+ link_dirs=[
169
+ f'${{{var_prefix}_LINK_DIRECTORIES}}',
170
+ ],
171
+ link_libs=[
172
+ f'${{{var_prefix}_LINK_LIBRARIES}}',
173
+ ],
174
+ extra_cmds=[
175
+ cmake.Command(
176
+ 'add_custom_command',
177
+ ['TARGET', ext_name, 'POST_BUILD'],
178
+ [
179
+ ' '.join([
180
+ 'COMMAND ${CMAKE_COMMAND} -E ',
181
+ f'copy $<TARGET_FILE_NAME:{ext_name}> ../../{os.path.dirname(ext_src)}/{so_name}',
182
+ ]),
183
+ 'COMMAND_EXPAND_LISTS',
184
+ ],
185
+ ),
186
+ ],
187
+ ))
188
+
189
+ print(out.getvalue())
190
+ with open(os.path.join(cmake_dir, 'CMakeLists.txt'), 'w') as f:
191
+ f.write(out.getvalue())
192
+
193
+
194
+ if __name__ == '__main__':
195
+ _main()
@@ -0,0 +1,88 @@
1
+ """
2
+ TODO:
3
+ - remove imp
4
+ - whitelist packages
5
+ """
6
+ import dataclasses as dc
7
+ import importlib
8
+ import importlib.abc
9
+ import importlib.machinery
10
+ import os.path
11
+ import sys
12
+ import types
13
+ import typing as ta
14
+
15
+ from . import build
16
+
17
+
18
+ def load_dynamic(name: str, path: str) -> types.ModuleType:
19
+ import importlib.machinery
20
+ loader = importlib.machinery.ExtensionFileLoader(name, path)
21
+
22
+ # Issue #24748: Skip the sys.modules check in _load_module_shim; always load new extension
23
+ spec = importlib.machinery.ModuleSpec(name=name, loader=loader, origin=path)
24
+
25
+ import importlib._bootstrap # FIXME: # noqa
26
+ return importlib._bootstrap._load(spec) # noqa
27
+
28
+
29
+ class CExtensionLoader(importlib.abc.Loader):
30
+
31
+ def __init__(self, fullname: str, path: str) -> None:
32
+ super().__init__()
33
+
34
+ self._fullname = fullname
35
+ self._path = path
36
+
37
+ def load_module(self, fullname: str) -> types.ModuleType:
38
+ so_path = build.build_ext(fullname, self._path)
39
+ return load_dynamic(self._fullname, so_path)
40
+
41
+
42
+ LoaderDetails: ta.TypeAlias = tuple[type[importlib.abc.Loader], list[str]]
43
+ loader_details = (CExtensionLoader, ['.c', '.cc', '.cpp', '.cxx'])
44
+
45
+
46
+ ##
47
+
48
+
49
+ @dc.dataclass(frozen=True)
50
+ class FileFinderPathHook:
51
+ lds: ta.Sequence[LoaderDetails]
52
+
53
+ def __call__(self, path: str) -> importlib.machinery.FileFinder:
54
+ if not path:
55
+ path = os.getcwd()
56
+ if not os.path.isdir(path):
57
+ raise ImportError('only directories are supported', path=path)
58
+ return importlib.machinery.FileFinder(path, *self.lds)
59
+
60
+
61
+ def _is_c_loader(h: ta.Any) -> bool:
62
+ return (
63
+ isinstance(h, FileFinderPathHook) and
64
+ h.lds == [loader_details]
65
+ )
66
+
67
+
68
+ def is_installed() -> bool:
69
+ return any(h for h in sys.path_hooks if _is_c_loader(h))
70
+
71
+
72
+ def _install(*, flush: bool = False) -> None:
73
+ sys.path_hooks.insert(0, FileFinderPathHook([loader_details]))
74
+ sys.path_importer_cache.clear()
75
+ if flush:
76
+ importlib.invalidate_caches()
77
+
78
+
79
+ def install(*, flush: bool = False) -> None:
80
+ if not is_installed():
81
+ _install(flush=flush)
82
+
83
+
84
+ def uninstall(*, flush: bool = False) -> None:
85
+ sys.path_hooks = [h for h in sys.path_hooks if not _is_c_loader(h)]
86
+ sys.path_importer_cache.clear()
87
+ if flush:
88
+ importlib.invalidate_caches()