1234from pathlib import Path5import sys6import xml.etree.ElementTree as ET78ANDROID_NS = "{http://schemas.android.com/apk/res/android}"9ROOT = Path(__file__).resolve().parents[1]10DEFAULT_INVENTORY = ROOT / "docs" / "android-release-manifest-inventory.txt"11DEFAULT_MERGED = ROOT / "app" / "build" / "intermediates" / "merged_manifest" / "release" / "processReleaseMainManifest" / "AndroidManifest.xml"121314def inventory(path: Path) -> str:15 root = ET.parse(path).getroot()16 lines = []17 for permission in sorted(root.findall("uses-permission"), key=lambda node: node.get(ANDROID_NS + "name", "")):18 lines.append(f"permission|{permission.get(ANDROID_NS + 'name', '')}")19 application = root.find("application")20 if application is None:21 raise SystemExit("release manifest has no application")22 for child in sorted(application, key=lambda node: (node.tag, node.get(ANDROID_NS + "name", ""))):23 name = child.get(ANDROID_NS + "name", "")24 exported = child.get(ANDROID_NS + "exported", "")25 permission = child.get(ANDROID_NS + "permission", "")26 lines.append(f"component|{child.tag}|{name}|exported={exported}|permission={permission}")27 for intent_filter in child.findall("intent-filter"):28 actions = sorted(action.get(ANDROID_NS + "name", "") for action in intent_filter.findall("action"))29 categories = sorted(category.get(ANDROID_NS + "name", "") for category in intent_filter.findall("category"))30 lines.append(f"intent-filter|{child.tag}|{name}|actions={','.join(actions)}|categories={','.join(categories)}")31 return "\n".join(lines) + "\n"323334USAGE = f"usage: {Path(sys.argv[0]).name} check|write [merged-manifest] [inventory]"3536if len(sys.argv) not in (2, 3, 4):37 raise SystemExit(USAGE)38MERGED = Path(sys.argv[2]) if len(sys.argv) > 2 else DEFAULT_MERGED39INVENTORY = Path(sys.argv[3]) if len(sys.argv) > 3 else DEFAULT_INVENTORY4041if not MERGED.is_file():42 raise SystemExit(f"merged release manifest not found: {MERGED}")4344if sys.argv[1] == "write":45 INVENTORY.write_text(inventory(MERGED))46elif sys.argv[1] == "check":47 if not INVENTORY.is_file():48 raise SystemExit(f"checked-in inventory not found: {INVENTORY}")49 actual = inventory(MERGED)50 expected = INVENTORY.read_text()51 if actual != expected:52 raise SystemExit("merged release manifest differs from checked-in inventory")53else:54 raise SystemExit(f"unknown command: {sys.argv[1]}\n{USAGE}")