|
1
|
|
|
import json |
|
2
|
|
|
from collections import OrderedDict |
|
3
|
|
|
|
|
4
|
|
|
from coalib.bearlib.abstractions.CorrectionBasedBear import CorrectionBasedBear |
|
5
|
|
|
from coalib.results.Result import Result |
|
6
|
|
|
|
|
7
|
|
|
|
|
8
|
|
|
class JSONFormatBear(CorrectionBasedBear): |
|
9
|
|
|
try: |
|
10
|
|
|
DecodeError = json.decoder.JSONDecodeError |
|
11
|
|
|
except: |
|
12
|
|
|
DecodeError = ValueError |
|
13
|
|
|
|
|
14
|
|
|
GET_REPLACEMENT = lambda self, **kwargs: self.get_plain_json(**kwargs) |
|
15
|
|
|
RESULT_MESSAGE = ("This file can be reformatted by sorting keys and " |
|
16
|
|
|
"following indentation.") |
|
17
|
|
|
|
|
18
|
|
|
@staticmethod |
|
19
|
|
|
def get_plain_json(file, json_sort, indent): |
|
20
|
|
|
json_content = json.loads(''.join(file), object_pairs_hook=OrderedDict) |
|
21
|
|
|
new_file = json.dumps(json_content, |
|
22
|
|
|
indent=indent, |
|
23
|
|
|
sort_keys=json_sort).splitlines(True) |
|
24
|
|
|
|
|
25
|
|
|
# Because of a bug in 3.2 we need to strip whitespaces |
|
26
|
|
|
return [line.rstrip(" \n")+"\n" for line in new_file], [] |
|
27
|
|
|
|
|
28
|
|
|
def run(self, filename, file, json_sort: bool=False, indent: int=4): |
|
29
|
|
|
""" |
|
30
|
|
|
Raises issues for any deviations from the pretty-printed JSON. |
|
31
|
|
|
|
|
32
|
|
|
:param json_sort: Whether or not keys should be sorted. |
|
33
|
|
|
:param indent: Number of spaces to indent. |
|
34
|
|
|
""" |
|
35
|
|
|
try: |
|
36
|
|
|
for result in self.retrieve_results(filename, |
|
37
|
|
|
file, |
|
38
|
|
|
json_sort=json_sort, |
|
39
|
|
|
indent=indent): |
|
40
|
|
|
yield result |
|
41
|
|
|
except self.DecodeError as err: |
|
42
|
|
|
yield Result.from_values( |
|
43
|
|
|
self, |
|
44
|
|
|
"This file does not contain parsable JSON. '{adv_msg}'" |
|
45
|
|
|
.format(adv_msg=str(err)), |
|
46
|
|
|
file=filename) |
|
47
|
|
|
|