mergefolio 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.
mergefolio/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Strict, stateless Word field rendering for a deliberately bounded OOXML subset."""
2
+
3
+ from .core import MergeError, fields, render
4
+
5
+ __all__ = ["MergeError", "fields", "render"]
mergefolio/core.py ADDED
@@ -0,0 +1,317 @@
1
+ import re
2
+ from collections.abc import Mapping, Sequence
3
+ from copy import deepcopy
4
+ from dataclasses import dataclass
5
+ from io import BytesIO
6
+ from zipfile import ZIP_DEFLATED, BadZipFile, ZipFile
7
+
8
+ from lxml import etree as E
9
+
10
+ W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
11
+ XML = "http://www.w3.org/XML/1998/namespace"
12
+
13
+
14
+ def w(local):
15
+ return f"{{{W}}}{local}"
16
+
17
+
18
+ class MergeError(ValueError):
19
+ """Malformed, unsupported or incomplete template."""
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Field:
24
+ name: str
25
+ nodes: tuple
26
+ style: object = None
27
+
28
+
29
+ def parse_instruction(value):
30
+ # Only simple identifiers and the cosmetic MERGEFORMAT switch are supported.
31
+ if not re.match(r"\s*MERGEFIELD(?:\s|$)", value, re.I):
32
+ return None
33
+ match = re.fullmatch(
34
+ r'\s*MERGEFIELD\s+(?:"([A-Za-z_][\w.-]*)"|([A-Za-z_][\w.-]*))(?:\s+\\\*\s+MERGEFORMAT)?\s*',
35
+ value,
36
+ re.I,
37
+ )
38
+ if not match:
39
+ raise MergeError(f"Unsupported MERGEFIELD instruction: {value!r}")
40
+ return match.group(1) or match.group(2)
41
+
42
+
43
+ def scan(root):
44
+ result = []
45
+ for simple in root.iter(w("fldSimple")):
46
+ name = parse_instruction(simple.get(w("instr"), ""))
47
+ if name:
48
+ if simple.getparent().tag != w("p") or any(
49
+ n.tag in (w("fldSimple"), w("fldChar"))
50
+ for n in simple.iterdescendants()
51
+ ):
52
+ raise MergeError("Nested or non-paragraph simple field")
53
+ result.append(
54
+ Field(name, (simple,), simple.find(f".//{w('rPr')}"))
55
+ )
56
+ for p in root.iter(w("p")):
57
+ stack = []
58
+ for node in p:
59
+ chars = list(node.iter(w("fldChar")))
60
+ if not chars:
61
+ if stack and any(n.tag == w("fldSimple") for n in node.iter()):
62
+ raise MergeError("Nested simple field is unsupported")
63
+ if stack:
64
+ stack[-1][0].append(node)
65
+ if not stack[-1][2]:
66
+ stack[-1][1].extend(
67
+ t.text or "" for t in node.iter(w("instrText"))
68
+ )
69
+ continue
70
+ if len(chars) != 1 or node.tag != w("r"):
71
+ raise MergeError("Unsupported field run structure")
72
+ kind = chars[0].get(w("fldCharType"))
73
+ if kind == "begin":
74
+ if stack:
75
+ raise MergeError("Nested complex fields are unsupported")
76
+ stack.append([[node], [], False, None])
77
+ elif kind in ("separate", "end"):
78
+ if not stack:
79
+ raise MergeError("Unbalanced complex field")
80
+ state = stack[-1]
81
+ state[0].append(node)
82
+ if kind == "separate":
83
+ if state[2]:
84
+ raise MergeError("Repeated field separator")
85
+ state[2] = True
86
+ else:
87
+ stack.pop()
88
+ name = parse_instruction("".join(state[1]))
89
+ if name:
90
+ if any(r.tag != w("r") for r in state[0]):
91
+ raise MergeError(
92
+ "Non-run content inside complex field"
93
+ )
94
+ style = next(
95
+ (
96
+ r.find(w("rPr"))
97
+ for r in state[0]
98
+ if r.find(w("rPr")) is not None
99
+ ),
100
+ None,
101
+ )
102
+ result.append(Field(name, tuple(state[0]), style))
103
+ else:
104
+ raise MergeError("Unknown field marker")
105
+ if stack:
106
+ raise MergeError("Fields spanning paragraphs are unsupported")
107
+ # Every MERGEFIELD instruction must have been handled (including fields
108
+ # inside unusual containers which the paragraph scanner cannot interpret).
109
+ covered = {
110
+ n for field in result for node in field.nodes for n in node.iter()
111
+ }
112
+ for n in root.iter(w("instrText")):
113
+ if "MERGEFIELD" in (n.text or "").upper() and n not in covered:
114
+ raise MergeError("Unsupported or orphan MERGEFIELD")
115
+ return result
116
+
117
+
118
+ def replace(field, value):
119
+ if not isinstance(value, str):
120
+ raise MergeError(
121
+ f"Field {field.name!r} requires a preformatted string"
122
+ )
123
+ if len(value) > 100_000:
124
+ raise MergeError("Field value exceeds 100,000 characters")
125
+ run = E.Element(w("r"))
126
+ if field.style is not None:
127
+ run.append(deepcopy(field.style))
128
+ try:
129
+ for i, line in enumerate(
130
+ value.replace("\r\n", "\n").replace("\r", "\n").split("\n")
131
+ ):
132
+ if i:
133
+ E.SubElement(run, w("br"))
134
+ for j, segment in enumerate(line.split("\t")):
135
+ if j:
136
+ E.SubElement(run, w("tab"))
137
+ t = E.SubElement(run, w("t"), {f"{{{XML}}}space": "preserve"})
138
+ t.text = segment
139
+ except ValueError as exc:
140
+ raise MergeError(
141
+ f"Invalid XML character in field {field.name!r}"
142
+ ) from exc
143
+ parent = field.nodes[0].getparent()
144
+ parent.insert(parent.index(field.nodes[0]), run)
145
+ for node in field.nodes:
146
+ parent.remove(node)
147
+
148
+
149
+ def load(data):
150
+ if len(data) > 16 * 1024**2:
151
+ raise MergeError("Template exceeds 16 MiB")
152
+ try:
153
+ with ZipFile(BytesIO(data)) as z:
154
+ infos = z.infolist()
155
+ names = [i.filename for i in infos]
156
+ if (
157
+ len(names) != len(set(names))
158
+ or len(names) > 2048
159
+ or sum(i.file_size for i in infos) > 64 * 1024**2
160
+ ):
161
+ raise MergeError("Invalid or excessive ZIP contents")
162
+ if any("vbaproject" in n.lower() for n in names) or not {
163
+ "[Content_Types].xml",
164
+ "word/document.xml",
165
+ } <= set(names):
166
+ raise MergeError("Expected non-macro DOCX")
167
+ parts = {i.filename: z.read(i) for i in infos}
168
+ except (BadZipFile, RuntimeError, OSError) as exc:
169
+ raise MergeError("Invalid DOCX package") from exc
170
+ roots = {}
171
+ try:
172
+ for name, content in parts.items():
173
+ if name.endswith((".xml", ".rels")):
174
+ root = E.fromstring(
175
+ content,
176
+ E.XMLParser(
177
+ resolve_entities=False, no_network=True, load_dtd=False
178
+ ),
179
+ )
180
+ if root.getroottree().docinfo.doctype:
181
+ raise MergeError("DTD is not permitted")
182
+ if name.endswith(".rels") and any(
183
+ e.get("TargetMode") == "External" for e in root
184
+ ):
185
+ raise MergeError(
186
+ "External relationships are not permitted"
187
+ )
188
+ if re.fullmatch(
189
+ r"word/(document|header\d+|footer\d+|footnotes|endnotes)\.xml",
190
+ name,
191
+ ):
192
+ roots[name] = root
193
+ elif any(
194
+ parse_instruction(n.get(w("instr"), ""))
195
+ for n in root.iter(w("fldSimple"))
196
+ ) or any(
197
+ "MERGEFIELD" in (n.text or "").upper()
198
+ for n in root.iter(w("instrText"))
199
+ ):
200
+ raise MergeError(
201
+ f"Merge fields in unsupported part: {name}"
202
+ )
203
+ if (
204
+ name == "word/settings.xml"
205
+ and root.find(w("mailMerge")) is not None
206
+ ):
207
+ root.remove(root.find(w("mailMerge")))
208
+ parts[name] = E.tostring(
209
+ root, encoding="UTF-8", xml_declaration=True
210
+ )
211
+ except E.XMLSyntaxError as exc:
212
+ raise MergeError("Invalid XML in template") from exc
213
+ return parts, roots
214
+
215
+
216
+ def fields(template: bytes) -> frozenset[str]:
217
+ _, roots = load(template)
218
+ return frozenset(f.name for root in roots.values() for f in scan(root))
219
+
220
+
221
+ def render(
222
+ template: bytes,
223
+ values: Mapping[str, str],
224
+ *,
225
+ rows: Mapping[str, Sequence[Mapping[str, str]]] | None = None,
226
+ ) -> bytes:
227
+ """Return a new document; unresolved fields fail closed.
228
+
229
+ Each row anchor must occur in exactly one table row. Values are explicitly formatted strings.
230
+ """
231
+ parts, roots = load(template)
232
+ rows = rows or {}
233
+ if not isinstance(values, Mapping) or not isinstance(rows, Mapping):
234
+ raise MergeError("Values and rows must be mappings")
235
+ if any(
236
+ not isinstance(v, Sequence) or isinstance(v, (str, bytes))
237
+ for v in rows.values()
238
+ ):
239
+ raise MergeError("Repeated rows must be sequences of mappings")
240
+ if any(
241
+ not isinstance(r, Mapping)
242
+ for records in rows.values()
243
+ for r in records
244
+ ):
245
+ raise MergeError("Repeated rows must be mappings")
246
+ if sum(len(v) for v in rows.values()) > 1000:
247
+ raise MergeError("Too many repeated rows")
248
+ expanded_budget = sum(len(v) for v in parts.values())
249
+ for anchor, records in rows.items():
250
+ matches = []
251
+ for root in roots.values():
252
+ for f in scan(root):
253
+ if f.name == anchor:
254
+ row = next(f.nodes[0].iterancestors(w("tr")), None)
255
+ if row is not None and row not in matches:
256
+ matches.append(row)
257
+ if len(matches) != 1:
258
+ raise MergeError(
259
+ f"Expected exactly one template row for {anchor!r}"
260
+ )
261
+ row = matches[0]
262
+ # Duplicating identifiers, drawings and nested tables can corrupt package semantics.
263
+ if any(
264
+ n.tag
265
+ in {
266
+ w(k)
267
+ for k in (
268
+ "bookmarkStart",
269
+ "bookmarkEnd",
270
+ "drawing",
271
+ "sdt",
272
+ "tbl",
273
+ "commentRangeStart",
274
+ "commentRangeEnd",
275
+ )
276
+ }
277
+ for n in row.iterdescendants()
278
+ ):
279
+ raise MergeError(
280
+ "Repeated row contains unsupported structural content"
281
+ )
282
+ expanded_budget += len(E.tostring(row)) * max(0, len(records) - 1)
283
+ expanded_budget += sum(
284
+ len(v.encode("utf-8")) * 6
285
+ for record in records
286
+ for v in record.values()
287
+ if isinstance(v, str)
288
+ )
289
+ if expanded_budget > 64 * 1024**2:
290
+ raise MergeError("Repeated rows exceed expansion budget")
291
+ parent = row.getparent()
292
+ index = parent.index(row)
293
+ for offset, record in enumerate(records):
294
+ clone = deepcopy(row)
295
+ for f in scan(clone):
296
+ if f.name in record:
297
+ replace(f, record[f.name])
298
+ elif f.name not in values:
299
+ raise MergeError(f"Missing row field: {f.name}")
300
+ parent.insert(index + offset, clone)
301
+ parent.remove(row)
302
+ for name, root in roots.items():
303
+ for field in scan(root):
304
+ if field.name not in values:
305
+ raise MergeError(f"Missing field: {field.name}")
306
+ value = values[field.name]
307
+ if isinstance(value, str):
308
+ expanded_budget += len(value.encode("utf-8")) * 6
309
+ if expanded_budget > 64 * 1024**2:
310
+ raise MergeError("Rendered document exceeds expansion budget")
311
+ replace(field, value)
312
+ parts[name] = E.tostring(root, encoding="UTF-8", xml_declaration=True)
313
+ out = BytesIO()
314
+ with ZipFile(out, "w", compression=ZIP_DEFLATED) as z:
315
+ for name, content in parts.items():
316
+ z.writestr(name, content)
317
+ return out.getvalue()
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.4
2
+ Name: mergefolio
3
+ Version: 0.1.0
4
+ Summary: Explicit, strict Word MERGEFIELD rendering without Microsoft Word
5
+ License-Expression: MIT
6
+ Project-URL: Inspiration, https://github.com/Bouke/docx-mailmerge
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE.md
10
+ License-File: NOTICE.md
11
+ Requires-Dist: lxml>=6.2.0
12
+ Provides-Extra: dev
13
+ Requires-Dist: build>=1.6.1; extra == "dev"
14
+ Requires-Dist: pytest>=9.2.0; extra == "dev"
15
+ Requires-Dist: ruff>=0.17.6; extra == "dev"
16
+ Requires-Dist: twine>=7.0.0; extra == "dev"
17
+ Dynamic: license-file
18
+
19
+ # Mergefolio 0.1.0
20
+
21
+ [![Lint](https://github.com/avtomatik/mergefolio/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/avtomatik/mergefolio/actions/workflows/ci.yml)
22
+ [![Python Version](https://img.shields.io/pypi/pyversions/mergefolio)](https://pypi.org/project/mergefolio/)
23
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE.md)
24
+ [![PyPI Downloads](https://static.pepy.tech/personalized-badge/mergefolio?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads)](https://pepy.tech/projects/mergefolio)
25
+
26
+ A small, independently written, strict Word mail-merge library inspired by Bouke Haarsma's `docx-mailmerge`. See [NOTICE](NOTICE.md). Not a drop-in replacement or official fork; `docx-mailmerge2` is the established continuation.
27
+
28
+ ```python
29
+ from pathlib import Path
30
+
31
+ from mergefolio import fields, render
32
+
33
+ template = Path("template.docx").read_bytes()
34
+ print(fields(template))
35
+ output = render(
36
+ template, {"title": "Draft"}, rows={"item": [{"item": "A"}, {"item": "B"}]}
37
+ )
38
+ Path("draft.docx").write_bytes(output)
39
+ ```
40
+
41
+ Supports simple and split-run complex Word MERGEFIELDs in document, numbered headers/footers, footnotes and endnotes; repeat one plain table row, preserve first field run style; Unicode, newlines and tabs; missing fields fail closed. Extra scalar keys are allowed so callers can supply a shared context. Values must be preformatted strings. Templates with external relationships, nested complex fields, non-MERGEFORMAT switches, complex rows with drawings/bookmarks/content controls, macros or DTDs are rejected. No IF/NEXT evaluation, document concatenation, image merging, Word date/number formatting, or arbitrary OOXML compatibility promise. Use trusted templates only. No network or Word required.
42
+
43
+ ## Release
44
+
45
+ Provisional name: verify availability and register the PyPI project before publication. `python -m build`, `python -m twine check dist/*`, test on Python 3.11–3.14, then publish via a configured PyPI trusted publisher (workflow provided). No publication performed. No code was copied from the upstream repository.
@@ -0,0 +1,8 @@
1
+ mergefolio/__init__.py,sha256=2IRvLZqaxnlvDJ3YJodCp6v9wkNLz0pyRM7KFTCM3T8,178
2
+ mergefolio/core.py,sha256=FquF0mhKK1pZ90ZfJz2R5msyQvUXWKDhwvznarAGK54,11987
3
+ mergefolio-0.1.0.dist-info/licenses/LICENSE.md,sha256=87wwutQerjHQipwASB2HDnz-omyN9LOAd1nGFHTtpv4,1091
4
+ mergefolio-0.1.0.dist-info/licenses/NOTICE.md,sha256=hCtJl_q-o3iS9SgGif5KQJy83LQ9e1BD5wlVev8RkIc,670
5
+ mergefolio-0.1.0.dist-info/METADATA,sha256=VPA13NaODG99LKkYSkwiC4nUDUKWALgBCHnrrgKmNSo,2714
6
+ mergefolio-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ mergefolio-0.1.0.dist-info/top_level.txt,sha256=DLobzX6a1mfuVhTVeNUUybWIRDxlg4ncILLRVH42tM4,11
8
+ mergefolio-0.1.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,22 @@
1
+
2
+ The MIT License (MIT)
3
+
4
+ Copyright (c) 2026 Mergefolio contributors
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ # Lineage
2
+
3
+ Mergefolio is an independently implemented, intentionally narrower successor in spirit to [docx-mailmerge](https://github.com/Bouke/docx-mailmerge), by Bouke Haarsma and contributors (Copyright (C) 2012 Bouke Haarsma, MIT). The original project was archived on 16 April 2022. Its author directed users to the community continuation [docx-mailmerge2](https://pypi.org/project/docx-mailmerge2/), which remains a distinct project. No endorsement or official succession is claimed. No upstream implementation was copied; the familiar `MERGEFIELD` and repeat-row concepts are retained in homage. See the upstream repository for its original copyright and license.
@@ -0,0 +1 @@
1
+ mergefolio