exploderino 1.0.1__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.
@@ -0,0 +1,27 @@
1
+ """Explode documents into directories of readable files and implode them back."""
2
+
3
+ __version__ = "1.0.1"
4
+
5
+ from .core import (
6
+ DEFAULT_MAX_SIZE,
7
+ MANIFEST_NAME,
8
+ ExplodeResult,
9
+ ExploderinoError,
10
+ ImplodeResult,
11
+ explode,
12
+ implode,
13
+ read_manifest,
14
+ verify,
15
+ )
16
+
17
+ __all__ = [
18
+ "DEFAULT_MAX_SIZE",
19
+ "MANIFEST_NAME",
20
+ "ExplodeResult",
21
+ "ExploderinoError",
22
+ "ImplodeResult",
23
+ "explode",
24
+ "implode",
25
+ "read_manifest",
26
+ "verify",
27
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
exploderino/cli.py ADDED
@@ -0,0 +1,188 @@
1
+ """Command-line interface: exploderino [explode|implode|verify|auto] ...
2
+
3
+ Without a command, each path is handled by what it is: a document is exploded, and a
4
+ directory created by explode is imploded.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import os
12
+ import sys
13
+ from dataclasses import asdict
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from . import __version__
18
+ from .core import (
19
+ DEFAULT_MAX_SIZE,
20
+ MANIFEST_NAME,
21
+ ExplodeResult,
22
+ ExploderinoError,
23
+ ImplodeResult,
24
+ explode,
25
+ implode,
26
+ verify,
27
+ )
28
+
29
+ COMMANDS = ("explode", "implode", "verify", "auto")
30
+ GLOBAL_OPTIONS = ("--json", "--version", "-h", "--help")
31
+
32
+
33
+ def _size(text: str) -> int:
34
+ try:
35
+ value = int(text)
36
+ except ValueError:
37
+ raise argparse.ArgumentTypeError(f"invalid number of bytes: {text!r}") from None
38
+ if value <= 0:
39
+ raise argparse.ArgumentTypeError("must be a positive number of bytes")
40
+ return value
41
+
42
+
43
+ def _build_parser() -> argparse.ArgumentParser:
44
+ parser = argparse.ArgumentParser(
45
+ prog="exploderino",
46
+ description="Explode documents (docx, xlsx, pptx, odt, epub, xps, ...) into directories and "
47
+ "implode them back. Without a command, documents are exploded and exploded directories imploded.",
48
+ # Abbreviations like --js would stop the default command from being inserted
49
+ allow_abbrev=False,
50
+ )
51
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
52
+ parser.add_argument("--json", action="store_true", help="print machine-readable results")
53
+ sub = parser.add_subparsers(dest="command", required=True)
54
+ size_help = "max total inflated bytes (default: 2 GiB)"
55
+
56
+ p = sub.add_parser("explode", help="unpack documents into directories")
57
+ p.add_argument("files", nargs="+", type=Path, help="documents to explode")
58
+ p.add_argument("-o", "--output", type=Path, help="output directory (single input only)")
59
+ p.add_argument("--no-pretty", action="store_true", help="keep XML parts byte-for-byte as stored")
60
+ p.add_argument("-r", "--recursive", action="store_true", help="also explode embedded documents")
61
+ p.add_argument("-f", "--force", action="store_true", help="replace an existing exploded directory")
62
+ p.add_argument("--max-size", type=_size, default=DEFAULT_MAX_SIZE, help=size_help)
63
+
64
+ p = sub.add_parser("implode", help="rebuild documents from exploded directories")
65
+ p.add_argument("dirs", nargs="+", type=Path, help="directories created by explode")
66
+ p.add_argument("-o", "--output", type=Path, help="output file (single input only)")
67
+ p.add_argument("-f", "--force", action="store_true", help="overwrite an existing output file")
68
+
69
+ p = sub.add_parser("verify", help="check that explode -> implode round-trips without changes")
70
+ p.add_argument("files", nargs="+", type=Path, help="ZIP-based documents to check")
71
+ p.add_argument("--max-size", type=_size, default=DEFAULT_MAX_SIZE, help=size_help)
72
+
73
+ p = sub.add_parser(
74
+ "auto",
75
+ help="explode documents and implode exploded directories (the default when no command is given)",
76
+ )
77
+ p.add_argument("paths", nargs="+", type=Path, help="documents and/or directories created by explode")
78
+ p.add_argument("-o", "--output", type=Path, help="output directory or file (single input only)")
79
+ p.add_argument("--no-pretty", action="store_true", help="explode: keep XML parts byte-for-byte as stored")
80
+ p.add_argument("-r", "--recursive", action="store_true", help="explode: also explode embedded documents")
81
+ p.add_argument("-f", "--force", action="store_true", help="replace an existing output directory or file")
82
+ p.add_argument("--max-size", type=_size, default=DEFAULT_MAX_SIZE, help=f"explode: {size_help}")
83
+ return parser
84
+
85
+
86
+ def _with_default_command(argv: list[str]) -> list[str]:
87
+ """Insert "auto" after the global options unless a command is given."""
88
+ for i, arg in enumerate(argv):
89
+ if arg not in GLOBAL_OPTIONS:
90
+ return argv if arg in COMMANDS else [*argv[:i], "auto", *argv[i:]]
91
+ return argv
92
+
93
+
94
+ def _action(command: str, path: Path) -> str:
95
+ """The action for one input: explicit, or (for auto) decided by what the path is."""
96
+ if command != "auto":
97
+ return command
98
+ if path.is_dir():
99
+ if not (path / MANIFEST_NAME).is_file():
100
+ raise ExploderinoError(f"{path}: directory was not created by exploderino (no {MANIFEST_NAME})")
101
+ return "implode"
102
+ return "explode"
103
+
104
+
105
+ def _jsonable(result: ExplodeResult | ImplodeResult) -> dict[str, Any]:
106
+ return {k: str(v) if isinstance(v, Path) else v for k, v in asdict(result).items()}
107
+
108
+
109
+ def _run(action: str, item: Path, args: argparse.Namespace) -> tuple[str, dict[str, Any], bool]:
110
+ """Run one action on one input; return its text output, its JSON result and success."""
111
+ if action == "explode":
112
+ exploded = explode(
113
+ item,
114
+ args.output,
115
+ pretty=not args.no_pretty,
116
+ recursive=args.recursive,
117
+ force=args.force,
118
+ max_size=args.max_size,
119
+ )
120
+ for warning in exploded.warnings:
121
+ print(f"warning: {item}: {warning}", file=sys.stderr)
122
+ return str(exploded.directory), _jsonable(exploded), True
123
+ if action == "implode":
124
+ imploded = implode(item, args.output, force=args.force)
125
+ for name in imploded.missing:
126
+ print(f"warning: {item}: {name} was deleted and is omitted", file=sys.stderr)
127
+ for name in imploded.added:
128
+ print(f"note: {item}: added new part {name}", file=sys.stderr)
129
+ return str(imploded.output), _jsonable(imploded), True
130
+ diffs = verify(item, max_size=args.max_size)
131
+ lines = [f"{'FAIL' if diffs else 'OK '} {item}", *(f" {d}" for d in diffs)]
132
+ return "\n".join(lines), {"file": str(item), "ok": not diffs, "differences": diffs}, not diffs
133
+
134
+
135
+ def _error_message(item: Path, exc: BaseException) -> str:
136
+ """The exception's message, starting with the input it concerns."""
137
+ message = str(exc)
138
+ if message.startswith((f"{item}:", f"{os.path.abspath(item)}:")):
139
+ return message
140
+ return f"{item}: {message}"
141
+
142
+
143
+ def _tolerant_output() -> None:
144
+ """Escape characters the console can't encode (e.g. Windows code pages) instead of failing."""
145
+ for stream in (sys.stdout, sys.stderr):
146
+ reconfigure = getattr(stream, "reconfigure", None)
147
+ if reconfigure is not None:
148
+ reconfigure(errors="backslashreplace")
149
+
150
+
151
+ def main(argv: list[str] | None = None) -> int:
152
+ """Run the command line; return the exit status (0 ok, 1 an input failed, 2 usage error)."""
153
+ argv = sys.argv[1:] if argv is None else argv
154
+ parser = _build_parser()
155
+ args = parser.parse_args(_with_default_command(argv))
156
+ inputs: list[Path] = getattr(args, {"implode": "dirs", "auto": "paths"}.get(args.command, "files"))
157
+ if getattr(args, "output", None) and len(inputs) > 1:
158
+ parser.print_usage(sys.stderr)
159
+ print("exploderino: error: -o/--output only works with a single input", file=sys.stderr)
160
+ return 2
161
+ _tolerant_output()
162
+
163
+ status = 0
164
+ results: list[dict[str, Any]] = []
165
+ for item in inputs:
166
+ try:
167
+ action = _action(args.command, item)
168
+ output, result, ok = _run(action, item, args)
169
+ except (ExploderinoError, OSError) as exc:
170
+ message = _error_message(item, exc)
171
+ except Exception as exc: # keep going: one bad input must not end a batch
172
+ message = f"{item}: unexpected {type(exc).__name__}: {exc}"
173
+ else:
174
+ if args.command == "auto":
175
+ result = {"action": action, **result}
176
+ results.append(result)
177
+ if not ok:
178
+ status = 1
179
+ if not args.json:
180
+ print(output)
181
+ continue
182
+ print(f"error: {message}", file=sys.stderr)
183
+ results.append({"input": str(item), "error": message})
184
+ status = 1
185
+
186
+ if args.json:
187
+ print(json.dumps(results, indent=2))
188
+ return status