1 #!/usr/bin/env python 2 3 import ihooks 4 import os, glob 5 from imp import PY_SOURCE, PKG_DIRECTORY, C_BUILTIN 6 import classfile, bytecode 7 import new 8 9 class ClassHooks(ihooks.Hooks): 10 11 "A filesystem hooks class providing information about supported files." 12 13 def get_suffixes(self): 14 15 "Return the recognised suffixes." 16 17 return ihooks.Hooks.get_suffixes(self) + [(os.extsep + "class", "r", PY_SOURCE)] 18 19 class ClassLoader(ihooks.ModuleLoader): 20 21 "A class providing support for searching directories for supported files." 22 23 def find_module_in_dir(self, name, dir): 24 25 """ 26 Find the module with the given 'name' in the given directory 'dir'. 27 Since Java packages/modules are directories containing class files, 28 return the required information tuple only when the path constructed 29 from 'dir' and 'name' refers to a directory containing class files. 30 """ 31 32 dir = dir or "." 33 34 # Provide a special name for the current directory. 35 36 if name == "__this__": 37 path = dir 38 else: 39 path = os.path.join(dir, name) 40 41 print "Processing name", name, "in", dir, "producing", path 42 if os.path.isdir(path): 43 if len(glob.glob(os.path.join(path, "*" + os.extsep + "class"))) != 0: 44 return (None, path, ("", "", PKG_DIRECTORY)) 45 return None 46 47 def load_module(self, name, stuff): 48 49 """ 50 Load the module with the given 'name', whose 'stuff' which describes the 51 location of the module is a tuple of the form (file, filename, (suffix, 52 mode, data type)). Return a module object or raise an ImportError if a 53 problem occurred in the import operation. 54 """ 55 56 # Just go into the directory and find the class files. 57 58 file, filename, info = stuff 59 60 # Prepare a dictionary of globals. 61 62 global_names = {} 63 global_names.update(__builtins__.__dict__) 64 module = self.hooks.add_module(name) 65 66 # Process each class file, producing a genuine Python class. 67 68 class_files = [] 69 for class_filename in glob.glob(os.path.join(filename, "*" + os.extsep + "class")): 70 print "Importing class", class_filename 71 f = open(class_filename, "rb") 72 s = f.read() 73 f.close() 74 class_file = classfile.ClassFile(s) 75 translator = bytecode.ClassTranslator(class_file) 76 cls = translator.process(global_names) 77 module.__dict__[cls.__name__] = cls 78 79 return module 80 81 class ClassImporter(ihooks.ModuleImporter): 82 83 def import_it(self, partname, fqname, parent, force_load=0): 84 try: 85 return parent.__dict__[partname] 86 87 except (KeyError, AttributeError): 88 return ihooks.ModuleImporter.import_it( 89 self, partname, fqname, parent, force_load 90 ) 91 92 importer = ClassImporter(loader=ClassLoader(hooks=ClassHooks())) 93 importer.install() 94 95 # vim: tabstop=4 expandtab shiftwidth=4