Update sdk/platform-tools to version 26.0.0.
[android_tools.git] / sdk / platform-tools / systrace / catapult / telemetry / third_party / modulegraph / modulegraph / util.py
blobacf6bc135a4f96058ae1351214cb3983b530807b
1 from __future__ import absolute_import
3 import os
4 import imp
5 import sys
6 import re
7 import marshal
8 import warnings
10 try:
11 unicode
12 except NameError:
13 unicode = str
16 if sys.version_info[0] == 2:
17 from StringIO import StringIO as BytesIO
18 from StringIO import StringIO
20 else:
21 from io import BytesIO, StringIO
25 def imp_find_module(name, path=None):
26 """
27 same as imp.find_module, but handles dotted names
28 """
29 names = name.split('.')
30 if path is not None:
31 if isinstance(path, (str, unicode)):
32 path = [os.path.realpath(path)]
33 for name in names:
34 result = imp.find_module(name, path)
35 if result[0] is not None:
36 result[0].close()
37 path = [result[1]]
38 return result
40 def _check_importer_for_path(name, path_item):
41 try:
42 importer = sys.path_importer_cache[path_item]
43 except KeyError:
44 for path_hook in sys.path_hooks:
45 try:
46 importer = path_hook(path_item)
47 break
48 except ImportError:
49 pass
50 else:
51 importer = None
52 sys.path_importer_cache.setdefault(path_item, importer)
55 if importer is None:
56 try:
57 return imp.find_module(name, [path_item])
58 except ImportError:
59 return None
60 return importer.find_module(name)
62 def imp_walk(name):
63 """
64 yields namepart, tuple_or_importer for each path item
66 raise ImportError if a name can not be found.
67 """
68 warnings.warn("imp_walk will be removed in a future version", DeprecationWarning)
70 if name in sys.builtin_module_names:
71 yield name, (None, None, ("", "", imp.C_BUILTIN))
72 return
73 paths = sys.path
74 res = None
75 for namepart in name.split('.'):
76 for path_item in paths:
77 res = _check_importer_for_path(namepart, path_item)
78 if hasattr(res, 'load_module'):
79 if res.path.endswith('.py') or res.path.endswith('.pyw'):
80 fp = StringIO(res.get_source(namepart))
81 res = (fp, res.path, ('.py', 'rU', imp.PY_SOURCE))
82 elif res.path.endswith('.pyc') or res.path.endswith('.pyo'):
83 co = res.get_code(namepart)
84 fp = BytesIO(imp.get_magic() + b'\0\0\0\0' + marshal.dumps(co))
85 res = (fp, res.path, ('.pyc', 'rb', imp.PY_COMPILED))
87 else:
88 res = (None, loader.path, (os.path.splitext(loader.path)[-1], 'rb', imp.C_EXTENSION))
90 break
91 elif isinstance(res, tuple):
92 break
93 else:
94 break
96 yield namepart, res
97 paths = [os.path.join(path_item, namepart)]
98 else:
99 return
101 raise ImportError('No module named %s' % (name,))
104 cookie_re = re.compile(b"coding[:=]\s*([-\w.]+)")
105 if sys.version_info[0] == 2:
106 default_encoding = 'ascii'
107 else:
108 default_encoding = 'utf-8'
110 def guess_encoding(fp):
112 for i in range(2):
113 ln = fp.readline()
115 m = cookie_re.search(ln)
116 if m is not None:
117 return m.group(1).decode('ascii')
119 return default_encoding