File: cli.py

package info (click to toggle)
python-jsonpath 2.0.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,028 kB
  • sloc: python: 9,473; makefile: 6
file content (373 lines) | stat: -rw-r--r-- 10,217 bytes parent folder | download
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
"""JSONPath, JSON Pointer and JSON Patch command line interface."""

import argparse
import json
import sys

import jsonpath
from jsonpath.__about__ import __version__
from jsonpath.exceptions import JSONPatchError
from jsonpath.exceptions import JSONPathIndexError
from jsonpath.exceptions import JSONPathSyntaxError
from jsonpath.exceptions import JSONPathTypeError
from jsonpath.exceptions import JSONPointerError

INDENT = 2


def path_sub_command(parser: argparse.ArgumentParser) -> None:  # noqa: D103
    parser.set_defaults(func=handle_path_command)
    group = parser.add_mutually_exclusive_group(required=True)

    group.add_argument(
        "-q",
        "--query",
        help="JSONPath query string.",
    )

    group.add_argument(
        "-r",
        "--path-file",
        type=argparse.FileType(mode="r"),
        help="Text file containing a JSONPath query.",
    )

    parser.add_argument(
        "-f",
        "--file",
        type=argparse.FileType(mode="rb"),
        default=sys.stdin,
        help=(
            "File to read the target JSON document from. "
            "Defaults to reading from the standard input stream."
        ),
    )

    parser.add_argument(
        "-o",
        "--output",
        type=argparse.FileType(mode="w"),
        default=sys.stdout,
        help=(
            "File to write resulting objects to, as a JSON array. "
            "Defaults to the standard output stream."
        ),
    )

    parser.add_argument(
        "--no-type-checks",
        action="store_true",
        help="Disables filter expression well-typedness checks.",
    )

    parser.add_argument(
        "--strict",
        action="store_true",
        help=(
            "Compile and evaluate JSONPath expressions with strict "
            "compliance with RFC 9535."
        ),
    )


def pointer_sub_command(parser: argparse.ArgumentParser) -> None:  # noqa: D103
    parser.set_defaults(func=handle_pointer_command)
    group = parser.add_mutually_exclusive_group(required=True)

    group.add_argument(
        "-p",
        "--pointer",
        help="RFC 6901 formatted JSON Pointer string.",
    )

    group.add_argument(
        "-r",
        "--pointer-file",
        type=argparse.FileType(mode="r"),
        help="Text file containing an RFC 6901 formatted JSON Pointer string.",
    )

    parser.add_argument(
        "-f",
        "--file",
        type=argparse.FileType(mode="rb"),
        default=sys.stdin,
        help=(
            "File to read the target JSON document from. "
            "Defaults to reading from the standard input stream."
        ),
    )

    parser.add_argument(
        "-o",
        "--output",
        type=argparse.FileType(mode="w"),
        default=sys.stdout,
        help=(
            "File to write the resulting object to, in JSON format. "
            "Defaults to the standard output stream."
        ),
    )

    parser.add_argument(
        "-u",
        "--uri-decode",
        action="store_true",
        help="Unescape URI escape sequences found in JSON Pointers",
    )


def patch_sub_command(parser: argparse.ArgumentParser) -> None:  # noqa: D103
    parser.set_defaults(func=handle_patch_command)

    parser.add_argument(
        "patch",
        type=argparse.FileType(mode="rb"),
        metavar="PATCH",
        help="File containing an RFC 6902 formatted JSON Patch.",
    )

    parser.add_argument(
        "-f",
        "--file",
        type=argparse.FileType(mode="rb"),
        default=sys.stdin,
        help=(
            "File to read the target JSON document from. "
            "Defaults to reading from the standard input stream."
        ),
    )

    parser.add_argument(
        "-o",
        "--output",
        type=argparse.FileType(mode="w"),
        default=sys.stdout,
        help=(
            "File to write the resulting JSON document to. "
            "Defaults to the standard output stream."
        ),
    )

    parser.add_argument(
        "-u",
        "--uri-decode",
        action="store_true",
        help="Unescape URI escape sequences found in JSON Pointers",
    )


_EPILOG = """\
Use [json COMMAND --help] for command specific help.

Usage Examples:
  Find objects in source.json matching a JSONPath, write them to result.json.
  $ json path -q "$.foo['bar'][?@.baz > 1]" -f source.json -o result.json

  Resolve a JSON Pointer against source.json, pretty print the result to stdout.
  $ json --pretty pointer -p "/foo/bar/0" -f source.json

  Apply JSON Patch patch.json to JSON from stdin, output to result.json.
  $ cat source.json | json patch /path/to/patch.json -o result.json
"""


class DescriptionHelpFormatter(
    argparse.RawDescriptionHelpFormatter,
    argparse.ArgumentDefaultsHelpFormatter,
):
    """Raw epilog formatter with defaults."""


def setup_parser() -> argparse.ArgumentParser:  # noqa: D103
    parser = argparse.ArgumentParser(
        prog="json",
        formatter_class=DescriptionHelpFormatter,
        description="JSONPath, JSON Pointer and JSON Patch utilities.",
        epilog=_EPILOG,
    )

    parser.add_argument(
        "--debug",
        action="store_true",
        help="Show stack traces.",
    )

    parser.add_argument(
        "--pretty",
        action="store_true",
        help="Add indents and newlines to output JSON.",
    )

    parser.add_argument(
        "-v",
        "--version",
        action="version",
        version=f"python-jsonpath, version {__version__}",
        help="Show the version and exit.",
    )

    parser.add_argument(
        "--no-unicode-escape",
        action="store_true",
        help="Disable decoding of UTF-16 escape sequence within paths and pointers.",
    )

    subparsers = parser.add_subparsers(
        dest="command",
        required=True,
        metavar="COMMAND",
    )

    path_sub_command(
        subparsers.add_parser(
            name="path",
            help="Find objects in a JSON document given a JSONPath.",
            description="Find objects in a JSON document given a JSONPath.",
        )
    )

    pointer_sub_command(
        subparsers.add_parser(
            name="pointer",
            help="Resolve a JSON Pointer against a JSON document.",
            description="Resolve a JSON Pointer against a JSON document.",
        )
    )

    patch_sub_command(
        subparsers.add_parser(
            name="patch",
            help="Apply a JSON Patch to a JSON document.",
            description="Apply a JSON Patch to a JSON document.",
        )
    )

    return parser


def handle_path_command(args: argparse.Namespace) -> None:  # noqa: PLR0912
    """Handle the `path` sub command."""
    # Empty string is OK.
    if args.query is not None:
        query = args.query
    else:
        query = args.query_file.read().strip()

    try:
        path = jsonpath.JSONPathEnvironment(
            unicode_escape=not args.no_unicode_escape,
            well_typed=not args.no_type_checks,
            strict=args.strict,
        ).compile(query)
    except JSONPathSyntaxError as err:
        if args.debug:
            raise
        sys.stderr.write(f"json path syntax error: {err}\n")
        sys.exit(1)
    except JSONPathTypeError as err:
        if args.debug:
            raise
        sys.stderr.write(f"json path type error: {err}\n")
        sys.exit(1)
    except JSONPathIndexError as err:
        if args.debug:
            raise
        sys.stderr.write(f"json path index error: {err}\n")
        sys.exit(1)

    try:
        matches = path.findall(args.file)
    except json.JSONDecodeError as err:
        if args.debug:
            raise
        sys.stderr.write(f"target document json decode error: {err}\n")
        sys.exit(1)
    except JSONPathTypeError as err:
        # Type errors are currently only occurring are compile-time.
        if args.debug:
            raise
        sys.stderr.write(f"json path type error: {err}\n")
        sys.exit(1)

    indent = INDENT if args.pretty else None
    json.dump(matches, args.output, indent=indent)


def handle_pointer_command(args: argparse.Namespace) -> None:
    """Handle the `pointer` sub command."""
    # Empty string is OK.
    if args.pointer is not None:
        pointer = args.pointer
    else:
        pointer = args.pointer_file.read().strip()

    try:
        match = jsonpath.pointer.resolve(
            pointer,
            args.file,
            unicode_escape=not args.no_unicode_escape,
            uri_decode=args.uri_decode,
        )
    except json.JSONDecodeError as err:
        if args.debug:
            raise
        sys.stderr.write(f"target document json decode error: {err}\n")
        sys.exit(1)
    except JSONPointerError as err:
        if args.debug:
            raise
        sys.stderr.write(str(err) + "\n")
        sys.exit(1)

    indent = INDENT if args.pretty else None
    json.dump(match, args.output, indent=indent)


def handle_patch_command(args: argparse.Namespace) -> None:
    """Handle the `patch` sub command."""
    try:
        patch = json.load(args.patch)
    except json.JSONDecodeError as err:
        if args.debug:
            raise
        sys.stderr.write(f"patch document json decode error: {err}\n")
        sys.exit(1)

    if not isinstance(patch, list):
        sys.stderr.write(
            "error: patch file does not look like an array of patch operations"
        )
        sys.exit(1)

    try:
        patched = jsonpath.patch.apply(
            patch,
            args.file,
            unicode_escape=not args.no_unicode_escape,
            uri_decode=args.uri_decode,
        )
    except json.JSONDecodeError as err:
        if args.debug:
            raise
        sys.stderr.write(f"target document json decode error: {err}\n")
        sys.exit(1)
    except JSONPatchError as err:
        if args.debug:
            raise
        sys.stderr.write(str(err) + "\n")
        sys.exit(1)

    indent = INDENT if args.pretty else None
    json.dump(patched, args.output, indent=indent)


def main() -> None:
    """CLI argument parser entry point."""
    parser = setup_parser()
    args = parser.parse_args()
    args.func(args)


if __name__ == "__main__":
    main()