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 ADDED
@@ -0,0 +1,56 @@
1
+ # 公開 API。ここに並べた物だけを利用者に約束する。
2
+ """Edit text files without changing their encoding, BOM, or line endings.
3
+
4
+ Read a file, change nothing, write it back: the bytes are identical. textkeep never guesses
5
+ an encoding, and on Windows it replaces files with ReplaceFileW so attributes, ACLs and
6
+ alternate data streams survive.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from .api import DEFAULT_ENCODINGS, MAX_BYTES, Doc, edit, info, read, write
12
+ from .errors import (
13
+ AmbiguousEncodingError,
14
+ BinaryFileError,
15
+ ChangedOnDiskError,
16
+ CleanupError,
17
+ FileLockedError,
18
+ FileTooLargeError,
19
+ LockingProcess,
20
+ ReadOnlyError,
21
+ RoundTripError,
22
+ TextKeepError,
23
+ UnencodableError,
24
+ UnknownEncodingError,
25
+ VerifyError,
26
+ WriteError,
27
+ )
28
+ from .shape import Shape
29
+
30
+ __version__ = "0.1.0"
31
+
32
+ __all__ = [
33
+ "DEFAULT_ENCODINGS",
34
+ "MAX_BYTES",
35
+ "AmbiguousEncodingError",
36
+ "BinaryFileError",
37
+ "ChangedOnDiskError",
38
+ "CleanupError",
39
+ "Doc",
40
+ "FileLockedError",
41
+ "FileTooLargeError",
42
+ "LockingProcess",
43
+ "ReadOnlyError",
44
+ "RoundTripError",
45
+ "Shape",
46
+ "TextKeepError",
47
+ "UnencodableError",
48
+ "UnknownEncodingError",
49
+ "VerifyError",
50
+ "WriteError",
51
+ "__version__",
52
+ "edit",
53
+ "info",
54
+ "read",
55
+ "write",
56
+ ]
textkeep/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ # python -m textkeep で CLI を動かす入口。
2
+ import sys
3
+
4
+ from .cli import main
5
+
6
+ sys.exit(main())
textkeep/api.py ADDED
@@ -0,0 +1,168 @@
1
+ # read / write / edit / info を組み立てる。
2
+ # write は「Shape で符号化 → 一時ファイル → 置き換え → 読み直して照合」の順(§2)。
3
+ # edit は本文か Shape が変わった時だけ、開いた時の sha256 を条件に書く(D-4・FR-5)。
4
+ from __future__ import annotations
5
+
6
+ import hashlib
7
+ import os
8
+ from collections.abc import Iterator
9
+ from contextlib import contextmanager
10
+ from dataclasses import dataclass
11
+
12
+ from . import lock, newline, replace
13
+ from .errors import FileTooLargeError, VerifyError
14
+ from .shape import Shape, detect, serialize
15
+
16
+ MAX_BYTES = 64 * 1024 * 1024
17
+ DEFAULT_ENCODINGS: tuple[str, ...] = ("cp932",)
18
+
19
+ PathArg = str | os.PathLike[str]
20
+
21
+
22
+ @dataclass
23
+ class Doc:
24
+ """A decoded text file. Change ``text``; keep ``shape`` unless you mean to change it."""
25
+
26
+ text: str
27
+ shape: Shape
28
+ sha256: str # of the bytes as read
29
+
30
+
31
+ def _read_bytes(target: str, display: str, max_bytes: int) -> bytes:
32
+ with replace.open_read(target) as f:
33
+ size = os.fstat(f.fileno()).st_size
34
+ if size > max_bytes:
35
+ raise FileTooLargeError(
36
+ f"{display} is {size} bytes; the limit is {max_bytes}",
37
+ path=display,
38
+ size=size,
39
+ limit=max_bytes,
40
+ )
41
+ data = f.read(max_bytes + 1)
42
+ if len(data) > max_bytes: # grew while we were reading
43
+ raise FileTooLargeError(
44
+ f"{display} is over the limit of {max_bytes} bytes",
45
+ path=display,
46
+ size=len(data),
47
+ limit=max_bytes,
48
+ )
49
+ return data
50
+
51
+
52
+ def read(
53
+ path: PathArg, encodings: tuple[str, ...] = DEFAULT_ENCODINGS, *, max_bytes: int = MAX_BYTES
54
+ ) -> Doc:
55
+ """Read a text file. Writing ``doc.text`` back unchanged gives the same bytes (INV-1).
56
+
57
+ The encoding is the BOM's, else UTF-8 if the bytes are valid UTF-8, else the first of
58
+ ``encodings`` that decodes strictly. A file whose bytes would not be written back
59
+ identically raises :class:`RoundTripError` here, before anything can be changed.
60
+ """
61
+ display = os.fspath(path)
62
+ if isinstance(encodings, str):
63
+ raise TypeError("encodings must be a tuple of names, e.g. ('cp932',)")
64
+ data = _read_bytes(replace.resolve(path), display, max_bytes)
65
+ shape, text = detect(data, encodings, path=display)
66
+ return Doc(text, shape, hashlib.sha256(data).hexdigest())
67
+
68
+
69
+ def _write(
70
+ path: PathArg,
71
+ data: bytes,
72
+ expect_sha256: str | None,
73
+ retries: int | None,
74
+ backoff: float | None,
75
+ ) -> str:
76
+ display = os.fspath(path)
77
+ retries = lock.DEFAULT_RETRIES if retries is None else retries
78
+ backoff = lock.DEFAULT_BACKOFF if backoff is None else backoff
79
+ if retries < 0 or backoff < 0:
80
+ raise ValueError("retries and backoff must not be negative")
81
+ target = replace.resolve(path)
82
+ replace.write_file(
83
+ target,
84
+ data,
85
+ expect_sha256=expect_sha256,
86
+ retries=retries,
87
+ backoff=backoff,
88
+ display=display,
89
+ )
90
+ try:
91
+ written = replace.read_back(target, retries, backoff)
92
+ except OSError as e:
93
+ raise VerifyError(
94
+ f"{display} was written, but could not be read back to verify it ({e})", path=display
95
+ ) from e
96
+ if written != data:
97
+ raise VerifyError(
98
+ f"{display} does not contain what was just written (another program may have "
99
+ f"changed it right away); the file was left as it is now",
100
+ path=display,
101
+ )
102
+ return hashlib.sha256(data).hexdigest()
103
+
104
+
105
+ def write(
106
+ path: PathArg,
107
+ text: str,
108
+ shape: Shape,
109
+ *,
110
+ expect_sha256: str | None = None,
111
+ retries: int | None = None,
112
+ backoff: float | None = None,
113
+ ) -> None:
114
+ """Write ``text`` in ``shape`` through a temporary file in the same folder.
115
+
116
+ Line breaks: for a uniform shape every break in ``text`` is written as ``shape.newline``;
117
+ for ``"mixed"`` and ``"none"`` the text is written as is. The final line break is whatever
118
+ ``text`` ends with. ``retries``/``backoff`` apply to sharing violations on Windows.
119
+ """
120
+ data = serialize(text, shape, path=os.fspath(path)) # UnencodableError before any I/O
121
+ _write(path, data, expect_sha256, retries, backoff)
122
+
123
+
124
+ @contextmanager
125
+ def edit(
126
+ path: PathArg,
127
+ encodings: tuple[str, ...] = DEFAULT_ENCODINGS,
128
+ *,
129
+ max_bytes: int = MAX_BYTES,
130
+ retries: int | None = None,
131
+ backoff: float | None = None,
132
+ ) -> Iterator[Doc]:
133
+ """Read, let the block change ``doc.text``, and write back only if something changed.
134
+
135
+ Nothing is written if the block raises, or if the text encodes to exactly the bytes
136
+ that were read (D-4): re-typing CRLF breaks as ``\\r\\n``, for example, is not a change.
137
+ The write fails with :class:`ChangedOnDiskError` if the file changed meanwhile (FR-5).
138
+ """
139
+ doc = read(path, encodings, max_bytes=max_bytes)
140
+ before = (doc.text, doc.shape)
141
+ yield doc
142
+ if (doc.text, doc.shape) == before:
143
+ return
144
+ data = serialize(doc.text, doc.shape, path=os.fspath(path))
145
+ if hashlib.sha256(data).hexdigest() != doc.sha256:
146
+ doc.sha256 = _write(path, data, doc.sha256, retries, backoff)
147
+
148
+
149
+ def info(
150
+ path: PathArg, encodings: tuple[str, ...] = DEFAULT_ENCODINGS, *, max_bytes: int = MAX_BYTES
151
+ ) -> dict[str, object]:
152
+ """Shape, line counts, size and sha256 of a file (FR-12)."""
153
+ display = os.fspath(path)
154
+ data = _read_bytes(replace.resolve(path), display, max_bytes)
155
+ shape, text = detect(data, encodings, path=display)
156
+ file_text = newline.to_file(text, shape.newline)
157
+ crlf, lf, cr = newline.count(file_text)
158
+ return {
159
+ "path": display,
160
+ "encoding": shape.encoding,
161
+ "bom": shape.bom,
162
+ "newline": shape.newline,
163
+ "final_newline": shape.final_newline,
164
+ "lines": newline.line_count(file_text),
165
+ "newlines": {"crlf": crlf, "lf": lf, "cr": cr},
166
+ "bytes": len(data),
167
+ "sha256": hashlib.sha256(data).hexdigest(),
168
+ }
textkeep/cli.py ADDED
@@ -0,0 +1,87 @@
1
+ # CLI: textkeep info <ファイル> [--json] [--encodings cp932,euc_jp]。
2
+ # 終了コード 0 = 読めた、1 = 使い方の誤り、2 = 読めない(文字コード・バイナリ・大きすぎ・開けない)。
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from collections.abc import Sequence
9
+ from typing import NoReturn
10
+
11
+ from . import __version__, codec
12
+ from .api import DEFAULT_ENCODINGS, info
13
+ from .errors import TextKeepError
14
+
15
+ EXIT_OK, EXIT_USAGE, EXIT_UNREADABLE = 0, 1, 2
16
+ _NEWLINE_NAMES = {"\r\n": "CRLF", "\n": "LF", "\r": "CR", "mixed": "mixed", "none": "none"}
17
+
18
+
19
+ class _Parser(argparse.ArgumentParser):
20
+ def error(self, message: str) -> NoReturn:
21
+ self.print_usage(sys.stderr)
22
+ self.exit(EXIT_USAGE, f"{self.prog}: error: {message}\n")
23
+
24
+
25
+ def _encodings(value: str) -> tuple[str, ...]:
26
+ names = tuple(n.strip() for n in value.split(",") if n.strip())
27
+ if not names:
28
+ raise argparse.ArgumentTypeError("give at least one encoding")
29
+ for name in names:
30
+ try:
31
+ codec.check_candidate(name)
32
+ except ValueError as e:
33
+ raise argparse.ArgumentTypeError(str(e)) from None
34
+ return names
35
+
36
+
37
+ def _parser() -> _Parser:
38
+ parser = _Parser(prog="textkeep", description="Inspect how a text file is stored.")
39
+ parser.add_argument("--version", action="version", version=f"textkeep {__version__}")
40
+ sub = parser.add_subparsers(dest="command", required=True, parser_class=_Parser)
41
+ p = sub.add_parser("info", help="show encoding, BOM, line endings, lines, size and sha256")
42
+ p.add_argument("file")
43
+ p.add_argument("--json", action="store_true", help="print JSON")
44
+ p.add_argument(
45
+ "--encodings",
46
+ type=_encodings,
47
+ default=DEFAULT_ENCODINGS,
48
+ metavar="NAMES",
49
+ help="comma-separated encodings to try after UTF-8 (default: cp932)",
50
+ )
51
+ return parser
52
+
53
+
54
+ def main(argv: Sequence[str] | None = None) -> int:
55
+ for stream in (sys.stdout, sys.stderr): # never crash on a console that lacks a character
56
+ reconfigure = getattr(stream, "reconfigure", None)
57
+ if reconfigure is not None:
58
+ reconfigure(errors="backslashreplace")
59
+ args = _parser().parse_args(argv)
60
+ try:
61
+ result = info(args.file, args.encodings)
62
+ except (TextKeepError, OSError) as e:
63
+ print(f"textkeep: {e}", file=sys.stderr)
64
+ return EXIT_UNREADABLE
65
+ if args.json:
66
+ print(json.dumps(result, ensure_ascii=True, indent=2))
67
+ return EXIT_OK
68
+ newlines = result["newlines"]
69
+ assert isinstance(newlines, dict)
70
+ rows = [
71
+ ("path", result["path"]),
72
+ ("encoding", result["encoding"]),
73
+ ("bom", "yes" if result["bom"] else "no"),
74
+ ("newline", _NEWLINE_NAMES[str(result["newline"])]),
75
+ ("final newline", "yes" if result["final_newline"] else "no"),
76
+ ("lines", result["lines"]),
77
+ ("line breaks", ", ".join(f"{k.upper()} {v}" for k, v in newlines.items())),
78
+ ("bytes", result["bytes"]),
79
+ ("sha256", result["sha256"]),
80
+ ]
81
+ for key, value in rows:
82
+ print(f"{key + ':':<15}{value}")
83
+ return EXIT_OK
84
+
85
+
86
+ if __name__ == "__main__": # pragma: no cover
87
+ sys.exit(main())
textkeep/codec.py ADDED
@@ -0,0 +1,182 @@
1
+ # 厳密な復号と符号化。「表せる」は「符号化して復号し直すと元の文字に戻る」と定義する。
2
+ # cp932 は Windows(WideCharToMultiByte)と同じ並びで符号化する(IBM 拡張は FA〜FC)。
3
+ # 表せない文字の位置と、§9.5 の候補の字を出す。
4
+ from __future__ import annotations
5
+
6
+ import codecs
7
+ import re
8
+
9
+ from .errors import UnencodableError
10
+ from .newline import locate
11
+
12
+ # §9.5: characters Python's cp932 codec silently turns into a different character, and the
13
+ # character the file will really contain. Kept only where the suggestion survives the codec.
14
+ SUGGESTIONS = {
15
+ "〜": "~", # WAVE DASH -> FULLWIDTH TILDE
16
+ "−": "-", # MINUS SIGN -> FULLWIDTH HYPHEN-MINUS
17
+ "‖": "∥", # DOUBLE VERTICAL LINE -> PARALLEL TO
18
+ "¢": "¢", # CENT SIGN -> FULLWIDTH CENT SIGN
19
+ "£": "£", # POUND SIGN -> FULLWIDTH POUND SIGN
20
+ "¬": "¬", # NOT SIGN -> FULLWIDTH NOT SIGN
21
+ }
22
+
23
+
24
+ def _windows_cp932_overrides() -> dict[str, bytes]:
25
+ """Characters Python encodes into NEC-selected IBM extensions (0xED/0xEE) but Windows
26
+ encodes into the IBM extensions (0xFA-0xFC). Derived from the codec itself."""
27
+ table: dict[str, bytes] = {}
28
+ for lead in (0xFA, 0xFB, 0xFC):
29
+ for trail in range(0x40, 0xFD):
30
+ seq = bytes((lead, trail))
31
+ try:
32
+ char = seq.decode("cp932")
33
+ except UnicodeDecodeError:
34
+ continue
35
+ if char.encode("cp932")[0] in (0xED, 0xEE):
36
+ table[char] = seq
37
+ return table
38
+
39
+
40
+ CP932_OVERRIDES = _windows_cp932_overrides()
41
+ _CP932_PATTERN = re.compile("[" + "".join(map(re.escape, sorted(CP932_OVERRIDES))) + "]")
42
+ _CP932_UNDEFINED = re.compile("[\uf8f0-\uf8f3]")
43
+
44
+
45
+ def normalize(name: str) -> str:
46
+ """Canonical codec name (``"MS932"`` -> ``"cp932"``); ``ValueError`` if Python lacks it."""
47
+ try:
48
+ return codecs.lookup(name).name
49
+ except LookupError:
50
+ raise ValueError(f"unknown encoding: {name!r}") from None
51
+
52
+
53
+ _ASCII_SAMPLE = '\t\n\r !"#09:@AZ[\\]^_`az{|}~'
54
+
55
+
56
+ def check_candidate(name: str) -> str:
57
+ """Canonical name of an encoding allowed as a candidate (and in a BOM-less Shape).
58
+
59
+ ``ValueError`` for an encoding textkeep could never pick (7-bit ones such as ISO-2022-JP:
60
+ their files are also valid UTF-8, which is tried first) or could not round-trip safely
61
+ (not ASCII-compatible, or with BOM handling of its own: UTF-16 without a byte order,
62
+ UTF-32, utf-8-sig).
63
+ """
64
+ enc = normalize(name)
65
+ if enc.startswith("iso2022") or enc in ("utf-7", "hz"):
66
+ raise ValueError(
67
+ f"{enc} is a 7-bit encoding: its files are also valid UTF-8, which textkeep tries "
68
+ f"first, so it would never be used; textkeep does not support it"
69
+ )
70
+ try:
71
+ compatible = _ASCII_SAMPLE.encode(enc) == _ASCII_SAMPLE.encode("ascii")
72
+ except (UnicodeError, LookupError):
73
+ compatible = False
74
+ if not compatible:
75
+ raise ValueError(
76
+ f"{enc} is not ASCII-compatible or adds a BOM of its own; textkeep reads UTF-16 "
77
+ f"only with a BOM and does not support UTF-32"
78
+ )
79
+ return enc
80
+
81
+
82
+ def decode(data: bytes, encoding: str) -> str:
83
+ """Strict decode. Raises ``UnicodeDecodeError``.
84
+
85
+ For cp932 the single bytes 0xA0 and 0xFD-0xFF are refused as Windows refuses them
86
+ (MultiByteToWideChar); Python's codec would read them as U+F8F0-U+F8F3.
87
+ """
88
+ text = data.decode(encoding)
89
+ if encoding == "cp932" and (m := _CP932_UNDEFINED.search(text)):
90
+ offset = len(_raw_encode(text[: m.start()], encoding))
91
+ raise UnicodeDecodeError(
92
+ encoding, data, offset, offset + 1, "byte not defined in Windows code page 932"
93
+ )
94
+ return text
95
+
96
+
97
+ def _raw_encode(text: str, encoding: str) -> bytes:
98
+ if encoding != "cp932" or _CP932_PATTERN.search(text) is None:
99
+ return text.encode(encoding)
100
+ out: list[bytes] = []
101
+ pos = 0
102
+ for m in [*_CP932_PATTERN.finditer(text), None]:
103
+ end = len(text) if m is None else m.start()
104
+ try:
105
+ out.append(text[pos:end].encode(encoding))
106
+ except UnicodeEncodeError as e: # re-anchor the position on the whole text
107
+ raise UnicodeEncodeError(e.encoding, text, pos + e.start, pos + e.end, e.reason) from e
108
+ if m is not None:
109
+ out.append(CP932_OVERRIDES[m.group()])
110
+ pos = m.end()
111
+ return b"".join(out)
112
+
113
+
114
+ def common_prefix(a: str | bytes, b: str | bytes) -> int:
115
+ """Length of the common prefix of two strings (or two byte strings)."""
116
+ lo, hi = 0, min(len(a), len(b))
117
+ while lo < hi: # binary search: slices compare in C, so this stays fast on 64 MiB
118
+ mid = (lo + hi + 1) // 2
119
+ if a[:mid] == b[:mid]:
120
+ lo = mid
121
+ else:
122
+ hi = mid - 1
123
+ return lo
124
+
125
+
126
+ def lossless(char: str, encoding: str) -> bool:
127
+ try:
128
+ return decode(_raw_encode(char, encoding), encoding) == char
129
+ except (UnicodeEncodeError, UnicodeDecodeError):
130
+ return False
131
+
132
+
133
+ def suggest(char: str, encoding: str, read_back: str | None = None) -> str | None:
134
+ for candidate in (SUGGESTIONS.get(char), read_back):
135
+ if candidate and candidate != char and lossless(candidate, encoding):
136
+ return candidate
137
+ return None
138
+
139
+
140
+ def _read_back(char: str, encoding: str) -> str | None:
141
+ try:
142
+ return decode(_raw_encode(char, encoding), encoding)
143
+ except (UnicodeEncodeError, UnicodeDecodeError):
144
+ return None
145
+
146
+
147
+ def encode(text: str, encoding: str, *, path: str | None = None) -> bytes:
148
+ """Strict, lossless encode. Raises :class:`UnencodableError` (positions refer to ``text``)."""
149
+ try:
150
+ data = _raw_encode(text, encoding)
151
+ if decode(data, encoding) == text:
152
+ return data
153
+ except (UnicodeEncodeError, UnicodeDecodeError):
154
+ pass
155
+ raise unencodable_error(text, encoding, path=path)
156
+
157
+
158
+ def unencodable_error(text: str, encoding: str, *, path: str | None = None) -> UnencodableError:
159
+ """Build the error for the first character that does not survive encode -> decode."""
160
+ bad = {c for c in set(text) if not lossless(c, encoding)}
161
+ # Only a stateful codec (iso2022_*) can fail on a text whose characters all pass alone;
162
+ # then the position is unknown and the first character is reported.
163
+ index = min(text.index(c) for c in bad) if bad else 0
164
+ char = text[index] if text else "\x00"
165
+ line, column = locate(text, index)
166
+ total = sum(text.count(c) for c in bad)
167
+ read_back = _read_back(char, encoding)
168
+ suggestion = suggest(char, encoding, read_back[0] if read_back else None)
169
+ hint = f"; did you mean {suggestion!r} (U+{ord(suggestion):04X})?" if suggestion else ""
170
+ more = f" ({total} such characters in total)" if total > 1 else ""
171
+ return UnencodableError(
172
+ f"{char!r} (U+{ord(char):04X}) at line {line}, column {column} cannot be stored "
173
+ f"in {encoding}{hint}{more}",
174
+ path=path,
175
+ encoding=encoding,
176
+ char=char,
177
+ line=line,
178
+ column=column,
179
+ index=index,
180
+ suggestion=suggestion,
181
+ count=max(total, 1),
182
+ )
textkeep/errors.py ADDED
@@ -0,0 +1,199 @@
1
+ # 例外の定義。すべて TextKeepError を基底にする(FR-13)。
2
+ # 行・列は 1 始まり、列はコードポイント単位で数える。
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class LockingProcess:
10
+ """A process that holds the file open (reported by the optional ``restartmgr``)."""
11
+
12
+ name: str
13
+ pid: int
14
+
15
+
16
+ class TextKeepError(Exception):
17
+ """Base class for every error raised by textkeep."""
18
+
19
+ def __init__(self, message: str, *, path: str | None = None) -> None:
20
+ super().__init__(message)
21
+ self.path = path
22
+
23
+
24
+ class UnknownEncodingError(TextKeepError):
25
+ """The bytes are not valid in any allowed encoding (D-2)."""
26
+
27
+ def __init__(
28
+ self, message: str, *, path: str | None = None, tried: tuple[str, ...] = ()
29
+ ) -> None:
30
+ super().__init__(message, path=path)
31
+ self.tried = tried
32
+
33
+
34
+ class AmbiguousEncodingError(UnknownEncodingError):
35
+ """Two or more allowed encodings pass every check but read the file as different text.
36
+
37
+ textkeep does not guess, so it picks none of them. ``candidates`` names those that passed.
38
+ """
39
+
40
+ def __init__(
41
+ self,
42
+ message: str,
43
+ *,
44
+ path: str | None = None,
45
+ tried: tuple[str, ...] = (),
46
+ candidates: tuple[str, ...],
47
+ ) -> None:
48
+ super().__init__(message, path=path, tried=tried)
49
+ self.candidates = candidates
50
+
51
+
52
+ class RoundTripError(UnknownEncodingError):
53
+ """The file decodes, but encoding the text again would not give the same bytes.
54
+
55
+ textkeep refuses to read such a file because writing it back would silently change
56
+ bytes the caller never touched (INV-1). ``line``/``column`` are 1-based.
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ message: str,
62
+ *,
63
+ path: str | None = None,
64
+ tried: tuple[str, ...] = (),
65
+ encoding: str,
66
+ offset: int,
67
+ line: int,
68
+ column: int,
69
+ char: str,
70
+ original: bytes,
71
+ reencoded: bytes,
72
+ ) -> None:
73
+ super().__init__(message, path=path, tried=tried)
74
+ self.encoding = encoding
75
+ self.offset = offset
76
+ self.line = line
77
+ self.column = column
78
+ self.char = char
79
+ self.original = original
80
+ self.reencoded = reencoded
81
+
82
+
83
+ class BinaryFileError(TextKeepError):
84
+ """The file contains a NUL character, so it is treated as binary."""
85
+
86
+ def __init__(self, message: str, *, path: str | None = None, offset: int) -> None:
87
+ super().__init__(message, path=path)
88
+ self.offset = offset
89
+
90
+
91
+ class UnencodableError(TextKeepError, ValueError):
92
+ """A character cannot be stored in the file's encoding (FR-6).
93
+
94
+ ``line``/``column`` are 1-based and refer to the text you passed in (``doc.text``).
95
+ ``suggestion`` is a look-alike character that the encoding can store, or ``None``.
96
+ """
97
+
98
+ def __init__(
99
+ self,
100
+ message: str,
101
+ *,
102
+ path: str | None = None,
103
+ encoding: str,
104
+ char: str,
105
+ line: int,
106
+ column: int,
107
+ index: int,
108
+ suggestion: str | None,
109
+ count: int,
110
+ ) -> None:
111
+ super().__init__(message, path=path)
112
+ self.encoding = encoding
113
+ self.char = char
114
+ self.codepoint = ord(char)
115
+ self.line = line
116
+ self.column = column
117
+ self.index = index
118
+ self.suggestion = suggestion
119
+ self.count = count
120
+
121
+
122
+ class ChangedOnDiskError(TextKeepError):
123
+ """The file on disk no longer has the expected sha256 (FR-4)."""
124
+
125
+ def __init__(
126
+ self, message: str, *, path: str | None = None, expected: str, actual: str
127
+ ) -> None:
128
+ super().__init__(message, path=path)
129
+ self.expected = expected
130
+ self.actual = actual
131
+
132
+
133
+ class FileLockedError(TextKeepError):
134
+ """Another process kept the file open through every retry (D-8)."""
135
+
136
+ def __init__(
137
+ self,
138
+ message: str,
139
+ *,
140
+ path: str | None = None,
141
+ winerror: int,
142
+ attempts: int,
143
+ processes: tuple[LockingProcess, ...] = (),
144
+ ) -> None:
145
+ super().__init__(message, path=path)
146
+ self.winerror = winerror
147
+ self.attempts = attempts
148
+ self.processes = processes
149
+
150
+
151
+ class ReadOnlyError(TextKeepError):
152
+ """The file is read-only; textkeep never clears the attribute (FR-11, INV-5)."""
153
+
154
+
155
+ class VerifyError(TextKeepError):
156
+ """Reading the file back after the write did not give the bytes that were written (D-9)."""
157
+
158
+
159
+ class FileTooLargeError(TextKeepError):
160
+ """The file is larger than ``max_bytes`` (default 64 MiB)."""
161
+
162
+ def __init__(self, message: str, *, path: str | None = None, size: int, limit: int) -> None:
163
+ super().__init__(message, path=path)
164
+ self.size = size
165
+ self.limit = limit
166
+
167
+
168
+ class WriteError(TextKeepError):
169
+ """Creating the temporary file or swapping it in failed; the original file is unchanged.
170
+
171
+ ``winerror`` is the Windows error code when ``ReplaceFileW`` failed, else ``None``.
172
+ ``leftovers`` names files textkeep could not remove (see the message for what they hold).
173
+ """
174
+
175
+ def __init__(
176
+ self,
177
+ message: str,
178
+ *,
179
+ path: str | None = None,
180
+ winerror: int | None = None,
181
+ leftovers: tuple[str, ...] = (),
182
+ ) -> None:
183
+ super().__init__(message, path=path)
184
+ self.winerror = winerror
185
+ self.leftovers = leftovers
186
+
187
+
188
+ class CleanupError(TextKeepError):
189
+ """A temporary file could not be removed (INV-3).
190
+
191
+ ``written`` tells whether the new content did reach the target file.
192
+ """
193
+
194
+ def __init__(
195
+ self, message: str, *, path: str | None = None, written: bool, leftovers: tuple[str, ...]
196
+ ) -> None:
197
+ super().__init__(message, path=path)
198
+ self.written = written
199
+ self.leftovers = leftovers