paul@98 | 1 | #!/usr/bin/env python |
paul@98 | 2 | |
paul@98 | 3 | """ |
paul@98 | 4 | Wrap Java packages, converting the skeleton Java classes to Python modules which |
paul@98 | 5 | connect to concrete Python implementation classes. |
paul@98 | 6 | """ |
paul@98 | 7 | |
paul@98 | 8 | import classfile |
paul@98 | 9 | import glob |
paul@98 | 10 | import sys |
paul@98 | 11 | import os |
paul@98 | 12 | |
paul@98 | 13 | if __name__ == "__main__": |
paul@98 | 14 | if len(sys.argv) < 2: |
paul@98 | 15 | print "wrap.py <package directory> <wrapped package>" |
paul@98 | 16 | print "For example:" |
paul@98 | 17 | print "wrap.py qtjava qt" |
paul@98 | 18 | sys.exit(1) |
paul@98 | 19 | |
paul@98 | 20 | # Process all directories in the list, producing for each a Python source |
paul@98 | 21 | # file containing the classes found in the given directory. |
paul@98 | 22 | |
paul@98 | 23 | directory, package = sys.argv[1:3] |
paul@98 | 24 | f = open(os.path.join(directory, "__init__.py"), "w") |
paul@98 | 25 | f.write("import %s\n" % package) |
paul@98 | 26 | |
paul@98 | 27 | # Process each class file. |
paul@98 | 28 | |
paul@98 | 29 | for filename in glob.glob(os.path.join(directory, "*.class")): |
paul@98 | 30 | print "Processing", filename |
paul@98 | 31 | cf = open(filename, "rb") |
paul@98 | 32 | c = classfile.ClassFile(cf.read()) |
paul@98 | 33 | cf.close() |
paul@98 | 34 | |
paul@98 | 35 | # Write the class into the source file. |
paul@98 | 36 | |
paul@98 | 37 | full_name = c.this_class.get_python_name() |
paul@98 | 38 | class_name = full_name.split(".")[-1] |
paul@101 | 39 | f.write("class %s(%s.%s, object):\n" % (class_name, package, class_name)) |
paul@98 | 40 | |
paul@98 | 41 | # Process methods in the class, writing wrapper code. |
paul@98 | 42 | |
paul@98 | 43 | method_names = [] |
paul@98 | 44 | for method in c.methods: |
paul@98 | 45 | wrapped_method_name = method.get_unqualified_python_name() |
paul@98 | 46 | f.write(" def %s(*args):\n" % wrapped_method_name) |
paul@98 | 47 | f.write(" return %s.%s.%s(*args)\n" % (package, class_name, wrapped_method_name)) |
paul@98 | 48 | method_name = method.get_python_name() |
paul@98 | 49 | method_names.append((method_name, wrapped_method_name)) |
paul@98 | 50 | |
paul@98 | 51 | # Produce method entries for the specially named methods. |
paul@98 | 52 | |
paul@98 | 53 | for method_name, wrapped_method_name in method_names: |
paul@98 | 54 | f.write("setattr(%s, '%s', %s.%s)\n" % (class_name, method_name, class_name, wrapped_method_name)) |
paul@98 | 55 | |
paul@100 | 56 | # Remove the original class. |
paul@100 | 57 | |
paul@100 | 58 | print "Removing", filename |
paul@100 | 59 | os.remove(filename) |
paul@100 | 60 | |
paul@98 | 61 | f.close() |
paul@98 | 62 | |
paul@98 | 63 | # vim: tabstop=4 expandtab shiftwidth=4 |