|
36 | 36 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
37 | 37 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
38 | 38 | # SOFTWARE. |
| 39 | +import posix |
39 | 40 | import sys |
40 | 41 | import _frozen_importlib |
41 | 42 |
|
@@ -163,6 +164,53 @@ def find_spec(self, fullname, path, target=None): |
163 | 164 | return _frozen_importlib.ModuleSpec(fullname, JavaTypeLoader, is_package=False) |
164 | 165 |
|
165 | 166 |
|
| 167 | +if sys.graal_python_jython_emulation_enabled: |
| 168 | + class JarImportLoader: |
| 169 | + def __init__(self, jarpath, zippath): |
| 170 | + self.jarpath = jarpath |
| 171 | + self.zippath = zippath |
| 172 | + |
| 173 | + def create_module(self, spec): |
| 174 | + newmod = _frozen_importlib._new_module(spec.name) |
| 175 | + newmod.__path__ = "%s!%s" % (self.jarpath, self.zippath) |
| 176 | + return newmod |
| 177 | + |
| 178 | + def exec_module(self, module): |
| 179 | + import zipfile |
| 180 | + with zipfile.ZipFile(self.jarpath) as z: |
| 181 | + code = z.read(self.zippath) |
| 182 | + exec(code, module.__dict__) |
| 183 | + |
| 184 | + |
| 185 | + class JarImportFinder: |
| 186 | + def __init__(self): |
| 187 | + self.namelist_cache = {} |
| 188 | + |
| 189 | + def find_spec(self, fullname, path, target=None): |
| 190 | + for path in sys.path: |
| 191 | + if ".jar!" in path: |
| 192 | + jarfile, _, zippath = path.partition("!") |
| 193 | + file_to_find = "%s/%s.py" % (zippath, fullname.replace(".", "/")) |
| 194 | + init_to_find = "%s/%s/__init__.py" % (zippath, fullname.replace(".", "/")) |
| 195 | + old_mtime, namelist = self.namelist_cache.get(jarfile, (None, None)) |
| 196 | + try: |
| 197 | + mtime = posix.stat(jarfile).st_mtime |
| 198 | + except OSError: |
| 199 | + mtime = -1 |
| 200 | + if namelist is None or mtime > old_mtime: |
| 201 | + import zipfile |
| 202 | + with zipfile.ZipFile(jarfile) as z: |
| 203 | + namelist = z.namelist() |
| 204 | + self.namelist_cache[jarfile] = (mtime, namelist) |
| 205 | + if file_to_find in namelist: |
| 206 | + return _frozen_importlib.ModuleSpec(fullname, JarImportLoader(jarfile, file_to_find), is_package=False) |
| 207 | + elif init_to_find in namelist: |
| 208 | + return _frozen_importlib.ModuleSpec(fullname, JarImportLoader(jarfile, init_to_find), is_package=True) |
| 209 | + |
| 210 | + |
| 211 | + sys.meta_path.append(JarImportFinder()) |
| 212 | + |
| 213 | + |
166 | 214 | sys.meta_path.append(JavaImportFinder()) |
167 | 215 | if sys.graal_python_jython_emulation_enabled: |
168 | 216 | __getattr__ = JavaPackageLoader._make_getattr("java") |
|
0 commit comments