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
|
from __future__ import print_function
import argparse
import logging
import sys
import traceback
import json
import os
import urlparse
import pkg_resources # part of setuptools
from typing import Any, Dict, List, Union
from rdflib import Graph, plugin
from rdflib.serializer import Serializer
from . import schema
from . import jsonld_context
from . import makedoc
from . import validate
from .sourceline import strip_dup_lineno
from .ref_resolver import Loader
_logger = logging.getLogger("salad")
from rdflib.plugin import register, Parser
register('json-ld', Parser, 'rdflib_jsonld.parser', 'JsonLDParser')
def printrdf(workflow, # type: str
wf, # type: Union[List[Dict[unicode, Any]], Dict[unicode, Any]]
ctx, # type: Dict[unicode, Any]
sr # type: str
):
# type: (...) -> None
g = jsonld_context.makerdf(workflow, wf, ctx)
print(g.serialize(format=sr))
def main(argsl=None): # type: (List[str]) -> int
if argsl is None:
argsl = sys.argv[1:]
parser = argparse.ArgumentParser()
parser.add_argument("--rdf-serializer",
help="Output RDF serialization format used by --print-rdf (one of turtle (default), n3, nt, xml)",
default="turtle")
exgroup = parser.add_mutually_exclusive_group()
exgroup.add_argument("--print-jsonld-context", action="store_true",
help="Print JSON-LD context for schema")
exgroup.add_argument(
"--print-rdfs", action="store_true", help="Print RDF schema")
exgroup.add_argument("--print-avro", action="store_true",
help="Print Avro schema")
exgroup.add_argument("--print-rdf", action="store_true",
help="Print corresponding RDF graph for document")
exgroup.add_argument("--print-pre", action="store_true",
help="Print document after preprocessing")
exgroup.add_argument(
"--print-index", action="store_true", help="Print node index")
exgroup.add_argument("--print-metadata",
action="store_true", help="Print document metadata")
exgroup.add_argument("--version", action="store_true",
help="Print version")
exgroup = parser.add_mutually_exclusive_group()
exgroup.add_argument("--strict", action="store_true", help="Strict validation (unrecognized or out of place fields are error)",
default=True, dest="strict")
exgroup.add_argument("--non-strict", action="store_false", help="Lenient validation (ignore unrecognized fields)",
default=True, dest="strict")
exgroup = parser.add_mutually_exclusive_group()
exgroup.add_argument("--verbose", action="store_true",
help="Default logging")
exgroup.add_argument("--quiet", action="store_true",
help="Only print warnings and errors.")
exgroup.add_argument("--debug", action="store_true",
help="Print even more logging")
parser.add_argument("schema", type=str)
parser.add_argument("document", type=str, nargs="?", default=None)
args = parser.parse_args(argsl)
if args.quiet:
_logger.setLevel(logging.WARN)
if args.debug:
_logger.setLevel(logging.DEBUG)
pkg = pkg_resources.require("schema_salad")
if pkg:
if args.version:
print("%s %s" % (sys.argv[0], pkg[0].version))
return 0
else:
_logger.info("%s %s", sys.argv[0], pkg[0].version)
# Get the metaschema to validate the schema
metaschema_names, metaschema_doc, metaschema_loader = schema.get_metaschema()
# Load schema document and resolve refs
schema_uri = args.schema
if not urlparse.urlparse(schema_uri)[0]:
schema_uri = "file://" + os.path.abspath(schema_uri)
schema_raw_doc = metaschema_loader.fetch(schema_uri)
try:
schema_doc, schema_metadata = metaschema_loader.resolve_all(
schema_raw_doc, schema_uri)
except (validate.ValidationException) as e:
_logger.error("Schema `%s` failed link checking:\n%s",
args.schema, e, exc_info=(True if args.debug else False))
_logger.debug("Index is %s", metaschema_loader.idx.keys())
_logger.debug("Vocabulary is %s", metaschema_loader.vocab.keys())
return 1
except (RuntimeError) as e:
_logger.error("Schema `%s` read error:\n%s",
args.schema, e, exc_info=(True if args.debug else False))
return 1
# Optionally print the schema after ref resolution
if not args.document and args.print_pre:
print(json.dumps(schema_doc, indent=4))
return 0
if not args.document and args.print_index:
print(json.dumps(metaschema_loader.idx.keys(), indent=4))
return 0
# Validate the schema document against the metaschema
try:
schema.validate_doc(metaschema_names, schema_doc,
metaschema_loader, args.strict,
source=schema_metadata["name"])
except validate.ValidationException as e:
_logger.error("While validating schema `%s`:\n%s" %
(args.schema, str(e)))
return 1
# Get the json-ld context and RDFS representation from the schema
metactx = {} # type: Dict[str, str]
if isinstance(schema_raw_doc, dict):
metactx = schema_raw_doc.get("$namespaces", {})
if "$base" in schema_raw_doc:
metactx["@base"] = schema_raw_doc["$base"]
(schema_ctx, rdfs) = jsonld_context.salad_to_jsonld_context(schema_doc, metactx)
# Create the loader that will be used to load the target document.
document_loader = Loader(schema_ctx)
# Make the Avro validation that will be used to validate the target
# document
if isinstance(schema_doc, list):
(avsc_names, avsc_obj) = schema.make_avro_schema(
schema_doc, document_loader)
else:
_logger.error("Schema `%s` must be a list.", args.schema)
return 1
if isinstance(avsc_names, Exception):
_logger.error("Schema `%s` error:\n%s", args.schema,
avsc_names, exc_info=((type(avsc_names), avsc_names,
None) if args.debug else None))
if args.print_avro:
print(json.dumps(avsc_obj, indent=4))
return 1
# Optionally print Avro-compatible schema from schema
if args.print_avro:
print(json.dumps(avsc_obj, indent=4))
return 0
# Optionally print the json-ld context from the schema
if args.print_jsonld_context:
j = {"@context": schema_ctx}
print(json.dumps(j, indent=4, sort_keys=True))
return 0
# Optionally print the RDFS graph from the schema
if args.print_rdfs:
print(rdfs.serialize(format=args.rdf_serializer))
return 0
if args.print_metadata and not args.document:
print(json.dumps(schema_metadata, indent=4))
return 0
# If no document specified, all done.
if not args.document:
print("Schema `%s` is valid" % args.schema)
return 0
# Load target document and resolve refs
try:
uri = args.document
if not urlparse.urlparse(uri)[0]:
doc = "file://" + os.path.abspath(uri)
document, doc_metadata = document_loader.resolve_ref(uri)
except (validate.ValidationException, RuntimeError) as e:
_logger.error("Document `%s` failed validation:\n%s",
args.document, strip_dup_lineno(unicode(e)), exc_info=args.debug)
return 1
# Optionally print the document after ref resolution
if args.print_pre:
print(json.dumps(document, indent=4))
return 0
if args.print_index:
print(json.dumps(document_loader.idx.keys(), indent=4))
return 0
# Validate the schema document against the metaschema
try:
schema.validate_doc(avsc_names, document,
document_loader, args.strict)
except validate.ValidationException as e:
_logger.error("While validating document `%s`:\n%s" %
(args.document, str(e)))
return 1
# Optionally convert the document to RDF
if args.print_rdf:
if isinstance(document, (dict, list)):
printrdf(args.document, document, schema_ctx, args.rdf_serializer)
return 0
else:
print("Document must be a dictionary or list.")
return 1
if args.print_metadata:
print(json.dumps(doc_metadata, indent=4))
return 0
print("Document `%s` is valid" % args.document)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
|