python-redlines 2.0.0__tar.gz → 3.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.
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: python-redlines
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.
3
+ Version: 3.1.0
4
+ Summary: Open-source DOCX comparison tool, powered by the Docxodus engine, 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
6
  Project-URL: Documentation, https://jsv4.github.io/Python-Redlines/
7
7
  Project-URL: Demo, https://redlines.opensource.legal
@@ -13,20 +13,20 @@ Keywords: compare-word-documents,diff,docx,docx-comparison,docxodus,legal-tech,o
13
13
  Classifier: Development Status :: 5 - Production/Stable
14
14
  Classifier: License :: OSI Approved :: MIT License
15
15
  Classifier: Programming Language :: Python
16
- Classifier: Programming Language :: Python :: 3.9
17
- Classifier: Programming Language :: Python :: 3.10
18
16
  Classifier: Programming Language :: Python :: 3.11
19
17
  Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
20
  Classifier: Programming Language :: Python :: Implementation :: CPython
21
- Requires-Python: >=3.9
21
+ Requires-Python: >=3.11
22
22
  Requires-Dist: platformdirs>=3.0
23
23
  Provides-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
+ Requires-Dist: python-redlines-docxodus==3.1.0; extra == 'all'
25
+ Requires-Dist: python-redlines-ooxmlpowertools==3.1.0; extra == 'all'
26
26
  Provides-Extra: docxodus
27
- Requires-Dist: python-redlines-docxodus==2.0.0; extra == 'docxodus'
27
+ Requires-Dist: python-redlines-docxodus==3.1.0; extra == 'docxodus'
28
28
  Provides-Extra: ooxmlpowertools
29
- Requires-Dist: python-redlines-ooxmlpowertools==2.0.0; extra == 'ooxmlpowertools'
29
+ Requires-Dist: python-redlines-ooxmlpowertools==3.1.0; extra == 'ooxmlpowertools'
30
30
  Description-Content-Type: text/markdown
31
31
 
32
32
  # python-redlines
@@ -68,10 +68,17 @@ version as the wrapper. For older releases, pin both packages explicitly (for
68
68
  example, `python-redlines[docxodus]==0.3.0` and
69
69
  `python-redlines-docxodus==0.3.0`). Existing published metadata is unchanged.
70
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.
71
+ 3.1.0 keeps the 3.0.0 engine. It adds `PendingRevisionsWarning`, emitted when an
72
+ input document carries pending tracked changes that the comparison will accept, and
73
+ an engine now starts from a binary extracted ahead of time onto a read-only
74
+ filesystem. See [Upgrading to 3.1.0](https://github.com/JSv4/Python-Redlines#upgrading-to-310).
75
+
76
+ 3.0.0 bundles Docxodus v17.0.0 and adds one setting, `minimum_anchor_word_count`.
77
+ Existing call signatures and settings are unchanged from 2.0.0, but comparison markup
78
+ and revision counts can differ, and some very deeply nested documents are now refused.
79
+ It requires Python 3.11 or newer; 2.0.0 was the last release to support 3.9 and 3.10.
73
80
  Review representative redlines when upgrading; see the
74
- [2.0.0 migration guide](https://github.com/JSv4/Python-Redlines#upgrading-to-200).
81
+ [3.0.0 migration guide](https://github.com/JSv4/Python-Redlines#upgrading-to-300).
75
82
 
76
83
  An unsuccessful engine exit raises `EngineExecutionError`, a subclass of
77
84
  `subprocess.CalledProcessError`. Its message includes the captured stderr and
@@ -37,10 +37,17 @@ version as the wrapper. For older releases, pin both packages explicitly (for
37
37
  example, `python-redlines[docxodus]==0.3.0` and
38
38
  `python-redlines-docxodus==0.3.0`). Existing published metadata is unchanged.
39
39
 
40
- 2.0.0 bundles Docxodus v14.1.0. Python call signatures and supported settings
41
- are unchanged from 1.0.0, but comparison markup and revision granularity can differ.
40
+ 3.1.0 keeps the 3.0.0 engine. It adds `PendingRevisionsWarning`, emitted when an
41
+ input document carries pending tracked changes that the comparison will accept, and
42
+ an engine now starts from a binary extracted ahead of time onto a read-only
43
+ filesystem. See [Upgrading to 3.1.0](https://github.com/JSv4/Python-Redlines#upgrading-to-310).
44
+
45
+ 3.0.0 bundles Docxodus v17.0.0 and adds one setting, `minimum_anchor_word_count`.
46
+ Existing call signatures and settings are unchanged from 2.0.0, but comparison markup
47
+ and revision counts can differ, and some very deeply nested documents are now refused.
48
+ It requires Python 3.11 or newer; 2.0.0 was the last release to support 3.9 and 3.10.
42
49
  Review representative redlines when upgrading; see the
43
- [2.0.0 migration guide](https://github.com/JSv4/Python-Redlines#upgrading-to-200).
50
+ [3.0.0 migration guide](https://github.com/JSv4/Python-Redlines#upgrading-to-300).
44
51
 
45
52
  An unsuccessful engine exit raises `EngineExecutionError`, a subclass of
46
53
  `subprocess.CalledProcessError`. Its message includes the captured stderr and
@@ -5,9 +5,9 @@ build-backend = "hatchling.build"
5
5
  [project]
6
6
  name = "python-redlines"
7
7
  dynamic = ["version", "optional-dependencies"]
8
- description = "Open-source DOCX comparison tool to generate native Word tracked changes (redlines) in Python without MS Word dependencies."
8
+ description = "Open-source DOCX comparison tool, powered by the Docxodus engine, to generate native Word tracked changes (redlines) in Python without MS Word dependencies."
9
9
  readme = "README.md"
10
- requires-python = ">=3.9"
10
+ requires-python = ">=3.11"
11
11
  license = "MIT"
12
12
  keywords = [
13
13
  "docx",
@@ -30,10 +30,10 @@ classifiers = [
30
30
  "Development Status :: 5 - Production/Stable",
31
31
  "License :: OSI Approved :: MIT License",
32
32
  "Programming Language :: Python",
33
- "Programming Language :: Python :: 3.9",
34
- "Programming Language :: Python :: 3.10",
35
33
  "Programming Language :: Python :: 3.11",
36
34
  "Programming Language :: Python :: 3.12",
35
+ "Programming Language :: Python :: 3.13",
36
+ "Programming Language :: Python :: 3.14",
37
37
  "Programming Language :: Python :: Implementation :: CPython",
38
38
  ]
39
39
  dependencies = [
@@ -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__ = "2.0.0"
4
+ __version__ = "3.1.0"
@@ -8,6 +8,7 @@ from .engines import (
8
8
  DocxodusEngine,
9
9
  EngineExecutionError,
10
10
  EngineNotInstalledError,
11
+ PendingRevisionsWarning,
11
12
  XmlPowerToolsEngine,
12
13
  )
13
14
 
@@ -17,5 +18,6 @@ __all__ = [
17
18
  "DocxodusEngine",
18
19
  "EngineExecutionError",
19
20
  "EngineNotInstalledError",
21
+ "PendingRevisionsWarning",
20
22
  "__version__",
21
23
  ]
@@ -1,15 +1,19 @@
1
+ import filecmp
1
2
  import importlib.metadata
2
3
  import importlib.resources
3
4
  import logging
4
5
  import os
5
6
  import platform
7
+ import posixpath
6
8
  import subprocess
7
9
  import tarfile
8
10
  import tempfile
9
11
  import warnings
10
12
  import zipfile
13
+ import zlib
11
14
  from pathlib import Path
12
15
  from typing import Optional, Tuple, Union
16
+ from xml.parsers import expat
13
17
 
14
18
  import platformdirs
15
19
 
@@ -22,6 +26,129 @@ class EngineNotInstalledError(ImportError):
22
26
  """Raised when an engine is used but its binary package is not installed."""
23
27
 
24
28
 
29
+ class PendingRevisionsWarning(UserWarning):
30
+ """An input document carries pending tracked changes that the comparison will accept.
31
+
32
+ Both engines compare the accepted view of each document, so the redline does not carry
33
+ those changes over as tracked changes by their original authors. Silence it with ``warnings.filterwarnings("ignore", category=PendingRevisionsWarning)``.
34
+ """
35
+
36
+
37
+ _W_NAMESPACES = (
38
+ 'http://schemas.openxmlformats.org/wordprocessingml/2006/main',
39
+ 'http://purl.oclc.org/ooxml/wordprocessingml/main', # Strict
40
+ )
41
+
42
+ # Every element that records a pending tracked change: insertions, deletions, moves,
43
+ # formatting changes, and table-structure changes. Tags are written as expat reports them
44
+ # with namespace_separator='}': 'namespace}local'.
45
+ _REVISION_TAGS = frozenset(
46
+ f'{namespace}}}{name}'
47
+ for namespace in _W_NAMESPACES
48
+ for name in (
49
+ 'ins', 'del', 'moveFrom', 'moveTo',
50
+ 'rPrChange', 'pPrChange', 'sectPrChange', 'numberingChange',
51
+ 'tblPrChange', 'tblPrExChange', 'tblGridChange', 'trPrChange', 'tcPrChange',
52
+ 'cellIns', 'cellDel', 'cellMerge',
53
+ 'customXmlInsRangeStart', 'customXmlDelRangeStart',
54
+ 'customXmlMoveFromRangeStart', 'customXmlMoveToRangeStart',
55
+ )
56
+ )
57
+
58
+ _RELATIONSHIP_TAG = 'http://schemas.openxmlformats.org/package/2006/relationships}Relationship'
59
+
60
+ # Relationship types, by their last segment (transitional and Strict share it), of the
61
+ # parts related to the main document whose revisions Docxodus accepts before comparing.
62
+ # It leaves the comments and glossary parts' own revisions in place.
63
+ _ACCEPTED_STORY_TYPES = ('header', 'footer', 'footnotes', 'endnotes', 'styles')
64
+
65
+
66
+ # What reading or parsing one part of a damaged package can raise: a missing part
67
+ # (KeyError), a DTD (ValueError, below), a bad CRC or truncated data, an unsupported or
68
+ # encrypted member, malformed XML, or an encoding Python does not know (LookupError).
69
+ # Each is confined to its part, so one bad part does not hide pending changes in the others.
70
+ _UNREADABLE_PART = (KeyError, ValueError, LookupError, EOFError, RuntimeError, NotImplementedError,
71
+ zlib.error, zipfile.BadZipFile, expat.ExpatError)
72
+
73
+
74
+ class _StopParsing(Exception):
75
+ """Raised from a parser callback once a part has answered the question."""
76
+
77
+
78
+ def _parse_part(package: zipfile.ZipFile, name: str, on_start) -> None:
79
+ """Stream one XML part through expat, calling ``on_start(tag, attributes)`` at each
80
+ element start, with *tag* written ``namespace}local``.
81
+
82
+ Raises ValueError for a part with a DTD, in whatever encoding: a .docx may not
83
+ contain one, and expanding its entities is how an entity bomb works.
84
+ """
85
+ def refuse_dtd(*_):
86
+ raise ValueError(f'{name} contains a DTD')
87
+
88
+ parser = expat.ParserCreate(namespace_separator='}')
89
+ parser.StartDoctypeDeclHandler = refuse_dtd
90
+ parser.StartElementHandler = on_start
91
+ with package.open(name) as stream:
92
+ parser.ParseFile(stream)
93
+
94
+
95
+ def _related_parts(package: zipfile.ZipFile, source: str, types) -> list:
96
+ """Names of the parts *source* ('' for the package itself) relates with one of *types*."""
97
+ folder, name = posixpath.split(source)
98
+ parts = []
99
+
100
+ def collect(tag, attributes):
101
+ if (tag == _RELATIONSHIP_TAG
102
+ and attributes.get('Type', '').rsplit('/', 1)[-1] in types
103
+ and attributes.get('TargetMode') != 'External'):
104
+ target = attributes.get('Target', '')
105
+ parts.append(target.lstrip('/') if target.startswith('/')
106
+ else posixpath.normpath(posixpath.join(folder, target)))
107
+
108
+ try:
109
+ _parse_part(package, posixpath.join(folder, '_rels', f'{name}.rels'), collect)
110
+ except _UNREADABLE_PART:
111
+ # No relationships part, or a damaged one: keep whatever was read before it failed.
112
+ logger.debug("Could not read the relationships of %r", source, exc_info=True)
113
+ return parts
114
+
115
+
116
+ def _has_pending_revision(package: zipfile.ZipFile, name: str) -> bool:
117
+ def stop_at_revision(tag, _attributes):
118
+ if tag in _REVISION_TAGS:
119
+ raise _StopParsing
120
+
121
+ try:
122
+ _parse_part(package, name, stop_at_revision)
123
+ except _StopParsing:
124
+ return True
125
+ except _UNREADABLE_PART:
126
+ # A part the package names but cannot supply or parse: skip it, and let the
127
+ # engine report it if it matters.
128
+ logger.debug("Could not check part %s for pending tracked changes", name, exc_info=True)
129
+ return False
130
+
131
+
132
+ def _pending_revision_parts(path) -> list:
133
+ """The parts of the .docx at *path* that hold pending tracked changes the engines
134
+ accept before comparing: the main document and its headers, footers, footnotes,
135
+ endnotes and styles.
136
+
137
+ Returns an empty list for anything that is not a readable .docx; the engine then
138
+ reports the problem itself.
139
+ """
140
+ try:
141
+ with zipfile.ZipFile(path) as package:
142
+ main_parts = _related_parts(package, '', ('officeDocument',))
143
+ stories = [story for main in main_parts
144
+ for story in _related_parts(package, main, _ACCEPTED_STORY_TYPES)]
145
+ return [name for name in dict.fromkeys(main_parts + stories)
146
+ if _has_pending_revision(package, name)]
147
+ except (OSError, ValueError, zipfile.BadZipFile):
148
+ logger.debug("Could not open %s to check it for pending tracked changes", path, exc_info=True)
149
+ return []
150
+
151
+
25
152
  class EngineExecutionError(subprocess.CalledProcessError):
26
153
  """An engine exited unsuccessfully; its diagnostics appear in the message.
27
154
 
@@ -70,6 +197,10 @@ class BaseEngine(object):
70
197
  BINARY_BASE_NAME: str = NotImplemented
71
198
  EXTRA_NAME: str = NotImplemented
72
199
 
200
+ # Whether the engine hands byte-identical inputs back untouched, pending tracked
201
+ # changes included, instead of comparing them.
202
+ _RETURNS_IDENTICAL_INPUTS_UNCHANGED = False
203
+
73
204
  def __init__(self, target_path: Optional[str] = None):
74
205
  self.target_path = target_path
75
206
  self.extracted_binaries_path = self._resolve_binary()
@@ -105,7 +236,9 @@ class BaseEngine(object):
105
236
  if not binary_path.exists():
106
237
  self._extract_archive(archive, extract_root)
107
238
 
108
- if not is_windows:
239
+ # chmod fails on a read-only filesystem and for a user that does not own the file,
240
+ # so only attempt it when the binary is not already executable.
241
+ if not is_windows and not os.access(binary_path, os.X_OK):
109
242
  os.chmod(binary_path, 0o755)
110
243
 
111
244
  return str(binary_path)
@@ -160,12 +293,17 @@ class BaseEngine(object):
160
293
  A nonzero engine exit raises EngineExecutionError (a CalledProcessError
161
294
  subclass) with captured stderr and stdout included in its message.
162
295
 
296
+ If either document carries pending tracked changes, a PendingRevisionsWarning
297
+ names it: the engine accepts those changes before comparing, so the redline
298
+ does not keep them as tracked changes by their original authors.
299
+
163
300
  Additional keyword arguments are passed to _build_command() for engine-specific
164
301
  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.
302
+ move_similarity_threshold, move_minimum_word_count, minimum_anchor_word_count,
303
+ detect_format_changes, conflate_spaces, date_time. It raises ValueError for
304
+ unrecognised settings and for the WmlComparer-era settings removed in Docxodus
305
+ v11.0.0 (engine, detail_threshold, simplify_move_markup). XmlPowerToolsEngine
306
+ ignores kwargs.
169
307
  """
170
308
  scratch_files = []
171
309
  try:
@@ -179,6 +317,7 @@ class BaseEngine(object):
179
317
  modified_path = self._as_path(modified, scratch_files)
180
318
 
181
319
  command = self._build_command(author_tag, original_path, modified_path, target_path, **kwargs)
320
+ self._warn_about_pending_revisions(original_path, modified_path)
182
321
 
183
322
  # Capture stdout and stderr
184
323
  try:
@@ -198,6 +337,27 @@ class BaseEngine(object):
198
337
  finally:
199
338
  self._cleanup_temp_files(scratch_files)
200
339
 
340
+ def _warn_about_pending_revisions(self, original_path, modified_path):
341
+ """Tell the caller that the comparison will accept the inputs' pending tracked
342
+ changes (issue #41). Called from run_redline, so stacklevel 3 is the caller."""
343
+ found = [(side, parts)
344
+ for side, path in (('original', original_path), ('modified', modified_path))
345
+ if (parts := _pending_revision_parts(path))]
346
+ if not found:
347
+ return
348
+ if self._RETURNS_IDENTICAL_INPUTS_UNCHANGED and filecmp.cmp(original_path, modified_path, shallow=False):
349
+ return
350
+
351
+ where = ' and the '.join(f"{side} document ({', '.join(parts)})" for side, parts in found)
352
+ warnings.warn(
353
+ f"Pending tracked changes found in the {where}. {type(self).__name__} accepts every "
354
+ "pending change in both documents before comparing them, so the redline does not "
355
+ "carry them over as tracked changes by their original authors. "
356
+ "Accept or reject them before comparing if that history matters.",
357
+ PendingRevisionsWarning,
358
+ stacklevel=3,
359
+ )
360
+
201
361
  def _as_path(self, document, scratch_files):
202
362
  """Return a filesystem path for *document*, writing bytes out if needed.
203
363
 
@@ -250,6 +410,11 @@ class DocxodusEngine(BaseEngine):
250
410
  BINARY_BASE_NAME = 'redline'
251
411
  EXTRA_NAME = 'docxodus'
252
412
 
413
+ # Docxodus skips the comparison for byte-identical inputs and returns the document
414
+ # as it came, pending changes and all (JSv4/Docxodus#1894), so there is nothing to
415
+ # warn about. tests/test_pending_revisions.py pins this against the bundled binary.
416
+ _RETURNS_IDENTICAL_INPUTS_UNCHANGED = True
417
+
253
418
  # Settings that died with WmlComparer in Docxodus v11.0.0. They are rejected
254
419
  # rather than dropped, because dropping them would not be a breaking change
255
420
  # but a wrong-answer one: the v12 CLI rejects --engine as an unknown flag,
@@ -288,6 +453,7 @@ class DocxodusEngine(BaseEngine):
288
453
  _VALUE_FLAGS = [
289
454
  ('move_similarity_threshold', '--move-similarity-threshold'),
290
455
  ('move_minimum_word_count', '--move-minimum-word-count'),
456
+ ('minimum_anchor_word_count', '--minimum-anchor-word-count'),
291
457
  ('date_time', '--date-time'),
292
458
  ]
293
459
 
@@ -322,6 +488,12 @@ class DocxodusEngine(BaseEngine):
322
488
  if not isinstance(val, int) or val < 1:
323
489
  raise ValueError(f"move_minimum_word_count must be a positive integer, got {val!r}")
324
490
 
491
+ if 'minimum_anchor_word_count' in kwargs:
492
+ val = kwargs['minimum_anchor_word_count']
493
+ # bool is an int subclass, but would reach the CLI as "True".
494
+ if isinstance(val, bool) or not isinstance(val, int) or val < 0:
495
+ raise ValueError(f"minimum_anchor_word_count must be a non-negative integer, got {val!r}")
496
+
325
497
  def _build_command(self, author_tag, original_path, modified_path, target_path, **kwargs):
326
498
  self._validate_kwargs(kwargs)
327
499