Skip to content

Commit

Permalink
Avoid os.chmod failing on Windows if file non-existant (#471)
Browse files Browse the repository at this point in the history
* Avoid os.chmod failing on Windows if file non-existant

* Update accessory_driver.py

---------

Co-authored-by: Ivan Kalchev <25887324+ikalchev@users.noreply.github.com>
  • Loading branch information
pjkundert and ikalchev authored Nov 3, 2024
1 parent 1feefd8 commit 1042ae5
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion pyhap/accessory_driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -642,16 +642,18 @@ def persist(self):
tmp_filename = None
try:
temp_dir = os.path.dirname(self.persist_file)
logger.debug("Creating temp persist file in '%s'", temp_dir)
with tempfile.NamedTemporaryFile(
mode="w", dir=temp_dir, delete=False
) as file_handle:
tmp_filename = file_handle.name
logger.debug("Created temp persist file '%s' named '%s'", file_handle, tmp_filename)
self.encoder.persist(file_handle, self.state)
if (
os.name == "nt"
): # Or `[WinError 5] Access Denied` will be raised on Windows
os.chmod(tmp_filename, 0o644)
os.chmod(self.persist_file, 0o644)
os.path.exists(self.persist_file) and os.chmod(self.persist_file, 0o644)
os.replace(tmp_filename, self.persist_file)
except Exception: # pylint: disable=broad-except
logger.exception("Failed to persist accessory state")
Expand Down

0 comments on commit 1042ae5

Please sign in to comment.