Anton Hansson | e673784 | 2021-09-27 12:18:20 +0100 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | # |
| 3 | # Copyright (C) 2021 The Android Open Source Project |
| 4 | # |
| 5 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | # you may not use this file except in compliance with the License. |
| 7 | # You may obtain a copy of the License at |
| 8 | # |
| 9 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | # |
| 11 | # Unless required by applicable law or agreed to in writing, software |
| 12 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | # See the License for the specific language governing permissions and |
| 15 | # limitations under the License. |
| 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() |