|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Update SharedPreferences XML with key/value pairs.""" |
| 3 | + |
| 4 | +import sys |
| 5 | +import xml.etree.ElementTree as ET |
| 6 | + |
| 7 | + |
| 8 | +def main() -> int: |
| 9 | + if len(sys.argv) < 2: |
| 10 | + print("usage: prefs-xml.py <xml-path> [--string key value] [--bool key true|false] ...", file=sys.stderr) |
| 11 | + return 2 |
| 12 | + |
| 13 | + path = sys.argv[1] |
| 14 | + args = sys.argv[2:] |
| 15 | + |
| 16 | + try: |
| 17 | + tree = ET.parse(path) |
| 18 | + root = tree.getroot() |
| 19 | + except Exception: |
| 20 | + root = ET.Element("map") |
| 21 | + tree = ET.ElementTree(root) |
| 22 | + |
| 23 | + if root.tag != "map": |
| 24 | + root = ET.Element("map") |
| 25 | + tree = ET.ElementTree(root) |
| 26 | + |
| 27 | + def remove_existing(key: str) -> None: |
| 28 | + for el in list(root): |
| 29 | + if el.attrib.get("name") == key: |
| 30 | + root.remove(el) |
| 31 | + |
| 32 | + idx = 0 |
| 33 | + while idx < len(args): |
| 34 | + flag = args[idx] |
| 35 | + if flag not in ("--string", "--bool"): |
| 36 | + print(f"unknown flag: {flag}", file=sys.stderr) |
| 37 | + return 2 |
| 38 | + if idx + 2 >= len(args): |
| 39 | + print(f"{flag} requires key and value", file=sys.stderr) |
| 40 | + return 2 |
| 41 | + key = args[idx + 1] |
| 42 | + val = args[idx + 2] |
| 43 | + idx += 3 |
| 44 | + |
| 45 | + remove_existing(key) |
| 46 | + if flag == "--string": |
| 47 | + el = ET.SubElement(root, "string", {"name": key}) |
| 48 | + el.text = val |
| 49 | + else: |
| 50 | + if val not in ("true", "false"): |
| 51 | + print(f"boolean must be true/false for {key}", file=sys.stderr) |
| 52 | + return 2 |
| 53 | + ET.SubElement(root, "boolean", {"name": key, "value": val}) |
| 54 | + |
| 55 | + if hasattr(ET, "indent"): |
| 56 | + ET.indent(tree, space=" ", level=0) |
| 57 | + |
| 58 | + with open(path, "wb") as f: |
| 59 | + tree.write(f, encoding="utf-8", xml_declaration=True) |
| 60 | + |
| 61 | + return 0 |
| 62 | + |
| 63 | + |
| 64 | +if __name__ == "__main__": |
| 65 | + raise SystemExit(main()) |
0 commit comments