Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
297 lines (254 loc) · 10.3 KB
/
Copy pathcli.py
File metadata and controls
297 lines (254 loc) · 10.3 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
"""Command-line interface for xls2html.
Parses arguments, discovers input files, converts each one, and reports
progress and results via Rich and tqdm. This module never lets an
exception escape to the user as a Python traceback: every failure mode is
caught in :func:`convert_one` and reported as a clean error line.
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from rich.console import Console
from rich.prompt import Confirm
from tqdm import tqdm
import html_writer
from converter import ConversionError, Workbook, read_workbook
from utils import find_xls_files, logger, sanitize_filename, setup_logging
console = Console()
CSS_FILENAME = "style.css"
def build_parser() -> argparse.ArgumentParser:
"""Construct the ``xls2html`` argument parser."""
parser = argparse.ArgumentParser(
prog="xls2html",
description="Zet oude Excel .xls bestanden om naar nette, semantische HTML.",
)
parser.add_argument(
"inputs",
nargs="+",
metavar="PAD",
help="Een of meer .xls bestanden en/of mappen om te converteren.",
)
parser.add_argument(
"-o",
"--output",
type=Path,
default=None,
metavar="PAD",
help=(
"Uitvoerbestand (bij één invoerbestand) of uitvoermap (bij meerdere "
"bestanden). Standaard: naast het bronbestand."
),
)
parser.add_argument(
"--recursive",
action="store_true",
help="Doorzoek submappen recursief wanneer een map is opgegeven.",
)
parser.add_argument(
"--overwrite",
action="store_true",
help="Overschrijf bestaande uitvoerbestanden zonder te vragen.",
)
parser.add_argument(
"--skip-hidden-sheets",
action="store_true",
help="Sla verborgen werkbladen over in plaats van ze te converteren.",
)
verbosity = parser.add_mutually_exclusive_group()
verbosity.add_argument("--verbose", action="store_true", help="Toon gedetailleerde logging.")
verbosity.add_argument("--quiet", action="store_true", help="Toon alleen foutmeldingen.")
parser.add_argument(
"--theme",
choices=("light", "dark"),
default=None,
help="Forceer licht of donker thema (standaard: volgt systeeminstelling).",
)
parser.add_argument(
"--css",
type=Path,
default=None,
metavar="PAD",
help="Gebruik een eigen stylesheet in plaats van de standaard stijl.",
)
parser.add_argument(
"--embed-css",
action="store_true",
help="Voeg CSS direct toe in de HTML in plaats van een los bestand te linken.",
)
page_mode = parser.add_mutually_exclusive_group()
page_mode.add_argument(
"--split-sheets",
action="store_true",
help="Schrijf elk werkblad naar een eigen HTML-bestand.",
)
page_mode.add_argument(
"--single-page",
action="store_true",
help="Alle werkbladen samen op één HTML-pagina (standaardgedrag).",
)
return parser
def _find_output_dir(explicit: Path | None, source: Path, *, batch: bool) -> Path:
"""Determine the directory an output file should live in."""
if explicit is None:
return source.parent
if batch:
return explicit
if explicit.suffix.lower() == ".html":
return explicit.parent
return explicit
def _single_output_path(explicit: Path | None, source: Path, *, batch: bool) -> Path:
if explicit is not None and not batch and explicit.suffix.lower() == ".html":
return explicit
directory = _find_output_dir(explicit, source, batch=batch)
return directory / f"{source.stem}.html"
def _split_output_paths(
explicit: Path | None, source: Path, sheet_names: list[str], *, batch: bool
) -> list[Path]:
directory = _find_output_dir(explicit, source, batch=batch)
used: set[str] = set()
paths = []
for name in sheet_names:
safe = sanitize_filename(name)
candidate = safe
counter = 2
while candidate in used:
candidate = f"{safe}-{counter}"
counter += 1
used.add(candidate)
paths.append(directory / f"{source.stem}-{candidate}.html")
return paths
def _confirm_overwrite(path: Path, *, force: bool) -> bool:
"""Return True if writing to ``path`` should proceed."""
if force or not path.exists():
return True
if not sys.stdin.isatty():
console.print(f"[yellow]Overgeslagen (bestaat al):[/yellow] {path}")
return False
return Confirm.ask(f"[yellow]{path} bestaat al. Overschrijven?[/yellow]", default=False)
def _ensure_css(directory: Path, *, embed: bool, custom_css: Path | None, written: set[Path]) -> None:
if embed or directory in written:
return
directory.mkdir(parents=True, exist_ok=True)
target = directory / CSS_FILENAME
target.write_text(html_writer.load_css(custom_css), encoding="utf-8")
written.add(directory)
def convert_one(
source: Path,
args: argparse.Namespace,
*,
batch: bool,
css_written: set[Path],
) -> str:
"""Convert a single .xls file according to ``args``.
Returns:
``"ok"``, ``"skipped"``, or ``"error"``.
"""
show_checklist = not batch
if show_checklist:
console.print("[green]✔[/green] Bestand gevonden")
try:
workbook: Workbook = read_workbook(source, skip_hidden_sheets=args.skip_hidden_sheets)
except ConversionError as exc:
console.print("[red]ERROR[/red]")
console.print(f"Kan bestand niet openen: [bold]{exc.path}[/bold]")
console.print(f"Oorzaak: {exc.reason}")
logger.debug("Conversiefout voor %s: %s", source, exc.reason)
return "error"
if show_checklist:
for sheet in workbook.sheets:
console.print(f"[green]✔[/green] {sheet.name}")
embedded_css = html_writer.load_css(args.css) if args.embed_css else None
try:
if args.css is not None and not args.css.exists():
raise ConversionError(source, f"Opgegeven CSS-bestand niet gevonden: {args.css}")
if args.split_sheets:
targets = _split_output_paths(args.output, source, [s.name for s in workbook.sheets], batch=batch)
for sheet, target in zip(workbook.sheets, targets, strict=True):
if not _confirm_overwrite(target, force=args.overwrite):
continue
html = html_writer.render_page(
title=f"{source.name} – {sheet.name}",
source_name=source.name,
sheets=[sheet],
theme=args.theme,
css_href=None if args.embed_css else CSS_FILENAME,
embedded_css=embedded_css,
)
_ensure_css(target.parent, embed=args.embed_css, custom_css=args.css, written=css_written)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(html, encoding="utf-8")
logger.debug("Geschreven: %s", target)
else:
target = _single_output_path(args.output, source, batch=batch)
if not _confirm_overwrite(target, force=args.overwrite):
return "skipped"
html = html_writer.render_page(
title=source.name,
source_name=source.name,
sheets=workbook.sheets,
theme=args.theme,
css_href=None if args.embed_css else CSS_FILENAME,
embedded_css=embedded_css,
)
_ensure_css(target.parent, embed=args.embed_css, custom_css=args.css, written=css_written)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(html, encoding="utf-8")
logger.debug("Geschreven: %s", target)
except ConversionError as exc:
console.print("[red]ERROR[/red]")
console.print(f"Kan bestand niet opslaan: [bold]{exc.path}[/bold]")
console.print(f"Oorzaak: {exc.reason}")
return "error"
except PermissionError as exc:
console.print("[red]ERROR[/red]")
console.print(f"Kan niet schrijven naar: [bold]{source}[/bold]")
console.print(f"Oorzaak: Toegang geweigerd ({exc.filename})")
return "error"
except OSError as exc:
console.print("[red]ERROR[/red]")
console.print(f"Kan niet schrijven naar: [bold]{source}[/bold]")
console.print(f"Oorzaak: {exc}")
return "error"
if show_checklist:
console.print("[green]✔[/green] HTML opgeslagen")
console.print("Done.")
return "ok"
def main(argv: list[str] | None = None) -> int:
"""Entry point. Returns a process exit code; never raises to the caller."""
parser = build_parser()
args = parser.parse_args(argv)
setup_logging(verbose=args.verbose, quiet=args.quiet)
if args.css is not None and not args.css.exists():
console.print(f"[red]ERROR[/red]\nOpgegeven CSS-bestand niet gevonden: {args.css}")
return 1
inputs = [Path(p) for p in args.inputs]
files = find_xls_files(inputs, recursive=args.recursive)
files = [f for f in files if f.suffix.lower() == ".xls" or f.is_file()]
if not files:
console.print("[red]ERROR[/red]\nGeen .xls bestanden gevonden.")
return 1
batch = len(files) > 1
css_written: set[Path] = set()
counts = {"ok": 0, "skipped": 0, "error": 0}
if batch:
for source in tqdm(files, desc="Converteren", unit="bestand", disable=args.quiet):
result = convert_one(source, args, batch=True, css_written=css_written)
counts[result] += 1
console.print(f"[blue]{counts['ok']}[/blue] bestanden verwerkt")
if counts["skipped"]:
console.print(f"[yellow]{counts['skipped']}[/yellow] overgeslagen")
if counts["error"]:
console.print(f"[red]{counts['error']}[/red] fout")
else:
result = convert_one(files[0], args, batch=False, css_written=css_written)
counts[result] += 1
return 1 if counts["error"] else 0
def run() -> None:
"""Console-script entry point wrapping :func:`main` with signal handling."""
try:
sys.exit(main())
except KeyboardInterrupt:
console.print("\n[yellow]Onderbroken door gebruiker.[/yellow]")
sys.exit(130)
if __name__ == "__main__": # pragma: no cover
run()