aboutsummaryrefslogtreecommitdiff
path: root/lib/python/qmk/json_encoders.py
diff options
context:
space:
mode:
authorZach White <skullydazed@gmail.com>2021-03-25 04:38:10 -0700
committerGitHub <noreply@github.com>2021-03-25 22:38:10 +1100
commit3e60997edba46544557b3a775bdb1538e07c3edf (patch)
tree165923c2cd6b5eeee150c0285ce8ed9eff44eaee /lib/python/qmk/json_encoders.py
parenta74846a0dbd5efbc7b993918f7f3122e1d620c24 (diff)
downloadqmk_firmware-3e60997edba46544557b3a775bdb1538e07c3edf.tar.gz
qmk_firmware-3e60997edba46544557b3a775bdb1538e07c3edf.zip
Add a `qmk format-json` command that will format JSON files (#12372)
* Add a command to format json files * change to work after rebase * add test for qmk format-json * add documentation for qmk format-json * Update lib/python/qmk/cli/format/json.py
Diffstat (limited to 'lib/python/qmk/json_encoders.py')
-rwxr-xr-xlib/python/qmk/json_encoders.py192
1 files changed, 192 insertions, 0 deletions
diff --git a/lib/python/qmk/json_encoders.py b/lib/python/qmk/json_encoders.py
new file mode 100755
index 000000000..9f3da022b
--- /dev/null
+++ b/lib/python/qmk/json_encoders.py
@@ -0,0 +1,192 @@
1"""Class that pretty-prints QMK info.json files.
2"""
3import json
4from decimal import Decimal
5
6newline = '\n'
7
8
9class QMKJSONEncoder(json.JSONEncoder):
10 """Base class for all QMK JSON encoders.
11 """
12 container_types = (list, tuple, dict)
13 indentation_char = " "
14
15 def __init__(self, *args, **kwargs):
16 super().__init__(*args, **kwargs)
17 self.indentation_level = 0
18
19 if not self.indent:
20 self.indent = 4
21
22 def encode_decimal(self, obj):
23 """Encode a decimal object.
24 """
25 if obj == int(obj): # I can't believe Decimal objects don't have .is_integer()
26 return int(obj)
27
28 return float(obj)
29
30 def encode_list(self, obj):
31 """Encode a list-like object.
32 """
33 if self.primitives_only(obj):
34 return "[" + ", ".join(self.encode(element) for element in obj) + "]"
35
36 else:
37 self.indentation_level += 1
38 output = [self.indent_str + self.encode(element) for element in obj]
39 self.indentation_level -= 1
40
41 return "[\n" + ",\n".join(output) + "\n" + self.indent_str + "]"
42
43 def encode(self, obj):
44 """Encode keymap.json objects for QMK.
45 """
46 if isinstance(obj, Decimal):
47 return self.encode_decimal(obj)
48
49 elif isinstance(obj, (list, tuple)):
50 return self.encode_list(obj)
51
52 elif isinstance(obj, dict):
53 return self.encode_dict(obj)
54
55 else:
56 return super().encode(obj)
57
58 def primitives_only(self, obj):
59 """Returns true if the object doesn't have any container type objects (list, tuple, dict).
60 """
61 if isinstance(obj, dict):
62 obj = obj.values()
63
64 return not any(isinstance(element, self.container_types) for element in obj)
65
66 @property
67 def indent_str(self):
68 return self.indentation_char * (self.indentation_level * self.indent)
69
70
71class InfoJSONEncoder(QMKJSONEncoder):
72 """Custom encoder to make info.json's a little nicer to work with.
73 """
74 def encode_dict(self, obj):
75 """Encode info.json dictionaries.
76 """
77 if obj:
78 if self.indentation_level == 4:
79 # These are part of a layout, put them on a single line.
80 return "{ " + ", ".join(f"{self.encode(key)}: {self.encode(element)}" for key, element in sorted(obj.items())) + " }"
81
82 else:
83 self.indentation_level += 1
84 output = [self.indent_str + f"{json.dumps(key)}: {self.encode(value)}" for key, value in sorted(obj.items(), key=self.sort_dict)]
85 self.indentation_level -= 1
86 return "{\n" + ",\n".join(output) + "\n" + self.indent_str + "}"
87 else:
88 return "{}"
89
90 def sort_dict(self, key):
91 """Forces layout to the back of the sort order.
92 """
93 key = key[0]
94
95 if self.indentation_level == 1:
96 if key == 'manufacturer':
97 return '10keyboard_name'
98
99 elif key == 'keyboard_name':
100 return '11keyboard_name'
101
102 elif key == 'maintainer':
103 return '12maintainer'
104
105 elif key in ('height', 'width'):
106 return '40' + str(key)
107
108 elif key == 'community_layouts':
109 return '97community_layouts'
110
111 elif key == 'layout_aliases':
112 return '98layout_aliases'
113
114 elif key == 'layouts':
115 return '99layouts'
116
117 else:
118 return '50' + str(key)
119
120 return key
121
122
123class KeymapJSONEncoder(QMKJSONEncoder):
124 """Custom encoder to make keymap.json's a little nicer to work with.
125 """
126 def encode_dict(self, obj):
127 """Encode dictionary objects for keymap.json.
128 """
129 if obj:
130 self.indentation_level += 1
131 output_lines = [f"{self.indent_str}{json.dumps(key)}: {self.encode(value)}" for key, value in sorted(obj.items(), key=self.sort_dict)]
132 output = ',\n'.join(output_lines)
133 self.indentation_level -= 1
134
135 return f"{{\n{output}\n{self.indent_str}}}"
136
137 else:
138 return "{}"
139
140 def encode_list(self, obj):
141 """Encode a list-like object.
142 """
143 if self.indentation_level == 2:
144 indent_level = self.indentation_level + 1
145 # We have a list of keycodes
146 layer = [[]]
147
148 for key in obj:
149 if key == 'JSON_NEWLINE':
150 layer.append([])
151 else:
152 layer[-1].append(f'"{key}"')
153
154 layer = [f"{self.indent_str*indent_level}{', '.join(row)}" for row in layer]
155
156 return f"{self.indent_str}[\n{newline.join(layer)}\n{self.indent_str*self.indentation_level}]"
157
158 elif self.primitives_only(obj):
159 return "[" + ", ".join(self.encode(element) for element in obj) + "]"
160
161 else:
162 self.indentation_level += 1
163 output = [self.indent_str + self.encode(element) for element in obj]
164 self.indentation_level -= 1
165
166 return "[\n" + ",\n".join(output) + "\n" + self.indent_str + "]"
167
168 def sort_dict(self, key):
169 """Sorts the hashes in a nice way.
170 """
171 key = key[0]
172
173 if self.indentation_level == 1:
174 if key == 'version':
175 return '00version'
176
177 elif key == 'author':
178 return '01author'
179
180 elif key == 'notes':
181 return '02notes'
182
183 elif key == 'layers':
184 return '98layers'
185
186 elif key == 'documentation':
187 return '99documentation'
188
189 else:
190 return '50' + str(key)
191
192 return key