1
+ import collections
1
2
import shutil
2
3
import json
3
4
import ruamel .yaml as yaml
4
5
try :
5
- from ruamel .yaml import CSafeLoader as SafeLoader
6
+ from ruamel .yaml import CSafeLoader as SafeLoader
6
7
except ImportError :
7
- from ruamel .yaml import SafeLoader
8
+ from ruamel .yaml import SafeLoader # type: ignore
8
9
import os
9
10
import subprocess
10
11
import copy
15
16
from rdflib import Graph , URIRef
16
17
import rdflib .namespace
17
18
from rdflib .namespace import RDF , RDFS
18
- try :
19
- import urlparse
20
- except ImportError :
21
- import urllib .parse as urlparse
22
- unicode = str
23
- basestring = str
19
+ import urlparse
24
20
import logging
25
21
from .aslist import aslist
26
- if sys . version_info >= ( 2 , 7 ):
27
- import typing
22
+ from typing import Any , cast , Dict , Iterable , Tuple , Union
23
+ from . ref_resolver import Loader
28
24
29
25
_logger = logging .getLogger ("salad" )
30
26
27
+
31
28
def pred (datatype , field , name , context , defaultBase , namespaces ):
29
+ # type: (Dict[str, Union[Dict, str]], Dict, str, Loader.ContextType, str, Dict[str, rdflib.namespace.Namespace]) -> Union[Dict, str]
32
30
split = urlparse .urlsplit (name )
33
31
34
- v = None
32
+ vee = None # type: Union[str, unicode]
35
33
36
34
if split .scheme :
37
- v = name
38
- (ns , ln ) = rdflib .namespace .split_uri (unicode (v ))
35
+ vee = name
36
+ (ns , ln ) = rdflib .namespace .split_uri (unicode (vee ))
39
37
name = ln
40
38
if ns [0 :- 1 ] in namespaces :
41
- v = unicode (namespaces [ns [0 :- 1 ]][ln ])
42
- _logger .debug ("name, v %s %s" , name , v )
39
+ vee = unicode (namespaces [ns [0 :- 1 ]][ln ])
40
+ _logger .debug ("name, v %s %s" , name , vee )
41
+
42
+ v = None # type: Any
43
43
44
44
if field and "jsonldPredicate" in field :
45
45
if isinstance (field ["jsonldPredicate" ], dict ):
46
46
v = {}
47
47
for k , val in field ["jsonldPredicate" ].items ():
48
- v [("@" + k [1 :] if k .startswith ("_" ) else k )] = val
48
+ v [("@" + k [1 :] if k .startswith ("_" ) else k )] = val
49
49
else :
50
50
v = field ["jsonldPredicate" ]
51
51
elif "jsonldPredicate" in datatype :
52
- for d in datatype ["jsonldPredicate" ]:
53
- if d ["symbol" ] == name :
54
- v = d ["predicate" ]
52
+ if isinstance (datatype ["jsonldPredicate" ], collections .Iterable ):
53
+ for d in datatype ["jsonldPredicate" ]:
54
+ if isinstance (d , dict ):
55
+ if d ["symbol" ] == name :
56
+ v = d ["predicate" ]
57
+ else :
58
+ raise Exception (
59
+ "entries in the jsonldPredicate List must be "
60
+ "Dictionaries" )
61
+ else :
62
+ raise Exception ("jsonldPredicate must be a List of Dictionaries." )
55
63
# if not v:
56
64
# if field and "jsonldPrefix" in field:
57
65
# defaultBase = field["jsonldPrefix"]
58
66
# elif "jsonldPrefix" in datatype:
59
67
# defaultBase = datatype["jsonldPrefix"]
60
68
61
- if not v :
62
- v = defaultBase + name
69
+ ret = v or vee
70
+
71
+ if not ret :
72
+ ret = defaultBase + name
63
73
64
74
if name in context :
65
- if context [name ] != v :
66
- raise Exception ("Predicate collision on %s, '%s' != '%s'" % (name , context [name ], v ))
75
+ if context [name ] != ret :
76
+ raise Exception ("Predicate collision on %s, '%s' != '%s'" %
77
+ (name , context [name ], ret ))
67
78
else :
68
- _logger .debug ("Adding to context '%s' %s (%s)" , name , v , type (v ))
69
- context [name ] = v
79
+ _logger .debug ("Adding to context '%s' %s (%s)" , name , ret , type (ret ))
80
+ context [name ] = ret
81
+
82
+ return ret
70
83
71
- return v
72
84
73
85
def process_type (t , g , context , defaultBase , namespaces , defaultPrefix ):
86
+ # type: (Dict[str, Any], Graph, Loader.ContextType, str, Dict[str, rdflib.namespace.Namespace], str) -> None
74
87
if t ["type" ] == "record" :
75
88
recordname = t ["name" ]
76
89
@@ -90,12 +103,14 @@ def process_type(t, g, context, defaultBase, namespaces, defaultPrefix):
90
103
predicate = "%s:%s" % (defaultPrefix , recordname )
91
104
92
105
if context .get (recordname , predicate ) != predicate :
93
- raise Exception ("Predicate collision on '%s', '%s' != '%s'" % (recordname , context [recordname ], predicate ))
106
+ raise Exception ("Predicate collision on '%s', '%s' != '%s'" % (
107
+ recordname , context [recordname ], predicate ))
94
108
95
109
if not recordname :
96
110
raise Exception ()
97
111
98
- _logger .debug ("Adding to context '%s' %s (%s)" , recordname , predicate , type (predicate ))
112
+ _logger .debug ("Adding to context '%s' %s (%s)" ,
113
+ recordname , predicate , type (predicate ))
99
114
context [recordname ] = predicate
100
115
101
116
for i in t .get ("fields" , []):
@@ -123,7 +138,8 @@ def process_type(t, g, context, defaultBase, namespaces, defaultPrefix):
123
138
# TODO generate range from datatype.
124
139
125
140
if isinstance (i ["type" ], dict ) and "name" in i ["type" ]:
126
- process_type (i ["type" ], g , context , defaultBase , namespaces , defaultPrefix )
141
+ process_type (i ["type" ], g , context , defaultBase ,
142
+ namespaces , defaultPrefix )
127
143
128
144
if "extends" in t :
129
145
for e in aslist (t ["extends" ]):
@@ -136,31 +152,26 @@ def process_type(t, g, context, defaultBase, namespaces, defaultPrefix):
136
152
137
153
138
154
def salad_to_jsonld_context (j , schema_ctx ):
139
- context = {}
155
+ # type: (Iterable, Dict[str, Any]) -> Tuple[Loader.ContextType, Graph]
156
+ context = {} # type: Loader.ContextType
140
157
namespaces = {}
141
158
g = Graph ()
142
159
defaultPrefix = ""
143
160
144
- for k ,v in schema_ctx .items ():
161
+ for k , v in schema_ctx .items ():
145
162
context [k ] = v
146
163
namespaces [k ] = rdflib .namespace .Namespace (v )
147
164
148
165
if "@base" in context :
149
- defaultBase = context ["@base" ]
166
+ defaultBase = cast ( str , context ["@base" ])
150
167
del context ["@base" ]
151
168
else :
152
169
defaultBase = ""
153
170
154
- for k ,v in namespaces .items ():
171
+ for k , v in namespaces .items ():
155
172
g .bind (k , v )
156
173
157
174
for t in j :
158
175
process_type (t , g , context , defaultBase , namespaces , defaultPrefix )
159
176
160
177
return (context , g )
161
-
162
- if __name__ == "__main__" :
163
- with open (sys .argv [1 ]) as f :
164
- j = yaml .load (f , Loader = SafeLoader )
165
- (ctx , g ) = salad_to_jsonld_context (j )
166
- print (json .dumps (ctx , indent = 4 , sort_keys = True ))
0 commit comments