python-redlines 0.3.0__py3-none-any.whl → 2.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.
@@ -1,4 +1,4 @@
1
1
  # SPDX-FileCopyrightText: 2024-present U.N. Owen <void@some.where>
2
2
  #
3
3
  # SPDX-License-Identifier: MIT
4
- __version__ = "0.3.0"
4
+ __version__ = "2.0.0"
@@ -6,6 +6,7 @@ from .__about__ import __version__
6
6
  from .engines import (
7
7
  BaseEngine,
8
8
  DocxodusEngine,
9
+ EngineExecutionError,
9
10
  EngineNotInstalledError,
10
11
  XmlPowerToolsEngine,
11
12
  )
@@ -14,6 +15,7 @@ __all__ = [
14
15
  "BaseEngine",
15
16
  "XmlPowerToolsEngine",
16
17
  "DocxodusEngine",
18
+ "EngineExecutionError",
17
19
  "EngineNotInstalledError",
18
20
  "__version__",
19
21
  ]
@@ -6,6 +6,7 @@ import platform
6
6
  import subprocess
7
7
  import tarfile
8
8
  import tempfile
9
+ import warnings
9
10
  import zipfile
10
11
  from pathlib import Path
11
12
  from typing import Optional, Tuple, Union
@@ -21,6 +22,21 @@ class EngineNotInstalledError(ImportError):
21
22
  """Raised when an engine is used but its binary package is not installed."""
22
23
 
23
24
 
25
+ class EngineExecutionError(subprocess.CalledProcessError):
26
+ """An engine exited unsuccessfully; its diagnostics appear in the message.
27
+
28
+ Retains CalledProcessError's returncode, cmd, stdout/output and stderr so
29
+ existing subprocess.CalledProcessError handlers keep working.
30
+ """
31
+
32
+ def __str__(self):
33
+ message = super().__str__()
34
+ for label, output in (("stderr", self.stderr), ("stdout", self.stdout)):
35
+ if output and output.strip():
36
+ message += f"\n{label}:\n{output.rstrip()}"
37
+ return message
38
+
39
+
24
40
  def _detect_rid() -> str:
25
41
  """Return the .NET-style runtime identifier for the current platform."""
26
42
  os_name = platform.system().lower()
@@ -138,28 +154,39 @@ class BaseEngine(object):
138
154
  Runs the redline binary. The 'original' and 'modified' arguments can be either bytes or file paths
139
155
  (as ``str`` or ``pathlib.Path``). Returns the redline output as bytes.
140
156
 
141
- Additional keyword arguments are passed to _build_command() for engine-specific options.
142
- DocxodusEngine supports: engine, detail_threshold, case_insensitive, detect_moves,
143
- simplify_move_markup, move_similarity_threshold, move_minimum_word_count,
144
- detect_format_changes, conflate_spaces, date_time.
157
+ A path the caller supplies is never deleted; only scratch files this
158
+ method creates are cleaned up.
159
+
160
+ A nonzero engine exit raises EngineExecutionError (a CalledProcessError
161
+ subclass) with captured stderr and stdout included in its message.
145
162
 
146
- DocxodusEngine's engine kwarg selects the comparison algorithm: 'wmlcomparer'
147
- (the default) or 'docxdiff'. The docxdiff engine ignores detail_threshold,
148
- simplify_move_markup, and detect_format_changes, so passing them alongside
149
- engine='docxdiff' raises ValueError rather than silently changing nothing.
163
+ Additional keyword arguments are passed to _build_command() for engine-specific
164
+ options. DocxodusEngine supports: case_insensitive, detect_moves,
165
+ move_similarity_threshold, move_minimum_word_count, detect_format_changes,
166
+ conflate_spaces, date_time. It raises ValueError for unrecognised settings and
167
+ for the WmlComparer-era settings removed in Docxodus v11.0.0 (engine,
168
+ detail_threshold, simplify_move_markup). XmlPowerToolsEngine ignores kwargs.
150
169
  """
151
- temp_files = []
170
+ scratch_files = []
152
171
  try:
172
+ # mkstemp, not NamedTemporaryFile: we want a path, and NamedTemporaryFile
173
+ # hands back an open file object that nothing here would close (issue #30).
174
+ handle, target_path = tempfile.mkstemp(suffix='.docx')
175
+ os.close(handle)
176
+ scratch_files.append(target_path)
153
177
 
154
- target_path = tempfile.NamedTemporaryFile(delete=False).name
155
- original_path = self._write_to_temp_file(original) if isinstance(original, bytes) else original
156
- modified_path = self._write_to_temp_file(modified) if isinstance(modified, bytes) else modified
157
- temp_files.extend([target_path, original_path, modified_path])
178
+ original_path = self._as_path(original, scratch_files)
179
+ modified_path = self._as_path(modified, scratch_files)
158
180
 
159
181
  command = self._build_command(author_tag, original_path, modified_path, target_path, **kwargs)
160
182
 
161
183
  # Capture stdout and stderr
162
- result = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
184
+ try:
185
+ result = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
186
+ except subprocess.CalledProcessError as exc:
187
+ raise EngineExecutionError(
188
+ exc.returncode, exc.cmd, output=exc.output, stderr=exc.stderr,
189
+ ) from exc
163
190
 
164
191
  stdout_output = result.stdout if isinstance(result.stdout, str) and len(result.stdout) > 0 else None
165
192
  stderr_output = result.stderr if isinstance(result.stderr, str) and len(result.stderr) > 0 else None
@@ -169,14 +196,27 @@ class BaseEngine(object):
169
196
  return redline_output, stdout_output, stderr_output
170
197
 
171
198
  finally:
172
- self._cleanup_temp_files(temp_files)
199
+ self._cleanup_temp_files(scratch_files)
200
+
201
+ def _as_path(self, document, scratch_files):
202
+ """Return a filesystem path for *document*, writing bytes out if needed.
203
+
204
+ Only a path this method creates is appended to *scratch_files*. A path
205
+ the caller passed in is the caller's own document, and registering it
206
+ for cleanup would delete the file they asked us to compare.
207
+ """
208
+ if isinstance(document, bytes):
209
+ path = self._write_to_temp_file(document)
210
+ scratch_files.append(path)
211
+ return path
212
+ return os.fspath(document)
173
213
 
174
214
  def _cleanup_temp_files(self, temp_files):
175
215
  for file_path in temp_files:
176
216
  try:
177
217
  os.remove(file_path)
178
218
  except OSError as e:
179
- print(f"Error deleting temp file {file_path}: {e}")
219
+ logger.warning("Error deleting temp file %s: %s", file_path, e)
180
220
 
181
221
  def _write_to_temp_file(self, data):
182
222
  """
@@ -193,24 +233,49 @@ class XmlPowerToolsEngine(BaseEngine):
193
233
  BINARY_BASE_NAME = 'redlines'
194
234
  EXTRA_NAME = 'ooxmlpowertools'
195
235
 
236
+ def __init__(self, target_path: Optional[str] = None):
237
+ warnings.warn(
238
+ "XmlPowerToolsEngine wraps the original, unmaintained Open-XML-PowerTools "
239
+ "WmlComparer and is deprecated; it will be removed in a future major "
240
+ "release. Use DocxodusEngine, which is actively maintained and runs the "
241
+ "DocxDiff algorithm.",
242
+ DeprecationWarning,
243
+ stacklevel=2,
244
+ )
245
+ super().__init__(target_path)
246
+
196
247
 
197
248
  class DocxodusEngine(BaseEngine):
198
249
  BINARY_PACKAGE = 'python_redlines_docxodus'
199
250
  BINARY_BASE_NAME = 'redline'
200
251
  EXTRA_NAME = 'docxodus'
201
252
 
202
- # Comparison engines accepted by the redline CLI's --engine flag.
203
- ENGINES = ('wmlcomparer', 'docxdiff')
204
-
205
- # DocxCompare.ToDocxDiffSettings drops these on the docxdiff branch, and the CLI
206
- # accepts them there without complaint, so reject them before we shell out.
207
- _WMLCOMPARER_ONLY = ('detail_threshold', 'simplify_move_markup', 'detect_format_changes')
253
+ # Settings that died with WmlComparer in Docxodus v11.0.0. They are rejected
254
+ # rather than dropped, because dropping them would not be a breaking change
255
+ # but a wrong-answer one: the v12 CLI rejects --engine as an unknown flag,
256
+ # and merely warns-and-ignores the other two, so a caller who passed
257
+ # engine='wmlcomparer' would silently receive DocxDiff output believing they
258
+ # had selected something else.
259
+ _REMOVED_KWARGS = {
260
+ 'engine': (
261
+ "the comparison-engine selector was removed in Docxodus v11.0.0, which "
262
+ "deleted WmlComparer. DocxDiff is now the only algorithm — drop the argument"
263
+ ),
264
+ 'detail_threshold': (
265
+ "it tuned WmlComparer's LCS granularity and went with it in Docxodus "
266
+ "v11.0.0. DocxDiff's granularity is structural, with no equivalent knob — "
267
+ "drop the argument"
268
+ ),
269
+ 'simplify_move_markup': (
270
+ "it worked around WmlComparer's move markup and went with it in Docxodus "
271
+ "v11.0.0. DocxDiff renders moves natively — drop the argument"
272
+ ),
273
+ }
208
274
 
209
275
  # Boolean flags (default False — presence enables)
210
276
  _BOOL_FLAGS = [
211
277
  ('case_insensitive', '--case-insensitive'),
212
278
  ('detect_moves', '--detect-moves'),
213
- ('simplify_move_markup', '--simplify-move-markup'),
214
279
  ]
215
280
 
216
281
  # Negatable flags (default True — --no- prefix disables)
@@ -221,43 +286,31 @@ class DocxodusEngine(BaseEngine):
221
286
 
222
287
  # Value flags
223
288
  _VALUE_FLAGS = [
224
- ('detail_threshold', '--detail-threshold'),
225
289
  ('move_similarity_threshold', '--move-similarity-threshold'),
226
290
  ('move_minimum_word_count', '--move-minimum-word-count'),
227
291
  ('date_time', '--date-time'),
228
292
  ]
229
293
 
230
294
  @classmethod
231
- def _normalize_engine(cls, kwargs):
232
- """The chosen engine, lowercased and stripped, or None if the caller didn't pick one."""
233
- if 'engine' not in kwargs:
234
- return None
235
-
236
- engine = kwargs['engine']
237
- if not isinstance(engine, str):
238
- raise ValueError(f"engine must be a string, got {engine!r}")
239
-
240
- normalized = engine.strip().lower()
241
- if normalized not in cls.ENGINES:
242
- raise ValueError(
243
- f"engine must be one of {', '.join(cls.ENGINES)}, got {engine!r}"
244
- )
245
- return normalized
295
+ def _supported_kwargs(cls):
296
+ """Every comparison setting this engine still understands."""
297
+ return {name for name, _ in (*cls._BOOL_FLAGS, *cls._NEG_FLAGS, *cls._VALUE_FLAGS)}
246
298
 
247
299
  @classmethod
248
300
  def _validate_kwargs(cls, kwargs):
249
- if cls._normalize_engine(kwargs) == 'docxdiff':
250
- for name in cls._WMLCOMPARER_ONLY:
251
- if name in kwargs:
252
- raise ValueError(
253
- f"{name} is not supported by the 'docxdiff' engine "
254
- f"(WmlComparer-only). Remove it or use engine='wmlcomparer'."
255
- )
256
-
257
- if 'detail_threshold' in kwargs:
258
- val = kwargs['detail_threshold']
259
- if not isinstance(val, (int, float)) or val < 0.0 or val > 1.0:
260
- raise ValueError(f"detail_threshold must be a float between 0.0 and 1.0, got {val!r}")
301
+ # Removed settings first, so they get their specific explanation rather
302
+ # than being lumped in with typos below.
303
+ for name, reason in cls._REMOVED_KWARGS.items():
304
+ if name in kwargs:
305
+ raise ValueError(f"{name} is no longer supported: {reason}.")
306
+
307
+ supported = cls._supported_kwargs()
308
+ unknown = sorted(set(kwargs) - supported)
309
+ if unknown:
310
+ raise ValueError(
311
+ f"Unknown comparison setting(s): {', '.join(unknown)}. "
312
+ f"Supported settings: {', '.join(sorted(supported))}."
313
+ )
261
314
 
262
315
  if 'move_similarity_threshold' in kwargs:
263
316
  val = kwargs['move_similarity_threshold']
@@ -271,14 +324,10 @@ class DocxodusEngine(BaseEngine):
271
324
 
272
325
  def _build_command(self, author_tag, original_path, modified_path, target_path, **kwargs):
273
326
  self._validate_kwargs(kwargs)
274
- engine = self._normalize_engine(kwargs)
275
327
 
276
328
  cmd = [self.extracted_binaries_path, original_path, modified_path, target_path,
277
329
  f'--author={author_tag}']
278
330
 
279
- if engine is not None:
280
- cmd.append(f'--engine={engine}')
281
-
282
331
  for kwarg, flag in self._BOOL_FLAGS:
283
332
  if kwargs.get(kwarg):
284
333
  cmd.append(flag)
@@ -1,14 +1,16 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: python-redlines
3
- Version: 0.3.0
4
- Summary: Generate tracked-change redline .docx documents by comparing Word files.
3
+ Version: 2.0.0
4
+ Summary: Open-source DOCX comparison tool to generate native Word tracked changes (redlines) in Python without MS Word dependencies.
5
5
  Project-URL: Homepage, https://github.com/JSv4/Python-Redlines
6
+ Project-URL: Documentation, https://jsv4.github.io/Python-Redlines/
7
+ Project-URL: Demo, https://redlines.opensource.legal
6
8
  Project-URL: Issues, https://github.com/JSv4/Python-Redlines/issues
7
9
  Project-URL: Source, https://github.com/JSv4/Python-Redlines
8
10
  Author: John Scrudato IV
9
11
  License-Expression: MIT
10
- Keywords: diff,docx,openxml,redline,tracked-changes,word
11
- Classifier: Development Status :: 4 - Beta
12
+ Keywords: compare-word-documents,diff,docx,docx-comparison,docxodus,legal-tech,openxml,python-docx-diff,redline,track-changes-api,tracked-changes,word
13
+ Classifier: Development Status :: 5 - Production/Stable
12
14
  Classifier: License :: OSI Approved :: MIT License
13
15
  Classifier: Programming Language :: Python
14
16
  Classifier: Programming Language :: Python :: 3.9
@@ -19,12 +21,12 @@ Classifier: Programming Language :: Python :: Implementation :: CPython
19
21
  Requires-Python: >=3.9
20
22
  Requires-Dist: platformdirs>=3.0
21
23
  Provides-Extra: all
22
- Requires-Dist: python-redlines-docxodus; extra == 'all'
23
- Requires-Dist: python-redlines-ooxmlpowertools; extra == 'all'
24
+ Requires-Dist: python-redlines-docxodus==2.0.0; extra == 'all'
25
+ Requires-Dist: python-redlines-ooxmlpowertools==2.0.0; extra == 'all'
24
26
  Provides-Extra: docxodus
25
- Requires-Dist: python-redlines-docxodus; extra == 'docxodus'
27
+ Requires-Dist: python-redlines-docxodus==2.0.0; extra == 'docxodus'
26
28
  Provides-Extra: ooxmlpowertools
27
- Requires-Dist: python-redlines-ooxmlpowertools; extra == 'ooxmlpowertools'
29
+ Requires-Dist: python-redlines-ooxmlpowertools==2.0.0; extra == 'ooxmlpowertools'
28
30
  Description-Content-Type: text/markdown
29
31
 
30
32
  # python-redlines
@@ -57,8 +59,23 @@ redline_bytes, stdout, stderr = engine.run_redline(
57
59
  )
58
60
  ```
59
61
 
60
- `DocxodusEngine` accepts `engine="wmlcomparer"` (default) or `engine="docxdiff"` to select the
61
- comparison algorithm. See the [project README](https://github.com/JSv4/Python-Redlines#choosing-an-engine).
62
+ `DocxodusEngine` runs DocxDiff. The `engine` selector was removed in 1.0.0 along
63
+ with WmlComparer. See the [project README](https://github.com/JSv4/Python-Redlines#comparison-settings-docxodusengine-only)
64
+ for supported settings.
65
+
66
+ From 2.0.0 onward, each extra pins its companion package to the same release
67
+ version as the wrapper. For older releases, pin both packages explicitly (for
68
+ example, `python-redlines[docxodus]==0.3.0` and
69
+ `python-redlines-docxodus==0.3.0`). Existing published metadata is unchanged.
70
+
71
+ 2.0.0 bundles Docxodus v14.1.0. Python call signatures and supported settings
72
+ are unchanged from 1.0.0, but comparison markup and revision granularity can differ.
73
+ Review representative redlines when upgrading; see the
74
+ [2.0.0 migration guide](https://github.com/JSv4/Python-Redlines#upgrading-to-200).
75
+
76
+ An unsuccessful engine exit raises `EngineExecutionError`, a subclass of
77
+ `subprocess.CalledProcessError`. Its message includes the captured stderr and
78
+ stdout; `returncode`, `cmd`, `stdout`/`output`, and `stderr` remain available.
62
79
 
63
80
  If an engine's companion package is not installed, instantiating the engine
64
81
  raises `EngineNotInstalledError` with the `pip install` command to fix it.
@@ -0,0 +1,6 @@
1
+ python_redlines/__about__.py,sha256=Fh5eqpAhiIOZkpbNkE8nqgWqIbmudP5vwr4gPo94lF8,122
2
+ python_redlines/__init__.py,sha256=0OBU8DqF4mTPMIOlQlbY4r7l-xo5nlHRGOly11Ugq2A,437
3
+ python_redlines/engines.py,sha256=JxfaxcWmbDhFYrorM7KaS1kAzTkovd2dAvUsg-JlmEE,13812
4
+ python_redlines-2.0.0.dist-info/METADATA,sha256=EYUDsskazYG0f_16adhxMrm9eLMdBCyvbxz2f_wLjSQ,3802
5
+ python_redlines-2.0.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
6
+ python_redlines-2.0.0.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.31.0
2
+ Generator: hatchling 1.32.4
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
@@ -1,6 +0,0 @@
1
- python_redlines/__about__.py,sha256=0wkJmZy74YRk69Xnaa2XwnAfwSrpYXnhUbNC6V9IxSU,122
2
- python_redlines/__init__.py,sha256=E3FScwuaU1ybyZHfrdultE52DXFwHxm9I6zpMqeiCdc,383
3
- python_redlines/engines.py,sha256=0eVMH-W3z4Z8XcvPZYNQUrqZs5N_6l7BONU8tZcFv9g,11661
4
- python_redlines-0.3.0.dist-info/METADATA,sha256=JpsZ7468PGmfP56Z5uXEqfgLiAkXe7S7EbWmLuLp8BU,2654
5
- python_redlines-0.3.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
6
- python_redlines-0.3.0.dist-info/RECORD,,