File: data-parse-test.py

package info (click to toggle)
libratbag 0.18-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,332 kB
  • sloc: ansic: 29,486; python: 3,757; sh: 412; makefile: 5
file content (349 lines) | stat: -rwxr-xr-x 9,640 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
#!/usr/bin/env python3
#
# Copyright © 2017 Red Hat, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
# Device data verification script
#

import argparse
import configparser
import pathlib
import re
import sys
import traceback


def check_match_str(string: str):
    bustypes = ["usb", "bluetooth"]

    matches = string.split(";")
    for match in matches:
        if not match:  # empty string if trailing ;
            continue

        parts = match.split(":")
        assert len(parts) == 3
        assert parts[0] in bustypes
        vid = parts[1]
        assert vid == f"{int(vid, 16):04x}"
        pid = parts[2]
        assert pid == f"{int(pid, 16):04x}"


def check_devicetype_str(string):
    permitted_types = ["mouse", "keyboard", "other"]
    assert string in permitted_types


def check_section_device(section: configparser.SectionProxy):
    required_keys = ["Name", "Driver", "DeviceMatch", "DeviceType"]

    for key in section:
        assert key in required_keys

    for r in required_keys:
        assert r in section

    check_devicetype_str(section["DeviceType"])

    check_match_str(section["DeviceMatch"])


def check_dpi_range_str(string: str):
    m = re.search("^([0-9]+):([0-9]+)@([0-9.]+)$", string)
    assert m is not None
    min = int(m.group(1))
    max = int(m.group(2))
    steps = float(m.group(3))

    assert min >= 0 and min <= 400
    assert max >= 2000 and max <= 36000
    assert steps > 0 and steps <= 100

    if int(steps) == steps:
        steps = int(steps)

    assert string == f"{min}:{max}@{steps}"


def check_dpi_list_str(string: str):
    entries = string.split(";")
    # Remove possible empty last entry if trailing with a ;
    if not entries[len(entries) - 1]:
        entries = entries[:-1]

    for idx, entry in enumerate(entries):
        dpi = int(entry)
        assert dpi >= 0 and dpi <= 12000
        if idx > 0:
            prev = entries[idx - 1]
            prev_dpi = int(prev)
            assert dpi > prev_dpi


def check_profile_type_str(string: str):
    types = ["G9", "G500", "G700"]
    assert string in types


def check_section_asus(section: configparser.SectionProxy):
    permitted_keys = (
        "ButtonMapping",
        "Buttons",
        "DpiRange",
        "Dpis",
        "Leds",
        "Profiles",
        "Quirks",
        "Wireless",
    )
    for key in section:
        assert key in permitted_keys

    try:
        check_dpi_range_str(section["DpiRange"])
    except KeyError:
        # No such section - not an error.
        pass

    try:
        quirks = (
            "DOUBLE_DPI",
            "STRIX_PROFILE",
        )
        for quirk in section["Quirks"].split(";"):
            assert quirk in quirks
    except KeyError:
        # No such section - not an error.
        pass


def check_section_hidpp10(section: configparser.SectionProxy):
    permitted = [
        "Profiles",
        "ProfileType",
        "DpiRange",
        "DpiList",
        "DeviceIndex",
        "Leds",
    ]
    for key in section:
        assert key in permitted

    try:
        nprofiles = int(section["Profiles"])
        # 10 is arbitrarily chosen
        assert nprofiles > 0 and nprofiles < 10
    except KeyError:
        # No such section - not an error.
        pass

    try:
        index = int(section["DeviceIndex"], 16)
        assert index > 0 and index <= 0xFF
    except KeyError:
        # No such section - not an error.
        pass

    try:
        check_dpi_range_str(section["DpiRange"])
        assert "DpiList" not in section.keys()
    except KeyError:
        # No such section - not an error.
        pass

    try:
        check_dpi_list_str(section["DpiList"])
        assert "DpiRange" not in section.keys()
    except KeyError:
        # No such section - not an error.
        pass

    try:
        check_profile_type_str(section["ProfileType"])
    except KeyError:
        # No such section - not an error.
        pass

    try:
        leds = int(section["Leds"])
        # 10 is arbitrarily chosen
        assert leds > 0 and leds < 10
    except KeyError:
        # No such section - not an error.
        pass


def check_section_hidpp20(section: configparser.SectionProxy):
    permitted = ["Buttons", "DeviceIndex", "Leds", "ReportRate", "Quirk"]
    for key in section:
        assert key in permitted

    try:
        index = int(section["DeviceIndex"], 16)
        assert index > 0 and index <= 0xFF
    except KeyError:
        # No such section - not an error.
        pass


def check_section_steelseries(section: configparser.SectionProxy):
    permitted_keys = (
        "Buttons",
        "DeviceVersion",
        "DpiList",
        "DpiRange",
        "Leds",
        "MacroLength",
        "Quirk",
    )
    for key in section:
        assert key in permitted_keys

    try:
        check_dpi_list_str(section["DpiList"])
        assert "DpiRange" not in section.keys()
    except KeyError:
        # No such section - not an error.
        pass

    try:
        check_dpi_range_str(section["DpiRange"])
        assert "DpiList" not in section.keys()
    except KeyError:
        # No such section - not an error.
        pass

    try:
        quirks = ("Rival100", "SenseiRAW")
        assert section["Quirk"] in quirks
    except KeyError:
        # No such section - not an error.
        pass


def check_section_driver(driver: str, section: configparser.SectionProxy):
    if driver == "asus":
        check_section_asus(section)
        return

    if driver == "hidpp10":
        check_section_hidpp10(section)
        return

    if driver == "hidpp20":
        check_section_hidpp20(section)
        return

    if driver == "steelseries":
        check_section_steelseries(section)
        return

    raise ValueError(f"Unsupported driver section {driver}")


def validate_data_file_name(path: str):
    # Matching any of the characters in the regular expression will throw an
    # error. Currently only tests the square brackets [], parentheses, and curly
    # braces.
    illegal_characters_regex = "([\\[\\]\\{\\}\\(\\)])"
    found_characters = re.findall(illegal_characters_regex, path)
    if found_characters:
        raise ValueError(
            "data file name '{}' contains illegal characters: '{}'".format(
                path, "".join(found_characters)
            )
        )


SINOWEALTH_FW_VERSION_LEN = 4
SINOWEALTH_DEVICE_SECTION_PREFIX = "Driver/sinowealth/devices/"
SINOWEALTH_REQUIRED_KEYS = (
    "DeviceName",
    "LedType",
)
SINOWEALTH_PERMITTED_KEYS = (
    *SINOWEALTH_REQUIRED_KEYS,
    "Buttons",
    "Profiles",
    "SensorType",
)


def parse_data_file(path: str):
    print(f"Parsing file {path}")
    data = configparser.ConfigParser(strict=True)
    # Don't convert to lowercase
    data.optionxform = lambda option: option
    data.read(path)

    assert "Device" in data.sections()
    check_section_device(data["Device"])

    driver = data["Device"]["Driver"]
    driver_section = f"Driver/{driver}"

    permitted_sections = ["Device", driver_section]
    # The sinowealth driver uses non-static section names in device files as it
    # uses a single device file for several actual devices. See the example
    # device file for details.
    if driver == "sinowealth":
        for device_section_name in data.sections():
            if not device_section_name.startswith(SINOWEALTH_DEVICE_SECTION_PREFIX):
                continue
            fw_version = device_section_name[len(SINOWEALTH_DEVICE_SECTION_PREFIX) :]
            assert len(fw_version) == SINOWEALTH_FW_VERSION_LEN

            device_section = data[device_section_name]
            for key in SINOWEALTH_REQUIRED_KEYS:
                assert key in device_section
            for key in device_section:
                assert key in SINOWEALTH_PERMITTED_KEYS
    else:
        for s in data.sections():
            assert s in permitted_sections

    if data.has_section(driver_section):
        check_section_driver(driver, data[driver_section])


def main() -> None:
    is_error = False

    parser = argparse.ArgumentParser(description="Device data-file checker")
    parser.add_argument("directory")
    args = parser.parse_args()
    for path in pathlib.Path(args.directory).glob("*.device"):
        path_str = str(path)
        try:
            validate_data_file_name(path_str)
            parse_data_file(path_str)
        except Exception:
            is_error = True
            traceback.print_exc(file=sys.stdout)

    if is_error:
        raise SystemExit(1)


if __name__ == "__main__":
    main()