improve how defaults are handled and print everything into the XML

This commit is contained in:
Jan Petykiewicz 2024-02-27 22:05:47 -08:00
parent 3e0a4a9da2
commit 06a66605d8

51
k2t.py
View File

@ -7,6 +7,11 @@ from dataclasses import dataclass, fields
from xml.etree import ElementTree
# Used when value is `None`, except on groups where they're left unset
DEFAULT_LINESTYLE = 'I0'
DEFAULT_DITHER = 'I1'
def k2t(
kfile: str,
tfile: str,
@ -101,16 +106,16 @@ def t2k(tfile: str, kfile: str) -> None:
@dataclass(slots=True)
class Entry:
name: str
source: str | None
frame_color: str | None
fill_color: str | None
name: str | None = None
source: str | None = None
frame_color: str | None = None
fill_color: str | None = None
members: list | None = None
expanded: bool = False
dither_pattern: str = 'C1'
line_style: str = 'C0'
dither_pattern: str | None = None
line_style: str | None = None
frame_brightness: int = 0
fill_brightness: int = 0
width: int = 1
@ -127,11 +132,7 @@ class Entry:
assert el.tag in ('properties', 'group-members')
members = []
args: dict[str, Any] = {
'frame_color': None,
'fill_color': None,
'source': None,
}
args: dict[str, Any] = {}
for child in el:
if not child.text:
continue
@ -157,6 +158,8 @@ class Entry:
if not members:
members = None
args.setdefault('line_style', DEFAULT_LINESTYLE)
args.setdefault('dither_pattern', DEFAULT_DITHER)
return cls(members=members, **args)
@ -165,22 +168,18 @@ class Entry:
el = ElementTree.Element(main_tag)
for field in fields(self):
val = getattr(self, field.name)
if val is None or field.name == 'members':
continue
if (val == field.default
and (field not in ('dither-pattern', 'line-style')
or self.source is None
)):
if field.name == 'members':
continue
tag = field.name.replace('_', '-')
if tag in ('frame-color', 'fill-color'):
val = '#' + val
el2 = ElementTree.Element(tag)
if val is not None:
if not isinstance(val, str):
val = str(val).lower()
el2 = ElementTree.Element(tag)
el2.text = val
elif tag == 'source':
el2.text = '*/*@*'
el.append(el2)
if self.members:
@ -195,7 +194,9 @@ class Entry:
s = '[[' + '.'.join(parts) + ']]\n'
for field in fields(self):
val = getattr(self, field.name)
if val == field.default or val is None:
if val == field.default:
continue
if field.name == 'members':
continue
if isinstance(val, str):
@ -219,11 +220,7 @@ class Entry:
@classmethod
def from_toml(cls: Type[Self], tree: dict) -> Self:
members = []
args: dict[str, Any] = {
'frame_color': None,
'fill_color': None,
'source': None,
}
args: dict[str, Any] = {}
for key, val in tree.items():
if key != 'members':
args[key.replace('-', '_')] = val
@ -234,6 +231,8 @@ class Entry:
if not members:
members = None
args.setdefault('line_style', DEFAULT_LINESTYLE)
args.setdefault('dither_pattern', DEFAULT_DITHER)
return cls(members=members, **args)