|
| 1 | +import os |
| 2 | +import shutil |
| 3 | +import argparse |
| 4 | +import tempfile |
| 5 | +import contextlib |
| 6 | + |
| 7 | + |
| 8 | +@contextlib.contextmanager |
| 9 | +def _working_dir(new_dir): |
| 10 | + previous_dir = os.getcwd() |
| 11 | + if not os.path.isdir(new_dir): |
| 12 | + os.makedirs(new_dir) |
| 13 | + os.chdir(new_dir) |
| 14 | + yield |
| 15 | + os.chdir(previous_dir) |
| 16 | + |
| 17 | + |
| 18 | +def _parse_cmd_line(): |
| 19 | + parser = argparse.ArgumentParser( |
| 20 | + description="Creates a JAR file consisting of modelled class files and " |
| 21 | + "other class files in the passed 'rt.jar'.") |
| 22 | + parser.add_argument("rt", type=str, |
| 23 | + help="A path-name of the 'rt.jar' file.") |
| 24 | + parser.add_argument("--output-name", type=str, default="rtm.jar", |
| 25 | + help="A name of the final JAR file (without path).") |
| 26 | + cmdline = parser.parse_args() |
| 27 | + if not os.path.isfile(cmdline.rt): |
| 28 | + print("ERROR: The passed file '" + cmdline.rt + "' does not exist.") |
| 29 | + exit(1) |
| 30 | + if os.path.splitext(cmdline.rt)[1].lower() != ".jar": |
| 31 | + print("ERROR: The passed file '" + cmdline.rt + "' does not have '.jar' extension.") |
| 32 | + exit(1) |
| 33 | + cmdline.rt = os.path.abspath(cmdline.rt) |
| 34 | + return cmdline |
| 35 | + |
| 36 | + |
| 37 | +def _mkrtm(cmdline): |
| 38 | + model_classes_root_dir = os.path.abspath(os.path.join("target", "classes")) |
| 39 | + temp_root_dir = tempfile.mkdtemp() |
| 40 | + classes_root_dir = os.path.join(temp_root_dir, "classes") |
| 41 | + rt_unpack_root_dir = os.path.join(temp_root_dir, "RT_UNPACK") |
| 42 | + dst_jar_pathname = os.path.abspath(os.path.join("target", cmdline.output_name)) |
| 43 | + |
| 44 | + shutil.copytree(model_classes_root_dir, classes_root_dir) |
| 45 | + with _working_dir(rt_unpack_root_dir): |
| 46 | + os.system("jar -xvf '" + cmdline.rt + "'") |
| 47 | + for root, _, file_names in os.walk(rt_unpack_root_dir): |
| 48 | + for filename in file_names: |
| 49 | + if os.path.splitext(filename)[1].lower() == ".class": |
| 50 | + src_pathname = os.path.abspath(os.path.join(root, filename)) |
| 51 | + rel_pathname = os.path.relpath(src_pathname, rt_unpack_root_dir) |
| 52 | + dst_pathname = os.path.join(classes_root_dir, rel_pathname) |
| 53 | + if not os.path.isfile(dst_pathname): |
| 54 | + if not os.path.isdir(os.path.dirname(dst_pathname)): |
| 55 | + os.makedirs(os.path.dirname(dst_pathname)) |
| 56 | + shutil.copy(src_pathname, dst_pathname) |
| 57 | + with _working_dir(classes_root_dir): |
| 58 | + os.system("jar cvfm " + os.path.basename(dst_jar_pathname) + " " + |
| 59 | + os.path.join(rt_unpack_root_dir, "META-INF", "MANIFEST.MF") + |
| 60 | + " .") |
| 61 | + shutil.copy(os.path.join(classes_root_dir, os.path.basename(dst_jar_pathname)), |
| 62 | + dst_jar_pathname) |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == '__main__': |
| 66 | + _mkrtm(_parse_cmd_line()) |
0 commit comments