diff --git a/launcher/build.py b/launcher/build.py index c1f17e9e..c1029c5b 100644 --- a/launcher/build.py +++ b/launcher/build.py @@ -3,6 +3,7 @@ and cancelling it with every compiler it started.""" import json import os import signal +import stat import subprocess import threading @@ -100,17 +101,26 @@ class Run: def game_running(game_dir, exe='ocarina.exe'): - """True when the built game runs from game_dir: Windows refuses to open a running exe for writing.""" + """True when the built game runs from game_dir: Windows refuses to open a running exe for writing. A read-only + exe (a copy restored from a backup or read-only media) is refused too, though nothing runs it: its read-only + attribute is cleared and the open tried again, as the next build replaces the file anyway.""" path = os.path.join(str(game_dir), exe) if os.name != 'nt' or not os.path.isfile(path): return False - try: - with open(path, 'r+b'): + for attempt in range(2): + try: + with open(path, 'r+b'): + return False + except PermissionError: + if attempt or not os.stat(path).st_file_attributes & stat.FILE_ATTRIBUTE_READONLY: + return True + try: + os.chmod(path, stat.S_IREAD | stat.S_IWRITE) + except OSError: + return True + except OSError: return False - except PermissionError: - return True - except OSError: - return False + return True def build_state(game_dir): diff --git a/launcher/saves.py b/launcher/saves.py index 25a68e7a..448ba2f6 100644 --- a/launcher/saves.py +++ b/launcher/saves.py @@ -181,17 +181,9 @@ def _newest(game, account): def game_running(game): - """Windows: ocarina.exe cannot be opened for writing while it runs.""" - exe = Path(game) / 'ocarina.exe' - if os.name != 'nt' or not exe.is_file(): - return False - try: - with open(exe, 'r+b'): - return False - except PermissionError: - return True - except OSError: - return False + """Windows: ocarina.exe cannot be opened for writing while it runs (launcher/build.py game_running).""" + from .build import game_running as running + return running(game) def import_save(game, folder=None, log=print): diff --git a/tests/launcher_test.py b/tests/launcher_test.py index 206e0c06..f7ab55b6 100644 --- a/tests/launcher_test.py +++ b/tests/launcher_test.py @@ -1216,6 +1216,15 @@ class SavesTest(unittest.TestCase): self.assertEqual((acct / 'save.dat').read_bytes(), b'older') self.assertFalse((tx / 'import').exists()) + @unittest.skipUnless(os.name == 'nt', 'the running check is Windows only') + def test_a_read_only_exe_is_not_a_running_game(self): + exe = self.game / 'ocarina.exe' + exe.write_bytes(b'MZ') + os.chmod(exe, stat.S_IREAD) + self.assertFalse(build.game_running(self.game)) + self.assertFalse(saves.game_running(self.game)) + self.assertTrue(os.access(exe, os.W_OK)) + def test_read_only_files_import_writable(self): acct = saves.account_dir(self.game) self.files(acct, {'save.dat': b'old'})