xlsx.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  1. #!/usr/bin/env python3
  2. """
  3. xlsx.py — Unified Excel Quality Assurance & Manipulation Tool
  4. Commands:
  5. recalc <xlsx> [timeout] Recalculate formulas via LibreOffice + error scan
  6. audit <xlsx> Formula error + zero-value + implicit array detection
  7. scan <xlsx> Reference anomaly detection
  8. inspect <xlsx> [--pretty] Structure analysis → JSON
  9. pivot <in> <out> [options] PivotTable with optional chart
  10. chart-verify <xlsx> Verify chart data content
  11. validate <xlsx> Structural validation (forbidden funcs, schema)
  12. Usage:
  13. "$(command -v zcode-python || command -v python3)" xlsx.py <command> [args...]
  14. "$(command -v zcode-python || command -v python3)" xlsx.py --help
  15. """
  16. from __future__ import annotations
  17. import argparse
  18. import asyncio
  19. import json
  20. import platform
  21. import re
  22. import sys
  23. import zipfile
  24. from collections import defaultdict
  25. from pathlib import Path
  26. from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
  27. # 统一脚本随插件分发;不再写用户默认宏库,Windows 也不复用 Linux 配置路径。
  28. # 导入统一入口不应在已分发插件中生成字节码缓存。
  29. sys.dont_write_bytecode = True
  30. sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'scripts'))
  31. from zcode_libreoffice import LibreOfficeInvocationError, LibreOfficeUnavailable, run_cli_operation, run_libreoffice
  32. try:
  33. from openpyxl import load_workbook, Workbook
  34. from openpyxl.utils import get_column_letter, column_index_from_string
  35. from openpyxl.utils.cell import coordinate_from_string
  36. except ImportError:
  37. print("Error: openpyxl required. Install: \"$(command -v zcode-python || command -v python3)\" -m pip install openpyxl", file=sys.stderr)
  38. sys.exit(1)
  39. # ═══════════════════════════════════════════════════════════════
  40. # Section 0: Command registry + shared constants & helpers
  41. # ═══════════════════════════════════════════════════════════════
  42. _COMMANDS: Dict[str, Callable] = {}
  43. def cmd(name: str):
  44. """Decorator that registers a function as a CLI command."""
  45. def decorator(fn: Callable) -> Callable:
  46. _COMMANDS[name] = fn
  47. return fn
  48. return decorator
  49. # --------------- constants ---------------
  50. EXCEL_ERRORS = {"#VALUE!", "#DIV/0!", "#REF!", "#NAME?", "#NULL!", "#NUM!", "#N/A"}
  51. # Implicit array formula patterns that work in LibreOffice but fail in MS Excel
  52. IMPLICIT_ARRAY_PATTERNS = [
  53. (re.compile(r'MATCH\s*\(\s*TRUE\s*\(\s*\)', re.IGNORECASE),
  54. "MATCH(TRUE(), ...) requires CSE in Excel. Use SUMPRODUCT or helper column."),
  55. (re.compile(r'MATCH\s*\(\s*TRUE\s*,', re.IGNORECASE),
  56. "MATCH(TRUE, ...) with comparison range requires CSE. Use SUMPRODUCT."),
  57. (re.compile(r'MATCH\s*\([^,]+[<>=!]+[^,]+,', re.IGNORECASE),
  58. "MATCH with inline comparison requires CSE. Use SUMPRODUCT or helper column."),
  59. ]
  60. FORBIDDEN_FUNCTIONS = {
  61. "FILTER", "UNIQUE", "SORT", "SORTBY", "XLOOKUP", "XMATCH",
  62. "SEQUENCE", "LET", "LAMBDA", "RANDARRAY",
  63. "ARRAYFORMULA", "QUERY", "IMPORTRANGE",
  64. }
  65. # [Fix ①] Pattern to detect valid formula content (function calls or cell references)
  66. # A real formula must contain at least one of:
  67. # - Function call: ALPHA_CHARS( e.g. SUM(, IF(, VLOOKUP(
  68. # - Cell reference: $?[A-Z]{1,3}$?\d+ e.g. A1, $B$5, $A$1:$A$10
  69. _VALID_FORMULA_PATTERN = re.compile(
  70. r'[A-Z]{2,}\s*\(' # function call (2+ uppercase letters followed by parenthesis)
  71. r'|'
  72. r'\$?[A-Z]{1,3}\$?\d+' # cell reference like A1, $B$5
  73. ,
  74. re.IGNORECASE,
  75. )
  76. # [Fix ②] Pattern to detect external file references in formulas
  77. # Matches [filename.xlsx]SheetName! or [filename.xls]SheetName! etc.
  78. _EXT_FILE_REF_PATTERN = re.compile(r"\[([^\]]+\.(xlsx?|xlsm|xlsb|csv))\]", re.IGNORECASE)
  79. # --------------- helpers ---------------
  80. def cell_ref(sheet_name: str, cell) -> str:
  81. return f"{sheet_name}!{cell.coordinate}"
  82. def is_formula(value) -> bool:
  83. return isinstance(value, str) and value.startswith("=")
  84. def parse_range(range_str: str) -> Tuple[Optional[str], int, int, int, int]:
  85. """Parse 'Sheet!A1:F100' into (sheet, min_col, min_row, max_col, max_row)."""
  86. if "!" in range_str:
  87. sheet, rng = range_str.rsplit("!", 1)
  88. sheet = sheet.strip("'\"")
  89. else:
  90. sheet = None
  91. rng = range_str
  92. parts = rng.split(":")
  93. if len(parts) == 2:
  94. c1, r1 = coordinate_from_string(parts[0])
  95. c2, r2 = coordinate_from_string(parts[1])
  96. return sheet, column_index_from_string(c1), r1, column_index_from_string(c2), r2
  97. else:
  98. c1, r1 = coordinate_from_string(parts[0])
  99. return sheet, column_index_from_string(c1), r1, column_index_from_string(c1), r1
  100. # ═══════════════════════════════════════════════════════════════
  101. # Section 1: recalc — LibreOffice recalculation + error scan
  102. # ═══════════════════════════════════════════════════════════════
  103. def _libreoffice_recalc(filename: str, timeout: int = 30) -> Dict[str, Any]:
  104. """
  105. Recalculate formulas in an Excel file via LibreOffice,
  106. then scan ALL cells for errors.
  107. Returns a dict with status, error counts, and locations.
  108. """
  109. if not Path(filename).exists():
  110. return {"error": f"File {filename} does not exist"}
  111. try:
  112. invocation = run_cli_operation(run_libreoffice([], recalculate=Path(filename), timeout=timeout))
  113. except asyncio.CancelledError as error:
  114. raise SystemExit(143 if error.args == ('SIGTERM',) else 130) from None
  115. except (LibreOfficeUnavailable, LibreOfficeInvocationError, OSError, ValueError) as error:
  116. return {"error": str(error)}
  117. # Scan recalculated file for Excel errors
  118. try:
  119. wb = load_workbook(filename, data_only=True)
  120. excel_errors_list = [
  121. "#VALUE!", "#DIV/0!", "#REF!", "#NAME?", "#NULL!", "#NUM!", "#N/A"
  122. ]
  123. error_details: Dict[str, List[str]] = {err: [] for err in excel_errors_list}
  124. total_errors = 0
  125. for sheet_name in wb.sheetnames:
  126. ws = wb[sheet_name]
  127. for row in ws.iter_rows():
  128. for cell in row:
  129. if cell.value is not None and isinstance(cell.value, str):
  130. for err in excel_errors_list:
  131. if err in cell.value:
  132. location = f"{sheet_name}!{cell.coordinate}"
  133. error_details[err].append(location)
  134. total_errors += 1
  135. break
  136. wb.close()
  137. out: Dict[str, Any] = {
  138. "status": "success" if total_errors == 0 else "errors_found",
  139. "total_errors": total_errors,
  140. "error_summary": {},
  141. "libreoffice_source": invocation.source,
  142. "libreoffice_version": invocation.version,
  143. }
  144. if invocation.source == "system":
  145. # 修复原因:原先只输出版本,丢掉统一入口给出的“受管版本未使用”原因,违反 LibreOffice 规格。
  146. out["notice"] = invocation.notice
  147. for err_type, locations in error_details.items():
  148. if locations:
  149. out["error_summary"][err_type] = {
  150. "count": len(locations),
  151. "locations": locations[:20],
  152. }
  153. # Count formulas for context
  154. wb_formulas = load_workbook(filename, data_only=False)
  155. formula_count = 0
  156. for sheet_name in wb_formulas.sheetnames:
  157. ws = wb_formulas[sheet_name]
  158. for row in ws.iter_rows():
  159. for cell in row:
  160. if cell.value and isinstance(cell.value, str) and cell.value.startswith("="):
  161. formula_count += 1
  162. wb_formulas.close()
  163. out["total_formulas"] = formula_count
  164. return out
  165. except Exception as e:
  166. return {"error": str(e)}
  167. @cmd("recalc")
  168. def cmd_recalc(argv: Sequence[str]) -> int:
  169. """Recalculate formulas via LibreOffice and report errors."""
  170. parser = argparse.ArgumentParser(prog="xlsx.py recalc",
  171. description="Recalculate Excel formulas via LibreOffice")
  172. parser.add_argument("file", help="Excel file path")
  173. parser.add_argument("timeout", nargs="?", type=int, default=30,
  174. help="Timeout in seconds (default: 30)")
  175. args = parser.parse_args(argv)
  176. result = _libreoffice_recalc(args.file, args.timeout)
  177. print(json.dumps(result, indent=2, ensure_ascii=False))
  178. if "error" in result:
  179. return 1
  180. return 0 if result.get("total_errors", 0) == 0 else 1
  181. # ═══════════════════════════════════════════════════════════════
  182. # Section 2: audit — Formula error + zero-value + implicit array
  183. # ═══════════════════════════════════════════════════════════════
  184. def _run_libreoffice_recalc_best_effort(filepath: str) -> None:
  185. """Attempt LibreOffice recalc (best-effort, swallow errors)."""
  186. try:
  187. _libreoffice_recalc(filepath, timeout=30)
  188. except Exception:
  189. pass
  190. @cmd("audit")
  191. def cmd_audit(argv: Sequence[str]) -> int:
  192. """Detect formula errors, zero-value formulas, and implicit array formulas."""
  193. parser = argparse.ArgumentParser(prog="xlsx.py audit",
  194. description="Formula error scan + zero-value + implicit array detection")
  195. parser.add_argument("file", help="Excel file path")
  196. args = parser.parse_args(argv)
  197. path = Path(args.file)
  198. if not path.exists():
  199. print(json.dumps({"error": f"File not found: {path}"}))
  200. return 1
  201. # Best-effort LibreOffice recalculation first
  202. _run_libreoffice_recalc_best_effort(str(path))
  203. wb_data = load_workbook(str(path), data_only=True)
  204. wb_form = load_workbook(str(path), data_only=False)
  205. errors: List[Dict[str, Any]] = []
  206. zero_values: List[Dict[str, str]] = []
  207. implicit_arrays: List[Dict[str, str]] = []
  208. total_formulas = 0
  209. for sname in wb_form.sheetnames:
  210. ws_d = wb_data[sname]
  211. ws_f = wb_form[sname]
  212. for row_d, row_f in zip(ws_d.iter_rows(), ws_f.iter_rows()):
  213. for cd, cf in zip(row_d, row_f):
  214. fval = cf.value
  215. if not is_formula(fval):
  216. continue
  217. total_formulas += 1
  218. fstr = str(fval)
  219. # Check for formula errors in calculated value
  220. dval = cd.value
  221. if dval is not None and isinstance(dval, str):
  222. for err in EXCEL_ERRORS:
  223. if err in dval:
  224. errors.append({
  225. "cell": cell_ref(sname, cd),
  226. "error": err,
  227. "formula": fstr[:120],
  228. })
  229. break
  230. # Check for zero values (potential reference errors)
  231. if isinstance(dval, (int, float)) and dval == 0:
  232. zero_values.append({
  233. "cell": cell_ref(sname, cd),
  234. "formula": fstr[:120],
  235. })
  236. # Check for implicit array formula patterns
  237. for pattern, msg in IMPLICIT_ARRAY_PATTERNS:
  238. if pattern.search(fstr):
  239. implicit_arrays.append({
  240. "cell": cell_ref(sname, cf),
  241. "formula": fstr[:120],
  242. "issue": msg,
  243. })
  244. break
  245. wb_data.close()
  246. wb_form.close()
  247. result: Dict[str, Any] = {
  248. "total_formulas": total_formulas,
  249. "error_count": len(errors),
  250. "zero_value_count": len(zero_values),
  251. "implicit_array_count": len(implicit_arrays),
  252. }
  253. if errors:
  254. result["errors"] = errors[:50]
  255. if zero_values:
  256. result["zero_values"] = zero_values[:30]
  257. if implicit_arrays:
  258. result["implicit_arrays"] = implicit_arrays[:20]
  259. print(json.dumps(result, indent=2, ensure_ascii=False))
  260. return 1 if errors else 0
  261. # ═══════════════════════════════════════════════════════════════
  262. # Section 3: scan — Reference anomaly detection
  263. # ═══════════════════════════════════════════════════════════════
  264. @cmd("scan")
  265. def cmd_scan(argv: Sequence[str]) -> int:
  266. """Detect reference anomalies in formulas."""
  267. parser = argparse.ArgumentParser(prog="xlsx.py scan",
  268. description="Reference anomaly detection")
  269. parser.add_argument("file", help="Excel file path")
  270. args = parser.parse_args(argv)
  271. path = Path(args.file)
  272. if not path.exists():
  273. print(json.dumps({"error": f"File not found: {path}"}))
  274. return 1
  275. wb = load_workbook(str(path), data_only=False)
  276. findings: List[Dict[str, str]] = []
  277. # Pre-collect max_row for every sheet (used for cross-sheet ref check)
  278. sheet_max_rows: Dict[str, int] = {}
  279. sheet_max_cols: Dict[str, int] = {}
  280. for sn in wb.sheetnames:
  281. sw = wb[sn]
  282. sheet_max_rows[sn] = sw.max_row or 1
  283. sheet_max_cols[sn] = sw.max_column or 1
  284. for sname in wb.sheetnames:
  285. ws = wb[sname]
  286. max_data_row = sheet_max_rows[sname]
  287. max_data_col = sheet_max_cols[sname]
  288. # Collect formulas by column for pattern analysis
  289. col_formulas: Dict[Tuple[str, str], List[Tuple[int, str]]] = defaultdict(list)
  290. for row in ws.iter_rows(min_row=1, max_row=max_data_row,
  291. min_col=1, max_col=max_data_col):
  292. for c in row:
  293. if not is_formula(c.value):
  294. continue
  295. fstr = str(c.value)
  296. col_letter = get_column_letter(c.column)
  297. col_formulas[(sname, col_letter)].append((c.row, fstr))
  298. # --- Out-of-range references ---
  299. # Check for cross-sheet references: SheetName!A1:A242
  300. cross_sheet = re.findall(r"([A-Za-z_]\w*?)!([A-Z]{1,3})(\d+):([A-Z]{1,3})(\d+)", fstr)
  301. if cross_sheet:
  302. for tgt_sheet, c1, r1, c2, r2 in cross_sheet:
  303. tgt_rows = sheet_max_rows.get(tgt_sheet, 0)
  304. r2_int = int(r2)
  305. # Only flag if target sheet exists and range truly exceeds it
  306. if tgt_rows > 0 and r2_int > tgt_rows * 3 and r2_int > 100:
  307. findings.append({
  308. "type": "out_of_range",
  309. "cell": cell_ref(sname, c),
  310. "detail": f"Range {tgt_sheet}!{c1}{r1}:{c2}{r2} extends far beyond {tgt_sheet} data ({tgt_rows} rows)",
  311. "formula": fstr[:100],
  312. })
  313. else:
  314. # Same-sheet reference check
  315. range_refs = re.findall(r'([A-Z]{1,3})(\d+):([A-Z]{1,3})(\d+)', fstr)
  316. for c1, r1, c2, r2 in range_refs:
  317. r1_int, r2_int = int(r1), int(r2)
  318. if r2_int > max_data_row * 3 and r2_int > 100:
  319. findings.append({
  320. "type": "out_of_range",
  321. "cell": cell_ref(sname, c),
  322. "detail": f"Range {c1}{r1}:{c2}{r2} extends far beyond data ({max_data_row} rows)",
  323. "formula": fstr[:100],
  324. })
  325. # --- Header row inclusion ---
  326. agg_pattern = re.compile(
  327. r'(SUM|AVERAGE|AVG|COUNT|COUNTA|MIN|MAX|SUMPRODUCT)\s*\(\s*([A-Z]{1,3})1:',
  328. re.IGNORECASE,
  329. )
  330. agg_match = agg_pattern.search(fstr)
  331. if agg_match and c.row > 1:
  332. findings.append({
  333. "type": "header_included",
  334. "cell": cell_ref(sname, c),
  335. "detail": f"{agg_match.group(1)}() starts at row 1 (header row)",
  336. "formula": fstr[:100],
  337. })
  338. # --- Insufficient aggregate range ---
  339. small_range = re.compile(
  340. r'(SUM|AVERAGE|AVG|COUNT|COUNTA)\s*\(\s*([A-Z]{1,3})(\d+):([A-Z]{1,3})(\d+)\s*\)',
  341. re.IGNORECASE,
  342. )
  343. for m in small_range.finditer(fstr):
  344. func, _, r1s, _, r2s = m.groups()
  345. span = abs(int(r2s) - int(r1s)) + 1
  346. if span <= 2:
  347. findings.append({
  348. "type": "small_aggregate",
  349. "cell": cell_ref(sname, c),
  350. "detail": f"{func}() covers only {span} cell(s)",
  351. "formula": fstr[:100],
  352. })
  353. # --- Inconsistent formula patterns within same column ---
  354. for (sh, col), entries in col_formulas.items():
  355. if len(entries) < 3:
  356. continue
  357. patterns: Dict[str, List[int]] = defaultdict(list)
  358. for row_num, fstr in entries:
  359. norm = re.sub(r'(\$?[A-Z]{1,3}\$?)\d+', r'\1#', fstr)
  360. patterns[norm].append(row_num)
  361. if len(patterns) <= 1:
  362. continue
  363. dominant_pat = max(patterns, key=lambda k: len(patterns[k]))
  364. dominant_rows = patterns[dominant_pat]
  365. for pat, rows in patterns.items():
  366. if pat == dominant_pat:
  367. continue
  368. if len(rows) <= 2 and len(rows) < len(dominant_rows):
  369. for r in rows:
  370. orig = next((f for rn, f in entries if rn == r), "?")
  371. findings.append({
  372. "type": "inconsistent_pattern",
  373. "cell": f"{sh}!{col}{r}",
  374. "detail": f"Formula differs from {len(dominant_rows)} other rows in column {col}",
  375. "formula": orig[:100],
  376. })
  377. wb.close()
  378. result: Dict[str, Any] = {
  379. "total_findings": len(findings),
  380. "by_type": {},
  381. }
  382. for f in findings:
  383. t = f["type"]
  384. result["by_type"].setdefault(t, 0)
  385. result["by_type"][t] += 1
  386. if findings:
  387. result["findings"] = findings[:60]
  388. print(json.dumps(result, indent=2, ensure_ascii=False))
  389. return 1 if findings else 0
  390. # ═══════════════════════════════════════════════════════════════
  391. # Section 4: inspect — Structure analysis → JSON
  392. # ═══════════════════════════════════════════════════════════════
  393. @cmd("inspect")
  394. def cmd_inspect(argv: Sequence[str]) -> int:
  395. """Analyse Excel file structure and output JSON."""
  396. parser = argparse.ArgumentParser(prog="xlsx.py inspect",
  397. description="Analyse file structure → JSON")
  398. parser.add_argument("file", help="Excel file path")
  399. parser.add_argument("--pretty", action="store_true", help="Pretty-print JSON")
  400. args = parser.parse_args(argv)
  401. path = Path(args.file)
  402. if not path.exists():
  403. print(json.dumps({"error": f"File not found: {path}"}))
  404. return 1
  405. wb = load_workbook(str(path), data_only=False, read_only=False)
  406. sheets_info: List[Dict[str, Any]] = []
  407. for sname in wb.sheetnames:
  408. ws = wb[sname]
  409. max_row = ws.max_row or 0
  410. max_col = ws.max_column or 0
  411. # Extract headers (first row)
  412. headers: List[Optional[str]] = []
  413. if max_row > 0 and max_col > 0:
  414. for cell in ws[1]:
  415. if cell.value is not None:
  416. headers.append(str(cell.value))
  417. else:
  418. headers.append(None)
  419. # Build data range string
  420. if max_row > 0 and max_col > 0:
  421. data_range = f"A1:{get_column_letter(max_col)}{max_row}"
  422. else:
  423. data_range = None
  424. # Count formulas and data rows
  425. formula_count = 0
  426. data_rows = 0
  427. for row in ws.iter_rows(min_row=2, max_row=max_row, max_col=max_col):
  428. has_data = False
  429. for c in row:
  430. if c.value is not None:
  431. has_data = True
  432. if is_formula(c.value):
  433. formula_count += 1
  434. if has_data:
  435. data_rows += 1
  436. # Detect charts
  437. chart_count = 0
  438. if hasattr(ws, "_charts"):
  439. chart_count = len(ws._charts)
  440. sheet_info: Dict[str, Any] = {
  441. "name": sname,
  442. "dataRange": data_range,
  443. "rows": max_row,
  444. "columns": max_col,
  445. "dataRows": data_rows,
  446. "formulaCount": formula_count,
  447. "chartCount": chart_count,
  448. "tables": [{
  449. "headers": [h for h in headers if h is not None]
  450. }] if headers and any(h is not None for h in headers) else [],
  451. }
  452. sheets_info.append(sheet_info)
  453. wb.close()
  454. output = {"sheets": sheets_info}
  455. indent = 2 if args.pretty else None
  456. print(json.dumps(output, indent=indent, ensure_ascii=False))
  457. return 0
  458. # ═══════════════════════════════════════════════════════════════
  459. # Section 5: pivot — PivotTable with optional chart
  460. # ═══════════════════════════════════════════════════════════════
  461. def _aggregate(values: List[float], method: str) -> float:
  462. """Compute aggregation on a list of numbers."""
  463. if not values:
  464. return 0.0
  465. if method == "sum":
  466. return sum(values)
  467. elif method == "count":
  468. return float(len(values))
  469. elif method == "average":
  470. return sum(values) / len(values)
  471. elif method == "max":
  472. return max(values)
  473. elif method == "min":
  474. return min(values)
  475. return sum(values)
  476. @cmd("pivot")
  477. def cmd_pivot(argv: Sequence[str]) -> int:
  478. """Create a PivotTable-like summary with optional chart using openpyxl."""
  479. parser = argparse.ArgumentParser(prog="xlsx.py pivot",
  480. description="Create PivotTable summary with optional chart")
  481. parser.add_argument("input", help="Input Excel file")
  482. parser.add_argument("output", help="Output Excel file")
  483. parser.add_argument("--source", required=True, help="Source range: 'Sheet!A1:Z100'")
  484. parser.add_argument("--values", required=True, help="Value fields: 'Revenue:sum,Units:count'")
  485. parser.add_argument("--rows", default=None, help="Row fields: 'Product,Region'")
  486. parser.add_argument("--cols", default=None, help="Column fields: 'Quarter'")
  487. parser.add_argument("--filters", default=None, help="Filter fields: 'Year'")
  488. parser.add_argument("--location", default="PivotTable!A3", help="Output location: 'Sheet!A3'")
  489. parser.add_argument("--name", default="PivotTable1", help="PivotTable name")
  490. parser.add_argument("--style", default="monochrome", choices=["monochrome", "finance"],
  491. help="Visual style theme")
  492. parser.add_argument("--chart", default=None, choices=["bar", "line", "pie"],
  493. help="Chart type (optional)")
  494. args = parser.parse_args(argv)
  495. input_path = Path(args.input)
  496. output_path = Path(args.output)
  497. if not input_path.exists():
  498. print(json.dumps({"error": f"Input file not found: {input_path}"}))
  499. return 1
  500. # Parse source range
  501. src_sheet, src_min_col, src_min_row, src_max_col, src_max_row = parse_range(args.source)
  502. # Parse location
  503. loc = parse_range(args.location)
  504. loc_sheet = loc[0]
  505. loc_start_col = loc[1]
  506. loc_start_row = loc[2]
  507. # Parse value fields
  508. value_fields: List[Tuple[str, str]] = []
  509. for vspec in args.values.split(","):
  510. vspec = vspec.strip()
  511. if ":" in vspec:
  512. fname, agg = vspec.rsplit(":", 1)
  513. agg = agg.strip().lower()
  514. if agg in ("avg", "average"):
  515. agg = "average"
  516. else:
  517. fname = vspec
  518. agg = "sum"
  519. value_fields.append((fname.strip(), agg))
  520. row_fields = [f.strip() for f in args.rows.split(",") if f.strip()] if args.rows else []
  521. col_fields = [f.strip() for f in args.cols.split(",") if f.strip()] if args.cols else []
  522. filter_fields = [f.strip() for f in args.filters.split(",") if f.strip()] if args.filters else []
  523. # Load workbook
  524. wb = load_workbook(str(input_path))
  525. if src_sheet not in wb.sheetnames:
  526. print(json.dumps({"error": f"Source sheet '{src_sheet}' not found"}))
  527. return 1
  528. ws_src = wb[src_sheet]
  529. # Read headers from first row of source
  530. headers: List[str] = []
  531. for col_idx in range(src_min_col, src_max_col + 1):
  532. val = ws_src.cell(row=src_min_row, column=col_idx).value
  533. headers.append(str(val) if val is not None else f"Col{col_idx}")
  534. # Build column index map
  535. col_map = {h: i for i, h in enumerate(headers)}
  536. # Validate field names
  537. all_fields = row_fields + col_fields + [vf[0] for vf in value_fields] + filter_fields
  538. for f in all_fields:
  539. if f not in col_map:
  540. print(json.dumps({"error": f"Field '{f}' not found. Available: {headers}"}))
  541. return 1
  542. # Read data rows
  543. data_rows: List[Dict[str, Any]] = []
  544. for row_idx in range(src_min_row + 1, src_max_row + 1):
  545. row_data: Dict[str, Any] = {}
  546. for col_idx in range(src_min_col, src_max_col + 1):
  547. h = headers[col_idx - src_min_col]
  548. row_data[h] = ws_src.cell(row=row_idx, column=col_idx).value
  549. if any(v is not None for v in row_data.values()):
  550. data_rows.append(row_data)
  551. # Aggregate data
  552. def make_key(row: Dict[str, Any], fields: List[str]) -> Tuple[str, ...]:
  553. return tuple(str(row.get(f, "")) for f in fields)
  554. group_fields = row_fields + col_fields
  555. groups: Dict[Tuple[str, ...], Dict[str, List[float]]] = defaultdict(lambda: defaultdict(list))
  556. for row in data_rows:
  557. key = make_key(row, group_fields)
  558. for vname, _ in value_fields:
  559. val = row.get(vname)
  560. if isinstance(val, (int, float)):
  561. groups[key][vname].append(float(val))
  562. # Create or get output sheet
  563. if loc_sheet and loc_sheet in wb.sheetnames:
  564. ws_out = wb[loc_sheet]
  565. elif loc_sheet:
  566. ws_out = wb.create_sheet(loc_sheet)
  567. else:
  568. ws_out = wb.create_sheet("PivotTable")
  569. # ---- Styling ----
  570. from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
  571. # --- Font resolution (mirrors templates/base.py logic) ---
  572. _platform_hints = {
  573. "Darwin": {"Noto Sans SC", "Noto Sans CJK SC"},
  574. "Windows": {"Noto Sans SC", "Noto Sans SC"},
  575. "Linux": {"Noto Sans CJK SC", "WenQuanYi Micro Hei"},
  576. }
  577. _cjk_chain = ["Noto Sans SC", "Noto Sans CJK SC",
  578. "Source Han Sans SC", "WenQuanYi Micro Hei"]
  579. _avail = _platform_hints.get(platform.system(), set())
  580. _font_name = next((f for f in _cjk_chain if f in _avail), _cjk_chain[0])
  581. _heavy = {"Noto Sans SC", "Noto Sans CJK SC",
  582. "Source Han Sans SC", "WenQuanYi Micro Hei"}
  583. _header_bold = _font_name not in _heavy
  584. if args.style == "finance":
  585. header_fill_color = "1B2A4A" # PRIMARY from design token
  586. alt_row_color = "D6E4F0" # PRIMARY_LIGHT
  587. else: # monochrome
  588. header_fill_color = "333333"
  589. alt_row_color = "F5F5F5"
  590. header_fill = PatternFill(start_color=header_fill_color,
  591. end_color=header_fill_color, fill_type="solid")
  592. header_font = Font(name=_font_name, color="FFFFFF", bold=_header_bold, size=11)
  593. data_font = Font(name=_font_name, size=11)
  594. alt_fill = PatternFill(start_color=alt_row_color,
  595. end_color=alt_row_color, fill_type="solid")
  596. border = Border(bottom=Side(style="thin", color="D0D0D0"))
  597. # Determine if cross-matrix mode (--cols provided)
  598. use_cross_matrix = len(col_fields) > 0
  599. if use_cross_matrix:
  600. # ── Cross-matrix mode: row_fields as rows, col_fields expanded as columns ──
  601. # Collect unique column dimension values
  602. col_dim_values: List[str] = []
  603. seen_col_vals: set = set()
  604. for row in data_rows:
  605. cv = str(row.get(col_fields[0], ""))
  606. if cv not in seen_col_vals:
  607. seen_col_vals.add(cv)
  608. col_dim_values.append(cv)
  609. col_dim_values.sort()
  610. # Build cross-matrix groups: key = row_fields only, sub-key = col_dim value
  611. cross_groups: Dict[Tuple[str, ...], Dict[str, Dict[str, List[float]]]] = defaultdict(
  612. lambda: defaultdict(lambda: defaultdict(list))
  613. )
  614. for row in data_rows:
  615. rkey = make_key(row, row_fields)
  616. cval = str(row.get(col_fields[0], ""))
  617. for vname, _ in value_fields:
  618. val = row.get(vname)
  619. if isinstance(val, (int, float)):
  620. cross_groups[rkey][cval][vname].append(float(val))
  621. # Build output headers: row_fields + (col_val - agg_name) for each combination
  622. out_headers: List[str] = list(row_fields)
  623. for cv in col_dim_values:
  624. for vname, agg in value_fields:
  625. if len(value_fields) == 1:
  626. out_headers.append(f"{cv}")
  627. else:
  628. out_headers.append(f"{cv} ({vname} {agg})")
  629. # Write headers
  630. r = loc_start_row
  631. for i, h in enumerate(out_headers):
  632. cell = ws_out.cell(row=r, column=loc_start_col + i, value=h)
  633. cell.fill = header_fill
  634. cell.font = header_font
  635. cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
  636. # Sort row keys
  637. sorted_row_keys = sorted(cross_groups.keys())
  638. # Write data rows
  639. for idx, rkey in enumerate(sorted_row_keys):
  640. r += 1
  641. for i, val in enumerate(rkey):
  642. cell = ws_out.cell(row=r, column=loc_start_col + i, value=val)
  643. cell.font = data_font
  644. cell.border = border
  645. if idx % 2 == 1:
  646. cell.fill = alt_fill
  647. col_offset = len(row_fields)
  648. for cv in col_dim_values:
  649. for vname, agg in value_fields:
  650. vals = cross_groups[rkey].get(cv, {}).get(vname, [])
  651. agg_result = _aggregate(vals, agg) if vals else 0
  652. cell = ws_out.cell(row=r, column=loc_start_col + col_offset,
  653. value=round(agg_result, 2))
  654. cell.font = data_font
  655. cell.border = border
  656. cell.number_format = "#,##0.00"
  657. if idx % 2 == 1:
  658. cell.fill = alt_fill
  659. col_offset += 1
  660. sorted_keys = sorted_row_keys
  661. total_data_rows_for_chart = len(sorted_row_keys)
  662. else:
  663. # ── Flat mode: no --cols, original behavior ──
  664. out_headers: List[str] = list(row_fields)
  665. for vname, agg in value_fields:
  666. out_headers.append(f"{vname} ({agg})")
  667. # Write headers
  668. r = loc_start_row
  669. for i, h in enumerate(out_headers):
  670. cell = ws_out.cell(row=r, column=loc_start_col + i, value=h)
  671. cell.fill = header_fill
  672. cell.font = header_font
  673. cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
  674. # Sort keys for consistent output
  675. sorted_keys = sorted(groups.keys())
  676. # Write data rows
  677. for idx, key in enumerate(sorted_keys):
  678. r += 1
  679. # Row fields
  680. for i, val in enumerate(key[:len(row_fields)]):
  681. cell = ws_out.cell(row=r, column=loc_start_col + i, value=val)
  682. cell.font = data_font
  683. cell.border = border
  684. if idx % 2 == 1:
  685. cell.fill = alt_fill
  686. # Value fields
  687. for i, (vname, agg) in enumerate(value_fields):
  688. vals = groups[key].get(vname, [])
  689. agg_result = _aggregate(vals, agg)
  690. col_offset = len(row_fields) + i
  691. cell = ws_out.cell(row=r, column=loc_start_col + col_offset,
  692. value=round(agg_result, 2))
  693. cell.font = data_font
  694. cell.border = border
  695. cell.number_format = "#,##0.00"
  696. if idx % 2 == 1:
  697. cell.fill = alt_fill
  698. total_data_rows_for_chart = len(sorted_keys)
  699. # Auto-adjust column widths (data-driven, headers wrap if too wide)
  700. try:
  701. from templates.base import auto_fit_columns, auto_fit_row_heights
  702. auto_fit_columns(ws_out, min_width=10, max_width=28,
  703. header_row=loc_start_row, data_start_row=loc_start_row + 1)
  704. auto_fit_row_heights(ws_out, header_row=loc_start_row, data_start_row=loc_start_row + 1)
  705. except ImportError:
  706. # Fallback: old logic
  707. for i, h in enumerate(out_headers):
  708. col_letter = get_column_letter(loc_start_col + i)
  709. ws_out.column_dimensions[col_letter].width = max(len(str(h)) + 4, 14)
  710. # Hide gridlines
  711. ws_out.sheet_view.showGridLines = False
  712. # Add chart if requested
  713. has_chart = False
  714. total_data_rows = total_data_rows_for_chart
  715. if args.chart and total_data_rows > 0:
  716. from openpyxl.chart import BarChart, LineChart, PieChart, Reference
  717. chart_type_map = {
  718. "bar": BarChart,
  719. "line": LineChart,
  720. "pie": PieChart,
  721. }
  722. ChartClass = chart_type_map.get(args.chart, BarChart)
  723. chart = ChartClass()
  724. chart.title = args.name or "PivotTable Summary"
  725. chart.style = 10
  726. data_ref = Reference(
  727. ws_out,
  728. min_col=loc_start_col + len(row_fields),
  729. min_row=loc_start_row,
  730. max_col=loc_start_col + len(out_headers) - 1,
  731. max_row=loc_start_row + total_data_rows,
  732. )
  733. cats_ref = Reference(
  734. ws_out,
  735. min_col=loc_start_col,
  736. min_row=loc_start_row + 1,
  737. max_row=loc_start_row + total_data_rows,
  738. )
  739. chart.add_data(data_ref, titles_from_data=True)
  740. chart.set_categories(cats_ref)
  741. if isinstance(chart, BarChart):
  742. chart.type = "col"
  743. # Pie chart: prevent label overlap with bestFit + leader lines
  744. if isinstance(chart, PieChart):
  745. from openpyxl.chart.label import DataLabelList
  746. chart.dataLabels = DataLabelList()
  747. chart.dataLabels.dLblPos = 'bestFit'
  748. chart.dataLabels.showLeaderLines = True
  749. chart.dataLabels.showCatName = True
  750. chart.dataLabels.showPercent = True
  751. chart.dataLabels.showVal = False
  752. chart.dataLabels.showSerName = False
  753. # Anchor with enough vertical offset to avoid chart-to-chart overlap
  754. # ~15 rows per chart height; leave 2 extra rows gap
  755. chart_row_offset = 17
  756. chart_anchor = ws_out.cell(
  757. row=loc_start_row + total_data_rows + 3,
  758. column=loc_start_col,
  759. ).coordinate
  760. ws_out.add_chart(chart, chart_anchor)
  761. has_chart = True
  762. wb.save(str(output_path))
  763. wb.close()
  764. # [Fix ③] Auto-recalc after pivot if chart was created, so chart data cache is populated
  765. if has_chart:
  766. try:
  767. _run_libreoffice_recalc_best_effort(str(output_path))
  768. except Exception:
  769. pass
  770. print(json.dumps({
  771. "status": "success",
  772. "output": str(output_path),
  773. "pivot_rows": total_data_rows,
  774. "fields": {
  775. "rows": row_fields,
  776. "columns": col_fields,
  777. "values": [f"{v}:{a}" for v, a in value_fields],
  778. "filters": filter_fields,
  779. },
  780. "chart": args.chart or "none",
  781. }, indent=2, ensure_ascii=False))
  782. return 0
  783. # ═══════════════════════════════════════════════════════════════
  784. # Section 6: chart-verify — Verify chart data content
  785. # ═══════════════════════════════════════════════════════════════
  786. def _check_charts(filepath: str) -> Tuple[List[Dict], List[Dict]]:
  787. """Core chart verification logic. Returns (ok_charts, empty_charts)."""
  788. wb = load_workbook(filepath)
  789. ok_charts: List[Dict[str, str]] = []
  790. empty_charts: List[Dict[str, str]] = []
  791. for sname in wb.sheetnames:
  792. ws = wb[sname]
  793. if not hasattr(ws, "_charts"):
  794. continue
  795. for chart in ws._charts:
  796. chart_title = "untitled"
  797. if chart.title:
  798. try:
  799. parts = []
  800. for p in chart.title.tx.rich.paragraphs:
  801. for run in p.r:
  802. if hasattr(run, 't') and run.t:
  803. parts.append(run.t)
  804. chart_title = "".join(parts) if parts else "untitled"
  805. except (AttributeError, TypeError):
  806. chart_title = "untitled"
  807. has_data = False
  808. for series in (chart.series if hasattr(chart, "series") else []):
  809. if hasattr(series, "val") and series.val:
  810. ref = series.val
  811. if hasattr(ref, "numRef") and ref.numRef:
  812. cache = ref.numRef.numCache if hasattr(ref.numRef, "numCache") else None
  813. if cache and hasattr(cache, "ptCount") and cache.ptCount and cache.ptCount > 0:
  814. has_data = True
  815. break
  816. if hasattr(ref, "numLit") and ref.numLit:
  817. has_data = True
  818. break
  819. entry = {"sheet": sname, "title": chart_title}
  820. if has_data:
  821. ok_charts.append(entry)
  822. else:
  823. empty_charts.append(entry)
  824. wb.close()
  825. return ok_charts, empty_charts
  826. @cmd("chart-verify")
  827. def cmd_chart_verify(argv: Sequence[str]) -> int:
  828. """Verify all charts have actual data content.
  829. [Fix ④] Automatically recalc first if charts appear empty, then re-check.
  830. """
  831. parser = argparse.ArgumentParser(prog="xlsx.py chart-verify",
  832. description="Verify all charts have actual data")
  833. parser.add_argument("file", help="Excel file path")
  834. parser.add_argument("--no-auto-recalc", action="store_true",
  835. help="Disable automatic recalc before checking")
  836. args = parser.parse_args(argv)
  837. path = Path(args.file)
  838. if not path.exists():
  839. print(json.dumps({"error": f"File not found: {path}"}))
  840. return 1
  841. ok_charts, empty_charts = _check_charts(str(path))
  842. # [Fix ④] If there are empty charts and auto-recalc is enabled, try recalc first
  843. if empty_charts and not args.no_auto_recalc:
  844. try:
  845. _run_libreoffice_recalc_best_effort(str(path))
  846. # Re-check after recalc
  847. ok_charts, empty_charts = _check_charts(str(path))
  848. except Exception:
  849. pass
  850. total_charts = len(ok_charts) + len(empty_charts)
  851. result: Dict[str, Any] = {
  852. "total_charts": total_charts,
  853. "charts_with_data": len(ok_charts),
  854. "empty_charts": len(empty_charts),
  855. }
  856. if empty_charts:
  857. result["empty"] = empty_charts
  858. if ok_charts:
  859. result["ok"] = ok_charts
  860. print(json.dumps(result, indent=2, ensure_ascii=False))
  861. if empty_charts:
  862. return 1
  863. if total_charts == 0:
  864. print("No charts found in workbook.", file=sys.stderr)
  865. return 0
  866. return 0
  867. # ═══════════════════════════════════════════════════════════════
  868. # Section 7: validate — Structural validation
  869. # ═══════════════════════════════════════════════════════════════
  870. @cmd("validate")
  871. def cmd_validate(argv: Sequence[str]) -> int:
  872. """Structural validation: forbidden functions, formula hygiene, schema basics."""
  873. parser = argparse.ArgumentParser(prog="xlsx.py validate",
  874. description="Structural validation (forbidden funcs, schema)")
  875. parser.add_argument("file", help="Excel file path")
  876. args = parser.parse_args(argv)
  877. path = Path(args.file)
  878. if not path.exists():
  879. print(json.dumps({"error": f"File not found: {path}"}))
  880. return 1
  881. wb = load_workbook(str(path), data_only=False)
  882. issues: List[Dict[str, str]] = []
  883. for sname in wb.sheetnames:
  884. ws = wb[sname]
  885. for row in ws.iter_rows():
  886. for c in row:
  887. if not is_formula(c.value):
  888. continue
  889. fstr = str(c.value).upper()
  890. # Check for forbidden functions
  891. for func in FORBIDDEN_FUNCTIONS:
  892. pattern = re.compile(rf'\b{func}\s*\(', re.IGNORECASE)
  893. if pattern.search(fstr):
  894. issues.append({
  895. "type": "forbidden_function",
  896. "cell": cell_ref(sname, c),
  897. "function": func,
  898. "detail": f"{func}() is not supported in Excel 2019 and earlier",
  899. "formula": str(c.value)[:100],
  900. })
  901. # Check for text accidentally treated as formula
  902. raw = str(c.value)
  903. is_formula_cell = getattr(c, "data_type", None) == "f"
  904. if (raw.startswith("=") and not is_formula_cell
  905. and not any(ch in raw for ch in "+-*/()&,!:$")):
  906. issues.append({
  907. "type": "text_as_formula",
  908. "cell": cell_ref(sname, c),
  909. "detail": "Text starts with '=' — may be misinterpreted as formula",
  910. "value": raw[:80],
  911. })
  912. # [Fix ①] Heuristic: data_type=='f' but content has no valid formula elements
  913. if is_formula_cell and raw.startswith("="):
  914. body = raw[1:] # strip leading =
  915. body_stripped = body.strip()
  916. if body_stripped.startswith('"'):
  917. pass # starts with a quoted string, likely intentional
  918. elif not _VALID_FORMULA_PATTERN.search(body):
  919. issues.append({
  920. "type": "text_as_formula",
  921. "cell": cell_ref(sname, c),
  922. "detail": "Cell stored as formula but contains no function calls or cell references — likely text starting with '='",
  923. "value": raw[:80],
  924. })
  925. # [Fix ②] Check for external file references in formulas
  926. if _EXT_FILE_REF_PATTERN.search(fstr):
  927. ext_matches = _EXT_FILE_REF_PATTERN.findall(fstr)
  928. for ext_file, _ in ext_matches:
  929. issues.append({
  930. "type": "external_file_ref",
  931. "cell": cell_ref(sname, c),
  932. "detail": f"Formula references external file: {ext_file}",
  933. "formula": str(c.value)[:100],
  934. })
  935. # Check for absolute paths / local file references in .rels
  936. try:
  937. with zipfile.ZipFile(str(path), "r") as zf:
  938. for name in zf.namelist():
  939. if name.endswith(".rels"):
  940. content = zf.read(name).decode("utf-8", errors="ignore")
  941. if re.search(r'Target="[A-Z]:\\', content):
  942. issues.append({
  943. "type": "absolute_path",
  944. "file": name,
  945. "detail": "Absolute Windows path in .rels file — causes Excel crash",
  946. })
  947. if "file:///" in content.lower():
  948. issues.append({
  949. "type": "local_file_ref",
  950. "file": name,
  951. "detail": "Local file:// reference in .rels — may cause security warning",
  952. })
  953. except Exception:
  954. pass # zipfile inspection is best-effort
  955. wb.close()
  956. by_type: Dict[str, int] = defaultdict(int)
  957. for iss in issues:
  958. by_type[iss["type"]] += 1
  959. result: Dict[str, Any] = {
  960. "status": "passed" if not issues else "failed",
  961. "total_issues": len(issues),
  962. "by_type": dict(by_type),
  963. }
  964. if issues:
  965. result["issues"] = issues[:50]
  966. print(json.dumps(result, indent=2, ensure_ascii=False))
  967. return 0 if not issues else 1
  968. # ═══════════════════════════════════════════════════════════════
  969. # Section 8: CLI entry point
  970. # ═══════════════════════════════════════════════════════════════
  971. _HELP_TEXT = """\
  972. xlsx.py — Unified Excel Quality Assurance & Manipulation Tool
  973. Usage: "$(command -v zcode-python || command -v python3)" xlsx.py <command> [args...]
  974. Commands:
  975. recalc <xlsx> [timeout] Recalculate formulas via LibreOffice + error scan
  976. audit <xlsx> Formula error + zero-value + implicit array detection
  977. scan <xlsx> Reference anomaly detection
  978. inspect <xlsx> [--pretty] Structure analysis → JSON
  979. pivot <in> <out> --source ... [options] PivotTable with optional chart
  980. chart-verify <xlsx> [--no-auto-recalc] Verify chart data content
  981. validate <xlsx> Structural validation
  982. Run '"$(command -v zcode-python || command -v python3)" xlsx.py <command> --help' for command-specific options.
  983. """
  984. def main() -> int:
  985. if len(sys.argv) < 2 or sys.argv[1] in ("--help", "-h"):
  986. print(_HELP_TEXT)
  987. return 0
  988. command = sys.argv[1]
  989. rest = sys.argv[2:]
  990. handler = _COMMANDS.get(command)
  991. if handler is None:
  992. print(f"Unknown command: {command}\n", file=sys.stderr)
  993. print(_HELP_TEXT, file=sys.stderr)
  994. return 1
  995. return handler(rest)
  996. if __name__ == "__main__":
  997. sys.exit(main())