Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
155 lines (132 loc) · 5.54 KB
/
Copy pathcli.py
File metadata and controls
155 lines (132 loc) · 5.54 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
"""
CLI — facturx-validate
Usage:
facturx-validate invoice.pdf --country FR
facturx-validate ./invoices/ --country FR --summary
facturx-validate invoice.xml --format CII --output json
facturx-validate invoice.pdf --strict
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
from typing import Optional
import click
from facturx_validator import validate, validate_batch
COUNTRY_CHOICES = ["FR", "DE", "IT", "ES", "BE", "NL", "EU", "AT", "PL", "PT"]
FORMAT_CHOICES = ["auto", "FACTURX", "CII", "UBL", "FATTURAPA"]
def _collect_files(paths: tuple[str], fmt_filter: Optional[str]) -> list[Path]:
"""Expand directories and glob patterns into a flat list of files."""
collected = []
extensions = {".pdf", ".xml"}
if fmt_filter == "UBL":
extensions = {".xml"}
elif fmt_filter == "FACTURX":
extensions = {".pdf"}
for p in paths:
path = Path(p)
if path.is_dir():
for ext in extensions:
collected.extend(path.glob(f"*{ext}"))
elif path.exists():
collected.append(path)
else:
# Try as a glob
parent = path.parent
pattern = path.name
collected.extend(parent.glob(pattern))
return sorted(set(collected))
@click.command()
@click.argument("sources", nargs=-1, required=True, metavar="FILE_OR_DIR...")
@click.option("--country", "-c", default="FR", show_default=True,
type=click.Choice(COUNTRY_CHOICES, case_sensitive=False),
help="Country profile for validation rules")
@click.option("--format", "-f", "fmt", default="auto",
type=click.Choice(FORMAT_CHOICES, case_sensitive=False),
help="Force invoice format (default: auto-detect)")
@click.option("--output", "-o", default="text",
type=click.Choice(["text", "json", "summary"]),
help="Output format")
@click.option("--strict", is_flag=True, default=False,
help="Treat warnings as errors")
@click.option("--summary", "show_summary", is_flag=True, default=False,
help="Show a one-line summary per file")
@click.option("--xsd", "xsd_path", default=None, type=click.Path(exists=True),
help="Path to XSD schema file for full XSD validation")
@click.option("--no-info", is_flag=True, default=False,
help="Hide INFO-level messages (show only errors and warnings)")
@click.version_option("0.1.0")
def cli(sources, country, fmt, output, strict, show_summary, xsd_path, no_info):
"""
✅ Validate Factur-X, UBL 2.1, and CII D22B e-invoices.
Supports single files, directories, and glob patterns.
\b
Examples:
facturx-validate invoice.pdf --country FR
facturx-validate ./invoices/ --country FR --output summary
facturx-validate invoice.xml --format CII --strict
facturx-validate *.pdf --country FR --output json
"""
files = _collect_files(sources, fmt if fmt != "auto" else None)
if not files:
click.echo("❌ No files found.", err=True)
sys.exit(1)
forced_fmt = None if fmt == "auto" else fmt
xsd = Path(xsd_path) if xsd_path else None
results = []
for f in files:
click.echo(f"🔍 Validating {f.name}…", err=True)
r = validate(
f,
country=country,
format=forced_fmt,
strict=strict,
xsd_path=xsd,
)
results.append(r)
# ------------------------------------------------------------------
# Output
# ------------------------------------------------------------------
if output == "json":
all_results = [r.to_dict() for r in results]
if len(all_results) == 1:
click.echo(json.dumps(all_results[0], indent=2, ensure_ascii=False))
else:
click.echo(json.dumps(all_results, indent=2, ensure_ascii=False))
elif output == "summary" or show_summary:
total = len(results)
valid = sum(1 for r in results if r.valid)
click.echo(f"\n{'─' * 60}")
click.echo(f" Files: {total}")
click.echo(f" Valid: {valid}")
click.echo(f" Invalid: {total - valid}")
click.echo(f"{'─' * 60}")
for r in results:
icon = "✅" if r.valid else "❌"
errs = f" ({r.error_count} error(s))" if not r.valid else ""
warns = f" ({r.warning_count} warning(s))" if r.warning_count else ""
click.echo(f" {icon} {r.filename or 'unknown'}{errs}{warns}")
else:
# text (default)
for r in results:
click.echo(f"\n{'═' * 60}")
for issue in r.issues:
if no_info and issue.severity == "INFO":
continue
icon = {"ERROR": "✗", "WARNING": "⚠", "INFO": "·"}[issue.severity]
color = {"ERROR": "red", "WARNING": "yellow", "INFO": "bright_black"}[issue.severity]
line = f" {icon} [{issue.rule_id}] {issue.message}"
if issue.value:
line += f" (got: {issue.value!r})"
click.echo(click.style(line, fg=color))
if issue.xpath:
click.echo(click.style(f" @ {issue.xpath}", fg="bright_black"))
click.echo()
click.echo(r.summary())
# ------------------------------------------------------------------
# Exit code
# ------------------------------------------------------------------
all_valid = all(r.valid for r in results)
sys.exit(0 if all_valid else 1)
if __name__ == "__main__":
cli()