Skip to content

Commit e67d469

Browse files
committed
add import loader to deal with imports from JAR files
1 parent ca03dd0 commit e67d469

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

graalpython/lib-graalpython/java.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3737
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
3838
# SOFTWARE.
39+
import posix
3940
import sys
4041
import _frozen_importlib
4142

@@ -163,6 +164,53 @@ def find_spec(self, fullname, path, target=None):
163164
return _frozen_importlib.ModuleSpec(fullname, JavaTypeLoader, is_package=False)
164165

165166

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+
166214
sys.meta_path.append(JavaImportFinder())
167215
if sys.graal_python_jython_emulation_enabled:
168216
__getattr__ = JavaPackageLoader._make_getattr("java")

0 commit comments

Comments
 (0)