Coverage for target/native-coverage/profiles/11fb979bfcf049d7ab666c331dc8db2a/project/.venv/lib/python3.13/site-packages/pyshacl_turbo/cli.py: 100%
151 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-30 14:51 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-30 14:51 +0000
1"""Command-line I/O for the native validator and rule runner."""
3import argparse
4import logging
5import os
6import sys
7from contextlib import ExitStack
8from importlib.metadata import version
10from rdflib.graph import Dataset, Graph
11from rdflib.namespace import SH
13from . import shacl_rules, validate, validate_each
16def table(headers, rows):
17 def split(value):
18 text = str(value)
19 return [text[i : i + 25] for i in range(0, len(text), 25)] or [""]
21 cells = [[split(value) for value in row] for row in [headers, *rows]]
22 widths = [max(len(line) for row in cells for line in row[i]) for i in range(len(headers))]
23 border = "+" + "+".join("-" * (width + 2) for width in widths) + "+"
24 result = [border]
25 for index, row in enumerate(cells):
26 for line in range(max(map(len, row))):
27 result.append(
28 "| "
29 + " | ".join(
30 (column[line] if line < len(column) else "").ljust(width)
31 for column, width in zip(row, widths)
32 )
33 + " |"
34 )
35 if index == 0:
36 result.append(border)
37 result.append(border)
38 return "\n".join(result) + "\n"
41def report_table(conforms, report):
42 output = table(["Conforms"], [[conforms]])
43 if conforms:
44 return output
45 rows = []
46 fields = [
47 SH.resultSeverity,
48 SH.focusNode,
49 SH.resultPath,
50 SH.resultMessage,
51 SH.sourceConstraintComponent,
52 SH.sourceShape,
53 SH.value,
54 ]
55 for index, result in enumerate(report.objects(None, SH.result), 1):
56 values = [
57 str(report.value(result, predicate) or "-").replace(str(SH), "") for predicate in fields
58 ]
59 rows.extend([[index, *values], [""] * 8])
60 return (
61 output
62 + "\n"
63 + table(
64 [
65 "No.",
66 "Severity",
67 "Focus Node",
68 "Result Path",
69 "Message",
70 "Component",
71 "Shape",
72 "Value",
73 ],
74 rows,
75 )
76 )
79def serialize_graph(graph, rdf_format):
80 if rdf_format in {"trig", "nquads"} and not graph.context_aware:
81 dataset = Dataset()
82 dataset.default_graph += graph
83 for prefix, namespace in graph.namespaces():
84 dataset.bind(prefix, namespace)
85 graph = dataset
86 return graph.serialize(format=rdf_format)
89def main(argv=None):
90 parser = argparse.ArgumentParser(prog="pyshacl-turbo")
91 parser.add_argument("data", nargs="*")
92 parser.add_argument("-s", "--shapes", "--shacl", dest="shacl_graph")
93 parser.add_argument("-e", "--ont-graph", dest="ont_graph")
94 parser.add_argument(
95 "-i", "--inference", choices=["none", "rdfs", "owlrl", "both"], default="none"
96 )
97 parser.add_argument("-a", "--advanced", action="store_true")
98 parser.add_argument("-m", "--metashacl", dest="meta_shacl", action="store_true")
99 parser.add_argument("-j", "--js", action="store_true")
100 parser.add_argument("-im", "--imports", dest="do_owl_imports", action="store_true")
101 parser.add_argument("-it", "--iterate-rules", action="store_true")
102 parser.add_argument("--abort", dest="abort_on_first", action="store_true")
103 parser.add_argument("--allow-info", "--allow-infos", dest="allow_infos", action="store_true")
104 parser.add_argument(
105 "-w", "--allow-warning", "--allow-warnings", dest="allow_warnings", action="store_true"
106 )
107 parser.add_argument("--max-depth", dest="max_validation_depth", type=int)
108 parser.add_argument("--validate-each", action="store_true")
109 parser.add_argument("--focus")
110 parser.add_argument("--shape")
111 parser.add_argument("-d", "--debug", action="store_true")
112 parser.add_argument("--rules", action="store_true")
113 parser.add_argument("-q", "--sparql-mode", dest="sparql_mode", action="store_true")
114 parser.add_argument("--server", action="store_true")
115 parser.add_argument("-df", "--data-file-format", dest="data_graph_format")
116 parser.add_argument("-sf", "--shacl-file-format", dest="shacl_graph_format")
117 parser.add_argument("-ef", "--ont-file-format", dest="ont_graph_format")
118 parser.add_argument(
119 "-f",
120 "--format",
121 default="human",
122 choices=["human", "table", "turtle", "trig", "xml", "json-ld", "nt", "n3", "nquads"],
123 )
124 parser.add_argument("-o", "--output")
125 parser.add_argument("-V", "--version", action="version", version=version("pyshacl-turbo"))
126 args = parser.parse_args(argv)
127 if args.server or (not args.rules and _server_requested(os.environ)):
128 return _no_server()
129 if not args.data:
130 print("Input Error. No DataGraph file or endpoint supplied.", file=sys.stderr)
131 parser.print_usage(sys.stderr)
132 return 1
133 if args.debug:
134 logging.basicConfig(level=logging.DEBUG)
135 options = {
136 name: getattr(args, name)
137 for name in [
138 "shacl_graph",
139 "ont_graph",
140 "inference",
141 "advanced",
142 "js",
143 "do_owl_imports",
144 "iterate_rules",
145 "data_graph_format",
146 "shacl_graph_format",
147 "ont_graph_format",
148 "debug",
149 "max_validation_depth",
150 ]
151 }
152 for name in ("data_graph_format", "shacl_graph_format", "ont_graph_format"):
153 if options[name] == "auto":
154 options[name] = None
155 options.update(
156 focus_nodes=[name.strip() for name in args.focus.split(",")] if args.focus else None,
157 use_shapes=[name.strip() for name in args.shape.split(",")] if args.shape else None,
158 )
159 if args.sparql_mode:
160 if len(args.data) > 1:
161 print(
162 "Input Error. SPARQL Endpoint mode only supports a single target.", file=sys.stderr
163 )
164 return 1
165 endpoint = args.data[0].strip()
166 if not endpoint.lower().startswith(("http:", "https:")):
167 print(
168 "Input Error. SPARQL Endpoint must start with http:// or https://.", file=sys.stderr
169 )
170 return 1
171 options["sparql_mode"] = True
172 return _run(args, [endpoint], options)
173 with ExitStack() as files:
174 try:
175 data = [
176 sys.stdin.buffer.read()
177 if source == "-"
178 else files.enter_context(open(source, "rb"))
179 for source in args.data
180 ]
181 except FileNotFoundError:
182 print("Input Error. DataGraph file not found.", file=sys.stderr)
183 return 1
184 except PermissionError:
185 print("Input Error. DataGraph file not readable.", file=sys.stderr)
186 return 1
187 return _run(args, data, options)
190def _server_requested(environ):
191 # pySHACL's str_is_true: any non-empty value except its false spellings.
192 value = environ.get("PYSHACL_SERVER", environ.get("PYSHACL_HTTP", ""))
193 return bool(value) and value.lower() not in {"0", "f", "n", "false", "no"}
196def _no_server():
197 # pySHACL exits 1 when its optional HTTP server components are missing.
198 print(
199 "pyshacl-turbo does not provide the pySHACL HTTP server; set PYSHACL_TURBO_ALIAS=0 "
200 "and install pyshacl[http] to run it.",
201 file=sys.stderr,
202 )
203 return 1
206def _validation_output(result, rdf_format):
207 conforms, report, text = result
208 if rdf_format == "table" and isinstance(report, Graph):
209 return report_table(conforms, report)
210 if rdf_format != "human" and isinstance(report, Graph):
211 return serialize_graph(report, rdf_format)
212 return text
215def _run(args, inputs, options):
216 data = inputs[0] if len(inputs) == 1 else inputs
217 try:
218 if args.rules:
219 options["advanced"] = True
220 report = shacl_rules(data, **options)
221 output_format = args.format if args.format not in {"human", "table"} else "trig"
222 text = serialize_graph(report, output_format)
223 conforms = True
224 else:
225 options.update(
226 {
227 name: getattr(args, name)
228 for name in ["meta_shacl", "abort_on_first", "allow_infos", "allow_warnings"]
229 }
230 )
231 if args.validate_each:
232 results = validate_each(inputs, **options)
233 conforms = all(result[0] for result in results.values())
234 text = "".join(
235 f"=== Validation result for {index} ===\n"
236 + _validation_output(result, args.format)
237 + "\n"
238 for index, result in results.items()
239 )
240 else:
241 result = validate(data, **options)
242 conforms = result[0]
243 text = _validation_output(result, args.format)
244 if args.output:
245 with open(args.output, "w", encoding="utf-8") as output:
246 output.write(text)
247 else:
248 sys.stdout.write(text)
249 return 0 if conforms else 1
250 except NotImplementedError as error:
251 print(error, file=sys.stderr)
252 return 3
253 except (ValueError, RuntimeError, OSError) as error:
254 print(error, file=sys.stderr)
255 return 2
258def entrypoint():
259 raise SystemExit(main())
262def rules_entrypoint():
263 raise SystemExit(main(["--rules", *sys.argv[1:]]))
266if __name__ == "__main__":
267 entrypoint()