Improve handling with nested objects (#1253)

This commit is contained in:
Pascal Vizeli 2019-08-22 14:24:50 +02:00 committed by GitHub
parent c0e3ccdb83
commit 8b9cd4f122
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 32 additions and 6 deletions

View File

@ -24,13 +24,13 @@ RE_GVARIANT_TYPE: re.Match = re.compile(
r"(?:boolean|byte|int16|uint16|int32|uint32|handle|int64|uint64|double|"
r"string|objectpath|signature) "
)
RE_GVARIANT_VARIANT: re.Match = re.compile(
r"(?<=(?: |{|\[))<((?:'|\").*?(?:'|\")|\d+(?:\.\d+)?)>(?=(?:|]|}|,))"
)
RE_GVARIANT_VARIANT: re.Match = re.compile(r"\"[^\"\\]*(?:\\.[^\"\\]*)*\"|(<|>)")
RE_GVARIANT_STRING_ESC: re.Match = re.compile(
r"(?<=(?: |{|\[|\())'[^']*?\"[^']*?'(?=(?:|]|}|,|\)))"
r"(?<=(?: |{|\[|\(|<))'[^']*?\"[^']*?'(?=(?:|]|}|,|\)|>))"
)
RE_GVARIANT_STRING: re.Match = re.compile(
r"(?<=(?: |{|\[|\(|<))'(.*?)'(?=(?:|]|}|,|\)|>))"
)
RE_GVARIANT_STRING: re.Match = re.compile(r"(?<=(?: |{|\[|\())'(.*?)'(?=(?:|]|}|,|\)))")
RE_GVARIANT_TUPLE_O: re.Match = re.compile(r"\"[^\"\\]*(?:\\.[^\"\\]*)*\"|(\()")
RE_GVARIANT_TUPLE_C: re.Match = re.compile(r"\"[^\"\\]*(?:\\.[^\"\\]*)*\"|(,?\))")
@ -110,11 +110,13 @@ class DBus:
def parse_gvariant(raw: str) -> Any:
"""Parse GVariant input to python."""
json_raw: str = RE_GVARIANT_TYPE.sub("", raw)
json_raw = RE_GVARIANT_VARIANT.sub(r"\1", json_raw)
json_raw = RE_GVARIANT_STRING_ESC.sub(
lambda x: x.group(0).replace('"', '\\"'), json_raw
)
json_raw = RE_GVARIANT_STRING.sub(r'"\1"', json_raw)
json_raw = RE_GVARIANT_VARIANT.sub(
lambda x: x.group(0) if not x.group(1) else "", json_raw
)
json_raw = RE_GVARIANT_TUPLE_O.sub(
lambda x: x.group(0) if not x.group(1) else "[", json_raw
)

View File

@ -276,3 +276,27 @@ def test_systemd_unitlist_complex():
],
]
]
def test_networkmanager_dns_properties():
"""Test NetworkManager DNS properties."""
raw = "({'Mode': <'default'>, 'RcManager': <'file'>, 'Configuration': <[{'nameservers': <['192.168.23.30']>, 'domains': <['syshack.local']>, 'interface': <'eth0'>, 'priority': <100>, 'vpn': <false>}]>},)"
# parse data
data = DBus.parse_gvariant(raw)
assert data == [
{
"Mode": "default",
"RcManager": "file",
"Configuration": [
{
"nameservers": ["192.168.23.30"],
"domains": ["syshack.local"],
"interface": "eth0",
"priority": 100,
"vpn": False,
}
],
}
]