|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +# This software was developed at the National Institute of Standards |
| 4 | +# and Technology by employees of the Federal Government in the course |
| 5 | +# of their official duties. Pursuant to title 17 Section 105 of the |
| 6 | +# United States Code this software is not subject to copyright |
| 7 | +# protection and is in the public domain. NIST assumes no |
| 8 | +# responsibility whatsoever for its use by other parties, and makes |
| 9 | +# no guarantees, expressed or implied, about its quality, |
| 10 | +# reliability, or any other characteristic. |
| 11 | +# |
| 12 | +# We would appreciate acknowledgement if the software is used. |
| 13 | + |
| 14 | +""" |
| 15 | +This script provides a wrapper to the pySHACL command line tool, |
| 16 | +available here: |
| 17 | +https://github.com/RDFLib/pySHACL |
| 18 | +
|
| 19 | +Portions of the pySHACL command line interface are preserved and passed |
| 20 | +through to the underlying pySHACL validation functionality. |
| 21 | +
|
| 22 | +Other portions of the pySHACL command line interface are adapted to |
| 23 | +CASE, specifically to support CASE and UCO as ontologies that store |
| 24 | +subclass hierarchy and node shapes together (rather than as separate |
| 25 | +ontology and shape graphs). More specifically to CASE, if no particular |
| 26 | +ontology or shapes graph is requested, the most recent version of CASE |
| 27 | +will be used. (That most recent version is shipped with this package as |
| 28 | +a monolithic file; see case_utils.ontology if interested in further |
| 29 | +details.) |
| 30 | +""" |
| 31 | + |
| 32 | +__version__ = "0.1.0" |
| 33 | + |
| 34 | +import argparse |
| 35 | +import importlib.resources |
| 36 | +import logging |
| 37 | +import os |
| 38 | +import pathlib |
| 39 | +import sys |
| 40 | +import typing |
| 41 | + |
| 42 | +import rdflib.util # type: ignore |
| 43 | +import pyshacl # type: ignore |
| 44 | + |
| 45 | +import case_utils.ontology |
| 46 | + |
| 47 | +from case_utils.ontology.version_info import * |
| 48 | + |
| 49 | +_logger = logging.getLogger(os.path.basename(__file__)) |
| 50 | + |
| 51 | +def main() -> None: |
| 52 | + parser = argparse.ArgumentParser(description="CASE wrapper to pySHACL command line tool.") |
| 53 | + |
| 54 | + # Configure debug logging before running parse_args, because there |
| 55 | + # could be an error raised before the construction of the argument |
| 56 | + # parser. |
| 57 | + logging.basicConfig(level=logging.DEBUG if ("--debug" in sys.argv or "-d" in sys.argv) else logging.INFO) |
| 58 | + |
| 59 | + case_version_choices_list = ["none", "case-" + CURRENT_CASE_VERSION] |
| 60 | + |
| 61 | + # Add arguments specific to case_validate. |
| 62 | + parser.add_argument( |
| 63 | + '-d', |
| 64 | + '--debug', |
| 65 | + action='store_true', |
| 66 | + help='Output additional runtime messages.' |
| 67 | + ) |
| 68 | + parser.add_argument( |
| 69 | + "--built-version", |
| 70 | + choices=tuple(case_version_choices_list), |
| 71 | + default="case-"+CURRENT_CASE_VERSION, |
| 72 | + help="Monolithic aggregation of CASE ontology files at certain versions. Does not require networking to use. Default is most recent CASE release." |
| 73 | + ) |
| 74 | + parser.add_argument( |
| 75 | + "--ontology-graph", |
| 76 | + action="append", |
| 77 | + help="Combined ontology (i.e. subclass hierarchy) and shapes (SHACL) file, in any format accepted by rdflib recognized by file extension (e.g. .ttl). Will supplement ontology selected by --built-version. Can be given multiple times." |
| 78 | + ) |
| 79 | + |
| 80 | + # Inherit arguments from pyshacl. |
| 81 | + parser.add_argument( |
| 82 | + '--abort', |
| 83 | + action='store_true', |
| 84 | + help='(As with pyshacl CLI) Abort on first invalid data.' |
| 85 | + ) |
| 86 | + parser.add_argument( |
| 87 | + '-w', |
| 88 | + '--allow-warnings', |
| 89 | + action='store_true', |
| 90 | + help='(As with pyshacl CLI) Shapes marked with severity of Warning or Info will not cause result to be invalid.', |
| 91 | + ) |
| 92 | + parser.add_argument( |
| 93 | + "-f", |
| 94 | + "--format", |
| 95 | + choices=('human', 'turtle', 'xml', 'json-ld', 'nt', 'n3'), |
| 96 | + default='human', |
| 97 | + help="(ALMOST as with pyshacl CLI) Choose an output format. Default is \"human\". Difference: 'table' not provided." |
| 98 | + ) |
| 99 | + parser.add_argument( |
| 100 | + '-im', |
| 101 | + '--imports', |
| 102 | + action='store_true', |
| 103 | + help='(As with pyshacl CLI) Allow import of sub-graphs defined in statements with owl:imports.', |
| 104 | + ) |
| 105 | + parser.add_argument( |
| 106 | + '-i', |
| 107 | + '--inference', |
| 108 | + choices=('none', 'rdfs', 'owlrl', 'both'), |
| 109 | + default='none', |
| 110 | + help="(As with pyshacl CLI) Choose a type of inferencing to run against the Data Graph before validating. Default is \"none\".", |
| 111 | + ) |
| 112 | + parser.add_argument( |
| 113 | + '-o', |
| 114 | + '--output', |
| 115 | + dest='output', |
| 116 | + nargs='?', |
| 117 | + type=argparse.FileType('x'), |
| 118 | + help="(ALMOST as with pyshacl CLI) Send output to a file. If absent, output will be written to stdout. Difference: If specified, file is expected not to exist. Clarification: Does NOT influence --format flag's default value of \"human\". (I.e., any machine-readable serialization format must be specified with --format.)", |
| 119 | + default=sys.stdout, |
| 120 | + ) |
| 121 | + |
| 122 | + parser.add_argument("in_graph") |
| 123 | + |
| 124 | + args = parser.parse_args() |
| 125 | + |
| 126 | + data_graph = rdflib.Graph() |
| 127 | + data_graph.parse(args.in_graph) |
| 128 | + |
| 129 | + ontology_graph = rdflib.Graph() |
| 130 | + if args.built_version != "none": |
| 131 | + ttl_filename = args.built_version + ".ttl" |
| 132 | + _logger.debug("ttl_filename = %r.", ttl_filename) |
| 133 | + ttl_data = importlib.resources.read_text(case_utils.ontology, ttl_filename) |
| 134 | + ontology_graph.parse(data=ttl_data, format="turtle") |
| 135 | + if args.ontology_graph: |
| 136 | + for arg_ontology_graph in args.ontology_graph: |
| 137 | + _logger.debug("arg_ontology_graph = %r.", arg_ontology_graph) |
| 138 | + ontology_graph.parse(arg_ontology_graph) |
| 139 | + |
| 140 | + # Determine output format. |
| 141 | + # pySHACL's determination of output formatting is handled solely |
| 142 | + # through the -f flag. Other CASE CLI tools handle format |
| 143 | + # determination by output file extension. case_validate will defer |
| 144 | + # to pySHACL behavior, as other CASE tools don't (at the time of |
| 145 | + # this writing) have the value "human" as an output format. |
| 146 | + validator_kwargs : typing.Dict[str, str] = dict() |
| 147 | + if args.format != "human": |
| 148 | + validator_kwargs['serialize_report_graph'] = args.format |
| 149 | + |
| 150 | + validate_result : typing.Tuple[ |
| 151 | + bool, |
| 152 | + typing.Union[Exception, bytes, str, rdflib.Graph], |
| 153 | + str |
| 154 | + ] |
| 155 | + validate_result = pyshacl.validate( |
| 156 | + data_graph, |
| 157 | + shacl_graph=ontology_graph, |
| 158 | + ont_graph=ontology_graph, |
| 159 | + inference=args.inference, |
| 160 | + abort_on_first=args.abort, |
| 161 | + allow_warnings=True if args.allow_warnings else False, |
| 162 | + debug=True if args.debug else False, |
| 163 | + do_owl_imports=True if args.imports else False, |
| 164 | + **validator_kwargs |
| 165 | + ) |
| 166 | + |
| 167 | + # Relieve RAM of the data graph after validation has run. |
| 168 | + del data_graph |
| 169 | + |
| 170 | + conforms = validate_result[0] |
| 171 | + validation_graph = validate_result[1] |
| 172 | + validation_text = validate_result[2] |
| 173 | + |
| 174 | + # NOTE: The output logistics code is adapted from pySHACL's file |
| 175 | + # pyshacl/cli.py. This section should be monitored for code drift. |
| 176 | + if args.format == "human": |
| 177 | + args.output.write(validation_text) |
| 178 | + else: |
| 179 | + if isinstance(validation_graph, rdflib.Graph): |
| 180 | + raise NotImplementedError("rdflib.Graph expected not to be created from --format value %r." % args.format) |
| 181 | + elif isinstance(validation_graph, bytes): |
| 182 | + args.output.write(validation_graph.decode("utf-8")) |
| 183 | + elif isinstance(validation_graph, str): |
| 184 | + args.output.write(validation_graph) |
| 185 | + else: |
| 186 | + raise NotImplementedError("Unexpected result type returned from validate: %r." % type(validation_graph)) |
| 187 | + |
| 188 | + sys.exit(0 if conforms else 1) |
| 189 | + |
| 190 | +if __name__ == "__main__": |
| 191 | + main() |
0 commit comments