@iasiv5/dsh-skills 1.3.3 → 1.3.5

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 (84) hide show
  1. package/NOTICE.md +1 -1
  2. package/package.json +1 -1
  3. package/skills/answer-me-with-html/SKILL.md +3 -3
  4. package/skills/answer-me-with-html/references/video.md +1 -0
  5. package/skills/answer-me-with-html/scripts/am.mjs +1671 -1131
  6. package/skills/darwin-skill/README.md +136 -121
  7. package/skills/darwin-skill/README_EN.md +138 -123
  8. package/skills/darwin-skill/SKILL.md +256 -421
  9. package/skills/darwin-skill/_archive/hero-2.0.gif +0 -0
  10. package/skills/darwin-skill/assets/banner-en.svg +1 -1
  11. package/skills/darwin-skill/assets/banner.svg +2 -2
  12. package/skills/darwin-skill/assets/chart-loop-en.html +2 -2
  13. package/skills/darwin-skill/assets/chart-loop-en.png +0 -0
  14. package/skills/darwin-skill/assets/chart-loop.html +2 -2
  15. package/skills/darwin-skill/assets/chart-loop.png +0 -0
  16. package/skills/darwin-skill/assets/chart-phases-en.html +12 -12
  17. package/skills/darwin-skill/assets/chart-phases-en.png +0 -0
  18. package/skills/darwin-skill/assets/chart-phases.html +13 -13
  19. package/skills/darwin-skill/assets/chart-phases.png +0 -0
  20. package/skills/darwin-skill/assets/darwin-3.0-launch.mp4 +0 -0
  21. package/skills/darwin-skill/assets/hero.gif +0 -0
  22. package/skills/darwin-skill/assets/result-card-example.png +0 -0
  23. package/skills/darwin-skill/docs/index.html +93 -357
  24. package/skills/darwin-skill/references/about-author.md +101 -0
  25. package/skills/darwin-skill/references/eval-protocol.md +156 -0
  26. package/skills/darwin-skill/references/skilllens-evidence.md +2 -1
  27. package/skills/darwin-skill/references/v3-evidence.md +114 -0
  28. package/skills/darwin-skill/scripts/darwin.py +400 -0
  29. package/skills/darwin-skill/scripts/screenshot.mjs +3 -2
  30. package/skills/darwin-skill/showcase.html +93 -357
  31. package/skills/darwin-skill/templates/result-card.html +36 -20
  32. package/skills/darwin-skill/templates/result-card.png +0 -0
  33. package/skills/darwin-skill/test-prompts.json +36 -12
  34. package/skills/docx/SKILL.md +5 -4
  35. package/skills/docx/scripts/office/helpers/__init__.py +22 -4
  36. package/skills/docx/scripts/office/helpers/pptx_chart.py +124 -11
  37. package/skills/docx/scripts/office/helpers/pptx_slide.py +43 -3
  38. package/skills/docx/scripts/office/soffice.py +85 -1
  39. package/skills/docx/scripts/office/validate.py +50 -7
  40. package/skills/docx/scripts/office/validators/base.py +16 -4
  41. package/skills/docx/scripts/office/validators/docx.py +59 -6
  42. package/skills/docx/scripts/office/validators/pptx.py +116 -8
  43. package/skills/docx/scripts/office/validators/redlining.py +292 -113
  44. package/skills/impeccable/SKILL.md +4 -2
  45. package/skills/impeccable/reference/adapt.md +1 -1
  46. package/skills/impeccable/reference/animate.md +17 -0
  47. package/skills/impeccable/reference/critique-rubric.md +496 -0
  48. package/skills/impeccable/reference/critique.md +12 -504
  49. package/skills/impeccable/reference/degraded/documenter.md +1 -1
  50. package/skills/impeccable/reference/degraded/motion-reviewer.md +29 -0
  51. package/skills/impeccable/reference/document.md +3 -1
  52. package/skills/impeccable/reference/foundations.md +44 -0
  53. package/skills/impeccable/reference/hooks.md +3 -3
  54. package/skills/impeccable/reference/live-setup.md +1 -1
  55. package/skills/impeccable/reference/live.md +26 -12
  56. package/skills/impeccable/reference/new-work-comp.md +24 -0
  57. package/skills/impeccable/reference/new-work-world.md +20 -0
  58. package/skills/impeccable/reference/new-work.md +6 -34
  59. package/skills/impeccable/reference/typeset.md +6 -0
  60. package/skills/impeccable/reference/visualize.md +1 -1
  61. package/skills/impeccable/scripts/VERSION +1 -1
  62. package/skills/impeccable/scripts/engine-checksums.txt +5 -5
  63. package/skills/impeccable/scripts/live-browser.js +51 -22
  64. package/skills/pdf/{forms.md → FORMS.md} +1 -1
  65. package/skills/pdf/{reference.md → REFERENCE.md} +3 -2
  66. package/skills/wechat-draft/SKILL.md +1 -0
  67. package/skills/xlsx/SKILL.md +19 -14
  68. package/skills/xlsx/scripts/office/helpers/__init__.py +22 -4
  69. package/skills/xlsx/scripts/office/helpers/pptx_chart.py +124 -11
  70. package/skills/xlsx/scripts/office/helpers/pptx_slide.py +43 -3
  71. package/skills/xlsx/scripts/office/soffice.py +85 -1
  72. package/skills/xlsx/scripts/office/validate.py +50 -7
  73. package/skills/xlsx/scripts/office/validators/base.py +16 -4
  74. package/skills/xlsx/scripts/office/validators/docx.py +59 -6
  75. package/skills/xlsx/scripts/office/validators/pptx.py +116 -8
  76. package/skills/xlsx/scripts/office/validators/redlining.py +292 -113
  77. package/skills/xlsx/scripts/recalc.py +731 -136
  78. package/skills-manifest.json +2 -2
  79. /package/skills/darwin-skill/{assets → _archive}/chart-ratchet-en.html +0 -0
  80. /package/skills/darwin-skill/{assets → _archive}/chart-ratchet-en.png +0 -0
  81. /package/skills/darwin-skill/{assets → _archive}/chart-ratchet.html +0 -0
  82. /package/skills/darwin-skill/{assets → _archive}/chart-ratchet.png +0 -0
  83. /package/skills/darwin-skill/{templates → _archive}/result-card-dark.html +0 -0
  84. /package/skills/darwin-skill/{templates → _archive}/result-card-white.html +0 -0
@@ -1,32 +1,38 @@
1
1
  """
2
2
  Excel Formula Recalculation Script
3
3
  Recalculates all formulas in an Excel file using LibreOffice
4
+
5
+ LibreOffice recalculates a copy of the workbook. Only the values it computed are then written
6
+ into the workbook itself, so nothing else in the file is rewritten.
4
7
  """
5
8
 
6
9
  import contextlib
10
+ import copy
11
+ import html
12
+ import io
7
13
  import json
14
+ import math
8
15
  import os
9
16
  import platform
17
+ import posixpath
10
18
  import re
11
19
  import shutil
20
+ import signal
12
21
  import subprocess
13
22
  import sys
14
23
  import tempfile
15
24
  import time
16
25
  import zipfile
17
26
  from pathlib import Path
27
+ from xml.parsers import expat
18
28
 
19
29
  from office.soffice import get_soffice_env, run_soffice
20
30
 
21
- from openpyxl import load_workbook
22
-
23
31
  MACRO_FILENAME = "Module1.xba"
24
32
  SOFFICE_MISSING = "soffice not found on PATH; LibreOffice is required to recalculate"
25
33
 
26
34
  MAX_LOCATIONS = 100
27
35
 
28
- EXTERNAL_REF_RE = re.compile(r"""(?<![\w"\[])'?\[\d+\][^!"\[\]]*'?!""")
29
-
30
36
  RECALCULATE_MACRO = """<?xml version="1.0" encoding="UTF-8"?>
31
37
  <!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
32
38
  <script:module xmlns:script="http://openoffice.org/2000/script" script:name="Module1" script:language="StarBasic">
@@ -78,90 +84,92 @@ def setup_libreoffice_macro(profile_dir: Path, timeout=30):
78
84
  return url, None
79
85
 
80
86
 
81
- def external_links_at_risk(filename):
82
- try:
83
- with zipfile.ZipFile(filename) as archive:
84
- names = archive.namelist()
85
- except (zipfile.BadZipFile, OSError):
86
- return []
87
- if not any(n.startswith("xl/externalLinks/") for n in names):
87
+ def _existing_cells(ws):
88
+ if not hasattr(ws, "iter_rows"):
88
89
  return []
90
+ return [ws._cells[key] for key in sorted(ws._cells)]
89
91
 
90
- with contextlib.ExitStack() as stack:
91
- formulas = load_workbook(filename, data_only=False)
92
- stack.callback(formulas.close)
93
- values = load_workbook(filename, data_only=True)
94
- stack.callback(values.close)
95
-
96
- external_names = [
97
- name
98
- for name, dn in formulas.defined_names.items()
99
- if isinstance(getattr(dn, "value", None), str) and EXTERNAL_REF_RE.search(dn.value)
100
- ]
101
- name_re = (
102
- re.compile(r"\b(" + "|".join(re.escape(n) for n in external_names) + r")\b")
103
- if external_names
104
- else None
105
- )
106
92
 
107
- at_risk = []
108
- for sheet in formulas.sheetnames:
109
- ws = formulas[sheet]
110
- if not hasattr(ws, "iter_rows"):
93
+ def _is_workbook(path):
94
+ try:
95
+ with zipfile.ZipFile(path) as archive:
96
+ return _workbook_part(archive) is not None
97
+ except Exception:
98
+ return False
99
+
100
+
101
+ def _part_that_is_not_xml(path):
102
+ with zipfile.ZipFile(path) as archive:
103
+ for item in archive.infolist():
104
+ if not item.filename.endswith((".xml", ".rels")) or item.file_size > 50_000_000:
111
105
  continue
112
- cached = values[sheet]
113
- for row in ws.iter_rows():
114
- for cell in row:
115
- v = cell.value
116
- if not (isinstance(v, str) and v.startswith("=")):
117
- continue
118
- reaches_out = EXTERNAL_REF_RE.search(v) or (name_re and name_re.search(v))
119
- if reaches_out and cached[cell.coordinate].value is None:
120
- at_risk.append(f"{sheet}!{cell.coordinate}")
121
- return at_risk
106
+ data = archive.read(item)
107
+ plain = data.replace(b"\x00", b"") if b"\x00" in data[:64] else data
108
+ if b"<!" in plain:
109
+ continue
110
+ try:
111
+ expat.ParserCreate().Parse(data, True)
112
+ except expat.ExpatError as e:
113
+ return f"{item.filename} is not well-formed XML: {e}"
114
+ return None
115
+
116
+
117
+ def _has_formulas(path):
118
+ try:
119
+ with zipfile.ZipFile(path) as archive:
120
+ for _, part_name in _worksheets(archive, any_namespace=True):
121
+ raw = archive.read(part_name)
122
+ plain = raw.replace(b"\x00", b"") if b"\x00" in raw[:64] else raw
123
+ if re.search(rb"<(?:\w+:)?f[\s/>]", plain):
124
+ return True
125
+ if b"<!" not in plain:
126
+ expat.ParserCreate().Parse(raw, True)
127
+ return False
128
+ except Exception:
129
+ return True
122
130
 
123
131
 
124
132
  def recalc(filename, timeout=30, force=False):
125
133
  if not Path(filename).exists():
126
134
  return {"error": f"File {filename} does not exist"}
127
135
 
128
- abs_path = str(Path(filename).absolute())
136
+ abs_path = os.path.realpath(filename)
129
137
 
130
- if not os.access(abs_path, os.W_OK):
131
- return {"error": f"{filename} is not writable; recalculation rewrites the file in place"}
138
+ if not _is_workbook(abs_path):
139
+ return {"error": f"{filename} is not an .xlsx or .xlsm workbook; recalc.py cannot read it"}
140
+
141
+ if not _has_formulas(abs_path):
142
+ report = _report(filename)
143
+ if "error" not in report:
144
+ return report
145
+ broken = _part_that_is_not_xml(abs_path)
146
+ if broken:
147
+ return {"error": f"{broken}; {filename} is unchanged"}
148
+ return {"status": "success", "total_errors": 0, "error_summary": {}, "total_formulas": 0}
149
+
150
+ if not (os.access(abs_path, os.W_OK) and os.access(os.path.dirname(abs_path), os.W_OK)):
151
+ return {
152
+ "error": f"{filename} or its folder is not writable; recalc.py needs to write to both"
153
+ }
132
154
 
133
155
  try:
134
156
  get_soffice_env()
135
157
  except Exception as e:
136
158
  return {"error": f"Could not prepare the LibreOffice environment: {e}"}
137
159
 
138
- if not force:
160
+ with tempfile.TemporaryDirectory(prefix="recalc-lo-", ignore_cleanup_errors=True) as work:
161
+ copy = os.path.join(work, "copy", os.path.basename(abs_path))
162
+ profile_dir = Path(work) / "profile"
139
163
  try:
140
- at_risk = external_links_at_risk(filename)
141
- except Exception as e:
142
- return {"error": f"Could not inspect {filename} for external links: {e}"}
143
- if at_risk:
144
- shown = at_risk[:MAX_LOCATIONS]
145
- return {
146
- "error": (
147
- "Refusing to recalculate: this workbook links to another workbook, and "
148
- f"{len(at_risk)} linked cell(s) have lost their cached value (openpyxl strips "
149
- "these on save). Recalculating would resolve them to #NAME? and delete the "
150
- "external links for good. Copy those cells' values from the original file "
151
- "before saving, or pass --force to accept the loss. Charts and conditional "
152
- "formats can hold external references too, so this list may not be exhaustive."
153
- ),
154
- "external_link_cells": shown,
155
- "external_link_cells_truncated": max(0, len(at_risk) - len(shown)),
156
- }
157
-
158
- with tempfile.TemporaryDirectory(
159
- prefix="recalc-lo-profile-", ignore_cleanup_errors=True
160
- ) as profile_dir:
161
- return _recalc_with_profile(filename, abs_path, timeout, Path(profile_dir))
162
-
163
-
164
- def _recalc_with_profile(filename, abs_path, timeout, profile_dir: Path):
164
+ os.mkdir(os.path.dirname(copy))
165
+ shutil.copyfile(abs_path, copy)
166
+ profile_dir.mkdir()
167
+ except OSError as e:
168
+ return {"error": f"Could not copy {filename} for LibreOffice to work on: {e}"}
169
+ return _recalc_with_profile(filename, abs_path, copy, timeout, profile_dir)
170
+
171
+
172
+ def _recalc_with_profile(filename, abs_path, copy, timeout, profile_dir: Path):
165
173
  started = time.monotonic()
166
174
  profile_url, err = setup_libreoffice_macro(profile_dir, timeout=timeout)
167
175
  if err:
@@ -169,7 +177,7 @@ def _recalc_with_profile(filename, abs_path, timeout, profile_dir: Path):
169
177
 
170
178
  timeout = max(5, int(timeout - (time.monotonic() - started)))
171
179
 
172
- before = _stamp(abs_path)
180
+ before = _stamp(copy)
173
181
 
174
182
  cmd = [
175
183
  "soffice",
@@ -177,7 +185,7 @@ def _recalc_with_profile(filename, abs_path, timeout, profile_dir: Path):
177
185
  "--norestore",
178
186
  f"-env:UserInstallation={profile_url}",
179
187
  "vnd.sun.star.script:Standard.Module1.RecalculateAndSave?language=Basic&location=application",
180
- abs_path,
188
+ copy,
181
189
  ]
182
190
 
183
191
  if platform.system() == "Linux" and shutil.which("timeout"):
@@ -203,101 +211,688 @@ def _recalc_with_profile(filename, abs_path, timeout, profile_dir: Path):
203
211
  detail = (result.stderr or "").strip() or f"soffice exited {result.returncode}"
204
212
  return {"error": f"LibreOffice failed to recalculate: {detail}"}
205
213
 
206
- if _stamp(abs_path) == before:
214
+ try:
215
+ rewritten = _stamp(copy) != before
216
+ except OSError:
217
+ rewritten = False
218
+ if not rewritten:
207
219
  return {
208
220
  "error": (
209
- "LibreOffice exited cleanly but never rewrote the file, so nothing was "
210
- "recalculated. Check that no other LibreOffice instance is running, then retry."
221
+ "LibreOffice exited cleanly but never rewrote its copy of the file, so nothing was "
222
+ "recalculated. Run it again; if the same happens, LibreOffice is not running the "
223
+ "recalculation macro on this machine."
211
224
  )
212
225
  }
213
226
 
214
227
  try:
215
- wb = load_workbook(filename, data_only=True)
216
-
217
- excel_errors = [
218
- "#VALUE!",
219
- "#DIV/0!",
220
- "#REF!",
221
- "#NAME?",
222
- "#NULL!",
223
- "#NUM!",
224
- "#N/A",
225
- ]
226
- error_details = {err: [] for err in excel_errors}
227
- total_errors = 0
228
-
229
- for sheet_name in wb.sheetnames:
230
- ws = wb[sheet_name]
231
- if not hasattr(ws, "iter_rows"):
232
- continue
233
- for row in ws.iter_rows():
234
- for cell in row:
235
- if cell.value is not None and isinstance(cell.value, str):
236
- for err in excel_errors:
237
- if err in cell.value:
238
- location = f"{sheet_name}!{cell.coordinate}"
239
- error_details[err].append(location)
240
- total_errors += 1
241
- break
242
-
243
- result = {
244
- "status": "success" if total_errors == 0 else "errors_found",
245
- "total_errors": total_errors,
246
- "error_summary": {},
247
- }
228
+ found = _write_values(abs_path, copy)
229
+ except Exception as e:
230
+ why = f"which is unchanged: {str(e) or type(e).__name__}"
231
+ return {"error": f"Could not write the new values into {filename}, {why}"}
248
232
 
249
- for err_type, locations in error_details.items():
250
- if locations:
251
- entry = {"count": len(locations), "locations": locations[:MAX_LOCATIONS]}
252
- if len(locations) > MAX_LOCATIONS:
253
- entry["locations_truncated"] = len(locations) - MAX_LOCATIONS
254
- result["error_summary"][err_type] = entry
233
+ return _report(filename, found)
255
234
 
256
- wb.close()
257
235
 
258
- wb_formulas = load_workbook(filename, data_only=False)
259
- formula_count = 0
260
- for sheet_name in wb_formulas.sheetnames:
261
- ws = wb_formulas[sheet_name]
262
- if not hasattr(ws, "iter_rows"):
263
- continue
264
- for row in ws.iter_rows():
265
- for cell in row:
266
- if (
267
- cell.value
268
- and isinstance(cell.value, str)
269
- and cell.value.startswith("=")
270
- ):
271
- formula_count += 1
272
- wb_formulas.close()
236
+ EXCEL_ERRORS = ["#VALUE!", "#DIV/0!", "#REF!", "#NAME?", "#NULL!", "#NUM!", "#N/A"]
237
+
238
+ _MAIN_NS = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
239
+ _REL_NS = "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}"
240
+ _CELL_REF_RE = re.compile(r"([A-Z]{1,3})([0-9]+)")
241
+ MAX_MERGE_CHECKS = 1_000_000
242
+ _MERGE_RE = re.compile(rb'<(?:\w+:)?mergeCell\b[^>]*\bref="([^"]*)"')
243
+
244
+
245
+ def _error_in(text):
246
+ if "#" in text:
247
+ for err in EXCEL_ERRORS:
248
+ if err in text:
249
+ return err
250
+ return None
251
+
252
+
253
+ def _rich_text(node):
254
+ runs = node.findall(f"{_MAIN_NS}t") + node.findall(f"{_MAIN_NS}r/{_MAIN_NS}t")
255
+ return "".join(t.text or "" for t in runs)
256
+
257
+
258
+ def _row_major(coordinate):
259
+ address = _CELL_REF_RE.fullmatch(coordinate)
260
+ if address is None:
261
+ raise ValueError(f"{coordinate[:20]!r} is not the address of a cell")
262
+ column, row = address.groups()
263
+ number = 0
264
+ for letter in column:
265
+ number = number * 26 + ord(letter) - ord("A") + 1
266
+ return int(row), number
267
+
268
+
269
+ def _merged_ranges(sheet_xml):
270
+ ranges = []
271
+ for ref in _MERGE_RE.findall(sheet_xml):
272
+ first, _, last = ref.decode().partition(":")
273
+ ranges.append((*_row_major(first), *_row_major(last)))
274
+ return ranges
275
+
273
276
 
274
- result["total_formulas"] = formula_count
277
+ def _hidden_by_a_merge(merged, row, column):
278
+ return any(
279
+ top <= row <= bottom and left <= column <= right and (row, column) != (top, left)
280
+ for top, left, bottom, right in merged
281
+ )
275
282
 
276
- return result
277
283
 
278
- except Exception as e:
284
+ def _utf8_or_refuse(data, what):
285
+ declared = re.search(rb"""<\?xml[^>]*\sencoding\s*=\s*["']([^"']+)""", data[:200])
286
+ utf8 = declared is None or declared[1].lower().replace(b"-", b"") == b"utf8"
287
+ if data[:2] in (b"\xff\xfe", b"\xfe\xff") or b"\x00" in data[:64] or not utf8:
288
+ raise ValueError(f"{what} is not in UTF-8, which is all this script can read")
289
+
290
+
291
+ def _xml(data, what="an XML part"):
292
+ try:
293
+ from defusedxml.ElementTree import fromstring
294
+ except ImportError:
295
+ _utf8_or_refuse(data, what)
296
+ if b"<!DOCTYPE" in data or b"<!ENTITY" in data:
297
+ raise ValueError("XML with a DTD, and defusedxml is not installed") from None
298
+ from xml.etree.ElementTree import fromstring
299
+ return fromstring(data)
300
+
301
+
302
+ def _workbook_part(archive):
303
+ if "_rels/.rels" not in archive.namelist():
304
+ return None
305
+ for rel in _xml(archive.read("_rels/.rels"), "_rels/.rels"):
306
+ if rel.get("Type", "").endswith("/officeDocument"):
307
+ name = posixpath.normpath(rel.get("Target", "")).lstrip("/")
308
+ return name if name in archive.namelist() else None
309
+ return None
310
+
311
+
312
+ def _workbook_xml(archive):
313
+ name = _workbook_part(archive)
314
+ if name is None:
315
+ raise ValueError("the package names no workbook part")
316
+ if archive.getinfo(name).file_size > 50_000_000:
317
+ raise ValueError(f"{name} is too large to be a workbook's")
318
+ return _xml(archive.read(name), name)
319
+
320
+
321
+ def _worksheets(archive, any_namespace=False):
322
+ workbook = _workbook_xml(archive)
323
+ if not any_namespace and workbook.tag != f"{_MAIN_NS}workbook":
324
+ namespace = workbook.tag.partition("}")[0].lstrip("{")
325
+ if "/ooxml/" in namespace:
326
+ raise ValueError("it is in Strict Open XML format, which this script cannot edit")
327
+ raise ValueError(f"its XML is in a namespace this script does not read ({namespace})")
328
+ folder, file_name = posixpath.split(_workbook_part(archive))
329
+ rels_name = posixpath.join(folder, "_rels", f"{file_name}.rels")
330
+ rels = {rel.get("Id"): rel for rel in _xml(archive.read(rels_name), rels_name)}
331
+ found = []
332
+ for sheet in workbook.iter():
333
+ if not sheet.tag.endswith("}sheet"):
334
+ continue
335
+ rel_id = next((value for key, value in sheet.attrib.items() if key.endswith("}id")), None)
336
+ rel = rels.get(rel_id)
337
+ if rel is None or not rel.get("Type", "").endswith("/worksheet"):
338
+ continue
339
+ target = rel.get("Target")
340
+ if target.startswith("/"):
341
+ part_name = target.lstrip("/")
342
+ else:
343
+ part_name = posixpath.normpath(posixpath.join(folder, target))
344
+ found.append((sheet.get("name"), part_name))
345
+ return found
346
+
347
+
348
+ def _sheet_names(archive):
349
+ return [s.get("name") for s in _workbook_xml(archive).iter() if s.tag.endswith("}sheet")]
350
+
351
+
352
+ def _scan_xml(filename):
353
+ from defusedxml.ElementTree import iterparse
354
+
355
+ error_details = {err: [] for err in EXCEL_ERRORS}
356
+ formula_count = 0
357
+ merge_checks = 0
358
+
359
+ with zipfile.ZipFile(filename) as archive:
360
+ shared_errors, shared_equals = {}, set()
361
+ if "xl/sharedStrings.xml" in archive.namelist():
362
+ with archive.open("xl/sharedStrings.xml") as part:
363
+ index = 0
364
+ for _, node in iterparse(part):
365
+ if node.tag != f"{_MAIN_NS}si":
366
+ continue
367
+ text = _rich_text(node).replace("x005F_", "")
368
+ err = _error_in(text)
369
+ if err:
370
+ shared_errors[index] = err
371
+ if text.startswith("="):
372
+ shared_equals.add(index)
373
+ index += 1
374
+ node.clear()
375
+
376
+ for sheet_name, part_name in _worksheets(archive):
377
+ found = []
378
+ xml = archive.read(part_name)
379
+ merged = _merged_ranges(xml)
380
+ for _, node in iterparse(io.BytesIO(xml)):
381
+ if node.tag == f"{_MAIN_NS}row":
382
+ node.clear()
383
+ if node.tag != f"{_MAIN_NS}c":
384
+ continue
385
+ if node.get("r") is None:
386
+ raise ValueError("a cell without its address")
387
+ formula = node.find(f"{_MAIN_NS}f")
388
+ is_formula = formula is not None and formula.get("t") != "dataTable"
389
+ err = None
390
+ cell_type = node.get("t", "n")
391
+ if cell_type == "s":
392
+ index = int(node.findtext(f"{_MAIN_NS}v"))
393
+ err = shared_errors.get(index)
394
+ is_formula = is_formula or (formula is None and index in shared_equals)
395
+ elif cell_type not in ("n", "b", "d"):
396
+ inline = node.find(f"{_MAIN_NS}is")
397
+ text = node.findtext(f"{_MAIN_NS}v") if inline is None else _rich_text(inline)
398
+ err = _error_in(text or "")
399
+ is_formula = is_formula or (formula is None and (text or "").startswith("="))
400
+ if not is_formula and not err:
401
+ continue
402
+ row, column = _row_major(node.get("r"))
403
+ merge_checks += len(merged)
404
+ if merge_checks > MAX_MERGE_CHECKS:
405
+ raise ValueError("too many merged ranges for this many cells")
406
+ if _hidden_by_a_merge(merged, row, column):
407
+ continue
408
+ formula_count += is_formula
409
+ if err:
410
+ found.append(((row, column), err, node.get("r")))
411
+ for _, err, coordinate in sorted(found):
412
+ error_details[err].append(f"{sheet_name}!{coordinate}")
413
+
414
+ return error_details, formula_count
415
+
416
+
417
+ def _scan_with_openpyxl(filename):
418
+ from openpyxl import load_workbook
419
+ from openpyxl.worksheet.formula import ArrayFormula
420
+
421
+ error_details = {err: [] for err in EXCEL_ERRORS}
422
+ wb = load_workbook(filename, data_only=True)
423
+ for sheet_name in wb.sheetnames:
424
+ ws = wb[sheet_name]
425
+ for cell in _existing_cells(ws):
426
+ if isinstance(cell.value, str):
427
+ err = _error_in(cell.value)
428
+ if err:
429
+ error_details[err].append(f"{sheet_name}!{cell.coordinate}")
430
+ wb.close()
431
+
432
+ wb_formulas = load_workbook(filename, data_only=False)
433
+ formula_count = 0
434
+ for sheet_name in wb_formulas.sheetnames:
435
+ ws = wb_formulas[sheet_name]
436
+ for cell in _existing_cells(ws):
437
+ v = cell.value
438
+ if isinstance(v, ArrayFormula):
439
+ v = v.text
440
+ if isinstance(v, str) and v.startswith("="):
441
+ formula_count += 1
442
+ wb_formulas.close()
443
+
444
+ return error_details, formula_count
445
+
446
+
447
+ def _sheet_names_too_long(filename):
448
+ try:
449
+ with zipfile.ZipFile(filename) as archive:
450
+ return [name for name in _sheet_names(archive) if len(name or "") > 31]
451
+ except Exception:
452
+ return []
453
+
454
+
455
+ def _report(filename, found=None):
456
+ try:
457
+ try:
458
+ error_details, formula_count = _scan_xml(filename)
459
+ except Exception:
460
+ error_details, formula_count = _scan_with_openpyxl(filename)
461
+ except Exception as e:
279
462
  return {"error": str(e)}
280
463
 
464
+ found = found or {}
465
+ kept = found.get("not_computed", [])
466
+ apart = set(kept) | set(found.get("#NAME?", ()))
467
+ in_file = [where for where in error_details["#NAME?"] if where not in apart]
468
+ error_details["#NAME?"] = in_file + found.get("#NAME?", [])
469
+ for error in EXCEL_ERRORS:
470
+ if error != "#NAME?":
471
+ error_details[error] += found.get(error, [])
472
+ error_details[UNBALANCED] = found.get(UNBALANCED, [])
473
+ error_details[TOO_LONG] = _sheet_names_too_long(filename)
474
+
475
+ total_errors = sum(len(locations) for locations in error_details.values())
476
+ result = {
477
+ "status": "success" if total_errors == 0 else "errors_found",
478
+ "total_errors": total_errors,
479
+ "error_summary": {},
480
+ }
481
+
482
+ for err_type, locations in error_details.items():
483
+ if locations:
484
+ entry = {"count": len(locations), "locations": locations[:MAX_LOCATIONS]}
485
+ if len(locations) > MAX_LOCATIONS:
486
+ entry["locations_truncated"] = len(locations) - MAX_LOCATIONS
487
+ result["error_summary"][err_type] = entry
488
+
489
+ result["total_formulas"] = formula_count
490
+ if kept:
491
+ result["not_computed"] = {"count": len(kept), "locations": kept[:MAX_LOCATIONS]}
492
+ if len(kept) > MAX_LOCATIONS:
493
+ result["not_computed"]["locations_truncated"] = len(kept) - MAX_LOCATIONS
494
+ return result
495
+
496
+
497
+
498
+ MAX_ARRAY_CELLS = 1_000_000
499
+
500
+ _ATTRS = rb"""((?:[^>"']|"[^"]*"|'[^']*')*?)"""
501
+ _ROW_OR_CELL_RE = re.compile(
502
+ rb"<((?:\w+:)?)(?:row(?=[\s/>])" + _ATTRS + rb"/?>"
503
+ rb"|c(?=[\s/>])" + _ATTRS + rb"(?:/>|>(.*?)</\1c\s*>))",
504
+ re.S,
505
+ )
506
+ _F_RE = re.compile(rb"<(?:\w+:)?f(?=[\s/>])" + _ATTRS + rb"(?:/>|>(.*?)</(?:\w+:)?f\s*>)", re.S)
507
+ _V_RE = re.compile(rb"<(?:\w+:)?v(?=[\s/>])[^>]*?(?:/>|>(.*?)</(?:\w+:)?v\s*>)", re.S)
508
+ _T_OR_VM_RE = re.compile(rb"""\s(?:t|vm)\s*=\s*(?:"[^"]*"|'[^']*')""")
509
+ _EXT_LST_RE = re.compile(rb"<(?:\w+:)?extLst\b.*</(?:\w+:)?extLst\s*>", re.S)
510
+ _NAME_ERROR = (b"e", b"#NAME?")
511
+ _STRING_RE = re.compile(r'"[^"]*"')
512
+ _QUOTED_RE = re.compile(r""""[^"]*"|'[^']*'|\[[^\[\]]*\]""")
513
+ _CALL_RE = re.compile(r"(?<![\w.])([A-Za-z_][\w.]*)\(")
514
+ _DELIMS = r"\s+\-*/^&=<>(),;:!%{}#@~|"
515
+ _WORD_RE = re.compile(rf"(?<![^{_DELIMS}])[^{_DELIMS}]+(?![^{_DELIMS}]|[(!])")
516
+ _EXTERNAL_REF_RE = re.compile(r"""(?<![\w"\[])'?\[[1-9]\d*\][^!"\[\]]*'?!""")
517
+ _PREFIX_RE = re.compile(r"^(?:_xlfn\.|_xlws\.)+", re.I)
518
+ UNBALANCED = "unbalanced brackets"
519
+ TOO_LONG = "sheet name over 31 characters"
520
+ _STORED_BARE = frozenset(
521
+ "CUBEVALUE CUBEMEMBER CUBESET CUBESETCOUNT CUBERANKEDMEMBER CUBEKPIMEMBER CUBEMEMBERPROPERTY "
522
+ "RTD CALL DBCS PHONETIC REGISTER.ID SQL.REQUEST USDOLLAR BAHTTEXT ECMA.CEILING".split()
523
+ )
524
+ LIBREOFFICE_LACKS = _STORED_BARE | frozenset(
525
+ "XLOOKUP XMATCH SORT SORTBY FILTER UNIQUE SEQUENCE RANDARRAY LET LAMBDA MAP REDUCE SCAN "
526
+ "MAKEARRAY BYROW BYCOL ISOMITTED TEXTBEFORE TEXTAFTER TEXTSPLIT VSTACK HSTACK TOROW TOCOL "
527
+ "WRAPROWS WRAPCOLS TAKE DROP CHOOSEROWS CHOOSECOLS EXPAND VALUETOTEXT ARRAYTOTEXT REGEXTEST "
528
+ "REGEXEXTRACT REGEXREPLACE PERCENTOF GROUPBY PIVOTBY TRIMRANGE IMAGE STOCKHISTORY FIELDVALUE "
529
+ "PY COPILOT TRANSLATE DETECTLANGUAGE ANCHORARRAY SINGLE BINOM.DIST.RANGE IMCOSH IMCOT IMCSC "
530
+ "IMCSCH IMSEC IMSECH IMSINH IMTAN QUERYSTRING".split()
531
+ )
532
+
533
+
534
+ def _attr_re(name):
535
+ return re.compile(rb"\s" + name + rb"""\s*=\s*(?:"([^"]*)"|'([^']*)')""")
536
+
537
+
538
+ _R_RE, _T_RE, _REF_RE, _SI_RE = _attr_re(b"r"), _attr_re(b"t"), _attr_re(b"ref"), _attr_re(b"si")
539
+
540
+
541
+ def _attr(pattern, attrs):
542
+ m = pattern.search(attrs)
543
+ if m is None:
544
+ return None
545
+ return m[1] if m[1] is not None else m[2]
546
+
547
+
548
+ def _sheet_data_span(xml):
549
+ if b"<!" in xml:
550
+ return None
551
+ parser = expat.ParserCreate(namespace_separator="}")
552
+ depth, found = [0], []
553
+
554
+ def start(name, _attributes):
555
+ depth[0] += 1
556
+ if depth[0] == 2 and name == _MAIN_NS[1:] + "sheetData" and not found:
557
+ found.append(parser.CurrentByteIndex)
558
+
559
+ def end(name):
560
+ if depth[0] == 2 and name == _MAIN_NS[1:] + "sheetData" and len(found) == 1:
561
+ found.append(parser.CurrentByteIndex)
562
+ depth[0] -= 1
563
+
564
+ parser.StartElementHandler, parser.EndElementHandler = start, end
565
+ parser.Parse(xml, True)
566
+ return tuple(found) if len(found) == 2 else None
567
+
568
+
569
+ def _cells(xml):
570
+ span = _sheet_data_span(xml)
571
+ row = column = 0
572
+ for m in _ROW_OR_CELL_RE.finditer(xml, *span) if span else ():
573
+ if m[3] is None:
574
+ number = _attr(_R_RE, m[2])
575
+ row, column = int(number) if number else row + 1, 0
576
+ continue
577
+ ref = _attr(_R_RE, m[3])
578
+ if ref:
579
+ row, column = _row_major(ref.decode())
580
+ else:
581
+ column += 1
582
+ yield row, column, m
583
+
584
+
585
+ def _sheet_xml(archive, part_name):
586
+ xml = archive.read(part_name)
587
+ _utf8_or_refuse(xml, part_name)
588
+ body = xml[3:] if xml.startswith(b"\xef\xbb\xbf") else xml
589
+ if b"<!" in xml or body.count(b"<?") > bool(re.match(rb"<\?xml\s", body)):
590
+ raise ValueError(
591
+ f"{part_name} holds a comment, CDATA, a DTD or a processing instruction, which this "
592
+ "script cannot edit. Load and save the workbook with openpyxl first, or leave it as is"
593
+ )
594
+ try:
595
+ expat.ParserCreate().Parse(xml, True)
596
+ except expat.ExpatError as e:
597
+ raise ValueError(f"{part_name} is not well-formed XML: {e}") from None
598
+ return xml
599
+
600
+
601
+ def _array_cells(xml, budget):
602
+ cells = {}
603
+ for f in _F_RE.finditer(xml):
604
+ if _attr(_T_RE, f[1]) not in (b"array", b"dataTable"):
605
+ continue
606
+ first, _, last = (_attr(_REF_RE, f[1]) or b"").decode().partition(":")
607
+ if not last:
608
+ continue
609
+ (top, left), (bottom, right) = _row_major(first), _row_major(last)
610
+ if bottom < top or right < left:
611
+ continue
612
+ if len(cells) + (bottom - top + 1) * (right - left + 1) > budget:
613
+ continue
614
+ cells.update(
615
+ ((r, c), (top, left)) for r in range(top, bottom + 1) for c in range(left, right + 1)
616
+ )
617
+ return cells
618
+
619
+
620
+ def _computed(copy_path, array_cells, names):
621
+ computed, lacked = {}, {}
622
+ with zipfile.ZipFile(copy_path) as archive:
623
+ strings = None
624
+ its_names = _sheet_names(archive)
625
+ by_name = {ours.casefold(): ours for ours in names}
626
+ ours = {its: by_name[its.casefold()] for its in its_names if its.casefold() in by_name}
627
+ if len(its_names) == len(names):
628
+ for its, in_that_place in zip(its_names, names):
629
+ if its not in ours and in_that_place not in ours.values():
630
+ ours[its] = in_that_place
631
+ for name, part_name in _worksheets(archive):
632
+ name = ours.get(name, name)
633
+ cells, lacks = computed.setdefault(name, {}), lacked.setdefault(name, set())
634
+ wanted = array_cells.get(name, ())
635
+ for row, column, m in _cells(archive.read(part_name)):
636
+ content = m[4] or b""
637
+ if (row, column) not in wanted and not _F_RE.search(content):
638
+ continue
639
+ v = _V_RE.search(content)
640
+ kind, text = _attr(_T_RE, m[3]) or b"n", v and v[1]
641
+ if text is not None and kind == b"s":
642
+ if strings is None:
643
+ shared = _xml(archive.read("xl/sharedStrings.xml"))
644
+ strings = [_rich_text(si) for si in shared.iter(f"{_MAIN_NS}si")]
645
+ kind, text = b"str", html.escape(strings[int(text)], quote=False).encode()
646
+ f = _F_RE.search(content)
647
+ its_formula = (f and f[2]) or b""
648
+ if re.search(rb"[a-z]", its_formula):
649
+ called = [_PREFIX_RE.sub("", n) for n in _called(_text(its_formula))]
650
+ if any(n != n.upper() and n.upper() in LIBREOFFICE_LACKS for n in called):
651
+ lacks.add((row, column))
652
+ if _calls_its_own(_text(its_formula)):
653
+ kind, text = _NAME_ERROR
654
+ if text is not None and (kind == b"str" or (text and kind in (b"n", b"b", b"e"))):
655
+ cells[row, column] = (kind, text)
656
+ return computed, lacked
657
+
658
+
659
+ def _same_value(old_kind, old, kind, text):
660
+ if old is None:
661
+ return False
662
+ if (old_kind, old) == (kind, text):
663
+ return True
664
+ if {old_kind, kind} <= {b"n", b"b"}:
665
+ try:
666
+ return math.isclose(float(old), float(text), rel_tol=1e-14, abs_tol=1e-12)
667
+ except ValueError:
668
+ return False
669
+ return old_kind == kind and html.unescape(old.decode()) == html.unescape(text.decode())
670
+
671
+
672
+ def _cell_with_value(m, f, kind, text):
673
+ p = m[1] or b""
674
+ attrs = _T_OR_VM_RE.sub(b"", m[3])
675
+ if kind != b"n":
676
+ attrs += b' t="' + kind + b'"'
677
+ kept = b"" if f is None else m[4][: f.end()]
678
+ ext_lst = _EXT_LST_RE.search(m[4] or b"")
679
+ rest = ext_lst[0] if ext_lst else b""
680
+ return b"<%sc%s>%s<%sv>%s</%sv>%s</%sc>" % (p, attrs, kept, p, text, p, rest, p)
681
+
682
+
683
+ def _coordinate(row, column):
684
+ letters = ""
685
+ while column:
686
+ column, index = divmod(column - 1, 26)
687
+ letters = chr(ord("A") + index) + letters
688
+ return f"{letters}{row}"
689
+
690
+
691
+ def _text(formula):
692
+ text = formula.decode()
693
+ for entity, character in (("&lt;", "<"), ("&gt;", ">"), ("&quot;", '"'), ("&apos;", "'")):
694
+ text = text.replace(entity, character)
695
+ return text.replace("&amp;", "&")
696
+
697
+
698
+ def _called(formula):
699
+ names = _CALL_RE.findall(_QUOTED_RE.sub("", formula))
700
+ return [name for name in names if not name.lower().startswith("_xlpm.")]
701
+
702
+
703
+ def _lacking(name):
704
+ bare = _PREFIX_RE.sub("", name)
705
+ if bare.upper() not in LIBREOFFICE_LACKS:
706
+ return None
707
+ return bare != name or bare.upper() in _STORED_BARE
708
+
709
+
710
+ def _calls_its_own(formula):
711
+ names = [_PREFIX_RE.sub("", name) for name in _called(formula)]
712
+ return any(name != name.upper() and name != name.lower() for name in names)
713
+
714
+
715
+ def _unbalanced(formula):
716
+ bare = _QUOTED_RE.sub("", formula)
717
+ return bare.count("(") != bare.count(")")
718
+
719
+
720
+ def _reads_another_workbook(formula, reaching):
721
+ plain = _STRING_RE.sub("", formula)
722
+ if _EXTERNAL_REF_RE.search(plain):
723
+ return True
724
+ words = _WORD_RE.findall(_QUOTED_RE.sub("", plain)) if reaching else ()
725
+ return any(word.lower() in reaching for word in words)
726
+
727
+
728
+ def _names_reaching_another_workbook(archive):
729
+ reaching, used_by = set(), {}
730
+ for name in _workbook_xml(archive).iter(f"{_MAIN_NS}definedName"):
731
+ key, plain = name.get("name", "").lower(), _STRING_RE.sub("", name.text or "")
732
+ if _EXTERNAL_REF_RE.search(plain):
733
+ reaching.add(key)
734
+ for word in _WORD_RE.findall(_QUOTED_RE.sub("", plain)):
735
+ used_by.setdefault(word.lower(), set()).add(key)
736
+ todo = list(reaching)
737
+ while todo:
738
+ for user in used_by.get(todo.pop(), ()):
739
+ if user not in reaching:
740
+ reaching.add(user)
741
+ todo.append(user)
742
+ return reaching
743
+
744
+
745
+ def _verdict(formula, reaching=frozenset()):
746
+ lacking = [_lacking(name) for name in _called(formula)]
747
+ if False in lacking:
748
+ return "mistake"
749
+ if _reads_another_workbook(formula, reaching):
750
+ return "link"
751
+ return "lacks" if True in lacking else None
752
+
753
+
754
+ def _splice(xml, computed, lacked, array_cells, sheet_name, reaching, found):
755
+ out, done = [], 0
756
+ filling, filled, shared = set(), set(), {}
757
+ for row, column, m in _cells(xml):
758
+ content = m[4] or b""
759
+ f = _F_RE.search(content)
760
+ if f is None and array_cells.get((row, column)) not in filling:
761
+ continue
762
+ v = _V_RE.search(content, f.end() if f else 0)
763
+ old = v and (v[1] or b"")
764
+ kind = _attr(_T_RE, m[3]) or b"n"
765
+ new = computed.get((row, column))
766
+ verdict = None
767
+ if f is None:
768
+ filled.add((row, column))
769
+ else:
770
+ where = f"{sheet_name}!{_coordinate(row, column)}"
771
+ text, si = _text(f[2] or b""), _attr(_SI_RE, f[1])
772
+ verdict = _verdict(text, reaching) if text else shared.get(si)
773
+ if text and si:
774
+ shared[si] = verdict
775
+ if verdict == "lacks" and (row, column) not in lacked:
776
+ verdict = None
777
+ if _unbalanced(text):
778
+ found[UNBALANCED].append(where)
779
+ if verdict or new is None or new == _NAME_ERROR:
780
+ if f is not None:
781
+ has_value = old or (old is not None and kind == b"str")
782
+ held = has_value and (kind, old) != _NAME_ERROR
783
+ no_value_held = not verdict and new == _NAME_ERROR and not held
784
+ mistake = verdict == "mistake" or no_value_held
785
+ found["#NAME?" if mistake else "not_computed"].append(where)
786
+ continue
787
+ if f is not None:
788
+ filling.add((row, column))
789
+ if _same_value(kind, old, *new):
790
+ continue
791
+ out += [xml[done : m.start()], _cell_with_value(m, f, *new)]
792
+ done = m.end()
793
+ for cell, first in array_cells.items():
794
+ new = computed.get(cell)
795
+ held_by_the_sheet = cell == first or cell in filled
796
+ if first in filling and not held_by_the_sheet and new and new[0] == b"e":
797
+ error = new[1].decode()
798
+ if error != "#NAME?" and error in EXCEL_ERRORS:
799
+ found.setdefault(error, []).append(f"{sheet_name}!{_coordinate(*cell)}")
800
+ if not out:
801
+ return xml
802
+ out.append(xml[done:])
803
+ return b"".join(out)
804
+
805
+
806
+ def _replace_parts(path, parts):
807
+ handle, new_path = tempfile.mkstemp(
808
+ dir=os.path.dirname(path), prefix=".recalc-", suffix=Path(path).suffix
809
+ )
810
+ try:
811
+ with (
812
+ os.fdopen(handle, "wb") as out,
813
+ zipfile.ZipFile(path) as old,
814
+ zipfile.ZipFile(out, "w") as new,
815
+ ):
816
+ new.comment = old.comment
817
+ for item in old.infolist():
818
+ if item.filename in parts:
819
+ new.writestr(item, parts[item.filename])
820
+ continue
821
+ with old.open(item) as source, new.open(copy.copy(item), "w") as target:
822
+ shutil.copyfileobj(source, target)
823
+ status = os.stat(path)
824
+ with contextlib.suppress(OSError, AttributeError):
825
+ os.chown(new_path, status.st_uid, status.st_gid)
826
+ shutil.copystat(path, new_path)
827
+ os.utime(new_path)
828
+ os.replace(new_path, path)
829
+ except BaseException:
830
+ with contextlib.suppress(OSError):
831
+ os.unlink(new_path)
832
+ raise
833
+
834
+
835
+ def _write_values(path, copy_path):
836
+ with zipfile.ZipFile(path) as archive:
837
+ sheets = _worksheets(archive)
838
+ reaching = _names_reaching_another_workbook(archive)
839
+ array_cells = {}
840
+ for name, part_name in sheets:
841
+ budget = MAX_ARRAY_CELLS - sum(map(len, array_cells.values()))
842
+ array_cells[name] = _array_cells(_sheet_xml(archive, part_name), budget)
843
+ computed, lacked = _computed(copy_path, array_cells, _sheet_names(archive))
844
+ parts, found = {}, {"#NAME?": [], UNBALANCED: [], "not_computed": []}
845
+ for name, part_name in sheets:
846
+ xml = archive.read(part_name)
847
+ if name not in computed and _F_RE.search(xml):
848
+ raise ValueError(
849
+ f"LibreOffice's copy has no sheet called {name!r}: it renames or drops some "
850
+ "sheets, such as one whose name is over 31 characters, so this sheet's "
851
+ "formulas cannot be recalculated"
852
+ )
853
+ cells, lacks = computed.get(name, {}), lacked.get(name, ())
854
+ new = _splice(xml, cells, lacks, array_cells[name], name, reaching, found)
855
+ if new is not xml:
856
+ try:
857
+ expat.ParserCreate().Parse(new, True)
858
+ except expat.ExpatError as e:
859
+ raise ValueError(f"editing {part_name} as text broke its XML ({e})") from None
860
+ parts[part_name] = new
861
+ if parts:
862
+ _replace_parts(path, parts)
863
+ return found
864
+
281
865
 
282
866
  def main():
867
+ signal.signal(signal.SIGTERM, lambda *_: sys.exit(143))
283
868
  args = [a for a in sys.argv[1:] if a != "--force"]
284
869
  force = "--force" in sys.argv[1:]
285
870
 
286
871
  if not args:
287
872
  print("Usage: python recalc.py <excel_file> [timeout_seconds] [--force]")
288
873
  print("\nRecalculates all formulas in an Excel file using LibreOffice")
874
+ print("LibreOffice works on a copy; only the values it computes are written into the file.")
289
875
  print("\nReturns JSON with error details:")
290
876
  print(" - status: 'success' or 'errors_found'")
291
877
  print(" - total_errors: Total number of Excel errors found")
292
878
  print(" - total_formulas: Number of formulas in the file")
293
879
  print(" - error_summary: Breakdown by error type with locations")
294
- print(" - #VALUE!, #DIV/0!, #REF!, #NAME?, #NULL!, #NUM!, #N/A")
880
+ print(" - #VALUE!, #DIV/0!, #REF!, #NAME?, #NULL!, #NUM!, #N/A, unbalanced brackets")
881
+ print(" - not_computed: only if LibreOffice could not compute some formulas: a function")
882
+ print(" it lacks, or a link to another workbook. Those cells are left as they were, and")
883
+ print(" Excel computes them when it opens a file openpyxl saved. A sound formula that")
884
+ print(" depends on one of them reports #NAME? too")
295
885
  print("\nOn any failure the JSON has an 'error' key and no 'status'.")
296
- print("--force recalculates even when it would destroy external links.")
886
+ print("--force is accepted and ignored.")
297
887
  sys.exit(1)
298
888
 
299
889
  filename = args[0]
300
- timeout = int(args[1]) if len(args) > 1 else 30
890
+ try:
891
+ timeout = int(args[1]) if len(args) > 1 else 30
892
+ except ValueError:
893
+ result = {"error": f"timeout must be an integer number of seconds, got {args[1]!r}"}
894
+ print(json.dumps(result, indent=2))
895
+ sys.exit(1)
301
896
 
302
897
  result = recalc(filename, timeout, force=force)
303
898
  print(json.dumps(result, indent=2))