Skip to content

Commit

Permalink
Mapper: Support renaming the file during save() if required
Browse files Browse the repository at this point in the history
  • Loading branch information
Tomas Babej committed Jun 13, 2023
1 parent 5d72550 commit ceaba5b
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion datafiles/mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from . import config, formats, hooks
from .converters import Converter, List, map_type, resolve
from .types import Missing, Trilean
from .utils import display, get_default_field_value, recursive_update, write
from .utils import display, get_default_field_value, recursive_update, write, remove


class Mapper:
Expand Down Expand Up @@ -45,6 +45,7 @@ def __init__(
self._last_load = 0.0
self._last_data: Dict = {}
self._root = root
self._original_path = self.path

@property
def classname(self) -> str:
Expand Down Expand Up @@ -264,6 +265,14 @@ def save(self, *, include_default_values: Trilean = None, _log=True) -> None:
self._root.save(include_default_values=include_default_values, _log=_log)
return

# Determine whether the attributes that are involved in the path were changed
file_rename_required = False
with hooks.disabled(): # hooks have to be disabled to prevent infinite loop
del self.__dict__["path"] # invalidate the cached property

if self.path != self._original_path:
file_rename_required = True

if self.path:
if self.exists and self._frozen:
raise dataclasses.FrozenInstanceError(
Expand All @@ -279,6 +288,9 @@ def save(self, *, include_default_values: Trilean = None, _log=True) -> None:
text = self._get_text(include_default_values=include_default_values)

write(self.path, text, display=True)
if file_rename_required:
remove(self._original_path)
self._original_path = self.path

self.modified = False

Expand Down

0 comments on commit ceaba5b

Please sign in to comment.