insert-usb-ids.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. # Reads the USB VID and PID from the file specified by sys.argv[1] and then
  2. # inserts those values into the template file specified by sys.argv[2],
  3. # printing the result to stdout
  4. from __future__ import print_function
  5. import sys
  6. import re
  7. import string
  8. needed_keys = ('USB_PID_CDC_MSC', 'USB_PID_CDC_HID', 'USB_PID_CDC', 'USB_VID')
  9. def parse_usb_ids(filename):
  10. rv = dict()
  11. for line in open(filename).readlines():
  12. line = line.rstrip('\r\n')
  13. match = re.match('^#define\s+(\w+)\s+\(0x([0-9A-Fa-f]+)\)$', line)
  14. if match and match.group(1).startswith('USBD_'):
  15. key = match.group(1).replace('USBD', 'USB')
  16. val = match.group(2)
  17. print("key =", key, "val =", val)
  18. if key in needed_keys:
  19. rv[key] = val
  20. for k in needed_keys:
  21. if k not in rv:
  22. raise Exception("Unable to parse %s from %s" % (k, filename))
  23. return rv
  24. if __name__ == "__main__":
  25. usb_ids_file = sys.argv[1]
  26. template_file = sys.argv[2]
  27. replacements = parse_usb_ids(usb_ids_file)
  28. for line in open(template_file, 'r').readlines():
  29. print(string.Template(line).safe_substitute(replacements), end='')