-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
320 lines (266 loc) · 10.4 KB
/
Copy pathcli.py
File metadata and controls
320 lines (266 loc) · 10.4 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
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
"""
Modified version of pyldcli script:
pyldcli - CLI script for PyLD
Source: https://github.com/digitalbazaar/pyld/pull/37/commits/3e990d4a486d577ea3cdeeabbf2a545b8fcba6f0
Author: Wes Turner
"""
import codecs
import json
import logging
import os
import sys
import pyld
from extra_parsers import register_rdflib_parsers
log = logging.getLogger()
# register parsers for other RDF serialization formats not supported by pyLD
register_rdflib_parsers()
def rdf_to_jsonld(path, options):
"""
Read an RDF dataset and generate a JSON-LD string
:param path: path to an RDF file
:param options: options dict
:returns: JSON-LD string
:rtype: str
"""
# format=None, useRdfType=False, useNativeTypes=False
# compact=None
log.debug("rdf_to_jsonld: %r, %r" % (path, options))
with codecs.open(path, 'r', encoding='utf8') as f:
output = pyld.jsonld.from_rdf(f.read(), options)
assert isinstance(output, list)
compact = options.get('compact')
frame = options.get('frame')
if compact:
if os.path.exists(compact):
with codecs.open(compact, 'r', encoding='utf-8') as f:
compact_str = f.read()
else:
compact_str = compact
output = pyld.jsonld.compact(output, compact_str)
elif options.get('expand'):
output = pyld.jsonld.expand(output)
elif options.get('flatten'):
output = pyld.jsonld.flatten(output)
elif frame:
output = pyld.jsonld.frame(output, frame) # TODO
elif options.get('normalize'):
output = pyld.jsonld.normalize(output, {'format': options.get('format')})
try:
json_str = json.dumps(output, indent=options.get('indent', 1))
log.debug("rdf_to_jsonld: len(output): %d" % len(json_str))
return json_str
except Exception as e:
log.error("Cannot dump data as json, returning original data")
return output
import unittest
class Test_pyldcli(unittest.TestCase):
def setUp(self):
self.TEST_NQUADS = '../tb/schema.ttl.nquads'
self.__exit = sys.exit
sys.exit = lambda x: x
def tearDown(self):
sys.exit = self.__exit
def test_00_pyldcli(self):
#output = main('')
#self.assertEqual(output, 0)
output = main('-h')
self.assertEqual(output, 0)
output = main('--help')
self.assertEqual(output, 0)
def test_01_rdf_to_jsonld(self):
output = main('--rdf-to-jsonld', self.TEST_NQUADS)
self.assertEqual(output, 0)
output = main('--rdf-to-jsonld', self.TEST_NQUADS,
'--format', 'application/nquads')
self.assertEqual(output, 0)
def test_01_rdf_to_jsonld_unknown_format_raises(self):
with self.assertRaises(pyld.jsonld.JsonLdError):
output = main('--rdf-to-jsonld', self.TEST_NQUADS,
'--format', 'application/xyz')
self.assertNotEqual(output, 0)
def test_02_rdf_to_jsonld_indent(self):
output = main('--rdf-to-jsonld', self.TEST_NQUADS, '--indent', '0')
self.assertEqual(output, 0)
output = main('--rdf-to-jsonld', self.TEST_NQUADS, '--indent', '2')
self.assertEqual(output, 0)
def test_03_rdf_to_jsonld_useRdfType(self):
output = main('--rdf-to-jsonld', self.TEST_NQUADS, '--rdf-type')
self.assertEqual(output, 0)
def test_04_rdf_to_jsonld_useNativeTypes(self):
output = main('--rdf-to-jsonld', self.TEST_NQUADS, '--native-types')
self.assertEqual(output, 0)
def test_05_rdf_to_jsonld_compact(self):
output = main('--rdf-to-jsonld', self.TEST_NQUADS,
'--compact', 'http://schema.org')
self.assertEqual(output, 0)
def test_06_rdf_to_jsonld_expand(self):
output = main('--rdf-to-jsonld', self.TEST_NQUADS,
'--expand')
self.assertEqual(output, 0)
def test_06_rdf_to_jsonld_flatten(self):
output = main('--rdf-to-jsonld', self.TEST_NQUADS,
'--flatten')
self.assertEqual(output, 0)
def test_06_rdf_to_jsonld_frame(self):
output = main('--rdf-to-jsonld', self.TEST_NQUADS,
'--frame')
self.assertEqual(output, 0)
def test_06_rdf_to_jsonld_normalize(self):
output = main('--rdf-to-jsonld', self.TEST_NQUADS,
'--normalize')
self.assertEqual(output, 0)
def main(*argv):
import argparse
prs = argparse.ArgumentParser() # usage="%prog [args] filename")
# from_rdf
prs.add_argument('--rdf-to-jsonld',
help='TASK: Convert an RDF dataset to JSON-LD',
dest='rdf_to_jsonld',
action='store')
prs.add_argument('--format',
help='Input file format [default: application/nquads]',
dest='format',
action='store')
prs.add_argument('-o', '--output',
help=('Output file path. If not given, then data will be'
'printed to stdout.'),
dest='output',
action='store')
prs.add_argument('--rdf-type',
help='Use rdf:type instead of @type',
dest='useRdfType',
action='store_true')
prs.add_argument('--native-types',
help='Convert XSD types into native types',
dest='useNativeTypes',
action='store_true')
prs.add_argument('--indent',
help='Indent json with n spaces [default: 1]',
dest='indent',
action='store',
type=int,
default=1)
prs.add_argument('--compact',
help=('ACTION: Compact the document with the given '
'@context file or URI'),
dest='compact',
action='store')
prs.add_argument('--expand',
help='ACTION: Perform JSON-LD expansion',
dest='expand',
action='store_true')
prs.add_argument('--flatten',
help='ACTION: Perform JSON-LD flattening',
dest='flatten',
action='store_true')
prs.add_argument('--frame',
help='ACTION: Perform JSON-LD framing',
dest='frame',
action='store_true')
prs.add_argument('--normalize',
help='ACTION: Perform JSON-LD normalization',
dest='normalize',
action='store_true',
default=False)
prs.add_argument('--base',
help='Base IRI to use',
dest='base',
action='store')
prs.add_argument('--dont-compact-arrays',
help='Don\'t compact arrays to single values',
dest='dont_compact_arrays',
action='store_true',
default=False)
prs.add_argument('--top-level-graph',
help='Always output a top level graph (default: False)',
dest='top_level_graph',
action='store_true',
default=False)
prs.add_argument('--expand-context',
help='@context file or URI to expand with',
dest='expandContext',
action='store',
default=None)
prs.add_argument('--no-embed',
help='default @embed flag (default: True)',
dest='embed',
action='store_false',
default=True)
prs.add_argument('--explicit',
help='default @explicit flag (default: False)',
dest='explicit',
action='store_true',
default=False)
prs.add_argument('--no-require-all',
help='default @requireAll flag (default: True)',
dest='requireAll',
action='store_false',
default=True)
prs.add_argument('--omit-default',
help='default @omitDefault flag (default: False)',
dest='omitDefault',
action='store_true',
default=False)
prs.add_argument('-v', '--verbose',
dest='verbose',
action='store_true',)
prs.add_argument('-q', '--quiet',
dest='quiet',
action='store_true',)
prs.add_argument('-t', '--test',
dest='run_tests',
action='store_true',)
if not argv:
_argv = sys.argv[1:]
else:
_argv = list(argv)
opts = prs.parse_args(args=_argv)
output = open(opts.output, 'w') if opts.output else sys.stdout
if not opts.quiet:
logging.basicConfig()
if opts.verbose:
logging.getLogger().setLevel(logging.DEBUG)
if opts.run_tests:
_args = _argv[:]
_args.remove('-t')
sys.argv = [sys.argv[0]] + _args
sys.exit(unittest.main())
if opts.rdf_to_jsonld:
options = {
# read_rdf
'useRdfType': opts.useRdfType,
'useNativeTypes': opts.useNativeTypes,
# rdf_to_jsonld
'compact': opts.compact,
'base': opts.base,
'compactArrays': not opts.dont_compact_arrays,
'graph': opts.top_level_graph,
'expandContext': opts.expandContext,
'expand': opts.expand,
# base
# expandContext
'flatten': opts.flatten,
# base
# expandContext
'frame': opts.frame,
# base
# expandContext
'embed': opts.embed,
'explicit': opts.explicit,
'requireAll': opts.requireAll,
'omitDefault': opts.omitDefault,
'normalize': opts.normalize,
# json.dumps
'indent': opts.indent,
}
if opts.format is not None:
options['format'] = opts.format # read_rdf
json_str = rdf_to_jsonld(opts.rdf_to_jsonld, options)
print(json_str, file=output)
output.close()
return 0
if __name__ == "__main__":
sys.exit(main(*sys.argv[1:]))