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 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
|
#!/usr/bin/python3
from __future__ import annotations
import argparse
import contextlib
import fnmatch
import logging
import os.path
import re
import shutil
import sys
from pathlib import Path
from typing import TYPE_CHECKING, Optional, IO, Union
from a38 import codec, models
if TYPE_CHECKING:
import fattura
from .fattura import Fattura
from .fattura_semplificata import FatturaElettronicaSemplificata
log = logging.getLogger("a38tool")
class Fail(Exception):
pass
class App:
NAME = None
def __init__(self, args):
self.args = args
def load_fattura(self, pathname) -> Union[Fattura, FatturaElettronicaSemplificata]:
codecs = codec.Codecs()
codec_cls = codecs.codec_from_filename(pathname)
return codec_cls().load(pathname)
@classmethod
def add_subparser(cls, subparsers):
name = getattr(cls, "NAME", None)
if name is None:
name = cls.__name__.lower()
parser = subparsers.add_parser(name, help=cls.__doc__.strip())
parser.set_defaults(app=cls)
return parser
class Diff(App):
"""
show the difference between two fatture
"""
NAME = "diff"
def __init__(self, args):
super().__init__(args)
self.first = args.first
self.second = args.second
@classmethod
def add_subparser(cls, subparsers):
parser = super().add_subparser(subparsers)
parser.add_argument("first", help="first input file (.xml or .xml.p7m)")
parser.add_argument("second", help="second input file (.xml or .xml.p7m)")
return parser
def run(self):
first = self.load_fattura(self.first)
second = self.load_fattura(self.second)
from a38.diff import Diff
res = Diff()
first.diff(res, second)
if res.differences:
for d in res.differences:
print(d)
return 1
class Validate(App):
"""
validate the contents of a fattura
"""
NAME = "validate"
def __init__(self, args):
super().__init__(args)
self.pathname = args.file
@classmethod
def add_subparser(cls, subparsers):
parser = super().add_subparser(subparsers)
parser.add_argument("file", help="input file (.xml or .xml.p7m)")
return parser
def run(self):
f = self.load_fattura(self.pathname)
from a38.validation import Validation
res = Validation()
f.validate(res)
if res.warnings:
for w in res.warnings:
print(str(w), file=sys.stderr)
if res.errors:
for e in res.errors:
print(str(e), file=sys.stderr)
return 1
class Exporter(App):
def __init__(self, args):
super().__init__(args)
self.files = args.files
self.output = args.output
self.codec = self.get_codec()
def get_codec(self) -> codec.Codec:
"""
Instantiate the output codec to use for this exporter
"""
raise NotImplementedError(
f"{self.__class__.__name__}.get_codec is not implemented"
)
def write(self, f: models.Model, file: Union[IO[str], IO[bytes]]):
self.codec.write_file(f, file)
@contextlib.contextmanager
def open_output(self):
if self.output is None:
if self.codec.binary:
yield sys.stdout.buffer
else:
yield sys.stdout
else:
with open(self.output, "wb" if self.codec.binary else "wt") as out:
yield out
def run(self):
with self.open_output() as out:
for pathname in self.files:
f = self.load_fattura(pathname)
self.write(f, out)
@classmethod
def add_subparser(cls, subparsers):
parser = super().add_subparser(subparsers)
parser.add_argument(
"-o", "--output", help="output file (default: standard output)"
)
parser.add_argument("files", nargs="+", help="input files (.xml or .xml.p7m)")
return parser
class ExportJSON(Exporter):
"""
output a fattura in JSON
"""
NAME = "json"
def get_codec(self) -> codec.Codec:
if self.args.indent == "no":
indent = None
else:
try:
indent = int(self.args.indent)
except ValueError:
raise Fail("--indent argument must be an integer on 'no'")
return codec.JSON(indent=indent)
@classmethod
def add_subparser(cls, subparsers):
parser = super().add_subparser(subparsers)
parser.add_argument(
"--indent",
default="1",
help="indentation space (default: 1, use 'no' for all in one line)",
)
return parser
class ExportYAML(Exporter):
"""
output a fattura in JSON
"""
NAME = "yaml"
def get_codec(self) -> codec.Codec:
return codec.YAML()
class ExportXML(Exporter):
"""
output a fattura in XML
"""
NAME = "xml"
def get_codec(self) -> codec.Codec:
return codec.XML()
class ExportPython(Exporter):
"""
output a fattura as Python code
"""
NAME = "python"
def get_codec(self) -> codec.Codec:
namespace = self.args.namespace
if namespace == "":
namespace = False
return codec.Python(namespace=namespace, unformatted=self.args.unformatted)
@classmethod
def add_subparser(cls, subparsers):
parser = super().add_subparser(subparsers)
parser.add_argument(
"--namespace",
default=None,
help="namespace to use for the model classes (default: the module fully qualified name)",
)
parser.add_argument(
"--unformatted",
action="store_true",
help="disable code formatting, outputting a single-line statement",
)
return parser
class Edit(App):
"""
Open a fattura for modification in a text editor
"""
def __init__(self, args):
super().__init__(args)
if self.args.style == "yaml":
self.edit_codec = codec.YAML()
elif self.args.style == "python":
self.edit_codec = codec.Python(loadable=True)
else:
raise Fail(f"Unsupported edit style {self.args.style!r}")
def write_out(self, f):
"""
Write a fattura, as much as possible over the file being edited
"""
codecs = codec.Codecs()
codec_cls = codecs.codec_from_filename(self.args.file)
if codec_cls == codec.P7M:
with open(self.args.file[:-4], "wb") as fd:
codec_cls().write_file(f, fd)
elif codec_cls.binary:
with open(self.args.file, "wb") as fd:
codec_cls().write_file(f, fd)
else:
with open(self.args.file, "wt") as fd:
codec_cls().write_file(f, fd)
def run(self):
f = self.load_fattura(self.args.file)
f1 = self.edit_codec.interactive_edit(f)
if f1 is not None and f != f1:
self.write_out(f1)
@classmethod
def add_subparser(cls, subparsers):
parser = super().add_subparser(subparsers)
parser.add_argument(
"-s",
"--style",
default="yaml",
help="editable representation to use, one of 'yaml' or 'python'. Default: $(default)s",
)
parser.add_argument("file", help="file to edit")
return parser
class Renderer(App):
"""
Base class for CLI commands that render a Fattura
"""
def __init__(self, args):
from a38.render import HAVE_LXML
if not HAVE_LXML:
raise Fail("python3-lxml is needed for XSLT based rendering")
super().__init__(args)
self.stylesheet = args.stylesheet
self.files = args.files
self.output = args.output
self.force = args.force
from a38.render import XSLTTransform
self.transform = XSLTTransform(self.stylesheet)
def render(self, f, output: str):
"""
Render the Fattura to the given destination file
"""
raise NotImplementedError(
self.__class__.__name__ + ".render is not implemented"
)
def run(self):
for pathname in self.files:
dirname = os.path.normpath(os.path.dirname(pathname))
basename = os.path.basename(pathname)
basename, ext = os.path.splitext(basename)
output = self.output.format(dirname=dirname, basename=basename, ext=ext)
if not self.force and os.path.exists(output):
log.warning(
"%s: output file %s already exists: skipped", pathname, output
)
else:
log.info("%s: writing %s", pathname, output)
f = self.load_fattura(pathname)
self.render(f, output)
@classmethod
def add_subparser(cls, subparsers):
parser = super().add_subparser(subparsers)
parser.add_argument(
"-f", "--force", action="store_true", help="overwrite existing output files"
)
default_output = "{dirname}/{basename}{ext}." + cls.NAME
parser.add_argument(
"-o",
"--output",
default=default_output,
help="output file; use {dirname} for the source file path,"
" {basename} for the source file name"
" (default: '" + default_output + "'",
)
parser.add_argument(
"stylesheet", help=".xsl/.xslt stylesheet file to use for rendering"
)
parser.add_argument("files", nargs="+", help="input files (.xml or .xml.p7m)")
return parser
class RenderHTML(Renderer):
"""
render a Fattura as HTML using a .xslt stylesheet
"""
NAME = "html"
def render(self, f, output):
html = self.transform(f)
html.write(output)
class RenderPDF(Renderer):
"""
render a Fattura as PDF using a .xslt stylesheet
"""
NAME = "pdf"
def __init__(self, args):
super().__init__(args)
self.wkhtmltopdf = shutil.which("wkhtmltopdf")
if self.wkhtmltopdf is None:
raise Fail("wkhtmltopdf is needed for PDF rendering")
def render(self, f, output: str):
self.transform.to_pdf(self.wkhtmltopdf, f, output)
class UpdateCAPath(App):
"""
create/update an openssl CApath with CA certificates that can be used to
validate digital signatures
"""
NAME = "update_capath"
def __init__(self, args):
super().__init__(args)
self.destdir = Path(args.destdir)
self.remove_old = args.remove_old
@classmethod
def add_subparser(cls, subparsers):
parser = super().add_subparser(subparsers)
parser.add_argument("destdir", help="CA certificate directory to update")
parser.add_argument(
"--remove-old", action="store_true", help="remove old certificates"
)
return parser
def run(self):
from a38 import trustedlist as tl
tl.update_capath(self.destdir, remove_old=self.remove_old)
class Allegati(App):
"""
Show the attachments in the fattura
"""
def __init__(self, args: argparse.Namespace) -> None:
super().__init__(args)
self.pathname = args.file
self.ids: set[int] = set()
self.globs: list[re.Pattern] = []
self.has_filter = False
for pattern in self.args.attachments:
self.has_filter = True
if pattern.isdigit():
self.ids.add(int(pattern))
elif pattern.startswith("^"):
self.globs.append(re.compile(pattern))
else:
self.globs.append(re.compile(fnmatch.translate(pattern)))
@classmethod
def add_subparser(cls, subparsers):
parser = super().add_subparser(subparsers)
parser.add_argument(
"--extract", "-x", action="store_true", help="extract selected attachments"
)
parser.add_argument(
"--json", action="store_true", help="show attachments in json format"
)
parser.add_argument(
"--yaml", action="store_true", help="show attachments in yaml format"
)
parser.add_argument(
"--output",
"-o",
action="store",
help="destination file name (-o file) or directory (-o dir/)",
)
parser.add_argument("file", help="input file (.xml or .xml.p7m)")
parser.add_argument(
"attachments",
nargs="*",
help="IDs or names of attachments to extract. Shell-like wildcards allowed, or regexps if starting with ^",
)
return parser
def match_allegato(self, index: int, allegato: fattura.Allegati) -> bool:
"""
Check if the given allegato matches the attachments patterns
"""
if not self.has_filter:
return True
for id in self.ids:
if index == id:
return True
for regex in self.globs:
if regex.match(allegato.nome_attachment):
return True
return False
def print_allegato(self, index: int, allegato: fattura.Allegati) -> None:
formato = allegato.formato_attachment or "-"
print(f"{index:02d}: {formato} {allegato.nome_attachment}")
if allegato.descrizione_attachment:
print(f" {allegato.descrizione_attachment}")
def run(self):
f = self.load_fattura(self.pathname)
selected: list[tuple[int, fattura.Allegati]] = []
index = 1
for body in f.fattura_elettronica_body:
for allegato in body.allegati:
if self.match_allegato(index, allegato):
selected.append((index, allegato))
index += 1
if self.args.json or self.args.yaml:
output = []
for index, allegato in selected:
jsonable = {"index": index}
jsonable.update(allegato.to_jsonable())
jsonable.pop("attachment", None)
output.append(jsonable)
if self.args.json:
import json
json.dump(output, sys.stdout, indent=2)
print()
else:
import yaml
yaml.dump(
output,
stream=sys.stdout,
default_flow_style=False,
sort_keys=False,
allow_unicode=True,
explicit_start=True,
Dumper=yaml.CDumper,
)
elif self.args.extract:
destname: Optional[str]
destdir: str
if self.args.output:
if os.path.isdir(self.args.output) or self.args.output.endswith(os.sep):
destname = None
destdir = self.args.output
else:
destname = self.args.output
destdir = "."
else:
destname = None
destdir = "."
if destname is not None and len(selected) > 1:
raise Fail(
"there are multiple attachment to save, and--output points to a single file name"
)
os.makedirs(destdir, exist_ok=True)
for index, allegato in selected:
if destname is None:
destname = os.path.basename(allegato.nome_attachment)
dest = os.path.join(destdir, destname)
log.info("Extracting %s to %s", allegato.nome_attachment, dest)
with open(dest, "wb") as fd:
fd.write(allegato.attachment)
else:
for index, allegato in selected:
self.print_allegato(index, allegato)
def main():
parser = argparse.ArgumentParser(description="Handle fattura elettronica files")
parser.add_argument("--verbose", "-v", action="store_true", help="verbose output")
parser.add_argument("--debug", action="store_true", help="debug output")
subparsers = parser.add_subparsers(help="actions", required=True)
subparsers.dest = "command"
ExportJSON.add_subparser(subparsers)
ExportYAML.add_subparser(subparsers)
ExportXML.add_subparser(subparsers)
ExportPython.add_subparser(subparsers)
Edit.add_subparser(subparsers)
Diff.add_subparser(subparsers)
Validate.add_subparser(subparsers)
RenderHTML.add_subparser(subparsers)
RenderPDF.add_subparser(subparsers)
UpdateCAPath.add_subparser(subparsers)
Allegati.add_subparser(subparsers)
args = parser.parse_args()
log_format = "%(levelname)s %(message)s"
level = logging.WARN
if args.debug:
level = logging.DEBUG
elif args.verbose:
level = logging.INFO
logging.basicConfig(level=level, stream=sys.stderr, format=log_format)
app = args.app(args)
res = app.run()
if isinstance(res, int):
sys.exit(res)
if __name__ == "__main__":
try:
main()
except Fail as e:
print(e, file=sys.stderr)
sys.exit(1)
except Exception:
log.exception("uncaught exception")
|