vba 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
vba/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """Read, change, debug and install VBA for Word, Excel and PowerPoint."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("vba")
7
+ except PackageNotFoundError:
8
+ __version__ = "0"
9
+
10
+
11
+ class VBAError(Exception):
12
+ """A problem to show to the user as is."""
13
+
14
+
15
+ class Busy(VBAError):
16
+ """The app waits on a dialog or a macro. Sending it anything more can make it quit (Excel does)."""
vba/cli.py ADDED
@@ -0,0 +1,200 @@
1
+ """The command line."""
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from . import VBAError, __version__, core, mac
8
+
9
+ HELP = """\
10
+ Read, change, debug and install VBA for Word, Excel and PowerPoint.
11
+
12
+ Usage:
13
+ vba APP list [--file FILE]
14
+ vba APP pull MACRO... [--file FILE] [-o OUT.bas]
15
+ vba APP load CODE.bas
16
+ vba APP run MACRO [ARG...] (--doc DOC | --new) [--in-place] [--timeout SEC]
17
+ vba APP exec CODE.bas MACRO [ARG...] (--doc DOC | --new) [--in-place] [--timeout SEC]
18
+ vba APP unload [--loader]
19
+ vba APP install CODE.bas [--file FILE] [--module NAME] [--dry-run]
20
+ vba APP status
21
+ vba mcp
22
+ APP word, excel (xl) or powerpoint (ppt)
23
+ list Macros in your macro file
24
+ pull A macro with the procedures it uses, as text to edit
25
+ load Load the code into the running app as a dev add-in; again to update it
26
+ run Run a loaded macro
27
+ exec load, run and unload
28
+ unload Remove the dev add-in
29
+ install Put the code in your macro file (the app must be closed)
30
+ status Whether the app runs, the add-in is loaded, or a dialog is open
31
+ mcp Serve the same actions, except install, as an MCP server
32
+ --file FILE Macro file (default: Normal.dotm, PERSONAL.XLSB)
33
+ --doc DOC Run on this file, opened if needed
34
+ --new Run on a new blank file, left open
35
+ --in-place Excel: use the file itself instead of a copy
36
+ --timeout SEC How long a macro may take (default: 60)
37
+ --loader Excel: also remove the loader add-in
38
+ --module NAME Module for code that is not in the file yet
39
+ --dry-run Show the change without writing
40
+ -V, --version Show the version
41
+ -h, --help Show this help
42
+
43
+ Notes:
44
+ 1. What works where:
45
+ Mac everything
46
+ Windows list, pull and install, not yet tried on a real Windows PC; no live commands (load, run, exec,
47
+ unload, status). Test a change in the VBA editor, then install it. Normal.dotm and PERSONAL.XLSB
48
+ are looked for in %APPDATA%\\Microsoft; use --file if yours is elsewhere.
49
+ Linux list, pull and install, with --file; not yet tried either
50
+ 2. PowerPoint has no default macro file: use --file or VBA_POWERPOINT_FILE.
51
+ VBA_WORD_FILE and VBA_EXCEL_FILE replace the other defaults.
52
+ 3. A .pptm with a .ppam beside it: install updates both.
53
+ 4. Excel cannot undo a macro, so run and exec work on a copy of --doc. Word and PowerPoint use the file itself.
54
+ 5. Excel needs a restart the first time, for its loader add-in.
55
+ 6. install replaces the procedures in CODE.bas by name, adds those the file lacks, and leaves the rest alone.
56
+ It never deletes one. It backs up, checks the result, then swaps the file in one step; undo is the backup.
57
+ 7. Backups and copies: ~/Library/Application Support/vba (Windows: %LOCALAPPDATA%\\vba; Linux:
58
+ ~/.local/share/vba), or VBA_HOME.
59
+ 8. A dialog is reported, never clicked, and nothing more is sent to the app until it is gone.
60
+ Seeing it needs the Accessibility permission, so live actions do too.
61
+
62
+ Example:
63
+ Fix a macro you already have:
64
+ vba word list # 1. find it
65
+ vba word pull Insert_FormattedTable -o box.bas # 2. copy it out with its helpers
66
+ (edit box.bas) # 3. keep the names; no renaming needed
67
+ vba word exec box.bas Insert_FormattedTable --doc t.docx # 4. test, edit, repeat; or --new (Mac)
68
+ vba word install box.bas --dry-run # 5. see the change
69
+ vba word install box.bas # 6. after quitting Word
70
+ A macro that uses the selection: select it in the file first, then exec.
71
+ """
72
+
73
+
74
+ class Parser(argparse.ArgumentParser):
75
+ def format_help(self):
76
+ return HELP
77
+
78
+ def error(self, message):
79
+ raise VBAError(f"{message} (try --help)")
80
+
81
+
82
+ def parser():
83
+ p = Parser(prog="vba")
84
+ p.add_argument("-V", "--version", action="version", version=__version__)
85
+ p.add_argument("app")
86
+ actions = p.add_subparsers(dest="action", required=True)
87
+
88
+ def action(name, *positional, file=False, where=False):
89
+ a = actions.add_parser(name)
90
+ for arg, kw in positional:
91
+ a.add_argument(arg, **kw)
92
+ if file:
93
+ a.add_argument("--file")
94
+ if where:
95
+ a.add_argument("--doc")
96
+ a.add_argument("--new", action="store_true")
97
+ a.add_argument("--in-place", action="store_true")
98
+ a.add_argument("--timeout", type=int, default=60)
99
+ return a
100
+
101
+ code, macro, args = ("code", {}), ("macro", {}), ("args", {"nargs": "*"})
102
+ action("list", file=True)
103
+ action("pull", ("names", {"nargs": "+"}), file=True).add_argument("-o", "--out")
104
+ action("load", code)
105
+ action("run", macro, args, where=True)
106
+ action("exec", code, macro, args, where=True)
107
+ action("unload").add_argument("--loader", action="store_true")
108
+ a = action("install", code, file=True)
109
+ a.add_argument("--module")
110
+ a.add_argument("--dry-run", action="store_true")
111
+ action("status")
112
+ return p
113
+
114
+
115
+ def warn(answer):
116
+ for w in answer.get("warnings", []):
117
+ print(f"note: {w}", file=sys.stderr)
118
+
119
+
120
+ def do(o):
121
+ host = core.get_host(o.app)
122
+ if o.action == "list":
123
+ answer = core.list_macros(host, o.file)
124
+ print(answer["file"])
125
+ for module, procs in answer["modules"].items():
126
+ for p in procs:
127
+ print(f"{module}\t{'private ' if p['private'] else ''}{p['kind']}\t{p['name']}")
128
+ elif o.action == "pull":
129
+ text = core.pull(host, o.names, o.file)
130
+ if o.out:
131
+ out = Path(o.out).expanduser()
132
+ if out.exists():
133
+ raise VBAError(f"{out} exists")
134
+ out.write_text(text, encoding="utf-8")
135
+ print(out)
136
+ else:
137
+ sys.stdout.write(text)
138
+ elif o.action == "load":
139
+ answer = core.load(host, core.read_code(o.code))
140
+ warn(answer)
141
+ print(f"loaded {answer['loaded']}")
142
+ elif o.action in ("run", "exec"):
143
+ where = {"doc": o.doc, "new": o.new, "in_place": o.in_place, "timeout": o.timeout}
144
+ if o.action == "run":
145
+ answer = core.run(host, o.macro, o.args, **where)
146
+ else:
147
+ answer = core.execute(host, core.read_code(o.code), o.macro, o.args, **where)
148
+ warn(answer)
149
+ print(f"ran {o.macro} on {answer['target']}{' (a copy)' if answer['copy'] else ''}", file=sys.stderr)
150
+ if answer["result"]:
151
+ print(answer["result"])
152
+ elif o.action == "unload":
153
+ if o.loader and host.key != "excel":
154
+ raise VBAError("--loader is for excel")
155
+ print("unloaded" if core.unload(host)["unloaded"] else "nothing was loaded")
156
+ if o.loader:
157
+ print("loader removed" if mac.remove_loader(host) else "no loader")
158
+ elif o.action == "install":
159
+ answer = core.install(host, core.read_code(o.code), o.file, o.module, o.dry_run)
160
+ for f in answer["files"]:
161
+ if answer["dry_run"]:
162
+ print(f["diff"] or f"{f['file']}: no change")
163
+ continue
164
+ print(f"{f['file']}: " + (f"replaced {', '.join(f['replaced']) or 'none'}; "
165
+ f"added {', '.join(f['added']) or 'none'}" if f["changed"] else "no change"))
166
+ if f["changed"]:
167
+ print(f"backup: {f['backup']}")
168
+ elif o.action == "status":
169
+ for key, value in core.status(host).items():
170
+ print(f"{key}\t{value}")
171
+
172
+
173
+ def main(argv=None):
174
+ argv = sys.argv[1:] if argv is None else argv
175
+ if not argv:
176
+ print(HELP, end="")
177
+ return 0
178
+ for stream in (sys.stdout, sys.stderr):
179
+ if hasattr(stream, "reconfigure"): # Windows may not print every character of the code otherwise
180
+ stream.reconfigure(encoding="utf-8")
181
+ try:
182
+ if argv == ["mcp"]:
183
+ from . import mcp
184
+ return mcp.serve()
185
+ # plain help for anything that asks, also after an action
186
+ if "-h" in argv or "--help" in argv:
187
+ print(HELP, end="")
188
+ return 0
189
+ do(parser().parse_args(argv))
190
+ except VBAError as e:
191
+ print(f"vba: {e}", file=sys.stderr)
192
+ return 1
193
+ except (OSError, KeyboardInterrupt) as e:
194
+ print(f"vba: {e or 'stopped'}", file=sys.stderr)
195
+ return 1
196
+ return 0
197
+
198
+
199
+ if __name__ == "__main__":
200
+ sys.exit(main())
vba/core.py ADDED
@@ -0,0 +1,227 @@
1
+ """The actions behind both the command line and the MCP server."""
2
+
3
+ import difflib
4
+ import os
5
+ import re
6
+ import shutil
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from . import Busy, VBAError, files, mac, source
11
+
12
+
13
+ def get_host(name):
14
+ key = name.lower()
15
+ key = {"ppt": "powerpoint", "xl": "excel"}.get(key, key)
16
+ if key not in files.HOSTS:
17
+ raise VBAError(f"unknown app {name}; use word, excel or powerpoint")
18
+ return files.HOSTS[key]
19
+
20
+
21
+ def default_file(key):
22
+ if sys.platform == "darwin":
23
+ return {"word": mac.CONTENT / "Templates.localized/Normal.dotm",
24
+ "excel": mac.CONTENT / "Startup.localized/Excel/PERSONAL.XLSB"}.get(key)
25
+ if sys.platform == "win32" and os.environ.get("APPDATA"):
26
+ office = Path(os.environ["APPDATA"]) / "Microsoft"
27
+ return {"word": office / "Templates/Normal.dotm", "excel": office / "Excel/XLSTART/PERSONAL.XLSB"}.get(key)
28
+ return None
29
+
30
+
31
+ def macro_file(host, given=None):
32
+ """The file that holds the user's own macros."""
33
+ path = given or os.environ.get(f"VBA_{host.key.upper()}_FILE")
34
+ if not path:
35
+ path = default_file(host.key)
36
+ if not path:
37
+ raise VBAError(f"name the macro file with --file or VBA_{host.key.upper()}_FILE")
38
+ return files.check(host, path)
39
+
40
+
41
+ def read_code(path):
42
+ """A .bas file: UTF-8, or the Mac encoding that the VBA editor exports."""
43
+ path = Path(path).expanduser()
44
+ if not path.is_file():
45
+ raise VBAError(f"no such file: {path}")
46
+ data = path.read_bytes()
47
+ try:
48
+ return data.decode("utf-8-sig")
49
+ except UnicodeDecodeError:
50
+ return data.decode("mac_roman")
51
+
52
+
53
+ def dev_source(host):
54
+ return files.home() / "dev" / f"{host.key}.bas"
55
+
56
+
57
+ def list_macros(host, file=None):
58
+ path = macro_file(host, file)
59
+ with files.Project(host, path) as p:
60
+ return {"file": str(path), "modules": {
61
+ m: [{"name": x.name, "kind": x.kind, "private": x.private} for x in ps]
62
+ for m, ps in p.procedures().items()}}
63
+
64
+
65
+ def pull(host, names, file=None):
66
+ path = macro_file(host, file)
67
+ with files.Project(host, path) as p:
68
+ module = None
69
+ for m, ps in p.procedures().items():
70
+ if names[0].lower() in {x.name.lower() for x in ps}:
71
+ module = m
72
+ break
73
+ if module is None:
74
+ raise VBAError(f"{names[0]} is not in {path.name}")
75
+ return source.extract(p.modules()[module], names)
76
+
77
+
78
+ def check_dev(host, code, file=None):
79
+ """Refuse what would run by itself; warn about what may behave differently in an add-in."""
80
+ code = source.normalize(code)
81
+ procs = source.procedures(code)
82
+ if not procs:
83
+ raise VBAError("the code has no procedure")
84
+ auto = [p.name for p in procs if source.AUTO.match(p.name)]
85
+ if auto:
86
+ raise VBAError(f"{host.app} could run {', '.join(auto)} by itself: rename or leave out")
87
+ reserved = [p.name for p in procs if p.name.lower().startswith("vbadev")]
88
+ if reserved:
89
+ raise VBAError(f"names starting with VBADev are used by this tool: {', '.join(reserved)}")
90
+ warnings = []
91
+ plain = "\n".join(source.without_comment(line) for line in code.split("\n"))
92
+ for word in ("ThisDocument", "ThisWorkbook", "Me"):
93
+ if re.search(rf"(?<![\w.]){word}\b", plain, re.I):
94
+ warnings.append(f"{word} means the add-in here, not the file the code came from")
95
+ try:
96
+ with files.Project(host, macro_file(host, file)) as p:
97
+ theirs = {x.name.lower() for ps in p.procedures().values() for x in ps if not x.private}
98
+ except VBAError:
99
+ theirs = set()
100
+ same = [p.name for p in procs if not p.private and p.name.lower() in theirs]
101
+ if same:
102
+ warnings.append(f"also in your macro file: {', '.join(same)}; run and exec use the code given here, "
103
+ "but a button or shortcut may run either while the add-in is loaded")
104
+ return warnings
105
+
106
+
107
+ def load(host, code):
108
+ warnings = check_dev(host, code)
109
+ path = mac.load(host, source.normalize(code))
110
+ keep = dev_source(host)
111
+ keep.parent.mkdir(parents=True, exist_ok=True)
112
+ keep.write_text(source.normalize(code), encoding="utf-8")
113
+ return {"loaded": str(path), "warnings": warnings}
114
+
115
+
116
+ def target(host, doc=None, new=False, in_place=False):
117
+ """(full name of the active target, the path used, whether it is a copy)"""
118
+ if new == bool(doc):
119
+ raise VBAError("say what to run on: --doc PATH or --new")
120
+ mac.start(host)
121
+ if new:
122
+ return mac.new_target(host), None, False
123
+ path = Path(doc).expanduser().resolve()
124
+ if not path.is_file():
125
+ raise VBAError(f"no such file: {path}")
126
+ copied = host.key == "excel" and not in_place
127
+ if copied:
128
+ folder = files.home() / "copies"
129
+ folder.mkdir(parents=True, exist_ok=True)
130
+ copy = folder / f"{path.stem}-{files.stamp()}{path.suffix}"
131
+ shutil.copy2(path, copy)
132
+ path = copy
133
+ return mac.open_target(host, path), path, copied
134
+
135
+
136
+ def run_code(host, code, macro, args=(), doc=None, new=False, in_place=False, timeout=60):
137
+ warnings = check_dev(host, code)
138
+ # fail on a wrong macro name before anything opens
139
+ mac.runner(host, code, macro, args, "", "")
140
+ if host.key == "excel":
141
+ # before the target, which would start Excel without it
142
+ mac.ensure_loader(host)
143
+ name, path, copied = target(host, doc, new, in_place)
144
+ result = mac.run(host, source.normalize(code), macro, list(args), name, timeout)
145
+ return {"result": result, "target": str(path or name), "copy": copied, "warnings": warnings}
146
+
147
+
148
+ def run(host, macro, args=(), **where):
149
+ keep = dev_source(host)
150
+ if not keep.is_file():
151
+ raise VBAError("nothing is loaded: use load first, or exec")
152
+ return run_code(host, keep.read_text(encoding="utf-8"), macro, args, **where)
153
+
154
+
155
+ def execute(host, code, macro, args=(), **where):
156
+ try:
157
+ answer = run_code(host, code, macro, args, **where)
158
+ except Busy as e:
159
+ raise Busy(f"{e}\nThe add-in is still loaded: once {host.app} is free, run unload.") from None
160
+ except BaseException as e:
161
+ try:
162
+ unload(host)
163
+ except VBAError as u:
164
+ raise VBAError(f"{e}\nand the add-in could not be unloaded: {u}") from None
165
+ raise
166
+ unload(host)
167
+ return answer
168
+
169
+
170
+ def unload(host):
171
+ had = mac.unload(host)
172
+ dev_source(host).unlink(missing_ok=True)
173
+ return {"unloaded": had}
174
+
175
+
176
+ def status(host):
177
+ mac.require_mac()
178
+ on = mac.running(host)
179
+ shown = mac.dialogs(host) if on else ""
180
+ answer = {"app": host.app, "running": on, "loaded": "unknown" if shown else mac.is_loaded(host),
181
+ "dev_file": mac.dev_path(host).exists(), "dialog": shown}
182
+ if host.key == "excel":
183
+ answer["loader"] = mac.LOADER.exists()
184
+ return answer
185
+
186
+
187
+ def install(host, code, file=None, module=None, dry_run=False):
188
+ """Put procedures in the user's macro file: backed up, checked, and only with the app closed."""
189
+ path = macro_file(host, file)
190
+ code = source.normalize(code)
191
+ targets = [path]
192
+ if path.suffix.lower() == ".ppam" and path.with_suffix(".pptm").exists():
193
+ raise VBAError(f"use --file {path.with_suffix('.pptm')}: it is the source, and the .ppam is updated with it")
194
+ if path.suffix.lower() == ".pptm" and path.with_suffix(".ppam").exists():
195
+ targets.append(path.with_suffix(".ppam"))
196
+ if not dry_run and files.running(host):
197
+ raise VBAError(f"quit {host.app} first: it would not see the change, and could overwrite it")
198
+
199
+ projects = [files.Project(host, t) for t in targets]
200
+ try:
201
+ # everything is checked before anything is written
202
+ plans = []
203
+ names = [p.name for p in source.procedures(code)]
204
+ for p in projects:
205
+ where = p.module_for(names, module)
206
+ old = p.modules()[where].replace("\r\n", "\n")
207
+ text, replaced, added = source.merge(old, code)
208
+ diff = "".join(difflib.unified_diff(old.splitlines(True), text.splitlines(True),
209
+ f"{p.path.name}:{where}", f"{p.path.name}:{where} (new)", n=1))
210
+ plans.append({"project": p, "module": where, "replaced": replaced, "added": added, "diff": diff,
211
+ "new": p.saved(where, text) if text != old else None})
212
+ answer = []
213
+ for plan in plans:
214
+ p = plan.pop("project")
215
+ new = plan.pop("new")
216
+ plan["file"] = str(p.path)
217
+ plan["changed"] = bool(new)
218
+ if new and not dry_run:
219
+ if p.path.read_bytes() != p.original.read_bytes():
220
+ raise VBAError(f"{p.path.name} changed meanwhile; nothing more was written")
221
+ plan["backup"] = str(files.backup(p.path))
222
+ files.replace(p.path, new)
223
+ answer.append(plan)
224
+ return {"dry_run": dry_run, "files": answer}
225
+ finally:
226
+ for p in projects:
227
+ p.__exit__()
vba/files.py ADDED
@@ -0,0 +1,226 @@
1
+ """Office files on disk, through pyOpenVBA. No Office needed, any platform."""
2
+
3
+ import os
4
+ import shutil
5
+ import subprocess
6
+ import sys
7
+ import tempfile
8
+ import zipfile
9
+ from dataclasses import dataclass
10
+ from datetime import datetime
11
+ from pathlib import Path
12
+
13
+ from pyopenvba import ExcelFile, PowerPointFile, WordFile
14
+
15
+ from . import VBAError, source
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class Host:
20
+ key: str
21
+ app: str # application and process name on a Mac
22
+ exe: str # process name on Windows
23
+ library: type
24
+ created: str # extension that pyOpenVBA can create
25
+ dev: str # file name of the dev add-in
26
+ editable: tuple
27
+ retype: tuple = () # content types (as created, as add-in) when the extensions differ
28
+ extra: str = "" # extension pyOpenVBA can only read: edited under the created type
29
+
30
+
31
+ HOSTS = {
32
+ "word": Host(
33
+ "word", "Microsoft Word", "WINWORD.EXE", WordFile, ".docm", "VBADev.dotm", (".dotm", ".docm"),
34
+ (b"application/vnd.ms-word.document.macroEnabled.main+xml",
35
+ b"application/vnd.ms-word.template.macroEnabledTemplate.main+xml"),
36
+ ),
37
+ "excel": Host("excel", "Microsoft Excel", "EXCEL.EXE", ExcelFile, ".xlam", "VBADev.xlam", (".xlsb", ".xlsm", ".xlam")),
38
+ "powerpoint": Host(
39
+ "powerpoint", "Microsoft PowerPoint", "POWERPNT.EXE", PowerPointFile, ".pptm", "VBADev.ppam", (".pptm", ".ppam"),
40
+ (b"application/vnd.ms-powerpoint.presentation.macroEnabled.main+xml",
41
+ b"application/vnd.ms-powerpoint.addin.macroEnabled.main+xml"),
42
+ ".ppam",
43
+ ),
44
+ }
45
+
46
+
47
+ def home():
48
+ """Backups, working copies and the loaded dev source."""
49
+ path = os.environ.get("VBA_HOME")
50
+ if path:
51
+ return Path(path).expanduser()
52
+ if sys.platform == "darwin":
53
+ return Path.home() / "Library/Application Support/vba"
54
+ if sys.platform == "win32":
55
+ return Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData/Local")) / "vba"
56
+ return Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share")) / "vba"
57
+
58
+
59
+ def running(host):
60
+ """Whether the app runs. Office runs on a Mac and on Windows only."""
61
+ if sys.platform == "darwin":
62
+ return subprocess.run(["pgrep", "-x", host.app], capture_output=True).returncode == 0
63
+ if sys.platform == "win32":
64
+ try:
65
+ done = subprocess.run(["tasklist", "/FI", f"IMAGENAME eq {host.exe}", "/NH"],
66
+ capture_output=True, text=True, errors="replace")
67
+ except OSError as e:
68
+ raise VBAError(f"cannot see whether {host.app} runs ({e})") from None
69
+ if done.returncode:
70
+ raise VBAError(f"cannot see whether {host.app} runs (tasklist failed)")
71
+ return host.exe.lower() in done.stdout.lower()
72
+ return False
73
+
74
+
75
+ def stamp():
76
+ return datetime.now().strftime("%Y%m%d-%H%M%S-%f")
77
+
78
+
79
+ def retype(src, dst, old, new):
80
+ """Copy an Office package with one content type replaced."""
81
+ with zipfile.ZipFile(src) as a, zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED) as b:
82
+ for name in a.namelist():
83
+ data = a.read(name)
84
+ if name == "[Content_Types].xml":
85
+ if old not in data:
86
+ raise VBAError(f"{src}: unexpected content type")
87
+ data = data.replace(old, new)
88
+ b.writestr(name, data)
89
+
90
+
91
+ def changed_parts(a, b):
92
+ with zipfile.ZipFile(a) as x, zipfile.ZipFile(b) as y:
93
+ names = set(x.namelist()) | set(y.namelist())
94
+ both = set(x.namelist()) & set(y.namelist())
95
+ return sorted(n for n in names if n not in both or x.read(n) != y.read(n))
96
+
97
+
98
+ def check(host, path):
99
+ path = Path(path).expanduser().resolve()
100
+ if path.suffix.lower() not in host.editable:
101
+ raise VBAError(f"{path.name}: {host.key} files are {', '.join(host.editable)}")
102
+ if not path.is_file():
103
+ raise VBAError(f"no such file: {path}")
104
+ return path
105
+
106
+
107
+ class Project:
108
+ """A private copy of a file, so that the original is only ever read here."""
109
+
110
+ def __init__(self, host, path):
111
+ self.host, self.path = host, check(host, path)
112
+ self._tmp = tempfile.TemporaryDirectory()
113
+ tmp = Path(self._tmp.name)
114
+ self.original = tmp / ("original" + self.path.suffix)
115
+ shutil.copyfile(self.path, self.original)
116
+ self.work = self.original
117
+ if self.path.suffix.lower() == host.extra:
118
+ self.work = tmp / ("work" + host.created)
119
+ retype(self.original, self.work, host.retype[1], host.retype[0])
120
+ self.file = host.library(self.work)
121
+
122
+ def __enter__(self):
123
+ return self
124
+
125
+ def __exit__(self, *exc):
126
+ self.file.close()
127
+ self._tmp.cleanup()
128
+
129
+ def modules(self):
130
+ return {name: self.file.get_module(name) for name in self.file.module_names()}
131
+
132
+ def procedures(self):
133
+ return {name: source.procedures(text) for name, text in self.modules().items()}
134
+
135
+ def module_for(self, names, wanted=None):
136
+ """The module that new code belongs in."""
137
+ procs = self.procedures()
138
+ if wanted:
139
+ match = [m for m in procs if m.lower() == wanted.lower()]
140
+ if not match:
141
+ raise VBAError(f"no module {wanted}; there is {', '.join(procs)}")
142
+ return match[0]
143
+ names = {n.lower() for n in names}
144
+ holders = [m for m, ps in procs.items() if names & {p.name.lower() for p in ps}]
145
+ holders = holders or [m for m, ps in procs.items() if ps]
146
+ if len(holders) != 1:
147
+ raise VBAError(f"name the module with --module: {', '.join(holders or procs)}")
148
+ return holders[0]
149
+
150
+ def saved(self, module, text):
151
+ """The file with one module changed, as a checked temporary file."""
152
+ others = {m: t for m, t in self.modules().items() if m != module}
153
+ self.file.set_module(module, text.replace("\n", "\r\n"))
154
+ tmp = Path(self._tmp.name)
155
+ out = tmp / ("out" + self.work.suffix)
156
+ self.file.save(out)
157
+ back = self.host.library(out)
158
+ try:
159
+ problems = list(back.validate())
160
+ if source.normalize(back.get_module(module)).rstrip() != source.normalize(text).rstrip():
161
+ problems.append("the code does not read back the same")
162
+ if any(back.get_module(m) != t for m, t in others.items()):
163
+ problems.append("another module changed")
164
+ finally:
165
+ back.close()
166
+ if self.work is not self.original:
167
+ final = tmp / ("final" + self.path.suffix)
168
+ retype(out, final, *self.host.retype)
169
+ out = final
170
+ bad = [p for p in changed_parts(self.original, out) if not p.endswith("vbaProject.bin")]
171
+ if bad:
172
+ problems.append(f"other parts changed: {', '.join(bad)}")
173
+ if problems:
174
+ raise VBAError("not written: " + "; ".join(problems))
175
+ return out
176
+
177
+
178
+ def backup(path):
179
+ """Outside the original's folder: Office opens whatever lies in a startup folder."""
180
+ folder = home() / "backups"
181
+ folder.mkdir(parents=True, exist_ok=True)
182
+ copy = folder / f"{path.stem}-{stamp()}{path.suffix}"
183
+ shutil.copy2(path, copy)
184
+ if copy.read_bytes() != path.read_bytes():
185
+ raise VBAError(f"the backup {copy} does not match")
186
+ return copy
187
+
188
+
189
+ def replace(path, new):
190
+ """Put new in place of path in one step, keeping its permissions."""
191
+ tmp = path.with_name(f".vba-{stamp()}.tmp")
192
+ try:
193
+ shutil.copyfile(new, tmp)
194
+ shutil.copymode(path, tmp)
195
+ os.replace(tmp, path)
196
+ finally:
197
+ tmp.unlink(missing_ok=True)
198
+
199
+
200
+ def build(host, code, out):
201
+ """An add-in file with one standard module."""
202
+ out = Path(out)
203
+ with tempfile.TemporaryDirectory() as tmp:
204
+ made = Path(tmp) / ("made" + host.created)
205
+ file = host.library.create_new(made)
206
+ text = code.replace("\r\n", "\n").replace("\n", "\r\n")
207
+ if "Module1" in file.module_names():
208
+ file.set_module("Module1", text)
209
+ else:
210
+ file.vba_project().add_module("Module1", text)
211
+ file.save(made)
212
+ file.close()
213
+ back = host.library(made)
214
+ try:
215
+ problems = list(back.validate())
216
+ if source.normalize(back.get_module("Module1")).rstrip() != source.normalize(code).rstrip():
217
+ problems.append("the code does not read back the same (unsupported characters?)")
218
+ finally:
219
+ back.close()
220
+ if problems:
221
+ raise VBAError("cannot build the add-in: " + "; ".join(problems))
222
+ if host.retype:
223
+ retype(made, out, *host.retype)
224
+ else:
225
+ shutil.copyfile(made, out)
226
+ return out