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/shape.py ADDED
@@ -0,0 +1,197 @@
1
+ # Shape(文字コード・BOM・改行・末尾の改行)と、バイト列から Shape を決める detect()。
2
+ # 推定はしない: BOM → UTF-8 の厳密な復号 → 利用者が許した候補、の順(D-2)。
3
+ # detect は serialize(書く時と同じ関数)で符号化し直し、元のバイトと一致する時だけ読める(INV-1)。
4
+ from __future__ import annotations
5
+
6
+ import re
7
+ from dataclasses import dataclass
8
+
9
+ from . import codec, newline
10
+ from .errors import (
11
+ AmbiguousEncodingError,
12
+ BinaryFileError,
13
+ RoundTripError,
14
+ UnencodableError,
15
+ UnknownEncodingError,
16
+ )
17
+
18
+ BOMS = {
19
+ "utf-8": b"\xef\xbb\xbf",
20
+ "utf-16-le": b"\xff\xfe",
21
+ "utf-16-be": b"\xfe\xff",
22
+ }
23
+ _UTF32_BOMS = (b"\xff\xfe\x00\x00", b"\x00\x00\xfe\xff")
24
+
25
+ # SjisKeep D-4: a legacy Japanese candidate must decode to at least one hiragana, katakana or
26
+ # CJK ideograph. Half-width katakana is deliberately not counted: cp1252 bytes 0xA1-0xDF decode
27
+ # to it as single bytes, so counting it would let Western text pass as cp932.
28
+ JAPANESE_ENCODINGS = frozenset(
29
+ {
30
+ "cp932",
31
+ "shift_jis",
32
+ "shift_jis_2004",
33
+ "shift_jisx0213",
34
+ "euc_jp",
35
+ "euc_jis_2004",
36
+ "euc_jisx0213",
37
+ "iso2022_jp",
38
+ "iso2022_jp_1",
39
+ "iso2022_jp_2",
40
+ "iso2022_jp_2004",
41
+ "iso2022_jp_3",
42
+ "iso2022_jp_ext",
43
+ }
44
+ )
45
+ _KANA_KANJI = re.compile("[ぁ-ゟ゠-ヿ㐀-䶿一-鿿豈-﫿]")
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class Shape:
50
+ """How a text file is stored.
51
+
52
+ ``encoding`` is a canonical Python codec name (``"utf-8"``, ``"utf-16-le"``,
53
+ ``"utf-16-be"``, ``"cp932"`` or a name you allowed). ``newline`` is ``"\\r\\n"``,
54
+ ``"\\n"``, ``"\\r"``, ``"mixed"`` or ``"none"`` (the file has no line break).
55
+ ``final_newline`` is informational: the text decides whether a final break is written.
56
+ """
57
+
58
+ encoding: str
59
+ bom: bool
60
+ newline: str
61
+ final_newline: bool
62
+
63
+ def __post_init__(self) -> None:
64
+ # Only shapes read() can return: otherwise write() would make a file textkeep
65
+ # itself could not read back the same way.
66
+ name = codec.normalize(self.encoding)
67
+ if name in ("utf-16-le", "utf-16-be"):
68
+ if not self.bom:
69
+ raise ValueError(f"{name} is only read with a BOM, so bom must be True")
70
+ elif name != "utf-8":
71
+ codec.check_candidate(name)
72
+ if self.bom:
73
+ raise ValueError(f"a BOM is only defined for {sorted(BOMS)}, not {name!r}")
74
+ if name != self.encoding:
75
+ object.__setattr__(self, "encoding", name)
76
+ if self.newline not in newline.VALUES:
77
+ raise ValueError(f"newline must be one of {newline.VALUES!r}, not {self.newline!r}")
78
+
79
+
80
+ def serialize(text: str, shape: Shape, *, path: str | None = None) -> bytes:
81
+ """``doc.text`` -> file bytes. The single encoder: read() checks itself with it."""
82
+ try:
83
+ body = codec.encode(newline.to_file(text, shape.newline), shape.encoding, path=path)
84
+ except UnencodableError:
85
+ # report positions in the caller's text, not in the newline-converted copy
86
+ raise codec.unencodable_error(text, shape.encoding, path=path) from None
87
+ return (BOMS[shape.encoding] if shape.bom else b"") + body
88
+
89
+
90
+ def detect(
91
+ data: bytes, encodings: tuple[str, ...] = ("cp932",), *, path: str | None = None
92
+ ) -> tuple[Shape, str]:
93
+ """Decide the Shape of ``data`` and return it with ``doc.text``.
94
+
95
+ Raises :class:`BinaryFileError`, :class:`UnknownEncodingError` or its subclass
96
+ :class:`RoundTripError` (the bytes decode, but would not be written back identically).
97
+ """
98
+ if data.startswith(_UTF32_BOMS):
99
+ raise UnknownEncodingError("UTF-32 is not supported", path=path, tried=("utf-32",))
100
+ for name, bom in BOMS.items():
101
+ if data.startswith(bom):
102
+ try:
103
+ text = codec.decode(data[len(bom) :], name)
104
+ except UnicodeDecodeError as e:
105
+ raise UnknownEncodingError(
106
+ f"the file starts with a {name} BOM but is not valid {name} "
107
+ f"(byte offset {len(bom) + e.start})",
108
+ path=path,
109
+ tried=(name,),
110
+ ) from None
111
+ if "\x00" in text:
112
+ offset = len(bom) + len(text[: text.index("\x00")].encode(name))
113
+ raise BinaryFileError("the file contains a NUL character", path=path, offset=offset)
114
+ return _checked(data, text, name, True, path, (name,))
115
+
116
+ nul = data.find(b"\x00")
117
+ if nul >= 0:
118
+ raise BinaryFileError("the file contains a NUL byte", path=path, offset=nul)
119
+
120
+ candidates = [codec.check_candidate(e) for e in encodings]
121
+ try: # UTF-8 is decided first, as before (D-2)
122
+ return _checked(data, codec.decode(data, "utf-8"), "utf-8", False, path, ("utf-8",))
123
+ except UnicodeDecodeError:
124
+ pass
125
+ tried: list[str] = ["utf-8"]
126
+ round_trip: RoundTripError | None = None
127
+ passed: list[tuple[str, Shape, str]] = []
128
+ for name in candidates:
129
+ if name in tried:
130
+ continue
131
+ tried.append(name)
132
+ try:
133
+ text = codec.decode(data, name)
134
+ except UnicodeDecodeError:
135
+ continue
136
+ if name in JAPANESE_ENCODINGS and not _KANA_KANJI.search(text):
137
+ continue
138
+ try:
139
+ passed.append((name, *_checked(data, text, name, False, path, tuple(tried))))
140
+ except RoundTripError as e:
141
+ round_trip = round_trip or e
142
+ if passed:
143
+ # No guessing (INV-4): if two allowed encodings both pass every check but read the
144
+ # bytes as different text, refuse rather than pick by order.
145
+ if any(text != passed[0][2] for _, _, text in passed[1:]):
146
+ names = tuple(name for name, _, _ in passed)
147
+ raise AmbiguousEncodingError(
148
+ f"the file is valid in {', '.join(names)}, and they read it as different text; "
149
+ f"pass only the one it is written in",
150
+ path=path,
151
+ tried=tuple(tried),
152
+ candidates=names,
153
+ )
154
+ return passed[0][1], passed[0][2]
155
+ if round_trip is not None:
156
+ round_trip.tried = tuple(tried)
157
+ raise round_trip
158
+ raise UnknownEncodingError(
159
+ f"not valid in any allowed encoding (tried {', '.join(tried)})",
160
+ path=path,
161
+ tried=tuple(tried),
162
+ )
163
+
164
+
165
+ def _checked(
166
+ data: bytes, text: str, encoding: str, bom: bool, path: str | None, tried: tuple[str, ...]
167
+ ) -> tuple[Shape, str]:
168
+ kind = newline.classify(text)
169
+ shape = Shape(encoding, bom, kind, text.endswith((newline.LF, newline.CR)))
170
+ doc_text = newline.to_doc(text, kind)
171
+ try:
172
+ again = serialize(doc_text, shape, path=path)
173
+ except UnencodableError:
174
+ again = b""
175
+ if again == data:
176
+ return shape, doc_text
177
+ start = len(BOMS[encoding]) if bom else 0
178
+ offset = codec.common_prefix(data, again)
179
+ # The bytes before ``offset`` match, so they decode to the characters before the culprit.
180
+ head = data[start:offset].decode(encoding, errors="ignore")
181
+ index = min(len(head), max(len(text) - 1, 0))
182
+ line, column = newline.locate(text, index)
183
+ char = text[index] if text else ""
184
+ raise RoundTripError(
185
+ f"{encoding}: the character {char!r} at line {line}, column {column} (byte offset "
186
+ f"{offset}) would be written back as different bytes, so the file cannot be edited "
187
+ f"without changing bytes you did not touch",
188
+ path=path,
189
+ tried=tried,
190
+ encoding=encoding,
191
+ offset=offset,
192
+ line=line,
193
+ column=column,
194
+ char=char,
195
+ original=data[offset : offset + 4],
196
+ reencoded=again[offset : offset + 4],
197
+ )
@@ -0,0 +1,276 @@
1
+ Metadata-Version: 2.5
2
+ Name: textkeep
3
+ Version: 0.1.0
4
+ Summary: Edit text files without changing their encoding, BOM, or line endings (CP932-aware, atomic, Windows-safe).
5
+ Project-URL: Homepage, https://github.com/takosasi-dev/textkeep
6
+ Project-URL: Issues, https://github.com/takosasi-dev/textkeep/issues
7
+ Project-URL: Changelog, https://github.com/takosasi-dev/textkeep/blob/main/CHANGELOG.md
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: atomic-write,bom,cp932,crlf,encoding,line-endings,round-trip,shift_jis
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Natural Language :: English
14
+ Classifier: Natural Language :: Japanese
15
+ Classifier: Operating System :: Microsoft :: Windows
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Operating System :: POSIX
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
25
+ Classifier: Programming Language :: Python :: 3.15
26
+ Classifier: Topic :: Text Processing
27
+ Classifier: Typing :: Typed
28
+ Requires-Python: >=3.10
29
+ Provides-Extra: windows
30
+ Requires-Dist: restartmgr>=1.0; (sys_platform == 'win32' and python_version >= '3.12') and extra == 'windows'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # textkeep
34
+
35
+ [![CI](https://github.com/takosasi-dev/textkeep/actions/workflows/ci.yml/badge.svg)](https://github.com/takosasi-dev/textkeep/actions/workflows/ci.yml)
36
+ [![PyPI](https://img.shields.io/pypi/v/textkeep.svg)](https://pypi.org/project/textkeep/)
37
+ [![Python](https://img.shields.io/pypi/pyversions/textkeep.svg)](https://pypi.org/project/textkeep/)
38
+
39
+ Edit text files without changing how they are stored: encoding (including CP932 / Shift_JIS),
40
+ BOM, line endings and the final newline stay as they were. Files are replaced atomically, and on
41
+ Windows the file keeps its attributes, ACL and alternate data streams.
42
+
43
+ [日本語の README](https://github.com/takosasi-dev/textkeep/blob/main/README.ja.md)
44
+
45
+ ## The promise
46
+
47
+ **Read a file, change nothing, write it back: the bytes are identical.**
48
+ Mixed line endings, a BOM, a missing final newline: all of it comes back byte for byte.
49
+ If textkeep cannot keep that promise for a file, it raises an exception instead of writing.
50
+
51
+ ```python
52
+ import textkeep
53
+
54
+ with textkeep.edit("setup.bat") as doc: # CP932, CRLF
55
+ doc.text = doc.text.replace("echo off", "echo on")
56
+ # Only the changed bytes differ. Still CP932, still CRLF, final newline as before.
57
+ ```
58
+
59
+ ## Install
60
+
61
+ ```
62
+ pip install textkeep
63
+ pip install "textkeep[windows]" # optional: name the process that locks a file (Python 3.12+)
64
+ ```
65
+
66
+ Python 3.10 or newer. No dependencies outside the standard library.
67
+
68
+ ## Usage
69
+
70
+ ```python
71
+ import textkeep
72
+
73
+ # Read, change, write back only if something changed.
74
+ with textkeep.edit("data.csv") as doc:
75
+ doc.text = doc.text.replace("Tokyo", "Osaka")
76
+
77
+ # The same in steps.
78
+ doc = textkeep.read("data.csv") # Doc(text, shape, sha256)
79
+ print(doc.shape) # Shape(encoding='cp932', bom=False, newline='\r\n', final_newline=True)
80
+ textkeep.write("data.csv", doc.text.upper(), doc.shape, expect_sha256=doc.sha256)
81
+
82
+ # Name the legacy encoding a file is in (tried after UTF-8). Pass one: short Japanese text in
83
+ # EUC-JP is often valid CP932 too, and textkeep refuses to choose (AmbiguousEncodingError).
84
+ doc = textkeep.read("old.txt", encodings=("euc_jp",))
85
+
86
+ # A character the encoding cannot store stops the write; the file is not touched.
87
+ try:
88
+ with textkeep.edit("data.csv") as doc:
89
+ doc.text += "〜\n" # WAVE DASH, not in CP932
90
+ except textkeep.UnencodableError as e:
91
+ print(e.line, e.column, e.char, e.suggestion) # 1-based; suggestion is "~" (U+FF5E)
92
+
93
+ textkeep.info("data.csv") # encoding, BOM, newline, final newline, lines, bytes, sha256
94
+ ```
95
+
96
+ Command line:
97
+
98
+ ```
99
+ $ textkeep info members.csv
100
+ path: members.csv
101
+ encoding: cp932
102
+ bom: no
103
+ newline: CRLF
104
+ final newline: yes
105
+ lines: 4
106
+ line breaks: CRLF 4, LF 0, CR 0
107
+ bytes: 102
108
+ sha256: be94d2378036194b5c2df7429b65c919e9064ba9ec1095582e9a50306f290cff
109
+ $ textkeep info --json --encodings euc_jp old.txt
110
+ ```
111
+
112
+ `python -m textkeep` works too. Exit codes: 0 read, 1 usage error, 2 cannot read (unknown
113
+ encoding, binary, too large, cannot open).
114
+
115
+ ## How it decides
116
+
117
+ **Encoding: no guessing.**
118
+
119
+ 1. A BOM: UTF-8, UTF-16 LE, UTF-16 BE.
120
+ 2. Strict UTF-8 (so pure ASCII is UTF-8).
121
+ 3. The `encodings` you allow (default `("cp932",)`). Each is checked: strict decoding; a Japanese
122
+ legacy encoding must produce at least one hiragana, katakana or kanji (half-width katakana does
123
+ not count, so Western text in Windows-1252 is not taken for CP932); and the round-trip check
124
+ below. If exactly one passes, or all that pass read the same text, that one is used. **If two
125
+ or more pass but read different text, textkeep picks none and raises
126
+ `AmbiguousEncodingError`** (`.candidates`). For example `"ひらがな\n"` in EUC-JP is also valid
127
+ CP932 (as `、メ、鬢ャ、ハ`): taking the first candidate would be a guess. (The original design,
128
+ D-2 in the specification, took the first candidate in order; this was changed on purpose.)
129
+ 4. Otherwise `UnknownEncodingError`. A NUL byte means `BinaryFileError` (UTF-16 is checked for a
130
+ NUL character instead).
131
+
132
+ The round-trip check: `read()` encodes the decoded text again with exactly the code `write()` uses
133
+ and compares the result with the bytes on disk. If they differ, that encoding fails with
134
+ `RoundTripError` (a subclass of `UnknownEncodingError`) giving the line, column and byte offset.
135
+ The check runs at read time on purpose: with `edit()` you might change line 1, and the write would
136
+ silently change some byte on line 900 that you never touched.
137
+
138
+ 7-bit encodings (ISO-2022-JP and the other `iso2022_*`, UTF-7, HZ) and encodings that are not
139
+ ASCII-compatible or handle a BOM themselves (`utf-16` without a byte order, `utf-32`, `utf-8-sig`)
140
+ are refused as candidates with `ValueError`: a 7-bit file is also valid UTF-8, so it would never
141
+ be read in the encoding you named. A `Shape` accepts only what `read()` can return.
142
+
143
+ **CP932 is written the way Windows writes it.** Python's `cp932` codec puts 373 characters
144
+ (IBM extension kanji such as 髙 and 﨑, small roman numerals ⅰ-ⅹ) into a different byte area than
145
+ Windows does, and silently turns six characters into look-alikes (U+301C 〜 becomes U+FF5E ~).
146
+ textkeep's CP932 gives the same bytes as Windows' `WideCharToMultiByte` for every BMP character
147
+ and refuses the six look-alikes. The one difference: U+F8F0-U+F8F3, which Windows writes as
148
+ `A0`/`FD`/`FE`/`FF` but refuses to read back, are refused in both directions. Details: [docs/cp932-findings.md](https://github.com/takosasi-dev/textkeep/blob/main/docs/cp932-findings.md).
149
+
150
+ **Line endings.** Only `\r\n`, `\n` and `\r` are line breaks (never `\x0b`, `\x0c`, `\x85`,
151
+ U+2028, ...: textkeep does not use `str.splitlines()` or text mode).
152
+
153
+ | File | `doc.text` | When written |
154
+ |---|---|---|
155
+ | CRLF only | `\n` | every break in the text becomes `\r\n` |
156
+ | LF only | `\n` | every break becomes `\n` |
157
+ | CR only | `\n` | every break becomes `\r` |
158
+ | mixed | as in the file | written as is |
159
+ | no break at all (`"none"`) | as in the file | written as is: a `\n` you add stays `\n`, whatever the OS |
160
+
161
+ For a uniform file, breaks you type in any style (`\r\n`, `\n`, `\r`) are written in the file's
162
+ style, so the file stays uniform. **The final newline** is whatever your text ends with;
163
+ `Shape.final_newline` only reports what was read.
164
+
165
+ ## What happens on write
166
+
167
+ 1. The text is encoded first. An unencodable character raises `UnencodableError`; nothing is
168
+ written.
169
+ 2. The file must exist. A read-only file raises `ReadOnlyError` and the attribute is left alone.
170
+ 3. The bytes go to a temporary file (`.textkeep-*.tmp`) in the same folder, flushed and fsynced.
171
+ 4. If `expect_sha256` is given (`edit()` always passes the hash it read), the file is hashed again
172
+ just before the swap; a mismatch raises `ChangedOnDiskError` and the other change stays.
173
+ 5. The temporary file replaces the original: `ReplaceFileW` on Windows, `os.replace` elsewhere.
174
+ Symbolic links and junctions are followed; the link stays a link and the target is rewritten.
175
+ 6. The file is read back and compared with what was written (`VerifyError` if a sync tool changed
176
+ it in between).
177
+
178
+ `edit()` does not write at all when the new text encodes to exactly the bytes it read (re-typing
179
+ CRLF breaks as `\r\n` is not a change), so the modification time stays and sync tools see nothing.
180
+
181
+ When something fails or is interrupted (even by Ctrl+C), textkeep looks at which files really
182
+ have which names before cleaning up, and deletes only what is provably redundant: the original
183
+ is left untouched or put back, and anything it cannot be sure about is kept and named in the
184
+ exception (`.leftovers`, or a note on `KeyboardInterrupt`).
185
+
186
+ On Windows, if another process changes the file in the moment between the hash check and the swap,
187
+ textkeep sees it in the replaced file and puts that version back (`ChangedOnDiskError`).
188
+ On Linux and macOS there is no way to see that, so such a change in that short window is lost
189
+ (a known limit, as with any rename-based tool).
190
+
191
+ ### What is kept
192
+
193
+ | | Windows (`ReplaceFileW`) | Linux / macOS (`os.replace`) |
194
+ |---|---|---|
195
+ | Content you did not change | yes | yes |
196
+ | Hidden and other attributes | yes | - |
197
+ | ACL (DACL, including explicit entries) | yes | no (POSIX ACLs and xattrs are not copied) |
198
+ | Alternate data streams (`Zone.Identifier`) | yes | - |
199
+ | Creation time | yes | - |
200
+ | Permission bits (mode) | - | yes |
201
+ | Hard links | **no**: the edited name becomes a new file | **no** |
202
+
203
+ Measured, not assumed: [docs/replacefile-findings.md](https://github.com/takosasi-dev/textkeep/blob/main/docs/replacefile-findings.md).
204
+
205
+ **Locked files (Windows).** If another program holds the file (or the new temporary file) open
206
+ without delete sharing, `ReplaceFileW` fails with error 32. textkeep retries every `backoff`
207
+ seconds up to `retries` times (defaults 0.1 s and 20, so about 2 s; measured in
208
+ [docs/locking-findings.md](https://github.com/takosasi-dev/textkeep/blob/main/docs/locking-findings.md)),
209
+ then raises `FileLockedError`. With the `windows` extra the error lists the processes
210
+ (`e.processes`, name and PID). Any other `ReplaceFileW` failure, for example on a network share,
211
+ raises `WriteError` with the Windows error number; textkeep never falls back to `os.replace`.
212
+
213
+ **Read-only on POSIX.** If the current user may not write the file (`os.access(path, W_OK)` is
214
+ false), `ReadOnlyError` is raised, even though replacing it through the folder would be possible.
215
+ The mode is never changed. (root passes this check, as with any other tool.)
216
+
217
+ ## What it will not do
218
+
219
+ - Convert between encodings, guess encodings, or use a detection library.
220
+ - Read binary files, UTF-32, or files larger than `max_bytes` (default 64 MiB, `FileTooLargeError`).
221
+ The whole file is read into memory.
222
+ - Use ISO-2022-JP or other 7-bit encodings (UTF-7, HZ): their files are valid UTF-8 too.
223
+ - Round-trip the 398 CP932 byte pairs that have a twin decoding to the same character (the
224
+ NEC-selected IBM extensions 0xED/0xEE, NEC row-13 duplicates 0x8790-0x879C, and 15 IBM
225
+ duplicates). Windows' encoder (`WideCharToMultiByte`) never produces them; files that contain
226
+ them (for example written by Python's own `cp932` codec) raise `RoundTripError`.
227
+ - Preserve hard links, or POSIX ownership, ACLs and extended attributes.
228
+ - Create new files (the file must exist), process folders, watch files, or understand file
229
+ formats (TOML, JSON, CSV).
230
+
231
+ ## Errors
232
+
233
+ All derive from `textkeep.TextKeepError`. Lines and columns are 1-based; columns count code points.
234
+
235
+ | Exception | When |
236
+ |---|---|
237
+ | `UnknownEncodingError` | no allowed encoding decodes the file (`.tried`) |
238
+ | `AmbiguousEncodingError` | two or more allowed encodings pass every check but read different text (`.candidates`) |
239
+ | `RoundTripError` | decodes, but would not be written back identically (`.line`, `.column`, `.offset`, `.char`) |
240
+ | `BinaryFileError` | NUL byte / character (`.offset`) |
241
+ | `FileTooLargeError` | larger than `max_bytes` (`.size`, `.limit`) |
242
+ | `UnencodableError` | a character cannot be stored (`.char`, `.codepoint`, `.line`, `.column`, `.suggestion`, `.count`); also a `ValueError` |
243
+ | `ChangedOnDiskError` | the file's sha256 is not `expect_sha256` (`.expected`, `.actual`) |
244
+ | `ReadOnlyError` | read-only attribute (Windows) / not writable (POSIX) |
245
+ | `FileLockedError` | still locked after the retries (`.winerror`, `.attempts`, `.processes`) |
246
+ | `WriteError` | temporary file or replacement failed; original unchanged or restored (`.winerror`, `.leftovers`) |
247
+ | `VerifyError` | the file read back differs from what was written |
248
+ | `CleanupError` | a temporary file could not be removed (`.leftovers`, `.written`) |
249
+
250
+ A missing file or a permission problem while reading is the usual `OSError`.
251
+
252
+ ## Why
253
+
254
+ Keeping the shape of a file while rewriting it is something many tools do internally: yapf returns
255
+ the encoding and line ending it read, tomlkit and tomlrt keep the style of TOML, Perl has
256
+ File::Edit::Portable. A search of PyPI in November 2026 found no general Python library for it:
257
+ eolnorm normalises line endings (the opposite), bom-open guesses encodings with chardet, and
258
+ atomicwrites (archived) / atomicwriter replace files but do not handle encodings or Windows
259
+ metadata. textkeep is that small missing piece, with CP932 treated as a first-class encoding.
260
+
261
+ ## Development
262
+
263
+ ```
264
+ python -m pip install -e . pytest ruff mypy
265
+ python -m ruff check . && python -m mypy && python -m pytest
266
+ ```
267
+
268
+ The files in `tests/samples/` are self-made samples that mimic real ones (a CP932 `.bat`, an
269
+ Excel-style CSV with IBM-extension kanji written as Windows writes them, a holiday-list CSV in the
270
+ same shape as the Cabinet Office's, a UTF-8-BOM PowerShell script, Markdown, mixed line endings,
271
+ UTF-16, and edge cases). They contain no personal data and are generated by
272
+ `tests/samples_def.py`. They are not files produced by Excel or downloaded from government sites.
273
+
274
+ ## License
275
+
276
+ MIT
@@ -0,0 +1,16 @@
1
+ textkeep/__init__.py,sha256=SYg2kffJ2yDJs4k1jbxVCyvtlmcGv08_cUjvxTFywDE,1314
2
+ textkeep/__main__.py,sha256=TI3pMW0HzExaIpF211R1TqWZiK3hPuCTsmJmfrMgmGM,103
3
+ textkeep/api.py,sha256=Svr4QML5hHw0sYo9k3WThUXpaD69mgYFB5mx9sAtQzA,5998
4
+ textkeep/cli.py,sha256=vD9APQwV9Nm54kewH8Qy6_kAcWqEf8ykO5CwjfxgjuE,3224
5
+ textkeep/codec.py,sha256=GFZwzYePZot8g1Bup7ypMm5xUhV0ZGETJRgVFcWeq4s,7165
6
+ textkeep/errors.py,sha256=OxWNlpec0IGH8T45AlvkgtCMxW1LXCP9HiPNmANLTUM,5851
7
+ textkeep/lock.py,sha256=MYr6WZLEyJUt6uZijlRfrd-O4rEN4al7qaLLUqrAK30,1656
8
+ textkeep/newline.py,sha256=ZCE-e_2b0kfL7s46f7kI0OWhzsPQRkRqPHobP3rCkC4,2111
9
+ textkeep/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ textkeep/replace.py,sha256=zflwIlQqA4XqfdY3VdGPLKKwvLufu28AfSCXQwattpU,18544
11
+ textkeep/shape.py,sha256=ao8Zn0KzftRFisRMF9g7uKUaHKE7G70x1_d2xYpAbc8,7771
12
+ textkeep-0.1.0.dist-info/METADATA,sha256=xg76aBkyn4v-EM6NJ2L313ITAaxP-wMKlNopAiHxhXI,14413
13
+ textkeep-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
14
+ textkeep-0.1.0.dist-info/entry_points.txt,sha256=A0hO2WLrKI98dxXTBX7ZcnzsjcvJbtXV99x6OBI5sGY,47
15
+ textkeep-0.1.0.dist-info/licenses/LICENSE,sha256=TjrbtlXEN0Woqk_uuKMXy6pGizm0TWlfSSVJoLQ_OtI,1069
16
+ textkeep-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ textkeep = textkeep.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 takosasi-dev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.