Repository navigation
Expand file tree
/
Copy pathjsonpatch_cli.py
More file actions
214 lines (181 loc) · 8.17 KB
/
Copy pathjsonpatch_cli.py
File metadata and controls
214 lines (181 loc) · 8.17 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
""" The jsondiff and jsonpatch command line programs """
import sys
import os.path
import json
import jsonpatch
import tempfile
import argparse
from contextlib import ExitStack
jsondiff_parser = argparse.ArgumentParser(
prog='jsondiff', description='Diff two JSON files')
jsondiff_parser.add_argument('FILE1', type=argparse.FileType('r', encoding='utf-8-sig'))
jsondiff_parser.add_argument('FILE2', type=argparse.FileType('r', encoding='utf-8-sig'))
jsondiff_parser.add_argument('--indent', type=int, default=None,
help='Indent output by n spaces')
jsondiff_parser.add_argument('-u', '--preserve-unicode', action='store_true',
help='Output Unicode character as-is without using Code Point')
jsondiff_parser.add_argument('-t', '--test-ops', action='store_true',
help='Precede each remove and replace operation '
'by a test of the value it changes')
jsondiff_parser.add_argument('-v', '--version', action='version',
version='%(prog)s ' + jsonpatch.__version__)
def _input_files(*streams):
""" Closes the input files when the returned context is left; stdin is
left open, as it is not ours """
inputs = ExitStack()
for stream in streams:
if stream is not sys.stdin:
inputs.enter_context(stream)
return inputs
def _load(stream, loads=json.loads):
""" Parses the JSON document in stream; errors name the file """
try:
return loads(stream.read())
except ValueError as ex:
# invalid JSON or, as a UnicodeDecodeError, invalid UTF-8
name = getattr(stream, 'name', '<input>')
raise ValueError('{0}: {1}'.format(name, ex)) from ex
def _run(parser, program):
""" Runs a command line program. Errors in its input, and in reading
and writing files, are reported in one line, with exit status 2 """
try:
program()
except KeyboardInterrupt:
sys.exit(1)
except (jsonpatch.JsonPatchException, jsonpatch.JsonPointerException,
ValueError, OSError) as ex:
parser.exit(2, '{0}: error: {1}\n'.format(parser.prog, ex))
def jsondiff_main():
_run(jsondiff_parser, diff_files)
def diff_files():
""" Diffs two JSON files and prints a patch """
args = jsondiff_parser.parse_args()
with _input_files(args.FILE1, args.FILE2):
doc1 = _load(args.FILE1)
doc2 = _load(args.FILE2)
patch = jsonpatch.make_patch(doc1, doc2, generate_test_ops=args.test_ops)
if patch.patch:
print(json.dumps(patch.patch, indent=args.indent, ensure_ascii=not args.preserve_unicode))
sys.exit(1)
jsonpatch_parser = argparse.ArgumentParser(
prog='jsonpatch',
description='Apply a JSON patch on a JSON file')
jsonpatch_parser.add_argument('ORIGINAL', type=argparse.FileType('r', encoding='utf-8-sig'),
help='Original file')
jsonpatch_parser.add_argument('PATCH', type=argparse.FileType('r', encoding='utf-8-sig'),
nargs='?', default=sys.stdin,
help='Patch file (read from stdin if omitted)')
jsonpatch_parser.add_argument('--indent', type=int, default=None,
help='Indent output by n spaces')
jsonpatch_parser.add_argument('-b', '--backup', action='store_true',
help='Back up ORIGINAL if modifying in-place')
jsonpatch_parser.add_argument('-i', '--in-place', action='store_true',
help='Modify ORIGINAL in-place instead of to stdout')
jsonpatch_parser.add_argument('-v', '--version', action='version',
version='%(prog)s ' + jsonpatch.__version__)
jsonpatch_parser.add_argument('-u', '--preserve-unicode', action='store_true',
help='Output Unicode character as-is without using Code Point')
def _link_backup(original, temporary):
""" Links original to its backup name, replacing an older backup """
# link() does not overwrite an existing file, so the link is created
# under a temporary name, and then moved over an older backup
link = temporary + '.orig'
os.link(original, link)
try:
os.replace(link, original + '.orig')
finally:
# It is still there if replacing failed, and if the older backup is
# a link to original already, as replace() does nothing then
try:
os.unlink(link)
except OSError:
pass
def jsonpatch_main():
_run(jsonpatch_parser, patch_files)
def patch_files():
""" Applies a JSON patch on a JSON file """
args = jsonpatch_parser.parse_args()
# The inputs are closed before anything is written, as Windows cannot
# replace ORIGINAL while it is open.
with _input_files(args.ORIGINAL, args.PATCH):
doc = _load(args.ORIGINAL)
patch = _load(args.PATCH, jsonpatch.JsonPatch.from_string)
result = patch.apply(doc)
if args.in_place:
dirname = os.path.abspath(os.path.dirname(args.ORIGINAL.name))
fd = None
try:
# Attempt to replace the file atomically. We do this by
# creating a temporary file in the same directory as the
# original file so we can atomically move the new file over
# the original later. (This is done in the same directory
# because atomic renames do not work across mount points.)
fd, pathname = tempfile.mkstemp(dir=dirname)
fp = os.fdopen(fd, 'w', encoding='utf-8')
atomic = True
except OSError:
# mkstemp may have succeeded before fdopen failed. Neither the
# descriptor nor the temporary file belongs to the fallback.
if fd is not None:
try:
os.close(fd)
except OSError:
pass
try:
os.unlink(pathname)
except OSError:
pass
# We failed to create the temporary file for an atomic
# replace, so fall back to non-atomic mode by backing up
# the original (if desired) and writing a new file.
if args.backup:
# like in atomic mode, an older backup is replaced
os.replace(args.ORIGINAL.name, args.ORIGINAL.name + '.orig')
# A same-inode replace may leave the original name in place.
try:
os.unlink(args.ORIGINAL.name)
except FileNotFoundError:
pass
fp = open(args.ORIGINAL.name, 'w', encoding='utf-8')
atomic = False
else:
# Since we're not replacing the original file in-place, write
# the modified JSON to stdout instead.
fp = sys.stdout
# By this point we have some sort of file object we can write the
# modified JSON to.
try:
json.dump(result, fp, indent=args.indent, ensure_ascii=not args.preserve_unicode)
fp.write('\n')
if args.in_place:
fp.close()
except BaseException:
if args.in_place:
# Cleanup must not replace the original output error.
try:
fp.close()
except OSError:
pass
if atomic:
try:
os.unlink(pathname)
except OSError:
pass
raise
if args.in_place:
if atomic:
try:
# Complete the atomic replace by linking the original
# to a backup (if desired), which replaces an older
# backup, fixing up the permissions
# on the temporary file, and moving it into place.
if args.backup:
_link_backup(args.ORIGINAL.name, pathname)
os.chmod(pathname, os.stat(args.ORIGINAL.name).st_mode)
os.replace(pathname, args.ORIGINAL.name)
except OSError:
# Preserve the original if backup, permissions, or replacement
# fails. replace() can overwrite an existing file on Windows
# without unlinking it first.
os.unlink(pathname)
raise