textkeep 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- textkeep/__init__.py +56 -0
- textkeep/__main__.py +6 -0
- textkeep/api.py +168 -0
- textkeep/cli.py +87 -0
- textkeep/codec.py +182 -0
- textkeep/errors.py +199 -0
- textkeep/lock.py +42 -0
- textkeep/newline.py +63 -0
- textkeep/py.typed +0 -0
- textkeep/replace.py +498 -0
- textkeep/shape.py +197 -0
- textkeep-0.1.0.dist-info/METADATA +276 -0
- textkeep-0.1.0.dist-info/RECORD +16 -0
- textkeep-0.1.0.dist-info/WHEEL +4 -0
- textkeep-0.1.0.dist-info/entry_points.txt +2 -0
- textkeep-0.1.0.dist-info/licenses/LICENSE +21 -0
textkeep/lock.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# 置き換えが共有違反で失敗した時の再試行の既定値と、ロックしているプロセスの名前の取得。
|
|
2
|
+
# プロセス名は任意の restartmgr(Windows・Python 3.12+)があれば使い、無ければ空で返す。
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib
|
|
6
|
+
import sys
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from .errors import LockingProcess
|
|
10
|
+
|
|
11
|
+
# Measured on Windows 11 (docs/locking-findings.md): while another process holds the file or the
|
|
12
|
+
# temporary file without FILE_SHARE_DELETE, ReplaceFileW fails with 32 and nothing else; a lock held
|
|
13
|
+
# for N ms is passed on try ceil(N / 100) + 1 at a 0.1 s interval. 20 x 0.1 s rides out locks of up
|
|
14
|
+
# to about 2 s before FileLockedError.
|
|
15
|
+
DEFAULT_RETRIES = 20
|
|
16
|
+
DEFAULT_BACKOFF = 0.1
|
|
17
|
+
ERROR_SHARING_VIOLATION = 32
|
|
18
|
+
RETRYABLE_WINERRORS = frozenset({ERROR_SHARING_VIOLATION})
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def plain_path(path: str) -> str:
|
|
22
|
+
"""Drop the ``\\\\?\\`` prefix for APIs and messages that do not want it."""
|
|
23
|
+
if path.startswith("\\\\?\\UNC\\"):
|
|
24
|
+
return "\\\\" + path[8:]
|
|
25
|
+
if path.startswith("\\\\?\\"):
|
|
26
|
+
return path[4:]
|
|
27
|
+
return path
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def locking_processes(path: str) -> tuple[LockingProcess, ...]:
|
|
31
|
+
"""Processes that hold ``path`` open, or ``()`` when restartmgr is missing or fails."""
|
|
32
|
+
if sys.platform != "win32":
|
|
33
|
+
return ()
|
|
34
|
+
try:
|
|
35
|
+
rm: Any = importlib.import_module("restartmgr")
|
|
36
|
+
except ImportError:
|
|
37
|
+
return ()
|
|
38
|
+
try:
|
|
39
|
+
found = rm.who_locks(plain_path(path))
|
|
40
|
+
return tuple(LockingProcess(name=str(p.app_name), pid=int(p.pid)) for p in found)
|
|
41
|
+
except Exception: # an optional helper must never hide the real error
|
|
42
|
+
return ()
|
textkeep/newline.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# 改行の判定(crlf / lf / cr / mixed / none)と、本文用にそろえる・ファイル用に戻す処理。
|
|
2
|
+
# 改行として数えるのは \r\n・\n・\r だけ。str.splitlines() は \x0b \x0c \x85 U+2028 なども
|
|
3
|
+
# 区切るので使わない。
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
CRLF = "\r\n"
|
|
7
|
+
LF = "\n"
|
|
8
|
+
CR = "\r"
|
|
9
|
+
MIXED = "mixed"
|
|
10
|
+
NONE = "none"
|
|
11
|
+
VALUES = (CRLF, LF, CR, MIXED, NONE)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def count(text: str) -> tuple[int, int, int]:
|
|
15
|
+
"""Return the number of (CRLF, lone LF, lone CR) line breaks."""
|
|
16
|
+
crlf = text.count(CRLF)
|
|
17
|
+
return crlf, text.count(LF) - crlf, text.count(CR) - crlf
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def classify(text: str) -> str:
|
|
21
|
+
crlf, lf, cr = count(text)
|
|
22
|
+
kinds = [k for k, n in ((CRLF, crlf), (LF, lf), (CR, cr)) if n]
|
|
23
|
+
if not kinds:
|
|
24
|
+
return NONE
|
|
25
|
+
return kinds[0] if len(kinds) == 1 else MIXED
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def to_doc(text: str, newline: str) -> str:
|
|
29
|
+
"""File text -> ``doc.text``: uniform breaks become ``\\n``; mixed/none stay as they are."""
|
|
30
|
+
if newline == CRLF:
|
|
31
|
+
return text.replace(CRLF, LF)
|
|
32
|
+
if newline == CR:
|
|
33
|
+
return text.replace(CR, LF)
|
|
34
|
+
return text
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def to_file(text: str, newline: str) -> str:
|
|
38
|
+
"""``doc.text`` -> file text.
|
|
39
|
+
|
|
40
|
+
For a uniform shape every break the caller wrote (``\\r\\n``, ``\\n`` or ``\\r``) becomes the
|
|
41
|
+
file's break, so the file stays uniform. For mixed/none the text is written unchanged.
|
|
42
|
+
"""
|
|
43
|
+
if newline in (CRLF, LF, CR):
|
|
44
|
+
if CR in text:
|
|
45
|
+
text = text.replace(CRLF, LF).replace(CR, LF)
|
|
46
|
+
return text if newline == LF else text.replace(LF, newline)
|
|
47
|
+
return text
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def line_count(text: str) -> int:
|
|
51
|
+
"""Lines as an editor shows them; a final line break does not start a new line."""
|
|
52
|
+
if not text:
|
|
53
|
+
return 0
|
|
54
|
+
breaks = sum(count(text))
|
|
55
|
+
return breaks if text.endswith((LF, CR)) else breaks + 1
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def locate(text: str, index: int) -> tuple[int, int]:
|
|
59
|
+
"""1-based (line, column) of ``text[index]``; the column counts code points."""
|
|
60
|
+
head = text[:index]
|
|
61
|
+
line = sum(count(head)) + 1
|
|
62
|
+
start = max(head.rfind(LF), head.rfind(CR)) + 1
|
|
63
|
+
return line, index - start + 1
|
textkeep/py.typed
ADDED
|
File without changes
|
textkeep/replace.py
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
# 同じフォルダの一時ファイルに書いてから置き換える。Windows は ReplaceFileW(ctypes)で
|
|
2
|
+
# 属性・ACL・代替データストリームを引き継ぎ、それ以外は mode を写してから os.replace。
|
|
3
|
+
# どの失敗でも元のファイルを途中まで書いた状態で残さず、一時ファイルは消す(INV-2・INV-3)。
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import hashlib
|
|
7
|
+
import os
|
|
8
|
+
import stat
|
|
9
|
+
import sys
|
|
10
|
+
import tempfile
|
|
11
|
+
import time
|
|
12
|
+
from collections.abc import Callable
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import BinaryIO, TypeVar
|
|
15
|
+
|
|
16
|
+
from . import lock
|
|
17
|
+
from .errors import (
|
|
18
|
+
ChangedOnDiskError,
|
|
19
|
+
CleanupError,
|
|
20
|
+
FileLockedError,
|
|
21
|
+
ReadOnlyError,
|
|
22
|
+
WriteError,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
TEMP_PREFIX = ".textkeep-"
|
|
26
|
+
TEMP_SUFFIX = ".tmp"
|
|
27
|
+
BACKUP_SUFFIX = ".bak"
|
|
28
|
+
|
|
29
|
+
ERROR_UNABLE_TO_REMOVE_REPLACED = 1175
|
|
30
|
+
ERROR_UNABLE_TO_MOVE_REPLACEMENT = 1176
|
|
31
|
+
ERROR_UNABLE_TO_MOVE_REPLACEMENT_2 = 1177
|
|
32
|
+
|
|
33
|
+
if sys.platform == "win32":
|
|
34
|
+
import ctypes
|
|
35
|
+
from ctypes import wintypes
|
|
36
|
+
|
|
37
|
+
_kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
38
|
+
_ReplaceFileW = _kernel32.ReplaceFileW
|
|
39
|
+
_ReplaceFileW.argtypes = [
|
|
40
|
+
wintypes.LPCWSTR, # lpReplacedFileName
|
|
41
|
+
wintypes.LPCWSTR, # lpReplacementFileName
|
|
42
|
+
wintypes.LPCWSTR, # lpBackupFileName
|
|
43
|
+
wintypes.DWORD, # dwReplaceFlags
|
|
44
|
+
wintypes.LPVOID, # lpExclude
|
|
45
|
+
wintypes.LPVOID, # lpReserved
|
|
46
|
+
]
|
|
47
|
+
_ReplaceFileW.restype = wintypes.BOOL
|
|
48
|
+
|
|
49
|
+
def replace_file(target: str, replacement: str, backup: str) -> int:
|
|
50
|
+
"""Call ReplaceFileW with no flags (merge errors are errors, so the ACL is never
|
|
51
|
+
dropped). Returns 0 on success, else the Windows error code."""
|
|
52
|
+
if _ReplaceFileW(target, replacement, backup, 0, None, None):
|
|
53
|
+
return 0
|
|
54
|
+
return ctypes.get_last_error()
|
|
55
|
+
|
|
56
|
+
def error_text(code: int) -> str:
|
|
57
|
+
return ctypes.FormatError(code).strip()
|
|
58
|
+
|
|
59
|
+
import msvcrt
|
|
60
|
+
|
|
61
|
+
_CreateFileW = _kernel32.CreateFileW
|
|
62
|
+
_CreateFileW.argtypes = [
|
|
63
|
+
wintypes.LPCWSTR, # lpFileName
|
|
64
|
+
wintypes.DWORD, # dwDesiredAccess
|
|
65
|
+
wintypes.DWORD, # dwShareMode
|
|
66
|
+
wintypes.LPVOID, # lpSecurityAttributes
|
|
67
|
+
wintypes.DWORD, # dwCreationDisposition
|
|
68
|
+
wintypes.DWORD, # dwFlagsAndAttributes
|
|
69
|
+
wintypes.HANDLE, # hTemplateFile
|
|
70
|
+
]
|
|
71
|
+
_CreateFileW.restype = wintypes.HANDLE
|
|
72
|
+
_CloseHandle = _kernel32.CloseHandle
|
|
73
|
+
_CloseHandle.argtypes = [wintypes.HANDLE]
|
|
74
|
+
_CloseHandle.restype = wintypes.BOOL
|
|
75
|
+
_INVALID_HANDLE = wintypes.HANDLE(-1).value
|
|
76
|
+
|
|
77
|
+
def open_read(path: str) -> BinaryIO:
|
|
78
|
+
"""Open for reading, sharing everything. Unlike ``open()`` (whose C runtime turns a
|
|
79
|
+
sharing violation into a bare EACCES), the OSError carries ``winerror`` (32 = locked)."""
|
|
80
|
+
handle = _CreateFileW(path, 0x80000000, 0x7, None, 3, 0x80, None) # GENERIC_READ,
|
|
81
|
+
if handle is None or handle == _INVALID_HANDLE: # share all, OPEN_EXISTING, NORMAL
|
|
82
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
83
|
+
try:
|
|
84
|
+
fd = msvcrt.open_osfhandle(handle, os.O_RDONLY | os.O_BINARY)
|
|
85
|
+
except OSError:
|
|
86
|
+
_CloseHandle(handle)
|
|
87
|
+
raise
|
|
88
|
+
return os.fdopen(fd, "rb")
|
|
89
|
+
|
|
90
|
+
else:
|
|
91
|
+
|
|
92
|
+
def open_read(path: str) -> BinaryIO:
|
|
93
|
+
return open(path, "rb")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def resolve(path: str | os.PathLike[str]) -> str:
|
|
97
|
+
"""Absolute path of the real file: symbolic links and junctions are followed (FR-10).
|
|
98
|
+
|
|
99
|
+
On Windows the result carries the ``\\\\?\\`` prefix so paths over 260 characters work
|
|
100
|
+
whether or not long paths are enabled on the machine.
|
|
101
|
+
"""
|
|
102
|
+
real = os.path.realpath(os.fspath(path))
|
|
103
|
+
if sys.platform == "win32" and not real.startswith("\\\\?\\"):
|
|
104
|
+
real = "\\\\?\\UNC\\" + real[2:] if real.startswith("\\\\") else "\\\\?\\" + real
|
|
105
|
+
return real
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def sha256_file(path: str) -> str:
|
|
109
|
+
h = hashlib.sha256()
|
|
110
|
+
with open_read(path) as f:
|
|
111
|
+
while chunk := f.read(1 << 20):
|
|
112
|
+
h.update(chunk)
|
|
113
|
+
return h.hexdigest()
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def check_writable(target: str, st: os.stat_result, display: str) -> None:
|
|
117
|
+
"""ReadOnlyError for a read-only file. The attribute / mode is never changed (INV-5)."""
|
|
118
|
+
if sys.platform == "win32":
|
|
119
|
+
if st.st_file_attributes & stat.FILE_ATTRIBUTE_READONLY:
|
|
120
|
+
raise ReadOnlyError(f"{display} has the read-only attribute", path=display)
|
|
121
|
+
elif not os.access(target, os.W_OK):
|
|
122
|
+
raise ReadOnlyError(f"{display} is not writable by this user", path=display)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def write_file(
|
|
126
|
+
target: str,
|
|
127
|
+
data: bytes,
|
|
128
|
+
*,
|
|
129
|
+
expect_sha256: str | None,
|
|
130
|
+
retries: int,
|
|
131
|
+
backoff: float,
|
|
132
|
+
display: str,
|
|
133
|
+
) -> None:
|
|
134
|
+
"""Replace ``target`` (an already resolved path) with ``data`` through a temporary file."""
|
|
135
|
+
st = os.stat(target)
|
|
136
|
+
if not stat.S_ISREG(st.st_mode):
|
|
137
|
+
raise WriteError(f"{display} is not a regular file", path=display)
|
|
138
|
+
check_writable(target, st, display)
|
|
139
|
+
folder = os.path.dirname(target)
|
|
140
|
+
try:
|
|
141
|
+
fd, tmp = tempfile.mkstemp(prefix=TEMP_PREFIX, suffix=TEMP_SUFFIX, dir=folder)
|
|
142
|
+
except OSError as e:
|
|
143
|
+
raise WriteError(
|
|
144
|
+
f"cannot create a temporary file in {lock.plain_path(folder)}: {e}", path=display
|
|
145
|
+
) from e
|
|
146
|
+
try:
|
|
147
|
+
try:
|
|
148
|
+
with os.fdopen(fd, "wb") as f:
|
|
149
|
+
if sys.platform != "win32":
|
|
150
|
+
os.fchmod(f.fileno(), stat.S_IMODE(st.st_mode))
|
|
151
|
+
f.write(data)
|
|
152
|
+
f.flush()
|
|
153
|
+
os.fsync(f.fileno())
|
|
154
|
+
except OSError as e:
|
|
155
|
+
raise WriteError(
|
|
156
|
+
f"could not write the temporary file {lock.plain_path(tmp)}: {e}; "
|
|
157
|
+
f"{display} was not changed",
|
|
158
|
+
path=display,
|
|
159
|
+
) from e
|
|
160
|
+
if sys.platform != "win32":
|
|
161
|
+
_check_expected(sha256_file(target), expect_sha256, display)
|
|
162
|
+
_swap_posix(target, tmp, display)
|
|
163
|
+
except BaseException as exc:
|
|
164
|
+
_discard_temp(tmp, exc, display)
|
|
165
|
+
raise
|
|
166
|
+
if sys.platform == "win32": # from here on the swap owns the temporary file
|
|
167
|
+
_swap_windows(target, tmp, data, expect_sha256, retries, backoff, display)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _check_expected(current: str, expect_sha256: str | None, display: str) -> None:
|
|
171
|
+
if expect_sha256 is not None and current != expect_sha256.lower():
|
|
172
|
+
raise ChangedOnDiskError(
|
|
173
|
+
f"{display} changed on disk since it was read; nothing was written",
|
|
174
|
+
path=display,
|
|
175
|
+
expected=expect_sha256.lower(),
|
|
176
|
+
actual=current,
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def is_sharing_violation(e: OSError) -> bool:
|
|
181
|
+
return getattr(e, "winerror", None) in lock.RETRYABLE_WINERRORS
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
T = TypeVar("T")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def retrying(action: Callable[[], T], retries: int, backoff: float) -> T:
|
|
188
|
+
"""Run ``action``, retrying sharing violations (Windows error 32) like the swap does."""
|
|
189
|
+
attempts = 0
|
|
190
|
+
while True:
|
|
191
|
+
attempts += 1
|
|
192
|
+
try:
|
|
193
|
+
return action()
|
|
194
|
+
except OSError as e:
|
|
195
|
+
if not is_sharing_violation(e) or attempts > retries:
|
|
196
|
+
raise
|
|
197
|
+
time.sleep(backoff)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def read_back(target: str, retries: int, backoff: float) -> bytes:
|
|
201
|
+
"""Read the whole file, riding out sharing violations like the swap does (Windows)."""
|
|
202
|
+
|
|
203
|
+
def read() -> bytes:
|
|
204
|
+
with open_read(target) as f:
|
|
205
|
+
return f.read()
|
|
206
|
+
|
|
207
|
+
return retrying(read, retries, backoff)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _discard_temp(tmp: str, exc: BaseException, display: str) -> None:
|
|
211
|
+
try:
|
|
212
|
+
os.remove(tmp)
|
|
213
|
+
except FileNotFoundError:
|
|
214
|
+
pass
|
|
215
|
+
except OSError as e:
|
|
216
|
+
message = (
|
|
217
|
+
f"the temporary file {lock.plain_path(tmp)} could not be removed ({e}); "
|
|
218
|
+
f"{display} itself was not changed"
|
|
219
|
+
)
|
|
220
|
+
if not isinstance(exc, Exception): # never turn Ctrl+C into another error
|
|
221
|
+
_note(exc, message)
|
|
222
|
+
return
|
|
223
|
+
raise CleanupError(
|
|
224
|
+
f"{exc}; in addition {message}",
|
|
225
|
+
path=display,
|
|
226
|
+
written=False,
|
|
227
|
+
leftovers=(lock.plain_path(tmp),),
|
|
228
|
+
) from exc
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _note(exc: BaseException, message: str) -> None:
|
|
232
|
+
"""Attach a note to an exception we must not replace (Ctrl+C, SystemExit)."""
|
|
233
|
+
if hasattr(exc, "add_note"): # Python 3.11+
|
|
234
|
+
exc.add_note(f"textkeep: {message}")
|
|
235
|
+
else: # pragma: no cover - Python 3.10 keeps the list but does not print it
|
|
236
|
+
notes = getattr(exc, "__notes__", None)
|
|
237
|
+
if not isinstance(notes, list):
|
|
238
|
+
notes = []
|
|
239
|
+
exc.__notes__ = notes # type: ignore[attr-defined]
|
|
240
|
+
notes.append(f"textkeep: {message}")
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _swap_posix(target: str, tmp: str, display: str) -> None:
|
|
244
|
+
try:
|
|
245
|
+
os.replace(tmp, target)
|
|
246
|
+
except OSError as e:
|
|
247
|
+
raise WriteError(f"could not replace {display}: {e}", path=display) from e
|
|
248
|
+
try: # make the rename durable; not every file system allows fsync on a directory
|
|
249
|
+
dfd = os.open(os.path.dirname(target), os.O_RDONLY)
|
|
250
|
+
except OSError:
|
|
251
|
+
return
|
|
252
|
+
try:
|
|
253
|
+
os.fsync(dfd)
|
|
254
|
+
except OSError:
|
|
255
|
+
pass
|
|
256
|
+
finally:
|
|
257
|
+
os.close(dfd)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
@dataclass(frozen=True)
|
|
261
|
+
class _Outcome:
|
|
262
|
+
"""What is on disk after a swap attempt, once the safe clean-up has been done."""
|
|
263
|
+
|
|
264
|
+
kind: str # swapped / unchanged / restored / other_change / lost / unknown
|
|
265
|
+
message: str
|
|
266
|
+
leftovers: tuple[str, ...] = ()
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _drop(path: str, retries: int, backoff: float) -> tuple[str, ...]:
|
|
270
|
+
"""Remove a file we know is redundant; return its name if that fails."""
|
|
271
|
+
try:
|
|
272
|
+
retrying(lambda: os.remove(path), retries, backoff)
|
|
273
|
+
except FileNotFoundError:
|
|
274
|
+
pass
|
|
275
|
+
except OSError:
|
|
276
|
+
return (lock.plain_path(path),)
|
|
277
|
+
return ()
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def settle(
|
|
281
|
+
target: str,
|
|
282
|
+
tmp: str,
|
|
283
|
+
backup: str,
|
|
284
|
+
data: bytes,
|
|
285
|
+
expect_sha256: str | None,
|
|
286
|
+
*,
|
|
287
|
+
finish: bool,
|
|
288
|
+
retries: int,
|
|
289
|
+
backoff: float,
|
|
290
|
+
display: str,
|
|
291
|
+
) -> _Outcome:
|
|
292
|
+
"""Look at what really has which name, and clean up only what is provably redundant.
|
|
293
|
+
|
|
294
|
+
The decision never relies on the error code alone: it checks whether the target, the
|
|
295
|
+
temporary file and the backup exist. ``finish`` is true only after ReplaceFileW reported
|
|
296
|
+
success; otherwise the previous content is kept and named rather than deleted.
|
|
297
|
+
"""
|
|
298
|
+
p = lock.plain_path
|
|
299
|
+
has_target, has_tmp, has_backup = (os.path.lexists(x) for x in (target, tmp, backup))
|
|
300
|
+
left: tuple[str, ...]
|
|
301
|
+
if not has_target:
|
|
302
|
+
if has_backup: # the original was moved to the backup name: put it back
|
|
303
|
+
try:
|
|
304
|
+
os.rename(backup, target)
|
|
305
|
+
except OSError as e:
|
|
306
|
+
left = (p(backup), p(tmp)) if has_tmp else (p(backup),)
|
|
307
|
+
new = f" and the new content in {p(tmp)}" if has_tmp else ""
|
|
308
|
+
return _Outcome(
|
|
309
|
+
"lost",
|
|
310
|
+
f"the name {display} is now empty: its previous content is in {p(backup)}"
|
|
311
|
+
f"{new} (moving it back failed: {e})",
|
|
312
|
+
left,
|
|
313
|
+
)
|
|
314
|
+
left = _drop(tmp, retries, backoff) if has_tmp else ()
|
|
315
|
+
return _Outcome("restored", f"{display} was restored", left)
|
|
316
|
+
if has_tmp:
|
|
317
|
+
return _Outcome(
|
|
318
|
+
"lost",
|
|
319
|
+
f"the name {display} is now empty and the only copy left is the new content "
|
|
320
|
+
f"in {p(tmp)}",
|
|
321
|
+
(p(tmp),),
|
|
322
|
+
)
|
|
323
|
+
return _Outcome("lost", f"{display} and textkeep's temporary files are all missing")
|
|
324
|
+
if has_tmp and has_backup: # not a documented state: we cannot tell what has the name
|
|
325
|
+
return _Outcome(
|
|
326
|
+
"unknown",
|
|
327
|
+
f"{display} exists, but a file also has the backup name {p(backup)} (possibly its "
|
|
328
|
+
f"previous content) and the new content is still in {p(tmp)}; both were kept",
|
|
329
|
+
(p(backup), p(tmp)),
|
|
330
|
+
)
|
|
331
|
+
if has_tmp: # the swap did not happen; the temporary file is ours and redundant
|
|
332
|
+
left = _drop(tmp, retries, backoff)
|
|
333
|
+
kept = f"; left behind: {', '.join(left)}" if left else ""
|
|
334
|
+
return _Outcome("unchanged", f"{display} was not changed{kept}", left)
|
|
335
|
+
# The swap happened: the new content has the name, the previous file is the backup.
|
|
336
|
+
if not has_backup:
|
|
337
|
+
return _Outcome("swapped", "")
|
|
338
|
+
if not finish:
|
|
339
|
+
return _Outcome(
|
|
340
|
+
"swapped",
|
|
341
|
+
f"{display} has the new content; its previous content is kept in {p(backup)}",
|
|
342
|
+
(p(backup),),
|
|
343
|
+
)
|
|
344
|
+
if expect_sha256 is not None:
|
|
345
|
+
try:
|
|
346
|
+
previous = retrying(lambda: sha256_file(backup), retries, backoff)
|
|
347
|
+
except OSError as e:
|
|
348
|
+
return _Outcome(
|
|
349
|
+
"swapped",
|
|
350
|
+
f"{display} was written, but its previous content in {p(backup)} could not be "
|
|
351
|
+
f"checked ({e}) and was kept",
|
|
352
|
+
(p(backup),),
|
|
353
|
+
)
|
|
354
|
+
if previous != expect_sha256.lower():
|
|
355
|
+
# Another process changed the file between the hash check and the swap. Its
|
|
356
|
+
# version is the backup (the same file object, ACL and streams): put it back.
|
|
357
|
+
try:
|
|
358
|
+
retrying(lambda: os.replace(backup, target), retries, backoff)
|
|
359
|
+
except OSError as e:
|
|
360
|
+
return _Outcome(
|
|
361
|
+
"other_change",
|
|
362
|
+
f"another process changed {display} just before the swap; its version is "
|
|
363
|
+
f"in {p(backup)} and could not be moved back ({e}), so {display} has "
|
|
364
|
+
f"textkeep's new content",
|
|
365
|
+
(p(backup),),
|
|
366
|
+
)
|
|
367
|
+
return _Outcome(
|
|
368
|
+
"other_change",
|
|
369
|
+
f"another process changed {display} just before the swap; its version was "
|
|
370
|
+
f"put back and nothing was written",
|
|
371
|
+
)
|
|
372
|
+
try:
|
|
373
|
+
retrying(lambda: os.remove(backup), retries, backoff)
|
|
374
|
+
except OSError as e:
|
|
375
|
+
return _Outcome(
|
|
376
|
+
"swapped",
|
|
377
|
+
f"{display} was written, but its previous content is left in {p(backup)} and "
|
|
378
|
+
f"could not be removed ({e})",
|
|
379
|
+
(p(backup),),
|
|
380
|
+
)
|
|
381
|
+
return _Outcome("swapped", "")
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
if sys.platform == "win32":
|
|
385
|
+
|
|
386
|
+
def _swap_windows(
|
|
387
|
+
target: str,
|
|
388
|
+
tmp: str,
|
|
389
|
+
data: bytes,
|
|
390
|
+
expect_sha256: str | None,
|
|
391
|
+
retries: int,
|
|
392
|
+
backoff: float,
|
|
393
|
+
display: str,
|
|
394
|
+
) -> None:
|
|
395
|
+
# A backup name makes every documented failure state known: without one,
|
|
396
|
+
# 1176 deletes the original and 1177 moves it to a name we cannot learn.
|
|
397
|
+
backup = tmp + BACKUP_SUFFIX
|
|
398
|
+
attempts = 0
|
|
399
|
+
|
|
400
|
+
def outcome(finish: bool) -> _Outcome:
|
|
401
|
+
return settle(
|
|
402
|
+
target,
|
|
403
|
+
tmp,
|
|
404
|
+
backup,
|
|
405
|
+
data,
|
|
406
|
+
expect_sha256,
|
|
407
|
+
finish=finish,
|
|
408
|
+
retries=retries,
|
|
409
|
+
backoff=backoff,
|
|
410
|
+
display=display,
|
|
411
|
+
)
|
|
412
|
+
|
|
413
|
+
try:
|
|
414
|
+
while True:
|
|
415
|
+
attempts += 1
|
|
416
|
+
# Hash right before the swap. A holder that denies reading (share mode 0)
|
|
417
|
+
# makes this fail with the same error 32 as the swap, so it is retried alike.
|
|
418
|
+
try:
|
|
419
|
+
before = sha256_file(target)
|
|
420
|
+
except OSError as e:
|
|
421
|
+
if not is_sharing_violation(e):
|
|
422
|
+
raise
|
|
423
|
+
err = lock.ERROR_SHARING_VIOLATION
|
|
424
|
+
else:
|
|
425
|
+
_check_expected(before, expect_sha256, display)
|
|
426
|
+
err = replace_file(target, tmp, backup)
|
|
427
|
+
if err == 0:
|
|
428
|
+
break
|
|
429
|
+
untouched = (
|
|
430
|
+
os.path.lexists(target) and os.path.lexists(tmp) and not os.path.lexists(backup)
|
|
431
|
+
)
|
|
432
|
+
if err in lock.RETRYABLE_WINERRORS and attempts <= retries and untouched:
|
|
433
|
+
time.sleep(backoff)
|
|
434
|
+
continue
|
|
435
|
+
break
|
|
436
|
+
except BaseException as exc: # includes Ctrl+C right before or after the call
|
|
437
|
+
out = outcome(finish=False)
|
|
438
|
+
if out.leftovers and isinstance(exc, Exception):
|
|
439
|
+
raise CleanupError(
|
|
440
|
+
f"{exc}; in addition {out.message}",
|
|
441
|
+
path=display,
|
|
442
|
+
written=out.kind == "swapped",
|
|
443
|
+
leftovers=out.leftovers,
|
|
444
|
+
) from exc
|
|
445
|
+
if out.message and out.kind != "unchanged":
|
|
446
|
+
_note(exc, out.message)
|
|
447
|
+
raise
|
|
448
|
+
|
|
449
|
+
if err == 0:
|
|
450
|
+
out = outcome(finish=True)
|
|
451
|
+
if out.kind == "other_change" and not out.leftovers:
|
|
452
|
+
raise ChangedOnDiskError(
|
|
453
|
+
out.message,
|
|
454
|
+
path=display,
|
|
455
|
+
expected=(expect_sha256 or "").lower(),
|
|
456
|
+
actual=_hash_or_empty(target),
|
|
457
|
+
)
|
|
458
|
+
if out.kind == "other_change": # the other version could not be put back
|
|
459
|
+
raise CleanupError(out.message, path=display, written=True, leftovers=out.leftovers)
|
|
460
|
+
if out.kind != "swapped": # reported success, yet the state says otherwise
|
|
461
|
+
raise WriteError(
|
|
462
|
+
f"ReplaceFileW reported success, but {out.message}",
|
|
463
|
+
path=display,
|
|
464
|
+
winerror=0,
|
|
465
|
+
leftovers=out.leftovers,
|
|
466
|
+
)
|
|
467
|
+
if out.leftovers:
|
|
468
|
+
raise CleanupError(out.message, path=display, written=True, leftovers=out.leftovers)
|
|
469
|
+
return
|
|
470
|
+
|
|
471
|
+
out = outcome(finish=False)
|
|
472
|
+
if err in lock.RETRYABLE_WINERRORS and out.kind == "unchanged" and not out.leftovers:
|
|
473
|
+
processes = lock.locking_processes(target)
|
|
474
|
+
names = ", ".join(f"{p.name} (pid {p.pid})" for p in processes)
|
|
475
|
+
raise FileLockedError(
|
|
476
|
+
f"{display} is in use by another process"
|
|
477
|
+
+ (f": {names}" if names else "")
|
|
478
|
+
+ f" (Windows error {err} after {attempts} attempts)",
|
|
479
|
+
path=display,
|
|
480
|
+
winerror=err,
|
|
481
|
+
attempts=attempts,
|
|
482
|
+
processes=processes,
|
|
483
|
+
)
|
|
484
|
+
left = f"; left behind: {', '.join(out.leftovers)}" if out.leftovers else ""
|
|
485
|
+
raise WriteError(
|
|
486
|
+
f"ReplaceFileW failed with Windows error {err} ({error_text(err)}); "
|
|
487
|
+
f"{out.message}{left}",
|
|
488
|
+
path=display,
|
|
489
|
+
winerror=err,
|
|
490
|
+
leftovers=out.leftovers,
|
|
491
|
+
)
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def _hash_or_empty(path: str) -> str:
|
|
495
|
+
try:
|
|
496
|
+
return sha256_file(path)
|
|
497
|
+
except OSError:
|
|
498
|
+
return ""
|