path:
/helper.py
4.66 KB | plain
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#!/usr/bin/env python3
"""Pack/unpack the extracted ODS, keeping Basic modules as .bas files."""
from pathlib import Path, PurePosixPath
import shutil
import sys
import tempfile
import xml.etree.ElementTree as ET
from xml.sax.saxutils import escape
import zipfile
ROOT = Path(__file__).resolve().parent
ODS = ROOT / "SondageAutomation.ods"
BASIC = ROOT / "Basic" / "Standard"
ODF_DIRS = ("Basic", "Configurations2", "META-INF", "Thumbnails")
# Git cannot track the original empty ZIP directories.
EMPTY_DIRS = ("toolpanel", "accelerator", "floater", "progressbar",
"images/Bitmaps", "menubar", "popupmenu", "statusbar", "toolbar")
MODULE = ('<?xml version="1.0" encoding="UTF-8"?>\n'
'<!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">\n'
'<script:module xmlns:script="http://openoffice.org/2000/script" '
'script:name="{name}" script:language="StarBasic" script:moduleType="normal">'
'{code}</script:module>')
def pack():
sources = sorted(BASIC.glob("*.bas"))
library = ET.parse(BASIC / "script-lb.xml").getroot()
declared = {element.get("{http://openoffice.org/2000/library}name") for element in library}
if not sources or {p.stem for p in sources} != declared:
raise ValueError(".bas files must match the Standard Basic library")
with tempfile.NamedTemporaryFile(suffix=".ods", dir=ROOT, delete=False) as file:
tmp = Path(file.name)
try:
with zipfile.ZipFile(tmp, "w") as archive:
archive.write(ROOT / "mimetype", "mimetype", compress_type=zipfile.ZIP_STORED)
files = [p for p in ROOT.iterdir() if p.is_file() and p.suffix in (".xml", ".rdf")]
files += [p for name in ODF_DIRS for p in (ROOT / name).rglob("*")
if p.is_file() and p.suffix != ".bas"]
for path in sorted(files):
name = path.relative_to(ROOT).as_posix()
if name.startswith("Basic/Standard/") and path.with_suffix(".bas").exists():
continue # .bas is the source, not a leftover generated XML file.
archive.write(path, name, compress_type=zipfile.ZIP_DEFLATED)
for path in sources:
archive.writestr("Basic/Standard/" + path.stem + ".xml",
MODULE.format(name=path.stem, code=escape(path.read_text(encoding="utf-8"))),
compress_type=zipfile.ZIP_DEFLATED)
for name in EMPTY_DIRS:
archive.writestr("Configurations2/" + name + "/", b"")
with zipfile.ZipFile(tmp) as archive:
assert archive.testzip() is None
assert archive.infolist()[0].filename == "mimetype"
assert archive.infolist()[0].compress_type == zipfile.ZIP_STORED
assert not archive.infolist()[0].extra
if ODS.exists():
shutil.copy2(ODS, ODS.with_suffix(".ods.bak"))
tmp.replace(ODS)
finally:
tmp.unlink(missing_ok=True)
print(f"packed {ODS.name} from {len(sources)} Basic modules")
def unpack():
with zipfile.ZipFile(ODS) as archive:
if archive.testzip() is not None:
raise ValueError("invalid workbook ZIP")
contents = {}
directories = []
for name in archive.namelist():
path = PurePosixPath(name)
if not path.parts or path.is_absolute() or ".." in path.parts or not (
name == "mimetype" or path.parts[0] in ODF_DIRS
or (len(path.parts) == 1 and path.suffix in (".xml", ".rdf"))):
raise ValueError(f"unexpected workbook path: {name}")
if name.endswith("/"):
directories.append(name)
else:
data = archive.read(name)
if name.startswith("Basic/Standard/") and name.endswith(".xml") and name != "Basic/Standard/script-lb.xml":
data = (ET.fromstring(data).text or "").encode("utf-8")
name = name[:-4] + ".bas"
contents[name] = data
for name in directories:
(ROOT / name).mkdir(parents=True, exist_ok=True)
for name, data in contents.items():
target = ROOT / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
if name.startswith("Basic/Standard/") and name.endswith(".bas"):
target.with_suffix(".xml").unlink(missing_ok=True)
print(f"unpacked {len(contents)} files from {ODS.name}")
if __name__ == "__main__":
if len(sys.argv) != 2 or sys.argv[1] not in ("pack", "unpack"):
raise SystemExit("usage: python helper.py {pack|unpack}")
(pack if sys.argv[1] == "pack" else unpack)()