forked from APrioriInvestments/typed_python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodebase.py
More file actions
269 lines (207 loc) · 9.73 KB
/
Copy pathCodebase.py
File metadata and controls
269 lines (207 loc) · 9.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# Copyright 2018 Braxton Mckee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import importlib
import tempfile
import os
import sys
import threading
import logging
from typed_python.SerializationContext import SerializationContext
_lock = threading.RLock()
_root_level_module_codebase_cache = {}
_coreSerializationContext = [None]
class Codebase:
"""Represents a bundle of code and objects on disk somewhere.
Also provides services for building a serialization context.
"""
def __init__(self, rootDirectory, filesToContents, modules):
self.rootDirectory = rootDirectory
self.filesToContents = filesToContents
self.modules = modules
self.serializationContext = Codebase.coreSerializationContext().union(
SerializationContext.FromModules(modules.values())
)
def getIsolatedSerializationContext(self):
return SerializationContext.FromModules(self.modules.values())
def allModuleLevelValues(self):
"""Iterate over all module-level values. Yields (name, object) pairs."""
for mname, module in self.modules.items():
for item in dir(module):
yield (mname + "." + item, getattr(module, item))
def getModuleByName(self, module_name):
if module_name not in self.modules:
raise ImportError(module_name)
return self.modules[module_name]
def getClassByName(self, qualifiedName):
modulename, classname = qualifiedName.rsplit(".", 1)
return getattr(self.getModuleByName(modulename), classname)
@staticmethod
def coreSerializationContext():
with _lock:
if _coreSerializationContext[0] is None:
import object_database
import typed_python
context1 = SerializationContext.FromModules(
Codebase._walkModuleDiskRepresentation(typed_python)[2].values()
)
context2 = SerializationContext.FromModules(
Codebase._walkModuleDiskRepresentation(object_database)[2].values()
)
_coreSerializationContext[0] = context1.union(context2)
return _coreSerializationContext[0]
@staticmethod
def FromRootlevelModule(module, **kwargs):
assert '.' not in module.__name__
return Codebase._FromModule(module, **kwargs)
@staticmethod
def _FromModule(module, **kwargs):
if '.' in module.__name__:
prefix = module.__name__.rsplit(".", 1)[0]
else:
prefix = None
with _lock:
if module in _root_level_module_codebase_cache:
return _root_level_module_codebase_cache[module]
assert module.__file__.endswith("__init__.py") or module.__file__.endswith("__init__.pyc")
root, files, modules = Codebase._walkModuleDiskRepresentation(module, prefix=prefix, **kwargs)
codebase = Codebase(root, files, modules)
_root_level_module_codebase_cache[module] = codebase
return _root_level_module_codebase_cache[module]
@staticmethod
def FromRootlevelPath(rootPath, **kwargs):
root, files, modules = Codebase._walkDiskRepresentation(rootPath, **kwargs)
codebase = Codebase(root, files, modules)
return codebase
@staticmethod
def _walkDiskRepresentation(rootPath, prefix=None, extensions=('.py',), maxTotalBytes=100 * 1024 * 1024):
""" Utility method that collects the code for a given root module.
Parameters:
-----------
rootPath : str
the root path for which to gather code
Returns:
--------
tuple(parentDir:str, files:dict(str->str), modules:dict(str->module))
parentDir:str is the path of the parent directory of the module
files:dict(str->str) maps file paths (relative to the parentDir) to their contents
modules:dict(str->module) maps module names to modules
"""
parentDir, moduleDir = os.path.split(rootPath)
# map: path:str -> contents:str
files = {}
total_bytes = [0]
def walkDisk(path, so_far):
if so_far.startswith("."):
return # skip hidden directories
for name in os.listdir(path):
fullpath = os.path.join(path, name)
so_far_with_name = os.path.join(so_far, name) if so_far else name
if os.path.isdir(fullpath):
walkDisk(fullpath, so_far_with_name)
else:
if os.path.splitext(name)[1] in extensions:
with open(fullpath, "r") as f:
contents = f.read()
total_bytes[0] += len(contents)
if total_bytes[0] > maxTotalBytes:
raise Exception(
"exceeded bytecount with %s of size %s" % (fullpath, len(contents))
)
files[so_far_with_name] = contents
walkDisk(os.path.abspath(rootPath), moduleDir)
modules_by_name = Codebase.filesToModuleNames(files, prefix)
modules = Codebase.importModulesByName(modules_by_name)
return parentDir, files, modules
@staticmethod
def _walkModuleDiskRepresentation(module, **kwargs):
dirpart = os.path.dirname(module.__file__)
return Codebase._walkDiskRepresentation(dirpart, **kwargs)
@staticmethod
def filesToModuleNames(files, prefix=None):
modules_by_name = set()
for fpath in files:
if fpath.endswith(".py"):
module_parts = fpath.split("/")
if module_parts[-1] == "__init__.py":
module_parts = module_parts[:-1]
else:
module_parts[-1] = module_parts[-1][:-3]
if prefix is not None:
module_parts = [prefix] + module_parts
modules_by_name.add(".".join(module_parts))
return modules_by_name
@staticmethod
def Instantiate(filesToContents, rootDirectory=None):
"""Instantiate a codebase on disk and import the modules."""
with _lock:
if rootDirectory is None:
# this works, despite the fact that we immediately destroy
# the directory, because we use 'makedirs' below to repopulate.
rootDirectory = tempfile.TemporaryDirectory().name
for fpath, fcontents in filesToContents.items():
path, name = os.path.split(fpath)
fullpath = os.path.join(rootDirectory, path)
if not os.path.exists(fullpath):
os.makedirs(fullpath)
with open(os.path.join(fullpath, name), "wb") as f:
f.write(fcontents.encode("utf-8"))
importlib.invalidate_caches()
sys.path = [rootDirectory] + sys.path
# get a list of all modules and import each one
modules_by_name = Codebase.filesToModuleNames(filesToContents)
try:
modules = Codebase.importModulesByName(modules_by_name)
finally:
sys.path.pop(0)
Codebase.removeUserModules([rootDirectory])
codebase = Codebase(rootDirectory, filesToContents, modules)
# now make sure we install these modules in our cache so that later
# we can walk them if we need to.
for m in modules:
if "." not in m:
_root_level_module_codebase_cache[modules[m]] = codebase
return codebase
@staticmethod
def importModulesByName(modules_by_name):
""" Returns a dict mapping module names (str) to modules. """
modules = {}
for mname in modules_by_name:
try:
modules[mname] = importlib.import_module(mname)
except Exception as e:
logging.getLogger(__name__).warn(
"Error importing module '%s' from codebase: %s", mname, e)
return modules
@staticmethod
def removeUserModules(paths):
paths = [os.path.abspath(path) for path in paths]
for f in list(sys.path_importer_cache):
if any(os.path.abspath(f).startswith(disk_path) for disk_path in paths):
del sys.path_importer_cache[f]
for m, sysmodule in list(sys.modules.items()):
if hasattr(sysmodule, '__file__') and any(sysmodule.__file__.startswith(p) for p in paths):
del sys.modules[m]
elif hasattr(sysmodule, '__path__') and hasattr(sysmodule.__path__, '_path'):
if any(any(pathElt.startswith(p) for p in paths) for pathElt in sysmodule.__path__._path):
del sys.modules[m]
@staticmethod
def rootlevelPathFromModule(module):
module_path = os.path.abspath(module.__file__)
if os.path.basename(module_path) == '__init__.py':
module_path = os.path.dirname(module_path)
# drop as many parts of the module_path as there dots to the
# module name
for _ in range(len(module.__name__.split("."))-1):
module_path = os.path.dirname(module_path)
return module_path