| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
"""Script to merge annotation XML files (created by e.g. metalava).""" |
| 18 |
|
| 19 |
from pathlib import Path |
| 20 |
import sys |
| 21 |
import xml.etree.ElementTree as ET |
| 22 |
import zipfile |
| 23 |
|
| 24 |
|
| 25 |
def validate_xml_assumptions(root): |
| 26 |
"""Verify the format of the annotations XML matches expectations""" |
| 27 |
prevName = "" |
| 28 |
assert root.tag == 'root' |
| 29 |
for child in root: |
| 30 |
assert child.tag == 'item', 'unexpected tag: %s' % child.tag |
| 31 |
assert list(child.attrib.keys()) == ['name'], 'unexpected attribs: %s' % child.attrib.keys() |
| 32 |
assert prevName < child.get('name'), 'items unexpectedly not strictly sorted (possibly duplicate entries)' |
| 33 |
prevName = child.get('name') |
| 34 |
|
| 35 |
|
| 36 |
def merge_xml(a, b): |
| 37 |
"""Merge two annotation xml files""" |
| 38 |
for xml in [a, b]: |
| 39 |
validate_xml_assumptions(xml) |
| 40 |
a.extend(b[:]) |
| 41 |
a[:] = sorted(a[:], key=lambda x: x.get('name')) |
| 42 |
validate_xml_assumptions(a) |
| 43 |
|
| 44 |
|
| 45 |
def merge_zip_file(out_dir, zip_file): |
| 46 |
"""Merge the content of the zip_file into out_dir""" |
| 47 |
for filename in zip_file.namelist(): |
| 48 |
path = Path(out_dir, filename) |
| 49 |
if path.exists(): |
| 50 |
existing_xml = ET.parse(path) |
| 51 |
with zip_file.open(filename) as other_file: |
| 52 |
other_xml = ET.parse(other_file) |
| 53 |
merge_xml(existing_xml.getroot(), other_xml.getroot()) |
| 54 |
existing_xml.write(path, encoding='UTF-8', xml_declaration=True) |
| 55 |
else: |
| 56 |
zip_file.extract(filename, out_dir) |
| 57 |
|
| 58 |
|
| 59 |
def main(): |
| 60 |
out_dir = Path(sys.argv[1]) |
| 61 |
zip_filenames = sys.argv[2:] |
| 62 |
|
| 63 |
assert not out_dir.exists() |
| 64 |
out_dir.mkdir() |
| 65 |
for zip_filename in zip_filenames: |
| 66 |
with zipfile.ZipFile(zip_filename) as zip_file: |
| 67 |
merge_zip_file(out_dir, zip_file) |
| 68 |
|
| 69 |
|
| 70 |
if __name__ == "__main__": |
| 71 |
main() |