##// END OF EJS Templates
py3: define and use json.loads polyfill...
Gregory Szorc -
r43697:579672b3 stable
parent child Browse files
Show More
@@ -955,7 +955,7 b' class bzrestapi(bzaccess):'
955 def _fetch(self, burl):
955 def _fetch(self, burl):
956 try:
956 try:
957 resp = url.open(self.ui, burl)
957 resp = url.open(self.ui, burl)
958 return json.loads(resp.read())
958 return pycompat.json_loads(resp.read())
959 except util.urlerr.httperror as inst:
959 except util.urlerr.httperror as inst:
960 if inst.code == 401:
960 if inst.code == 401:
961 raise error.Abort(_(b'authorization failed'))
961 raise error.Abort(_(b'authorization failed'))
@@ -978,7 +978,7 b' class bzrestapi(bzaccess):'
978 req = request_type(burl, data, {b'Content-Type': b'application/json'})
978 req = request_type(burl, data, {b'Content-Type': b'application/json'})
979 try:
979 try:
980 resp = url.opener(self.ui).open(req)
980 resp = url.opener(self.ui).open(req)
981 return json.loads(resp.read())
981 return pycompat.json_loads(resp.read())
982 except util.urlerr.httperror as inst:
982 except util.urlerr.httperror as inst:
983 if inst.code == 401:
983 if inst.code == 401:
984 raise error.Abort(_(b'authorization failed'))
984 raise error.Abort(_(b'authorization failed'))
@@ -126,7 +126,6 b' from __future__ import absolute_import'
126
126
127 import collections
127 import collections
128 import itertools
128 import itertools
129 import json
130 import os
129 import os
131 import re
130 import re
132 import subprocess
131 import subprocess
@@ -642,7 +641,7 b' def fixfile(ui, repo, opts, fixers, fixc'
642 if fixer.shouldoutputmetadata():
641 if fixer.shouldoutputmetadata():
643 try:
642 try:
644 metadatajson, newerdata = stdout.split(b'\0', 1)
643 metadatajson, newerdata = stdout.split(b'\0', 1)
645 metadata[fixername] = json.loads(metadatajson)
644 metadata[fixername] = pycompat.json_loads(metadatajson)
646 except ValueError:
645 except ValueError:
647 ui.warn(
646 ui.warn(
648 _(b'ignored invalid output from fixer tool: %s\n')
647 _(b'ignored invalid output from fixer tool: %s\n')
@@ -363,7 +363,7 b' class _gitlfsremote(object):'
363 _(b'LFS error: %s') % _urlerrorreason(ex), hint=hint
363 _(b'LFS error: %s') % _urlerrorreason(ex), hint=hint
364 )
364 )
365 try:
365 try:
366 response = json.loads(rawjson)
366 response = pycompat.json_loads(rawjson)
367 except ValueError:
367 except ValueError:
368 raise LfsRemoteError(
368 raise LfsRemoteError(
369 _(b'LFS server returns invalid JSON: %s')
369 _(b'LFS server returns invalid JSON: %s')
@@ -133,7 +133,7 b' def _processbatchrequest(repo, req, res)'
133 return True
133 return True
134
134
135 # XXX: specify an encoding?
135 # XXX: specify an encoding?
136 lfsreq = json.loads(req.bodyfh.read())
136 lfsreq = pycompat.json_loads(req.bodyfh.read())
137
137
138 # If no transfer handlers are explicitly requested, 'basic' is assumed.
138 # If no transfer handlers are explicitly requested, 'basic' is assumed.
139 if r'basic' not in lfsreq.get(r'transfers', [r'basic']):
139 if r'basic' not in lfsreq.get(r'transfers', [r'basic']):
@@ -152,8 +152,8 b' def vcrcommand(name, flags, spec, helpca'
152 value = r1params[key][0]
152 value = r1params[key][0]
153 # we want to compare json payloads without worrying about ordering
153 # we want to compare json payloads without worrying about ordering
154 if value.startswith(b'{') and value.endswith(b'}'):
154 if value.startswith(b'{') and value.endswith(b'}'):
155 r1json = json.loads(value)
155 r1json = pycompat.json_loads(value)
156 r2json = json.loads(r2params[key][0])
156 r2json = pycompat.json_loads(r2params[key][0])
157 if r1json != r2json:
157 if r1json != r2json:
158 return False
158 return False
159 elif r2params[key][0] != value:
159 elif r2params[key][0] != value:
@@ -307,7 +307,7 b' def callconduit(ui, name, params):'
307 if isinstance(x, pycompat.unicode)
307 if isinstance(x, pycompat.unicode)
308 else x,
308 else x,
309 # json.loads only accepts bytes from py3.6+
309 # json.loads only accepts bytes from py3.6+
310 json.loads(encoding.unifromlocal(body)),
310 pycompat.json_loads(encoding.unifromlocal(body)),
311 )
311 )
312 if parsed.get(b'error_code'):
312 if parsed.get(b'error_code'):
313 msg = _(b'Conduit Error (%s): %s') % (
313 msg = _(b'Conduit Error (%s): %s') % (
@@ -332,7 +332,7 b' def debugcallconduit(ui, repo, name):'
332 lambda x: encoding.unitolocal(x)
332 lambda x: encoding.unitolocal(x)
333 if isinstance(x, pycompat.unicode)
333 if isinstance(x, pycompat.unicode)
334 else x,
334 else x,
335 json.loads(rawparams),
335 pycompat.json_loads(rawparams),
336 )
336 )
337 # json.dumps only accepts unicode strings
337 # json.dumps only accepts unicode strings
338 result = pycompat.rapply(
338 result = pycompat.rapply(
@@ -12,6 +12,7 b' from __future__ import absolute_import'
12
12
13 import getopt
13 import getopt
14 import inspect
14 import inspect
15 import json
15 import os
16 import os
16 import shlex
17 import shlex
17 import sys
18 import sys
@@ -88,6 +89,7 b' def rapply(f, xs):'
88
89
89 if ispy3:
90 if ispy3:
90 import builtins
91 import builtins
92 import codecs
91 import functools
93 import functools
92 import io
94 import io
93 import struct
95 import struct
@@ -340,6 +342,48 b' if ispy3:'
340 iteritems = lambda x: x.items()
342 iteritems = lambda x: x.items()
341 itervalues = lambda x: x.values()
343 itervalues = lambda x: x.values()
342
344
345 # Python 3.5's json.load and json.loads require str. We polyfill its
346 # code for detecting encoding from bytes.
347 if sys.version_info[0:2] < (3, 6):
348
349 def _detect_encoding(b):
350 bstartswith = b.startswith
351 if bstartswith((codecs.BOM_UTF32_BE, codecs.BOM_UTF32_LE)):
352 return 'utf-32'
353 if bstartswith((codecs.BOM_UTF16_BE, codecs.BOM_UTF16_LE)):
354 return 'utf-16'
355 if bstartswith(codecs.BOM_UTF8):
356 return 'utf-8-sig'
357
358 if len(b) >= 4:
359 if not b[0]:
360 # 00 00 -- -- - utf-32-be
361 # 00 XX -- -- - utf-16-be
362 return 'utf-16-be' if b[1] else 'utf-32-be'
363 if not b[1]:
364 # XX 00 00 00 - utf-32-le
365 # XX 00 00 XX - utf-16-le
366 # XX 00 XX -- - utf-16-le
367 return 'utf-16-le' if b[2] or b[3] else 'utf-32-le'
368 elif len(b) == 2:
369 if not b[0]:
370 # 00 XX - utf-16-be
371 return 'utf-16-be'
372 if not b[1]:
373 # XX 00 - utf-16-le
374 return 'utf-16-le'
375 # default
376 return 'utf-8'
377
378 def json_loads(s, *args, **kwargs):
379 if isinstance(s, (bytes, bytearray)):
380 s = s.decode(_detect_encoding(s), 'surrogatepass')
381
382 return json.loads(s, *args, **kwargs)
383
384 else:
385 json_loads = json.loads
386
343 else:
387 else:
344 import cStringIO
388 import cStringIO
345
389
@@ -417,6 +461,7 b' else:'
417 getargspec = inspect.getargspec
461 getargspec = inspect.getargspec
418 iteritems = lambda x: x.iteritems()
462 iteritems = lambda x: x.iteritems()
419 itervalues = lambda x: x.itervalues()
463 itervalues = lambda x: x.itervalues()
464 json_loads = json.loads
420
465
421 isjython = sysplatform.startswith(b'java')
466 isjython = sysplatform.startswith(b'java')
422
467
@@ -98,7 +98,7 b' def request(host, path, show):'
98 if formatjson:
98 if formatjson:
99 # json.dumps() will print trailing newlines. Eliminate them
99 # json.dumps() will print trailing newlines. Eliminate them
100 # to make tests easier to write.
100 # to make tests easier to write.
101 data = json.loads(data)
101 data = pycompat.json_loads(data)
102 lines = json.dumps(data, sort_keys=True, indent=2).splitlines()
102 lines = json.dumps(data, sort_keys=True, indent=2).splitlines()
103 for line in lines:
103 for line in lines:
104 bodyfh.write(pycompat.sysbytes(line.rstrip()))
104 bodyfh.write(pycompat.sysbytes(line.rstrip()))
General Comments 0
You need to be logged in to leave comments. Login now