Debian Codegraph @

Cheetah/ImportManager.py

raw symbols SCIP
1 """
2 Provides an emulator/replacement for Python's standard import system.
3
4 @@TR: Be warned that Import Hooks are in the deepest, darkest corner of
5 Python's jungle. If you need to start hacking with this, be prepared to get
6 lost for a while. Also note, this module predates the newstyle import hooks in
7 Python 2.3 http://www.python.org/peps/pep-0302.html.
8
9 This is a hacked/documented version of Gordon McMillan's iu.py. I have:
10
11 - made it a little less terse
12
13 - added docstrings and explanatations
14
15 - standardized the variable naming scheme
16
17 - reorganized the code layout to enhance readability
18 """
19
20 import marshal
21 import py_compile
22 import sys
23 from .compat import PY2, string_type, new_module, get_suffixes, \
24 load_module_from_file, cache_from_source, \
25 ModuleNotFoundError, RecursionError
26 if PY2:
27 import imp
28 else:
29 import importlib.machinery
30
31 _installed = False
32
33 # _globalOwnerTypes is defined at the bottom of this file
34
35 _os_stat = _os_path_join = _os_getcwd = _os_path_dirname = None
36
37 ##################################################
38 # FUNCTIONS
39
40
41 def _os_bootstrap():
42 """
43 Set up 'os' module replacement functions for use during import bootstrap
44 """
45
46 names = sys.builtin_module_names
47
48 join = dirname = None
49 if 'posix' in names:
50 sep = '/'
51 from posix import stat, getcwd
52 elif 'nt' in names:
53 sep = '\\'
54 from nt import stat, getcwd
55 elif 'dos' in names:
56 sep = '\\'
57 from dos import stat, getcwd
58 elif 'os2' in names:
59 sep = '\\'
60 from os2 import stat, getcwd
61 elif 'mac' in names:
62 from mac import stat, getcwd
63
64 if join is None:
65 def join(a, b):
66 if a == '':
67 return b
68 if ':' not in a:
69 a = ':' + a
70 if a[-1:] != ':':
71 a = a + ':'
72 return a + b
73 else:
74 raise ModuleNotFoundError('no os specific module found')
75
76 if join is None:
77 def join(a, b, sep=sep):
78 if a == '':
79 return b
80 lastchar = a[-1:]
81 if lastchar == '/' or lastchar == sep:
82 return a + b
83 return a + sep + b
84
85 if dirname is None:
86 def dirname(a, sep=sep):
87 for i in range(len(a) - 1, -1, -1):
88 c = a[i]
89 if c == '/' or c == sep:
90 return a[:i]
91 return ''
92
93 global _os_stat
94 _os_stat = stat
95
96 global _os_path_join
97 _os_path_join = join
98
99 global _os_path_dirname
100 _os_path_dirname = dirname
101
102 global _os_getcwd
103 _os_getcwd = getcwd
104
105
106 _os_bootstrap()
107
108
109 def packageName(s):
110 for i in range(len(s) - 1, -1, -1):
111 if s[i] == '.':
112 break
113 else:
114 return ''
115 return s[:i]
116
117
118 def nameSplit(s):
119 rslt = []
120 i = j = 0
121 for j in range(len(s)):
122 if s[j] == '.':
123 rslt.append(s[i:j])
124 i = j + 1
125 if i < len(s):
126 rslt.append(s[i:])
127 return rslt
128
129
130 def getPathExt(fnm):
131 for i in range(len(fnm) - 1, -1, -1):
132 if fnm[i] == '.':
133 return fnm[i:]
134 return ''
135
136
137 def pathIsDir(pathname):
138 "Local replacement for os.path.isdir()."
139 try:
140 s = _os_stat(pathname)
141 except OSError:
142 return None
143 return (s[0] & 0o170000) == 0o040000
144
145
146 def getDescr(fnm):
147 ext = getPathExt(fnm)
148 for (suffix, mode, typ) in get_suffixes():
149 if suffix == ext:
150 return (suffix, mode, typ)
151
152 ##################################################
153 # CLASSES
154
155
156 class Owner:
157
158 """An Owner does imports from a particular piece of turf That is, there's
159 an Owner for each thing on sys.path There are owners for directories and
160 .pyz files. There could be owners for zip files, or even URLs. A
161 shadowpath (a dictionary mapping the names in sys.path to their owners) is
162 used so that sys.path (or a package's __path__) is still a bunch of
163 strings.
164 """
165
166 def __init__(self, path):
167 self.path = path
168
169 def __str__(self):
170 return self.path
171
172 def getmod(self, nm):
173 return None
174
175
176 class DirOwner(Owner):
177
178 def __init__(self, path):
179 if path == '':
180 path = _os_getcwd()
181 if not pathIsDir(path):
182 raise ValueError("%s is not a directory" % path)
183 Owner.__init__(self, path)
184
185 def getmod(self, nm, getsuffixes=get_suffixes,
186 loadco=marshal.loads, newmod=new_module):
187
188 pth = _os_path_join(self.path, nm)
189
190 possibles = [(pth, 0, None)]
191 if pathIsDir(pth):
192 possibles.insert(0, (_os_path_join(pth, '__init__'), 1, pth))
193 py = pyc = None
194 for pth, ispkg, pkgpth in possibles:
195 for ext, mode, typ in getsuffixes():
196 if typ == 2: # imp.PY_COMPILED
197 attempt = cache_from_source(pth + '.py')
198 else:
199 attempt = pth + ext
200 try:
201 st = _os_stat(attempt)
202 except Exception:
203 pass
204 else:
205 if typ == 3: # imp.C_EXTENSION
206 return load_module_from_file(nm, nm, attempt)
207 elif typ == 1: # imp.PY_SOURCE
208 py = (attempt, st)
209 elif typ == 2: # imp.PY_COMPILED
210 pyc = (attempt, st)
211 else:
212 raise ValueError("Unknown module type %d" % typ)
213 if py or pyc:
214 break
215 if py is None and pyc is None:
216 return None
217 while True:
218 if pyc is None or py and pyc[1][8] < py[1][8]:
219 try:
220 try:
221 with open(py[0], 'r') as py_code_file:
222 py_code = py_code_file.read()
223 except UnicodeDecodeError:
224 with open(py[0], 'r', encoding='utf-8') \
225 as py_code_file:
226 py_code = py_code_file.read()
227 co = compile(py_code + '\n', py[0], 'exec')
228 try:
229 py_compile.compile(py[0])
230 except IOError:
231 pass
232 __file__ = py[0]
233 break
234 except SyntaxError as e:
235 print("Invalid syntax in %s" % py[0])
236 print(e.args)
237 raise
238 elif pyc:
239 with open(pyc[0], 'rb') as pyc_file:
240 stuff = pyc_file.read()
241 try:
242 # Different Python versions
243 # change marshalled byte-code format
244 if PY2:
245 offset = 8
246 else:
247 sv = sys.version_info[:2]
248 if sv >= (3, 7):
249 offset = 16
250 else:
251 offset = 12
252 co = loadco(stuff[offset:])
253 __file__ = pyc[0]
254 break
255 except (ValueError, EOFError):
256 pyc = None
257 else:
258 return None
259 mod = newmod(nm)
260 mod.__file__ = __file__
261 if ispkg:
262 mod.__path__ = [pkgpth]
263 subimporter = PathImportDirector(mod.__path__)
264 mod.__importsub__ = subimporter.getmod
265 mod.__co__ = co
266 return mod
267
268
269 class ImportDirector(Owner):
270 """ImportDirectors live on the metapath There's one for builtins, one for
271 frozen modules, and one for sys.path Windows gets one for modules gotten
272 from the Registry Mac would have them for PY_RESOURCE modules etc. A
273 generalization of Owner - their concept of 'turf' is broader"""
274
275 pass
276
277
278 class BuiltinImportDirector(ImportDirector):
279 """Directs imports of builtin modules"""
280 def __init__(self):
281 self.path = 'Builtins'
282
283 def getmod(self, nm):
284 if nm in sys.builtin_module_names:
285 try:
286 importfunc = __oldimport__
287 except NameError:
288 importfunc = __import__
289 return importfunc(nm)
290 return None
291
292
293 class FrozenImportDirector(ImportDirector):
294 """Directs imports of frozen modules"""
295
296 def __init__(self):
297 self.path = 'FrozenModules'
298
299 def getmod(self, nm):
300 mod = None
301 if PY2:
302 if imp.is_frozen(nm):
303 mod = imp.load_module(nm, None, nm, ('', '', imp.PY_FROZEN))
304 else:
305 if importlib.machinery.FrozenImporter.find_spec(nm):
306 mod = importlib.machinery.FrozenImporter.load_module(nm)
307 if mod and hasattr(mod, '__path__'):
308 mod.__importsub__ = \
309 lambda name, pname=nm, owner=self: \
310 owner.getmod(pname + '.' + name)
311 return mod
312
313
314 class RegistryImportDirector(ImportDirector):
315 """Directs imports of modules stored in the Windows Registry"""
316
317 def __init__(self):
318 self.path = "WindowsRegistry"
319 self.map = {}
320 try:
321 import win32api
322 # import win32con
323 except ImportError:
324 pass
325 else:
326 HKEY_CURRENT_USER = -2147483647
327 HKEY_LOCAL_MACHINE = -2147483646
328 KEY_ALL_ACCESS = 983103
329 subkey = r"Software\Python\PythonCore\%s\Modules" % sys.winver
330 for root in (HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE):
331 try:
332 hkey = win32api.RegOpenKeyEx(root, subkey,
333 0, KEY_ALL_ACCESS)
334 except Exception:
335 pass
336 else:
337 numsubkeys, numvalues, lastmodified = \
338 win32api.RegQueryInfoKey(hkey)
339 for i in range(numsubkeys):
340 subkeyname = win32api.RegEnumKey(hkey, i)
341 hskey = win32api.RegOpenKeyEx(hkey, subkeyname,
342 0, KEY_ALL_ACCESS)
343 val = win32api.RegQueryValueEx(hskey, '')
344 desc = getDescr(val[0])
345 self.map[subkeyname] = (val[0], desc)
346 hskey.Close()
347 hkey.Close()
348 break
349
350 def getmod(self, nm):
351 stuff = self.map.get(nm)
352 if stuff:
353 fnm = stuff[0]
354 return load_module_from_file(nm, nm, fnm)
355 return None
356
357
358 class PathImportDirector(ImportDirector):
359 """Directs imports of modules stored on the filesystem."""
360
361 def __init__(self, pathlist=None, importers=None, ownertypes=None):
362 if pathlist is None:
363 self.path = sys.path
364 else:
365 self.path = pathlist
366 if ownertypes is None:
367 self._ownertypes = _globalOwnerTypes
368 else:
369 self._ownertypes = ownertypes
370 if importers:
371 self._shadowPath = importers
372 else:
373 self._shadowPath = {}
374 self._inMakeOwner = False
375 self._building = {}
376
377 def getmod(self, nm):
378 mod = None
379 for thing in self.path:
380 if isinstance(thing, string_type):
381 owner = self._shadowPath.get(thing, -1)
382 if owner == -1:
383 owner = self._shadowPath[thing] = self._makeOwner(thing)
384 if owner:
385 mod = owner.getmod(nm)
386 else:
387 mod = thing.getmod(nm)
388 if mod:
389 break
390 return mod
391
392 def _makeOwner(self, path):
393 if self._building.get(path):
394 return None
395 self._building[path] = 1
396 owner = None
397 for klass in self._ownertypes:
398 try:
399 # this may cause an import, which may cause recursion
400 # hence the protection
401 owner = klass(path)
402 except Exception:
403 pass
404 else:
405 break
406 del self._building[path]
407 return owner
408
409 # =================ImportManager============================#
410 # The one-and-only ImportManager
411 # ie, the builtin import
412
413
414 UNTRIED = -1
415
416
417 class ImportManager:
418 # really the equivalent of builtin import
419 def __init__(self):
420 self.metapath = [
421 BuiltinImportDirector(),
422 FrozenImportDirector(),
423 RegistryImportDirector(),
424 PathImportDirector()
425 ]
426 self.threaded = 0
427 self.rlock = None
428 self.locker = None
429 self.setThreaded()
430
431 def setThreaded(self):
432 thread = sys.modules.get('thread', None)
433 if thread and not self.threaded:
434 self.threaded = 1
435 self.rlock = thread.allocate_lock()
436 self._get_ident = thread.get_ident
437
438 def install(self):
439 try:
440 import builtins as builtin
441 except ImportError: # PY2
442 import __builtin__ as builtin
443 builtin.__import__ = self.importHook
444 builtin.reload = self.reloadHook
445
446 def importHook(self, name, globals=None, locals=None,
447 fromlist=None, level=-1):
448 '''
449 NOTE: Currently importHook will accept the keyword-argument "level"
450 but it will *NOT* use it. Details about the "level" keyword
451 argument can be found here:
452 https://docs.python.org/2/library/functions.html#__import__
453 '''
454 # first see if we could be importing a relative name
455 _sys_modules_get = sys.modules.get
456 contexts = [None]
457 if (PY2 or not name or level > 0) and globals:
458 importernm = globals.get('__name__', '')
459 if importernm:
460 if hasattr(_sys_modules_get(importernm), '__path__'):
461 contexts.insert(0, importernm)
462 else:
463 pkgnm = packageName(importernm)
464 if pkgnm:
465 contexts.insert(0, pkgnm)
466 # so contexts is [pkgnm, None] or just [None]
467 # now break the name being imported up so we get:
468 # a.b.c -> [a, b, c]
469 nmparts = nameSplit(name)
470 _self_doimport = self.doimport
471 threaded = self.threaded
472 for context in contexts:
473 i = 0
474 ctx = context
475 for i in range(len(nmparts)):
476 nm = nmparts[i]
477 if ctx:
478 fqname = ctx + '.' + nm
479 else:
480 fqname = nm
481 if threaded:
482 self._acquire()
483 mod = _sys_modules_get(fqname, UNTRIED)
484 if mod is UNTRIED:
485 mod = _self_doimport(nm, ctx, fqname)
486 if threaded:
487 self._release()
488 if mod:
489 ctx = fqname
490 else:
491 break
492 else:
493 # no break, point i beyond end
494 i = i + 1
495 if i:
496 break
497
498 if i < len(nmparts):
499 if ctx and hasattr(sys.modules[ctx], nmparts[i]):
500 return sys.modules[nmparts[0]]
501 del sys.modules[fqname]
502 raise ModuleNotFoundError("No module named %s" % fqname)
503 if fromlist is None:
504 if context:
505 return sys.modules[context + '.' + nmparts[0]]
506 return sys.modules[nmparts[0]]
507 bottommod = sys.modules[ctx]
508 if hasattr(bottommod, '__path__'):
509 fromlist = list(fromlist)
510 i = 0
511 while i < len(fromlist):
512 nm = fromlist[i]
513 if nm == '*':
514 fromlist[i:i+1] = list(getattr(bottommod, '__all__', [])) # noqa: E226,E501 missing whitespace around operator
515 if i >= len(fromlist):
516 break
517 nm = fromlist[i]
518 i = i + 1
519 if not hasattr(bottommod, nm):
520 if self.threaded:
521 self._acquire()
522 mod = self.doimport(nm, ctx, ctx + '.' + nm)
523 if self.threaded:
524 self._release()
525 if not mod:
526 raise ModuleNotFoundError(
527 "%s not found in %s" % (nm, ctx))
528 return bottommod
529
530 def doimport(self, nm, parentnm, fqname):
531 # Not that nm is NEVER a dotted name at this point
532 mod = None
533 if parentnm:
534 parent = sys.modules[parentnm]
535 if hasattr(parent, '__path__'):
536 importfunc = getattr(parent, '__importsub__', None)
537 if not importfunc:
538 subimporter = PathImportDirector(parent.__path__)
539 importfunc = parent.__importsub__ = subimporter.getmod
540 mod = importfunc(nm)
541 if mod:
542 setattr(parent, nm, mod)
543 else:
544 return None
545 else:
546 # now we're dealing with an absolute import
547 for director in self.metapath:
548 try:
549 mod = director.getmod(nm)
550 except RecursionError:
551 try:
552 mod = __oldimport__(nm) # noqa: F821 undefined name
553 except RecursionError:
554 pass
555 if mod:
556 break
557 if mod:
558 mod.__name__ = fqname
559 sys.modules[fqname] = mod
560 if hasattr(mod, '__co__'):
561 co = mod.__co__
562 del mod.__co__
563 exec(co, mod.__dict__)
564 if fqname == 'thread' and not self.threaded:
565 self.setThreaded()
566 else:
567 sys.modules[fqname] = None
568 return mod
569
570 def reloadHook(self, mod):
571 fqnm = mod.__name__
572 nm = nameSplit(fqnm)[-1]
573 parentnm = packageName(fqnm)
574 newmod = self.doimport(nm, parentnm, fqnm)
575 mod.__dict__.update(newmod.__dict__)
576 # return newmod
577
578 def _acquire(self):
579 if self.rlock.locked():
580 if self.locker == self._get_ident():
581 self.lockcount = self.lockcount + 1
582 return
583 self.rlock.acquire()
584 self.locker = self._get_ident()
585 self.lockcount = 0
586
587 def _release(self):
588 if self.lockcount:
589 self.lockcount = self.lockcount - 1
590 else:
591 self.rlock.release()
592
593
594 ##################################################
595 # MORE CONSTANTS & GLOBALS
596
597 _globalOwnerTypes = [
598 DirOwner,
599 Owner,
600 ]