textkeep 0.1.0__tar.gz

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.
Files changed (48) hide show
  1. textkeep-0.1.0/.gitignore +16 -0
  2. textkeep-0.1.0/CHANGELOG.md +37 -0
  3. textkeep-0.1.0/LICENSE +21 -0
  4. textkeep-0.1.0/PKG-INFO +276 -0
  5. textkeep-0.1.0/README.ja.md +188 -0
  6. textkeep-0.1.0/README.md +244 -0
  7. textkeep-0.1.0/docs/cp932-findings.md +68 -0
  8. textkeep-0.1.0/docs/locking-findings.md +61 -0
  9. textkeep-0.1.0/docs/replacefile-findings.md +127 -0
  10. textkeep-0.1.0/pyproject.toml +68 -0
  11. textkeep-0.1.0/src/textkeep/__init__.py +56 -0
  12. textkeep-0.1.0/src/textkeep/__main__.py +6 -0
  13. textkeep-0.1.0/src/textkeep/api.py +168 -0
  14. textkeep-0.1.0/src/textkeep/cli.py +87 -0
  15. textkeep-0.1.0/src/textkeep/codec.py +182 -0
  16. textkeep-0.1.0/src/textkeep/errors.py +199 -0
  17. textkeep-0.1.0/src/textkeep/lock.py +42 -0
  18. textkeep-0.1.0/src/textkeep/newline.py +63 -0
  19. textkeep-0.1.0/src/textkeep/py.typed +0 -0
  20. textkeep-0.1.0/src/textkeep/replace.py +498 -0
  21. textkeep-0.1.0/src/textkeep/shape.py +197 -0
  22. textkeep-0.1.0/tests/conftest.py +7 -0
  23. textkeep-0.1.0/tests/samples/ascii_crlf.txt +2 -0
  24. textkeep-0.1.0/tests/samples/bom_only.txt +1 -0
  25. textkeep-0.1.0/tests/samples/cp932_no_final.txt +2 -0
  26. textkeep-0.1.0/tests/samples/cr_only.txt +2 -0
  27. textkeep-0.1.0/tests/samples/echo.bat +5 -0
  28. textkeep-0.1.0/tests/samples/empty.txt +0 -0
  29. textkeep-0.1.0/tests/samples/feff_inside.txt +2 -0
  30. textkeep-0.1.0/tests/samples/members.csv +4 -0
  31. textkeep-0.1.0/tests/samples/mixed.txt +4 -0
  32. textkeep-0.1.0/tests/samples/note.md +4 -0
  33. textkeep-0.1.0/tests/samples/one_line.txt +1 -0
  34. textkeep-0.1.0/tests/samples/profile.ps1 +5 -0
  35. textkeep-0.1.0/tests/samples/separators.txt +3 -0
  36. textkeep-0.1.0/tests/samples/syukujitsu.csv +6 -0
  37. textkeep-0.1.0/tests/samples/utf16be.txt +0 -0
  38. textkeep-0.1.0/tests/samples/utf16le.txt +0 -0
  39. textkeep-0.1.0/tests/samples_def.py +127 -0
  40. textkeep-0.1.0/tests/test_api.py +318 -0
  41. textkeep-0.1.0/tests/test_cli.py +68 -0
  42. textkeep-0.1.0/tests/test_codec.py +218 -0
  43. textkeep-0.1.0/tests/test_newline_detect.py +169 -0
  44. textkeep-0.1.0/tests/test_posix.py +67 -0
  45. textkeep-0.1.0/tests/test_review_fixes.py +118 -0
  46. textkeep-0.1.0/tests/test_samples.py +48 -0
  47. textkeep-0.1.0/tests/test_windows.py +410 -0
  48. textkeep-0.1.0/tests/test_windows_recovery.py +200 -0
@@ -0,0 +1,16 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ build/
5
+ dist/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .mypy_cache/
9
+ .ruff_cache/
10
+ .coverage
11
+ htmlcov/
12
+ .DS_Store
13
+ Thumbs.db
14
+ .vscode/
15
+ .idea/
16
+ .tmp-exfat/
@@ -0,0 +1,37 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here.
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0] - 2026-12-03
10
+
11
+ ### Added
12
+
13
+ - `read`, `write`, `edit` and `info`: read a text file, change it, and write it back with the same
14
+ encoding, BOM, line endings and final newline. Unchanged text gives identical bytes.
15
+ - Encoding decided without guessing: BOM, then strict UTF-8, then the allowed `encodings`
16
+ (default `("cp932",)`). Japanese legacy encodings must contain kana or kanji.
17
+ - `AmbiguousEncodingError`: when two or more allowed encodings pass every check but read different
18
+ text, none is chosen. This deliberately departs from the specification's D-2 (first candidate in
19
+ order), because picking by order is a guess (for example EUC-JP text that is also valid CP932).
20
+ - 7-bit encodings (ISO-2022-JP, UTF-7, HZ) and encodings with their own BOM handling or without
21
+ ASCII compatibility are refused as candidates and in `Shape` (`ValueError`).
22
+ - Failure and interruption handling decided by which files really exist under which names; on
23
+ Windows a change made by another process between the hash check and the swap is put back.
24
+ - `edit()` writes nothing when the new text encodes to the bytes that were read.
25
+ - Every `read()` checks that the text encodes back to the same bytes (`RoundTripError` otherwise).
26
+ - CP932 encoded the way Windows does (IBM extensions in 0xFA-0xFC), and the six characters Python's
27
+ codec silently replaces are refused with a suggestion (`UnencodableError`).
28
+ - Atomic replacement through a temporary file in the same folder: `ReplaceFileW` on Windows (keeps
29
+ attributes, ACL, alternate data streams), `os.replace` with the file mode elsewhere.
30
+ - Retries on sharing violations (default 20 x 0.1 s) and `FileLockedError`, naming the locking
31
+ processes when the optional `restartmgr` is installed (`textkeep[windows]`).
32
+ - `expect_sha256` / automatic check in `edit()`, read-back verification, read-only protection,
33
+ symbolic link and junction resolution, long and UNC paths on Windows.
34
+ - Command line: `textkeep info <file> [--json] [--encodings ...]`, also `python -m textkeep`.
35
+
36
+ [Unreleased]: https://github.com/takosasi-dev/textkeep/compare/v0.1.0...HEAD
37
+ [0.1.0]: https://github.com/takosasi-dev/textkeep/releases/tag/v0.1.0
textkeep-0.1.0/LICENSE ADDED
@@ -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.
@@ -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,188 @@
1
+ # textkeep(日本語)
2
+
3
+ [![CI](https://github.com/takosasi-dev/textkeep/actions/workflows/ci.yml/badge.svg)](https://github.com/takosasi-dev/textkeep/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/textkeep.svg)](https://pypi.org/project/textkeep/)
5
+ [![Python](https://img.shields.io/pypi/pyversions/textkeep.svg)](https://pypi.org/project/textkeep/)
6
+
7
+ テキストファイルを「読む → 直す → 書き戻す」とき、文字コード(CP932・Shift_JIS を含む)・BOM・
8
+ 改行・末尾の改行を元のまま保つ Python のライブラリです。置き換えは一時ファイルから一度に行い、
9
+ Windows ではファイルの属性・ACL・代替データストリームも引き継ぎます。
10
+
11
+ [English README](https://github.com/takosasi-dev/textkeep/blob/main/README.md)
12
+
13
+ ## 守る約束
14
+
15
+ **読んで、何も変えずに書けば、バイトが元と完全に一致する。**
16
+ 改行の混在・BOM・末尾の改行が無いことも含めて、そのまま戻ります。
17
+ この約束を守れないファイルは、書かずに例外にします。
18
+
19
+ ```python
20
+ import textkeep
21
+
22
+ with textkeep.edit("setup.bat") as doc: # CP932・CRLF
23
+ doc.text = doc.text.replace("echo off", "echo on")
24
+ # 変えた所のバイトだけが変わる。CP932・CRLF・末尾の改行はそのまま。
25
+ ```
26
+
27
+ ## 入れ方
28
+
29
+ ```
30
+ pip install textkeep
31
+ pip install "textkeep[windows]" # 任意: ロックしているプロセスの名前を出す(Python 3.12 以上)
32
+ ```
33
+
34
+ Python 3.10 以上。標準ライブラリだけで動きます。
35
+
36
+ ## 使い方
37
+
38
+ ```python
39
+ import textkeep
40
+
41
+ with textkeep.edit("data.csv") as doc: # 変わった時だけ書く
42
+ doc.text = doc.text.replace("東京", "大阪")
43
+
44
+ doc = textkeep.read("data.csv") # Doc(text, shape, sha256)
45
+ textkeep.write("data.csv", doc.text, doc.shape, expect_sha256=doc.sha256)
46
+
47
+ # UTF-8 の後に試す古い文字コード。1 つだけ渡す: 短い EUC-JP の文は CP932 としても読めることが多く、
48
+ # 2 つ渡すと textkeep は選ばずに AmbiguousEncodingError にする。
49
+ doc = textkeep.read("old.txt", encodings=("euc_jp",))
50
+
51
+ try:
52
+ with textkeep.edit("data.csv") as doc:
53
+ doc.text += "〜\n" # 波ダッシュは CP932 で表せない
54
+ except textkeep.UnencodableError as e:
55
+ print(e.line, e.column, e.suggestion) # 行・列は 1 始まり。候補は "~"(U+FF5E)
56
+ ```
57
+
58
+ ```
59
+ textkeep info data.csv
60
+ textkeep info --json --encodings euc_jp old.txt
61
+ python -m textkeep info data.csv
62
+ ```
63
+
64
+ 終了コード: 0 = 読めた、1 = 使い方の誤り、2 = 読めない(文字コード・バイナリ・大きすぎ・開けない)。
65
+
66
+ ## 決め方
67
+
68
+ **文字コードは推測しません。** BOM(UTF-8・UTF-16 LE/BE)→ UTF-8 の厳密な復号、の順に決め、
69
+ それでも決まらなければ `encodings`(既定は `("cp932",)`)の候補を全部確かめます。確かめるのは、
70
+ 厳密な復号・日本語の判定(ひらがな・カタカナ・漢字が1字以上。半角カナは数えません。Windows-1252 の
71
+ 英文を CP932 と取り違えないため)・下の往復の照合です。通った候補が1つだけか、通った候補が全部同じ
72
+ 本文を返すなら、それを使います。**2つ以上が通って本文が違えば、どれも選ばず
73
+ `AmbiguousEncodingError`(`.candidates`)にします。** たとえば EUC-JP の「ひらがな\n」は CP932 と
74
+ しても読めて「、メ、鬢ャ、ハ」になります。候補の順で選ぶのは推測です(仕様書 D-2 の「順に最初に合った
75
+ 物」からの意図的な変更)。どれでも読めなければ `UnknownEncodingError`、NUL があれば
76
+ `BinaryFileError` です。
77
+
78
+ 往復の照合: `read()` は、`write()` と同じ関数で符号化し直して元のバイトと比べます。一致しなければ
79
+ その候補は `RoundTripError`(`UnknownEncodingError` の子。行・列・バイト位置つき)です。書く時まで
80
+ 遅らせないのは、`edit()` で1行目を直しただけなのに、触っていない 900 行目のバイトが変わるのを
81
+ 防ぐためです。
82
+
83
+ 7 ビットの文字コード(ISO-2022-JP などの `iso2022_*`、UTF-7、HZ)と、ASCII と互換でない・自分で BOM を
84
+ 扱う物(端の指定のない `utf-16`、`utf-32`、`utf-8-sig`)は、候補に渡すと `ValueError` です。7 ビットの
85
+ ファイルは UTF-8 としても読めるので、指定しても使われることがないためです。`Shape` も `read()` が
86
+ 返しうる物だけを受け付けます。
87
+
88
+ **CP932 は Windows と同じ並びで書きます。** Python の `cp932` は 373 字(髙・﨑 などの IBM 拡張の
89
+ 漢字、ⅰ〜ⅹ)を Windows と違う場所(0xED/0xEE)に書き、6 字(〜 − ‖ ¢ £ ¬)を黙って似た字に
90
+ 変えます。textkeep の CP932 は BMP の全文字で Windows の `WideCharToMultiByte` と同じバイトを出し、
91
+ 似た字への置き換えは `UnencodableError` にします。違いは U+F8F0〜U+F8F3 だけで、Windows は
92
+ `A0`・`FD`・`FE`・`FF` と書くのに読み戻せないため、textkeep は読み書きとも拒みます。詳しくは
93
+ [docs/cp932-findings.md](https://github.com/takosasi-dev/textkeep/blob/main/docs/cp932-findings.md)。
94
+
95
+ **改行**として数えるのは `\r\n`・`\n`・`\r` だけです(`str.splitlines()` もテキストモードも使いません)。
96
+
97
+ | 元のファイル | `doc.text` | 書くとき |
98
+ |---|---|---|
99
+ | CRLF だけ | `\n` | 本文の改行をすべて `\r\n` にする |
100
+ | LF だけ | `\n` | すべて `\n` |
101
+ | CR だけ | `\n` | すべて `\r` |
102
+ | 混在 | 元のまま | 変換しない |
103
+ | 改行が無い(`"none"`) | 元のまま | 変換しない(足した `\n` は OS に関係なく `\n`) |
104
+
105
+ 改行がそろったファイルでは、本文に `\r\n` や `\r` を書いてもファイルの改行にそろえて書きます。
106
+ **末尾の改行**は本文の通りです(`Shape.final_newline` は読んだ時の様子を示すだけ)。
107
+
108
+ ## 書くときの流れ
109
+
110
+ 1. 先に符号化する。表せない文字があれば `UnencodableError` で、何も書かない。
111
+ 2. ファイルが無ければ `FileNotFoundError`。読み取り専用なら `ReadOnlyError`(属性は外さない)。
112
+ 3. 同じフォルダの一時ファイル(`.textkeep-*.tmp`)に書いて fsync する。
113
+ 4. `expect_sha256` があれば(`edit()` は読んだ時の値を必ず渡す)、置き換えの直前にもう一度 sha256 を
114
+ 取り、違えば `ChangedOnDiskError`。別の手の変更が残る。
115
+ 5. 置き換える。Windows は `ReplaceFileW`、それ以外は mode を写してから `os.replace`。
116
+ シンボリックリンク・ジャンクションは先の実体を書き換え、リンクはリンクのまま。
117
+ 6. 読み直して、書いたバイトと照合する(`VerifyError`)。
118
+
119
+ `edit()` は、新しい本文を符号化したバイトが読んだバイトと同じなら書きません(CRLF のファイルで
120
+ `\r\n` と打ち直しただけでも書かない。更新日時が変わらない)。
121
+
122
+ 失敗や中断(Ctrl+C を含む)の時は、どの名前に何があるかを確かめてから後始末し、要らないと
123
+ 分かった物だけを消します。元のファイルは変わらないか元に戻し、分からない物は残して例外
124
+ (`.leftovers`、または `KeyboardInterrupt` の注記)に名前を出します。
125
+
126
+ Windows では、ハッシュの照合から置き換えまでの一瞬に別のプロセスが書き換えた場合、置き換えられた
127
+ 側に残ったその版を元の名前へ戻して `ChangedOnDiskError` にします。Linux・macOS ではそれを見分ける
128
+ 手段が無く、その一瞬の変更は失われます(既知の限界)。
129
+
130
+ ### 引き継ぐ物
131
+
132
+ | | Windows(`ReplaceFileW`) | Linux / macOS(`os.replace`) |
133
+ |---|---|---|
134
+ | 隠し属性などの属性 | 引き継ぐ | - |
135
+ | ACL(明示的な項目を含む) | 引き継ぐ | 引き継がない(POSIX の ACL・拡張属性) |
136
+ | 代替データストリーム(`Zone.Identifier`) | 引き継ぐ | - |
137
+ | 作成日時 | 引き継ぐ | - |
138
+ | 権限(mode) | - | 引き継ぐ |
139
+ | ハードリンク | **切れる**(直した名前が別のファイルになる) | **切れる** |
140
+
141
+ 実測は [docs/replacefile-findings.md](https://github.com/takosasi-dev/textkeep/blob/main/docs/replacefile-findings.md)。
142
+
143
+ **ロック(Windows)。** 別のプログラムが削除の共有なしでファイル(か一時ファイル)を開いていると
144
+ `ReplaceFileW` はエラー 32 になります。`backoff` 秒(既定 0.1)おきに `retries` 回(既定 20、
145
+ 約 2 秒)試し直し、だめなら `FileLockedError` です。`windows` の追加を入れていれば、ロックしている
146
+ プロセスの名前と PID が入ります。根拠は
147
+ [docs/locking-findings.md](https://github.com/takosasi-dev/textkeep/blob/main/docs/locking-findings.md)。
148
+ それ以外の失敗(ネットワークのドライブなど)は番号つきの `WriteError` で止まり、`os.replace` に
149
+ 黙って切り替えません。
150
+
151
+ **POSIX の読み取り専用。** 自分に書き込み権限が無い(`os.access(path, W_OK)` が偽)ファイルは、
152
+ フォルダ経由で置き換えられる場合でも `ReadOnlyError` にします。mode は変えません(root は通ります)。
153
+
154
+ ## できないこと
155
+
156
+ - 文字コードの変換、推定、推定ライブラリの利用。
157
+ - バイナリ、UTF-32、`max_bytes`(既定 64 MiB)を超えるファイル(`FileTooLargeError`)。ファイル全体を
158
+ メモリに読みます。
159
+ - ISO-2022-JP などの 7 ビットの文字コード(UTF-7・HZ も)。そのファイルは UTF-8 としても読めるため。
160
+ - 同じ文字に読める双子を持つ CP932 の 398 通りの2バイト(NEC 選定 IBM 拡張 0xED/0xEE、NEC 13 区の
161
+ 重複 0x8790〜0x879C、IBM 拡張の重複 15 字)の往復。Windows の符号化(`WideCharToMultiByte`)は
162
+ これらを出しません。含むファイル(Python の `cp932` で書いた物など)は `RoundTripError` です。
163
+ - ハードリンク、POSIX の所有者・ACL・拡張属性の保持。
164
+ - 新しいファイルを作ること、フォルダの一括処理、監視、ファイルの書式(TOML・JSON・CSV)の理解。
165
+
166
+ ## 例外
167
+
168
+ すべて `textkeep.TextKeepError` の子です。行・列は 1 始まりで、列はコードポイントで数えます。
169
+ 一覧は [English README の Errors](https://github.com/takosasi-dev/textkeep/blob/main/README.md#errors)
170
+ を見てください。
171
+
172
+ ## なぜ作ったか
173
+
174
+ 元の形を保って書き戻す処理は、yapf・tomlkit・tomlrt などがそれぞれ中に持っていて、Perl には
175
+ File::Edit::Portable があります。2026 年 11 月に PyPI を探した限り、汎用の Python ライブラリは
176
+ ありませんでした(eolnorm は改行をそろえる道具、bom-open は chardet で推定する、atomicwrites は
177
+ アーカイブ済みで文字コードは扱わない)。
178
+
179
+ ## 開発メモ
180
+
181
+ `tests/samples/` の見本は、実物に似せて自作した物です(CP932 の .bat、Windows が書く IBM 拡張の
182
+ バイトを含む Excel 風の CSV、内閣府の祝日 CSV と同じ形の物、UTF-8 BOM の PowerShell、Markdown、
183
+ 改行の混在、UTF-16、端のための物)。個人のデータは入っておらず、`tests/samples_def.py` から
184
+ 作り直せます。Excel が実際に書いた CSV や内閣府から取った実物ではありません。
185
+
186
+ ## ライセンス
187
+
188
+ MIT