exactedit 0.0.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.
exactedit/__init__.py ADDED
@@ -0,0 +1,24 @@
1
+ """Generate and apply line-based JSON edit instructions (``text-edit-v1``)."""
2
+
3
+ from ._core import (
4
+ FORMAT_VERSION,
5
+ ContentMismatchError,
6
+ InvalidInstructionsError,
7
+ TextEditError,
8
+ apply_edits,
9
+ generate_pair,
10
+ number_lines,
11
+ )
12
+
13
+ __version__ = "0.2.0"
14
+
15
+ __all__ = [
16
+ "FORMAT_VERSION",
17
+ "ContentMismatchError",
18
+ "InvalidInstructionsError",
19
+ "TextEditError",
20
+ "__version__",
21
+ "apply_edits",
22
+ "generate_pair",
23
+ "number_lines",
24
+ ]
exactedit/_core.py ADDED
@@ -0,0 +1,248 @@
1
+ """Implementation of the ``text-edit-v1`` instruction format.
2
+
3
+ Everything public is re-exported from :mod:`exactedit`; import from there.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import difflib
9
+ import itertools
10
+ import json
11
+ import re
12
+ from collections.abc import Mapping
13
+ from typing import Any, NamedTuple
14
+
15
+ FORMAT_VERSION = "text-edit-v1"
16
+
17
+ # Fixed header fields every payload must carry. They pin down the conventions
18
+ # the operations rely on, so a future format revision can change them safely.
19
+ _HEADER: dict[str, str] = {
20
+ "format": FORMAT_VERSION,
21
+ "indexing": "1-based",
22
+ "position_reference": "original",
23
+ "line_ending_policy": "preserve-exactly",
24
+ }
25
+
26
+ _MIN_LINE_WIDTH = 6
27
+ _PREVIEW_LIMIT = 80
28
+
29
+ # A line is any run of non-terminator characters followed by "\r\n", "\r" or
30
+ # "\n"; the last line may have no terminator. Unlike ``str.splitlines`` this
31
+ # does not treat form feed, U+2028 and friends as line boundaries.
32
+ _LINE_RE = re.compile(r"[^\r\n]*(?:\r\n?|\n)|[^\r\n]+")
33
+
34
+
35
+ class TextEditError(ValueError):
36
+ """Base class for all errors raised by this package."""
37
+
38
+
39
+ class InvalidInstructionsError(TextEditError):
40
+ """The instruction payload is malformed, unsupported, or self-conflicting."""
41
+
42
+
43
+ class ContentMismatchError(TextEditError):
44
+ """The text does not contain the lines that the instructions expect."""
45
+
46
+
47
+ class _Edit(NamedTuple):
48
+ op_index: int # position in the payload's ``operations`` list, for messages
49
+ start: int # 0-based first line affected
50
+ end: int # 0-based line after the last one deleted (== start for inserts)
51
+ expected: list[str]
52
+ replacement: list[str]
53
+
54
+
55
+ def _split_lines(text: str) -> list[str]:
56
+ return _LINE_RE.findall(text)
57
+
58
+
59
+ def _preview(value: object) -> str:
60
+ """``repr`` truncated so error messages stay short and log-friendly."""
61
+ text = repr(value)
62
+ if len(text) <= _PREVIEW_LIMIT:
63
+ return text
64
+ return text[: _PREVIEW_LIMIT - 3] + "..."
65
+
66
+
67
+ def number_lines(text: str) -> str:
68
+ """Return a 1-based, line-numbered view of *text*.
69
+
70
+ Each line is rendered as ``NNNNNN | "<json string>"`` so line terminators
71
+ and other invisible characters are explicit. Lines are separated by a
72
+ plain ``"\\n"``. Empty text yields an empty string.
73
+ """
74
+ lines = _split_lines(text)
75
+ width = max(_MIN_LINE_WIDTH, len(str(len(lines))))
76
+ return "\n".join(
77
+ f"{number:0{width}d} | {json.dumps(line, ensure_ascii=False)}"
78
+ for number, line in enumerate(lines, start=1)
79
+ )
80
+
81
+
82
+ def generate_pair(original: str, edited: str) -> tuple[str, str]:
83
+ """Diff *original* against *edited* line by line.
84
+
85
+ Returns ``(numbered_original, instructions)``: the output of
86
+ :func:`number_lines` for *original*, and a ``text-edit-v1`` JSON document
87
+ which :func:`apply_edits` can use to turn *original* into *edited*.
88
+ Operations are listed bottom-to-top.
89
+ """
90
+ old = _split_lines(original)
91
+ new = _split_lines(edited)
92
+
93
+ # Lines shared at the start and end never need diffing. Trimming them keeps
94
+ # difflib, which is quadratic on repetitive input, fast for localised edits.
95
+ limit = min(len(old), len(new))
96
+ head = 0
97
+ while head < limit and old[head] == new[head]:
98
+ head += 1
99
+ tail = 0
100
+ while tail < limit - head and old[-1 - tail] == new[-1 - tail]:
101
+ tail += 1
102
+ old_mid = old[head : len(old) - tail]
103
+ new_mid = new[head : len(new) - tail]
104
+
105
+ matcher = difflib.SequenceMatcher(None, old_mid, new_mid, autojunk=False)
106
+ operations: list[dict[str, Any]] = [
107
+ {
108
+ "at_line": head + i1 + 1,
109
+ "delete_count": i2 - i1,
110
+ "expected": old_mid[i1:i2],
111
+ "replacement": new_mid[j1:j2],
112
+ }
113
+ for tag, i1, i2, j1, j2 in matcher.get_opcodes()
114
+ if tag != "equal"
115
+ ]
116
+ operations.reverse() # opcodes are top-to-bottom; the format lists bottom-to-top
117
+
118
+ payload = {**_HEADER, "operations": operations}
119
+ return number_lines(original), json.dumps(payload, ensure_ascii=False, indent=2)
120
+
121
+
122
+ def apply_edits(original: str, instructions: str | bytes | Mapping[str, Any]) -> str:
123
+ """Apply ``text-edit-v1`` *instructions* to *original* and return the result.
124
+
125
+ *instructions* is a JSON document (``str`` or ``bytes``) or an
126
+ already-parsed mapping. Every operation is validated and checked against
127
+ *original* before anything is applied, so either the complete result is
128
+ returned or an exception is raised; *original* and *instructions* are never
129
+ modified. Operations may appear in any order: all positions refer to the
130
+ original text.
131
+
132
+ Raises:
133
+ InvalidInstructionsError: the payload is malformed, uses an unsupported
134
+ format, or contains overlapping or ambiguous operations.
135
+ ContentMismatchError: an operation's ``expected`` lines differ from the
136
+ corresponding lines of *original*.
137
+ """
138
+ payload = _load_payload(instructions)
139
+
140
+ for key, wanted in _HEADER.items():
141
+ found = payload.get(key)
142
+ if found != wanted:
143
+ raise InvalidInstructionsError(
144
+ f"Unsupported {key!r}: expected {wanted!r}, got {_preview(found)}"
145
+ )
146
+
147
+ operations = payload.get("operations")
148
+ if not isinstance(operations, list):
149
+ raise InvalidInstructionsError("'operations' must be a list")
150
+
151
+ lines = _split_lines(original)
152
+ edits = [_parse_operation(op, i, len(lines)) for i, op in enumerate(operations)]
153
+
154
+ for edit in edits:
155
+ actual = lines[edit.start : edit.end]
156
+ if actual != edit.expected:
157
+ _raise_mismatch(edit, actual)
158
+ _check_no_conflicts(edits)
159
+
160
+ # Work bottom-to-top so earlier edits cannot shift the line numbers that
161
+ # later ones still depend on.
162
+ for edit in sorted(edits, key=lambda e: (e.start, e.end), reverse=True):
163
+ lines[edit.start : edit.end] = edit.replacement
164
+ return "".join(lines)
165
+
166
+
167
+ def _load_payload(instructions: str | bytes | Mapping[str, Any]) -> Mapping[str, Any]:
168
+ if isinstance(instructions, Mapping):
169
+ return instructions
170
+ try:
171
+ payload = json.loads(instructions)
172
+ except (ValueError, RecursionError) as exc: # JSONDecodeError is a ValueError
173
+ raise InvalidInstructionsError(
174
+ f"Instructions are not valid JSON: {exc}"
175
+ ) from exc
176
+ if not isinstance(payload, Mapping):
177
+ raise InvalidInstructionsError("Instructions must be a JSON object")
178
+ return payload
179
+
180
+
181
+ def _parse_operation(op: object, index: int, total_lines: int) -> _Edit:
182
+ where = f"operations[{index}]"
183
+ if not isinstance(op, Mapping):
184
+ raise InvalidInstructionsError(f"{where} must be an object")
185
+
186
+ at_line = op.get("at_line")
187
+ delete_count = op.get("delete_count")
188
+ expected = op.get("expected")
189
+ replacement = op.get("replacement")
190
+
191
+ # ``type(...) is int`` deliberately rejects bool, which subclasses int.
192
+ if type(at_line) is not int or type(delete_count) is not int:
193
+ raise InvalidInstructionsError(
194
+ f"{where}: 'at_line' and 'delete_count' must be integers"
195
+ )
196
+ if not 1 <= at_line <= total_lines + 1:
197
+ raise InvalidInstructionsError(
198
+ f"{where}: 'at_line' {at_line} is outside 1..{total_lines + 1}"
199
+ )
200
+ if delete_count < 0:
201
+ raise InvalidInstructionsError(f"{where}: 'delete_count' cannot be negative")
202
+ if not isinstance(expected, list) or not isinstance(replacement, list):
203
+ raise InvalidInstructionsError(
204
+ f"{where}: 'expected' and 'replacement' must be lists"
205
+ )
206
+ if not all(isinstance(line, str) for line in (*expected, *replacement)):
207
+ raise InvalidInstructionsError(
208
+ f"{where}: 'expected' and 'replacement' must contain only strings"
209
+ )
210
+ if len(expected) != delete_count:
211
+ raise InvalidInstructionsError(
212
+ f"{where}: 'delete_count' ({delete_count}) does not match the "
213
+ f"length of 'expected' ({len(expected)})"
214
+ )
215
+
216
+ start = at_line - 1
217
+ end = start + delete_count
218
+ if end > total_lines:
219
+ raise InvalidInstructionsError(
220
+ f"{where}: deleting {delete_count} line(s) from line {at_line} "
221
+ f"extends past the end of the text ({total_lines} line(s))"
222
+ )
223
+ return _Edit(index, start, end, expected, replacement)
224
+
225
+
226
+ def _raise_mismatch(edit: _Edit, actual: list[str]) -> None:
227
+ offset = next(
228
+ i for i, (e, a) in enumerate(zip(edit.expected, actual, strict=True)) if e != a
229
+ )
230
+ raise ContentMismatchError(
231
+ f"Content mismatch at line {edit.start + offset + 1} "
232
+ f"(operations[{edit.op_index}]): expected {_preview(edit.expected[offset])}, "
233
+ f"found {_preview(actual[offset])}"
234
+ )
235
+
236
+
237
+ def _check_no_conflicts(edits: list[_Edit]) -> None:
238
+ """Reject overlapping edits, and insertions sharing a start with another edit."""
239
+ ordered = sorted(edits, key=lambda e: (e.start, e.end))
240
+ for prev, cur in itertools.pairwise(ordered):
241
+ pair = f"operations[{prev.op_index}] and operations[{cur.op_index}]"
242
+ if cur.start < prev.end:
243
+ raise InvalidInstructionsError(f"Overlapping edit operations: {pair}")
244
+ if cur.start == prev.start:
245
+ # Only reachable when at least one of them is an insertion.
246
+ raise InvalidInstructionsError(
247
+ f"Ambiguous edit operations at the same line position: {pair}"
248
+ )
exactedit/py.typed ADDED
File without changes
@@ -0,0 +1,156 @@
1
+ Metadata-Version: 2.4
2
+ Name: exactedit
3
+ Version: 0.0.0
4
+ Summary: Generate and safely apply line-based JSON edit instructions, preserving line endings exactly.
5
+ Author-email: Alan Tseng <langesant@outlook.com>
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/agentlans/exactedit.git
8
+ Keywords: diff,patch,edit,text,lines,json
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Topic :: Text Processing
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Dynamic: license-file
26
+
27
+ # exactedit
28
+
29
+ Generate, validate, and apply line-based JSON edit instructions with exact line-ending preservation and zero external dependencies.
30
+
31
+ ## Features
32
+
33
+ * **Explicit numbered views:** Format text with zero-padded line numbers (at least six digits) and JSON-encoded line strings so line endings and invisible characters are unambiguous.
34
+ * **Line-stable JSON edit format (`exactedit-v1`):** Express insertions, deletions, and replacements using 1-based line numbers anchored to the original text.
35
+ * **Atomic, non-overlapping validation:** Verify instructions and expected lines before applying changes, leaving untouched text byte-for-byte intact and never mutating inputs.
36
+ * **Convention-faithful line splitting:** Split on `"\n"`, `"\r\n"`, and `"\r"` (with an optional final terminator) while treating other `str.splitlines()` boundary characters as ordinary text.
37
+ * **Safe error reporting:** Raise `ContentMismatchError` or `InvalidInstructionsError` (both subclasses of `TextEditError` and `ValueError`) with operation indices, first mismatch details, and truncated line excerpts.
38
+ * **Typed and self-contained:** Includes `py.typed` type annotations as well as `FORMAT_VERSION` and `__version__`.
39
+
40
+ ## Installation
41
+
42
+ ```bash
43
+ pip install exactedit
44
+
45
+ ```
46
+
47
+ ## Quick Start
48
+
49
+ ```python
50
+ from exactedit import apply_edits, generate_pair, number_lines
51
+
52
+ original = "alpha\nbeta\ngamma\n"
53
+ edited = "alpha\nBETA\ngamma\ndelta\n"
54
+
55
+ numbered, instructions = generate_pair(original, edited)
56
+ assert numbered == number_lines(original)
57
+ assert apply_edits(original, instructions) == edited
58
+
59
+ ```
60
+
61
+ `number_lines(original)` produces:
62
+
63
+ ```text
64
+ 000001 | "alpha\n"
65
+ 000002 | "beta\n"
66
+ 000003 | "gamma\n"
67
+
68
+ ```
69
+
70
+ And `generate_pair(original, edited)` returns that numbered view alongside a `exactedit-v1` JSON document:
71
+
72
+ ```json
73
+ {
74
+ "format": "exactedit-v1",
75
+ "indexing": "1-based",
76
+ "position_reference": "original",
77
+ "line_ending_policy": "preserve-exactly",
78
+ "operations": [
79
+ {
80
+ "at_line": 4,
81
+ "delete_count": 0,
82
+ "expected": [],
83
+ "replacement": [
84
+ "delta\n"
85
+ ]
86
+ },
87
+ {
88
+ "at_line": 2,
89
+ "delete_count": 1,
90
+ "expected": [
91
+ "beta\n"
92
+ ],
93
+ "replacement": [
94
+ "BETA\n"
95
+ ]
96
+ }
97
+ ]
98
+ }
99
+
100
+ ```
101
+
102
+ ## Usage
103
+
104
+ ### Writing and Applying `exactedit-v1` Instructions
105
+
106
+ Instructions do not have to come from `generate_pair`; `apply_edits` accepts a JSON string, `bytes`, or an already-parsed mapping. Every payload must include the four header fields shown above with their exact values and a list of non-overlapping operations:
107
+
108
+ | Field | Type | Description |
109
+ | --- | --- | --- |
110
+ | `at_line` | `int` | 1-based line number in the original text where the operation starts (`len(lines) + 1` appends at the end). |
111
+ | `delete_count` | `int` (`>= 0`) | Number of original lines to remove (`0` for a pure insertion). |
112
+ | `expected` | `list[str]` | Exact original lines being removed, including line terminators; must contain `delete_count` items. |
113
+ | `replacement` | `list[str]` | Lines inserted in place of removed lines, used verbatim without adding or normalizing terminators. |
114
+
115
+ Key rules when constructing operations:
116
+
117
+ * **Original line coordinates:** Line positions always refer to the original text rather than a partially edited state, so operation order does not affect application (though `generate_pair` orders operations bottom-to-top for readability).
118
+ * **No overlapping or ambiguous edits:** Adjacent operations are allowed (such as deleting line 1 and inserting at line 2), while two insertions at the same line or an insertion at the first line of a deleted range are rejected.
119
+ * **Line splitting:** Only `"\n"`, `"\r\n"`, and `"\r"` split lines (the final line need not end with a terminator); `"".join(lines)` reproduces the original text exactly.
120
+
121
+ ### Handling Mismatches and Invalid Payloads
122
+
123
+ If `expected` does not match the original text, nothing is modified and `ContentMismatchError` is raised. Malformed JSON, invalid fields, out-of-range positions, or overlapping operations raise `InvalidInstructionsError`.
124
+
125
+ ```python
126
+ from exactedit import ContentMismatchError, apply_edits, generate_pair
127
+
128
+ _, instructions = generate_pair("alpha\nbeta\ngamma\n", "alpha\nBETA\ngamma\n")
129
+
130
+ try:
131
+ apply_edits("alpha\nDIFFERENT\ngamma\n", instructions)
132
+ except ContentMismatchError as exc:
133
+ print(exc)
134
+ # Content mismatch at line 2 (operations[0]): expected 'beta\n', found 'DIFFERENT\n'
135
+
136
+ ```
137
+
138
+ ## Public API and Performance Notes
139
+
140
+ * **Functions:**
141
+ - `number_lines(text: str) -> str`
142
+ - `generate_pair(original: str, edited: str) -> tuple[str, str]`
143
+ - `apply_edits(original: str, instructions: str | bytes | Mapping[str, Any]) -> str`.
144
+ * **Constants and exceptions:** `FORMAT_VERSION` (`"exactedit-v1"`), `__version__`, `TextEditError` (subclass of `ValueError`), `InvalidInstructionsError`, and `ContentMismatchError`. Line excerpts in error messages are truncated to avoid dumping large or sensitive text into logs.
145
+ * **Performance:** `number_lines` and `apply_edits` run in linear time with respect to text size. `generate_pair` relies on `difflib` after skipping unchanged leading and trailing lines, so localized edits are fast, while repeated lines in changed regions increase cost quadratically (in testing, localized edits across 20,000 and 50,000 lines took under a second and about four seconds, respectively, and 200,000 mostly unique lines took about half a second).
146
+
147
+ ## Requirements and Compatibility
148
+
149
+ * **Python:** Python 3.10 or newer.
150
+ * **Dependencies:** None (standard library only).
151
+ * **Typing:** Ships with a `py.typed` marker for static type checkers.
152
+
153
+ ## Licence
154
+
155
+ MIT
156
+
@@ -0,0 +1,8 @@
1
+ exactedit/__init__.py,sha256=zKDwTLgPMgSVyXWfpd7rx-TJzkf_tG6q0yfgU22KPG0,472
2
+ exactedit/_core.py,sha256=Gco1TF_aQkrnaDjthkNu2pDCjg1zvf-x_a2B5Ouekbs,9387
3
+ exactedit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ exactedit-0.0.0.dist-info/licenses/LICENSE,sha256=_8nnWgBHoYzLv1_hSWlLi_froj6EaZPPhoQ3Rrg4JxY,1079
5
+ exactedit-0.0.0.dist-info/METADATA,sha256=FOh2fGVIS-08JEkBiv13AQHTkErTxLpdUTgZzvkseT0,6725
6
+ exactedit-0.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ exactedit-0.0.0.dist-info/top_level.txt,sha256=O_WsFFxemsZGvU8UfwAjBpvFvokHFdijBOSkA280m3E,10
8
+ exactedit-0.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 exactedit contributors
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 @@
1
+ exactedit