Skip to content

Commit

Permalink
Use less xpath
Browse files Browse the repository at this point in the history
  • Loading branch information
Josef-Friedrich committed Jan 20, 2024
1 parent 05ab074 commit 78efd09
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 55 deletions.
37 changes: 18 additions & 19 deletions mscxyz/score.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,26 +220,25 @@ def save(self, new_dest: str = "", mscore: bool = False) -> None:
# To get the same xml tag structure as the original score file
# has.
for xpath in (
"//LayerTag",
"//metaTag",
"//font",
"//i",
"//evenFooterL",
"//evenFooterC",
"//evenFooterR",
"//oddFooterL",
"//oddFooterC",
"//oddFooterR",
"//chord/name",
"//chord/render",
"//StaffText/text",
"//Jump/continueAt",
".//LayerTag",
".//metaTag",
".//font",
".//i",
".//evenFooterL",
".//evenFooterC",
".//evenFooterR",
".//oddFooterL",
".//oddFooterC",
".//oddFooterR",
".//chord/name",
".//chord/render",
".//StaffText/text",
".//Jump/continueAt",
):
x: list[_Element] | None = self.xml.xpathall(xpath)
if x:
for tag in x:
if not tag.text:
tag.text = ""
x = self.xml.findall(xpath)
for tag in x:
if not tag.text:
tag.text = ""

xml_dest = dest

Expand Down
41 changes: 18 additions & 23 deletions mscxyz/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,10 @@
from pathlib import Path
from typing import Any, Generator, List, Literal, Optional

import lxml
import lxml.etree
import termcolor
from lxml.etree import _Element, _ElementTree

from mscxyz.settings import get_args
from mscxyz.xml import Xml

ListExtension = Literal["mscz", "mscx", "both"]

Expand Down Expand Up @@ -345,26 +343,23 @@ class ZipContainer:

def __init__(self, abspath: str | Path) -> None:
self.tmp_dir = ZipContainer._extract_zip(abspath)
container_info: _ElementTree = lxml.etree.parse(
self.tmp_dir / "META-INF" / "container.xml"
)
root_files = container_info.xpath("/container/rootfiles")
if isinstance(root_files, list):
for root_file in root_files[0]:
if isinstance(root_file, _Element):
relpath = root_file.get("full-path")
if isinstance(relpath, str):
abs_path: Path = self.tmp_dir / relpath
if relpath.endswith(".mscx"):
self.xml_file = abs_path
elif relpath.endswith(".mss"):
self.score_style_file = abs_path
elif relpath.endswith(".png"):
self.thumbnail_file = abs_path
elif relpath.endswith("audiosettings.json"):
self.audiosettings_file = abs_path
elif relpath.endswith("viewsettings.json"):
self.viewsettings_file = abs_path

xml = Xml.new(self.tmp_dir / "META-INF" / "container.xml")

for root_file in xml.findall(".//rootfiles/rootfile"):
relpath = root_file.get("full-path")
if isinstance(relpath, str):
abs_path: Path = self.tmp_dir / relpath
if relpath.endswith(".mscx"):
self.xml_file = abs_path
elif relpath.endswith(".mss"):
self.score_style_file = abs_path
elif relpath.endswith(".png"):
self.thumbnail_file = abs_path
elif relpath.endswith("audiosettings.json"):
self.audiosettings_file = abs_path
elif relpath.endswith("viewsettings.json"):
self.viewsettings_file = abs_path

@staticmethod
def _extract_zip(abspath: str | Path) -> Path:
Expand Down
33 changes: 20 additions & 13 deletions mscxyz/xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,16 @@
from pathlib import Path
from typing import Literal, Optional, Union

import lxml
import lxml.etree
from lxml.etree import _Element, _ElementTree
from lxml.etree import (
XML,
Element,
SubElement,
XMLSyntaxError,
_Element,
_ElementTree,
parse,
tostring,
)

if typing.TYPE_CHECKING:
from lxml.etree import _DictAnyStr, _XPathObject
Expand Down Expand Up @@ -47,27 +54,27 @@ def parse_file(path: str | Path | TextIOWrapper) -> _Element:
:return: The root element of the XML file.
"""
return lxml.etree.parse(path).getroot()
return parse(path).getroot()

@staticmethod
def parse_string(xml_markup: str) -> _Element:
return lxml.etree.XML(xml_markup)
return XML(xml_markup)

@staticmethod
def parse_file_try(
path: str | Path | TextIOWrapper,
file_path: str | Path | TextIOWrapper,
) -> tuple[_Element | None, Exception | None]:
element: _Element | None = None
error: Exception | None = None
try:
element = lxml.etree.parse(path).getroot()
except lxml.etree.XMLSyntaxError as e:
element = parse(file_path).getroot()
except XMLSyntaxError as e:
error = e
return (element, error)

@staticmethod
def new(path: str | Path | TextIOWrapper) -> Xml:
return Xml(Xml.parse_file(path))
def new(file_path: str | Path | TextIOWrapper) -> Xml:
return Xml(Xml.parse_file(file_path))

def tostring(self, element: ElementLike = None) -> str:
"""
Expand All @@ -80,7 +87,7 @@ def tostring(self, element: ElementLike = None) -> str:
# TestFileCompare not passing ...
return (
'<?xml version="1.0" encoding="UTF-8"?>\n'
+ lxml.etree.tostring(element, encoding="UTF-8").decode("utf-8")
+ tostring(element, encoding="UTF-8").decode("utf-8")
+ "\n"
)

Expand Down Expand Up @@ -285,7 +292,7 @@ def remove(element: _Element | None) -> None:

@staticmethod
def create_element(tag_name: str) -> _Element:
return lxml.etree.Element(tag_name)
return Element(tag_name)

@staticmethod
def create_sub_element(
Expand All @@ -294,7 +301,7 @@ def create_sub_element(
text: Optional[str] = None,
attrib: Optional[_DictAnyStr] = None,
) -> _Element:
element: _Element = lxml.etree.SubElement(parent, tag_name, attrib=attrib)
element: _Element = SubElement(parent, tag_name, attrib=attrib)
if text:
element.text = text
return element
Expand Down

0 comments on commit 78efd09

Please sign in to comment.