From 954aef1d2cbd97cf76462484b96969568f1680bc Mon Sep 17 00:00:00 2001 From: Martin Lehmann Date: Tue, 7 Nov 2023 16:14:34 +0100 Subject: [PATCH] fix(loader): Write to the correct file handlers on save Saving a ModelFile used to write back into the same FileHandler that it was loaded from. This caused inconsistencies and unexpected behavior when trying to change the save location at runtime by modifying `loader.resources`. Now, ModelFiles always use the expected FileHandler. --- capellambse/loader/core.py | 32 ++++++++++++++------------------ 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/capellambse/loader/core.py b/capellambse/loader/core.py index 2d352e400..e5150eb5a 100644 --- a/capellambse/loader/core.py +++ b/capellambse/loader/core.py @@ -312,28 +312,22 @@ def iterall_xt( def write_xml( self, - filename: pathlib.PurePosixPath, + file: t.BinaryIO, encoding: str = "utf-8", ) -> None: """Write this file's XML into the file specified by ``path``.""" - LOGGER.debug("Saving tree %r to file %s", self, filename) - if filename.suffix in { - ".capella", - ".capellafragment", - ".melodyfragment", - ".melodymodeller", - }: + if self.fragment_type == FragmentType.SEMANTIC: line_length = exs.LINE_LENGTH else: line_length = sys.maxsize - with self.filehandler.open(filename, "wb") as file: - exs.write( - self.root, - file, - encoding=encoding, - line_length=line_length, - siblings=True, - ) + + exs.write( + self.root, + file, + encoding=encoding, + line_length=line_length, + siblings=True, + ) def unfollow_href(self, element_id: str) -> etree._Element: """Unfollow a fragment link and return the placeholder element. @@ -472,7 +466,7 @@ def __load_referenced_files( self.__load_referenced_files(ref_name) def save(self, **kw: t.Any) -> None: - """Save all model files back to their original locations. + """Save all model files. Parameters ---------- @@ -518,7 +512,9 @@ def save(self, **kw: t.Any) -> None: if resname != "\0": continue - tree.write_xml(fname) + LOGGER.debug("Saving tree %r to file %s", tree, fname) + with self.resources[resname].open(fname, "wb") as f: + tree.write_xml(f) def idcache_index(self, subtree: etree._Element) -> None: """Index the IDs of ``subtree``.