master ohmu/fastfetch-openbsd / scripts / gen-pciids.py
ohmu  ·  2026-10-15
 1#!/usr/bin/env python3
 2
 3import sys
 4
 5class PciDeviceModel:
 6    def __init__(self, id: int, name: str):
 7        self.id = id
 8        self.name = name
 9
10class PciVendorModel:
11    def __init__(self, id: int, name: str):
12        self.id = id
13        self.name = name
14        self.devices = []
15
16def main(keep_vendor_list: set, pci_ids_path: str):
17    vendors = []
18    with open(pci_ids_path, 'r') as f:
19        full_text = f.read()
20
21    if full_text == '':
22        sys.exit(f'Error: {pci_ids_path} file is empty')
23
24    dev_list_text = full_text[:full_text.rfind('\n\n\n')]  # remove known classes
25    for line in dev_list_text.split('\n'):
26        if not line or line[0] == '#':
27            continue
28        if line[0] != '\t':
29            id, name = line.split('  ', maxsplit=1)
30            vendors.append(PciVendorModel(int(id, 16), name))
31        elif line[1] != '\t':
32            id, name = line[1:].split('  ', maxsplit=1)
33            vendors[-1].devices.append(PciDeviceModel(int(id, 16), name))
34
35    code = """\
36// SPDX-License-Identifier: BSD-3-Clause
37// https://opensource.org/license/BSD-3-Clause
38// Generated from https://pci-ids.ucw.cz/v2.2/pci.ids
39
40#include <stdint.h>
41#include <stddef.h>
42
43typedef struct FFPciDevice
44{
45    const uint32_t id;
46    const char* name;
47} FFPciDevice;
48
49typedef struct FFPciVendor
50{
51    const uint32_t id;
52    const char* name;
53    const FFPciDevice* devices;
54    const uint32_t nDevices;
55} FFPciVendor;
56"""
57
58    if keep_vendor_list:
59        vendors = [vendor for vendor in vendors if vendor.id in keep_vendor_list]
60
61    for vendor in vendors:
62        if vendor.devices:
63            piece = ',\n    '.join('{{ 0x{:04X}, "{}" }}'.format(device.id, device.name.replace('"', '\\"')) for device in vendor.devices)
64            code += f"""
65// {vendor.name}
66static const FFPciDevice pciDevices_{vendor.id:04X}[] = {{
67    {piece},
68    {{}},
69}};
70"""
71
72    piece = ',\n    '.join('{{ 0x{:04X}, "{}", {}, {} }}'.format(vendor.id, vendor.name.replace('"', '\\"'), vendor.devices and f"pciDevices_{vendor.id:04X}" or "NULL", len(vendor.devices)) for vendor in vendors)
73    code += f"""
74const FFPciVendor ffPciVendors[] = {{
75    {piece},
76    {{}},
77}};"""
78
79    print(code)
80
81if __name__ == '__main__':
82    len(sys.argv) == 2 or sys.exit('Usage: gen-pciids.py </path/to/pci.ids>')
83
84    # From <src/detection/gpu/gpu.c>
85    main({
86        0x106b, # Apple
87        0x1002, 0x1022, # AMD
88        0x8086, 0x8087, 0x03e7, # Intel
89        0x0955, 0x10de, 0x12d2, # Nvidia
90        0x1ed5, # MThreads
91        0x5143, # Qualcomm
92        0x14c3, # MTK
93        0x15ad, # VMware
94        0x1af4, # RedHat
95        0x1ab8, # Parallel
96        0x1414, # Microsoft
97        0x108e, # Oracle
98    }, sys.argv[1])