You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

714 lines
24 KiB

  1. """Functions that help us generate and use info.json files.
  2. """
  3. import json
  4. from collections.abc import Mapping
  5. from glob import glob
  6. from pathlib import Path
  7. import jsonschema
  8. from milc import cli
  9. from qmk.constants import CHIBIOS_PROCESSORS, LUFA_PROCESSORS, VUSB_PROCESSORS, LED_INDICATORS
  10. from qmk.c_parse import find_layouts
  11. from qmk.keyboard import config_h, rules_mk
  12. from qmk.keymap import list_keymaps
  13. from qmk.makefile import parse_rules_mk_file
  14. from qmk.math import compute
  15. led_matrix_properties = {
  16. 'driver_count': 'LED_DRIVER_COUNT',
  17. 'driver_addr1': 'LED_DRIVER_ADDR_1',
  18. 'driver_addr2': 'LED_DRIVER_ADDR_2',
  19. 'driver_addr3': 'LED_DRIVER_ADDR_3',
  20. 'driver_addr4': 'LED_DRIVER_ADDR_4',
  21. 'led_count': 'LED_DRIVER_LED_COUNT',
  22. 'timeout': 'ISSI_TIMEOUT',
  23. 'persistence': 'ISSI_PERSISTENCE'
  24. }
  25. rgblight_properties = {
  26. 'led_count': ('RGBLED_NUM', int),
  27. 'pin': ('RGB_DI_PIN', str),
  28. 'max_brightness': ('RGBLIGHT_LIMIT_VAL', int),
  29. 'hue_steps': ('RGBLIGHT_HUE_STEP', int),
  30. 'saturation_steps': ('RGBLIGHT_SAT_STEP', int),
  31. 'brightness_steps': ('RGBLIGHT_VAL_STEP', int)
  32. }
  33. rgblight_toggles = {
  34. 'sleep': 'RGBLIGHT_SLEEP',
  35. 'split': 'RGBLIGHT_SPLIT',
  36. }
  37. rgblight_animations = {
  38. 'all': 'RGBLIGHT_ANIMATIONS',
  39. 'alternating': 'RGBLIGHT_EFFECT_ALTERNATING',
  40. 'breathing': 'RGBLIGHT_EFFECT_BREATHING',
  41. 'christmas': 'RGBLIGHT_EFFECT_CHRISTMAS',
  42. 'knight': 'RGBLIGHT_EFFECT_KNIGHT',
  43. 'rainbow_mood': 'RGBLIGHT_EFFECT_RAINBOW_MOOD',
  44. 'rainbow_swirl': 'RGBLIGHT_EFFECT_RAINBOW_SWIRL',
  45. 'rgb_test': 'RGBLIGHT_EFFECT_RGB_TEST',
  46. 'snake': 'RGBLIGHT_EFFECT_SNAKE',
  47. 'static_gradient': 'RGBLIGHT_EFFECT_STATIC_GRADIENT',
  48. 'twinkle': 'RGBLIGHT_EFFECT_TWINKLE'
  49. }
  50. usb_properties = {'vid': 'VENDOR_ID', 'pid': 'PRODUCT_ID', 'device_ver': 'DEVICE_VER'}
  51. true_values = ['1', 'on', 'yes']
  52. false_values = ['0', 'off', 'no']
  53. def info_json(keyboard):
  54. """Generate the info.json data for a specific keyboard.
  55. """
  56. cur_dir = Path('keyboards')
  57. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  58. if 'DEFAULT_FOLDER' in rules:
  59. keyboard = rules['DEFAULT_FOLDER']
  60. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk', rules)
  61. info_data = {
  62. 'keyboard_name': str(keyboard),
  63. 'keyboard_folder': str(keyboard),
  64. 'keymaps': {},
  65. 'layouts': {},
  66. 'parse_errors': [],
  67. 'parse_warnings': [],
  68. 'maintainer': 'qmk',
  69. }
  70. # Populate the list of JSON keymaps
  71. for keymap in list_keymaps(keyboard, c=False, fullpath=True):
  72. info_data['keymaps'][keymap.name] = {'url': f'https://raw.githubusercontent.com/qmk/qmk_firmware/master/{keymap}/keymap.json'}
  73. # Populate layout data
  74. for layout_name, layout_json in _find_all_layouts(info_data, keyboard).items():
  75. if not layout_name.startswith('LAYOUT_kc'):
  76. layout_json['c_macro'] = True
  77. info_data['layouts'][layout_name] = layout_json
  78. # Merge in the data from info.json, config.h, and rules.mk
  79. info_data = merge_info_jsons(keyboard, info_data)
  80. info_data = _extract_config_h(info_data)
  81. info_data = _extract_rules_mk(info_data)
  82. # Validate against the jsonschema
  83. try:
  84. keyboard_api_validate(info_data)
  85. except jsonschema.ValidationError as e:
  86. json_path = '.'.join([str(p) for p in e.absolute_path])
  87. cli.log.error('Invalid API data: %s: %s: %s', keyboard, json_path, e.message)
  88. print(dir(e))
  89. exit()
  90. # Make sure we have at least one layout
  91. if not info_data.get('layouts'):
  92. _log_error(info_data, 'No LAYOUTs defined! Need at least one layout defined in the keyboard.h or info.json.')
  93. # Make sure we supply layout macros for the community layouts we claim to support
  94. # FIXME(skullydazed): This should be populated into info.json and read from there instead
  95. if 'LAYOUTS' in rules and info_data.get('layouts'):
  96. # Match these up against the supplied layouts
  97. supported_layouts = rules['LAYOUTS'].strip().split()
  98. for layout_name in sorted(info_data['layouts']):
  99. layout_name = layout_name[7:]
  100. if layout_name in supported_layouts:
  101. supported_layouts.remove(layout_name)
  102. if supported_layouts:
  103. for supported_layout in supported_layouts:
  104. _log_error(info_data, 'Claims to support community layout %s but no LAYOUT_%s() macro found' % (supported_layout, supported_layout))
  105. return info_data
  106. def _json_load(json_file):
  107. """Load a json file from disk.
  108. Note: file must be a Path object.
  109. """
  110. try:
  111. return json.load(json_file.open())
  112. except json.decoder.JSONDecodeError as e:
  113. cli.log.error('Invalid JSON encountered attempting to load {fg_cyan}%s{fg_reset}:\n\t{fg_red}%s', json_file, e)
  114. exit(1)
  115. def _jsonschema(schema_name):
  116. """Read a jsonschema file from disk.
  117. FIXME(skullydazed/anyone): Refactor to make this a public function.
  118. """
  119. schema_path = Path(f'data/schemas/{schema_name}.jsonschema')
  120. if not schema_path.exists():
  121. schema_path = Path('data/schemas/false.jsonschema')
  122. return _json_load(schema_path)
  123. def keyboard_validate(data):
  124. """Validates data against the keyboard jsonschema.
  125. """
  126. schema = _jsonschema('keyboard')
  127. validator = jsonschema.Draft7Validator(schema).validate
  128. return validator(data)
  129. def keyboard_api_validate(data):
  130. """Validates data against the api_keyboard jsonschema.
  131. """
  132. base = _jsonschema('keyboard')
  133. relative = _jsonschema('api_keyboard')
  134. resolver = jsonschema.RefResolver.from_schema(base)
  135. validator = jsonschema.Draft7Validator(relative, resolver=resolver).validate
  136. return validator(data)
  137. def _extract_debounce(info_data, config_c):
  138. """Handle debounce.
  139. """
  140. if 'debounce' in info_data and 'DEBOUNCE' in config_c:
  141. _log_warning(info_data, 'Debounce is specified in both info.json and config.h, the config.h value wins.')
  142. if 'DEBOUNCE' in config_c:
  143. info_data['debounce'] = int(config_c['DEBOUNCE'])
  144. return info_data
  145. def _extract_diode_direction(info_data, config_c):
  146. """Handle the diode direction.
  147. """
  148. if 'diode_direction' in info_data and 'DIODE_DIRECTION' in config_c:
  149. _log_warning(info_data, 'Diode direction is specified in both info.json and config.h, the config.h value wins.')
  150. if 'DIODE_DIRECTION' in config_c:
  151. info_data['diode_direction'] = config_c.get('DIODE_DIRECTION')
  152. return info_data
  153. def _extract_indicators(info_data, config_c):
  154. """Find the LED indicator information.
  155. """
  156. for json_key, config_key in LED_INDICATORS.items():
  157. if json_key in info_data.get('indicators', []) and config_key in config_c:
  158. _log_warning(info_data, f'Indicator {json_key} is specified in both info.json and config.h, the config.h value wins.')
  159. if 'indicators' not in info_data:
  160. info_data['indicators'] = {}
  161. if config_key in config_c:
  162. if 'indicators' not in info_data:
  163. info_data['indicators'] = {}
  164. info_data['indicators'][json_key] = config_c.get(config_key)
  165. return info_data
  166. def _extract_community_layouts(info_data, rules):
  167. """Find the community layouts in rules.mk.
  168. """
  169. community_layouts = rules['LAYOUTS'].split() if 'LAYOUTS' in rules else []
  170. if 'community_layouts' in info_data:
  171. for layout in community_layouts:
  172. if layout not in info_data['community_layouts']:
  173. community_layouts.append(layout)
  174. else:
  175. info_data['community_layouts'] = community_layouts
  176. return info_data
  177. def _extract_features(info_data, rules):
  178. """Find all the features enabled in rules.mk.
  179. """
  180. # Special handling for bootmagic which also supports a "lite" mode.
  181. if rules.get('BOOTMAGIC_ENABLE') == 'lite':
  182. rules['BOOTMAGIC_LITE_ENABLE'] = 'on'
  183. del rules['BOOTMAGIC_ENABLE']
  184. if rules.get('BOOTMAGIC_ENABLE') == 'full':
  185. rules['BOOTMAGIC_ENABLE'] = 'on'
  186. # Skip non-boolean features we haven't implemented special handling for
  187. for feature in 'HAPTIC_ENABLE', 'QWIIC_ENABLE':
  188. if rules.get(feature):
  189. del rules[feature]
  190. # Process the rest of the rules as booleans
  191. for key, value in rules.items():
  192. if key.endswith('_ENABLE'):
  193. key = '_'.join(key.split('_')[:-1]).lower()
  194. value = True if value.lower() in true_values else False if value.lower() in false_values else value
  195. if 'config_h_features' not in info_data:
  196. info_data['config_h_features'] = {}
  197. if 'features' not in info_data:
  198. info_data['features'] = {}
  199. if key in info_data['features']:
  200. _log_warning(info_data, 'Feature %s is specified in both info.json and rules.mk, the rules.mk value wins.' % (key,))
  201. info_data['features'][key] = value
  202. info_data['config_h_features'][key] = value
  203. return info_data
  204. def _extract_led_drivers(info_data, rules):
  205. """Find all the LED drivers set in rules.mk.
  206. """
  207. if 'LED_MATRIX_DRIVER' in rules:
  208. if 'led_matrix' not in info_data:
  209. info_data['led_matrix'] = {}
  210. if info_data['led_matrix'].get('driver'):
  211. _log_warning(info_data, 'LED Matrix driver is specified in both info.json and rules.mk, the rules.mk value wins.')
  212. info_data['led_matrix']['driver'] = rules['LED_MATRIX_DRIVER']
  213. return info_data
  214. def _extract_led_matrix(info_data, config_c):
  215. """Handle the led_matrix configuration.
  216. """
  217. led_matrix = info_data.get('led_matrix', {})
  218. for json_key, config_key in led_matrix_properties.items():
  219. if config_key in config_c:
  220. if json_key in led_matrix:
  221. _log_warning(info_data, 'LED Matrix: %s is specified in both info.json and config.h, the config.h value wins.' % (json_key,))
  222. led_matrix[json_key] = config_c[config_key]
  223. def _extract_rgblight(info_data, config_c):
  224. """Handle the rgblight configuration.
  225. """
  226. rgblight = info_data.get('rgblight', {})
  227. animations = rgblight.get('animations', {})
  228. if 'RGBLED_SPLIT' in config_c:
  229. raw_split = config_c.get('RGBLED_SPLIT', '').replace('{', '').replace('}', '').strip()
  230. rgblight['split_count'] = [int(i) for i in raw_split.split(',')]
  231. for json_key, config_key_type in rgblight_properties.items():
  232. config_key, config_type = config_key_type
  233. if config_key in config_c:
  234. if json_key in rgblight:
  235. _log_warning(info_data, 'RGB Light: %s is specified in both info.json and config.h, the config.h value wins.' % (json_key,))
  236. try:
  237. rgblight[json_key] = config_type(config_c[config_key])
  238. except ValueError as e:
  239. cli.log.error('%s: config.h: Could not convert "%s" to %s: %s', info_data['keyboard_folder'], config_c[config_key], config_type.__name__, e)
  240. for json_key, config_key in rgblight_toggles.items():
  241. if config_key in config_c and json_key in rgblight:
  242. _log_warning(info_data, 'RGB Light: %s is specified in both info.json and config.h, the config.h value wins.', json_key)
  243. rgblight[json_key] = config_key in config_c
  244. for json_key, config_key in rgblight_animations.items():
  245. if config_key in config_c:
  246. if json_key in animations:
  247. _log_warning(info_data, 'RGB Light: animations: %s is specified in both info.json and config.h, the config.h value wins.' % (json_key,))
  248. animations[json_key] = config_c[config_key]
  249. if animations:
  250. rgblight['animations'] = animations
  251. if rgblight:
  252. info_data['rgblight'] = rgblight
  253. return info_data
  254. def _pin_name(pin):
  255. """Returns the proper representation for a pin.
  256. """
  257. pin = pin.strip()
  258. if not pin:
  259. return None
  260. elif pin.isdigit():
  261. return int(pin)
  262. elif pin == 'NO_PIN':
  263. return None
  264. elif pin[0] in 'ABCDEFGHIJK' and pin[1].isdigit():
  265. return pin
  266. raise ValueError(f'Invalid pin: {pin}')
  267. def _extract_pins(pins):
  268. """Returns a list of pins from a comma separated string of pins.
  269. """
  270. return [_pin_name(pin) for pin in pins.split(',')]
  271. def _extract_direct_matrix(info_data, direct_pins):
  272. """
  273. """
  274. info_data['matrix_pins'] = {}
  275. direct_pin_array = []
  276. while direct_pins[-1] != '}':
  277. direct_pins = direct_pins[:-1]
  278. for row in direct_pins.split('},{'):
  279. if row.startswith('{'):
  280. row = row[1:]
  281. if row.endswith('}'):
  282. row = row[:-1]
  283. direct_pin_array.append([])
  284. for pin in row.split(','):
  285. if pin == 'NO_PIN':
  286. pin = None
  287. direct_pin_array[-1].append(pin)
  288. return direct_pin_array
  289. def _extract_matrix_info(info_data, config_c):
  290. """Populate the matrix information.
  291. """
  292. row_pins = config_c.get('MATRIX_ROW_PINS', '').replace('{', '').replace('}', '').strip()
  293. col_pins = config_c.get('MATRIX_COL_PINS', '').replace('{', '').replace('}', '').strip()
  294. direct_pins = config_c.get('DIRECT_PINS', '').replace(' ', '')[1:-1]
  295. if 'MATRIX_ROWS' in config_c and 'MATRIX_COLS' in config_c:
  296. if 'matrix_size' in info_data:
  297. _log_warning(info_data, 'Matrix size is specified in both info.json and config.h, the config.h values win.')
  298. info_data['matrix_size'] = {
  299. 'cols': compute(config_c.get('MATRIX_COLS', '0')),
  300. 'rows': compute(config_c.get('MATRIX_ROWS', '0')),
  301. }
  302. if row_pins and col_pins:
  303. if 'matrix_pins' in info_data:
  304. _log_warning(info_data, 'Matrix pins are specified in both info.json and config.h, the config.h values win.')
  305. info_data['matrix_pins'] = {
  306. 'cols': _extract_pins(col_pins),
  307. 'rows': _extract_pins(row_pins),
  308. }
  309. if direct_pins:
  310. if 'matrix_pins' in info_data:
  311. _log_warning(info_data, 'Direct pins are specified in both info.json and config.h, the config.h values win.')
  312. info_data['matrix_pins']['direct'] = _extract_direct_matrix(info_data, direct_pins)
  313. return info_data
  314. def _extract_usb_info(info_data, config_c):
  315. """Populate the USB information.
  316. """
  317. if 'usb' not in info_data:
  318. info_data['usb'] = {}
  319. for info_name, config_name in usb_properties.items():
  320. if config_name in config_c:
  321. if info_name in info_data['usb']:
  322. _log_warning(info_data, '%s in config.h is overwriting usb.%s in info.json' % (config_name, info_name))
  323. info_data['usb'][info_name] = '0x' + config_c[config_name][2:].upper()
  324. return info_data
  325. def _extract_config_h(info_data):
  326. """Pull some keyboard information from existing config.h files
  327. """
  328. config_c = config_h(info_data['keyboard_folder'])
  329. _extract_debounce(info_data, config_c)
  330. _extract_diode_direction(info_data, config_c)
  331. _extract_indicators(info_data, config_c)
  332. _extract_matrix_info(info_data, config_c)
  333. _extract_usb_info(info_data, config_c)
  334. _extract_led_matrix(info_data, config_c)
  335. _extract_rgblight(info_data, config_c)
  336. return info_data
  337. def _extract_rules_mk(info_data):
  338. """Pull some keyboard information from existing rules.mk files
  339. """
  340. rules = rules_mk(info_data['keyboard_folder'])
  341. mcu = rules.get('MCU', info_data.get('processor'))
  342. if mcu in CHIBIOS_PROCESSORS:
  343. arm_processor_rules(info_data, rules)
  344. elif mcu in LUFA_PROCESSORS + VUSB_PROCESSORS:
  345. avr_processor_rules(info_data, rules)
  346. else:
  347. cli.log.warning("%s: Unknown MCU: %s" % (info_data['keyboard_folder'], mcu))
  348. unknown_processor_rules(info_data, rules)
  349. _extract_community_layouts(info_data, rules)
  350. _extract_features(info_data, rules)
  351. _extract_led_drivers(info_data, rules)
  352. return info_data
  353. def _merge_layouts(info_data, new_info_data):
  354. """Merge new_info_data into info_data in an intelligent way.
  355. """
  356. for layout_name, layout_json in new_info_data['layouts'].items():
  357. if layout_name in info_data['layouts']:
  358. # Pull in layouts we have a macro for
  359. if len(info_data['layouts'][layout_name]['layout']) != len(layout_json['layout']):
  360. msg = '%s: %s: Number of elements in info.json does not match! info.json:%s != %s:%s'
  361. _log_error(info_data, msg % (info_data['keyboard_folder'], layout_name, len(layout_json['layout']), layout_name, len(info_data['layouts'][layout_name]['layout'])))
  362. else:
  363. for i, key in enumerate(info_data['layouts'][layout_name]['layout']):
  364. key.update(layout_json['layout'][i])
  365. else:
  366. # Pull in layouts that have matrix data
  367. missing_matrix = False
  368. for key in layout_json.get('layout', {}):
  369. if 'matrix' not in key:
  370. missing_matrix = True
  371. if not missing_matrix:
  372. if layout_name in info_data['layouts']:
  373. # Update an existing layout with new data
  374. for i, key in enumerate(info_data['layouts'][layout_name]['layout']):
  375. key.update(layout_json['layout'][i])
  376. else:
  377. # Copy in the new layout wholesale
  378. layout_json['c_macro'] = False
  379. info_data['layouts'][layout_name] = layout_json
  380. return info_data
  381. def _search_keyboard_h(path):
  382. current_path = Path('keyboards/')
  383. layouts = {}
  384. for directory in path.parts:
  385. current_path = current_path / directory
  386. keyboard_h = '%s.h' % (directory,)
  387. keyboard_h_path = current_path / keyboard_h
  388. if keyboard_h_path.exists():
  389. layouts.update(find_layouts(keyboard_h_path))
  390. return layouts
  391. def _find_all_layouts(info_data, keyboard):
  392. """Looks for layout macros associated with this keyboard.
  393. """
  394. layouts = _search_keyboard_h(Path(keyboard))
  395. if not layouts:
  396. # If we don't find any layouts from info.json or keyboard.h we widen our search. This is error prone which is why we want to encourage people to follow the standard above.
  397. info_data['parse_warnings'].append('%s: Falling back to searching for KEYMAP/LAYOUT macros.' % (keyboard))
  398. for file in glob('keyboards/%s/*.h' % keyboard):
  399. if file.endswith('.h'):
  400. these_layouts = find_layouts(file)
  401. if these_layouts:
  402. layouts.update(these_layouts)
  403. return layouts
  404. def _log_error(info_data, message):
  405. """Send an error message to both JSON and the log.
  406. """
  407. info_data['parse_errors'].append(message)
  408. cli.log.error('%s: %s', info_data.get('keyboard_folder', 'Unknown Keyboard!'), message)
  409. def _log_warning(info_data, message):
  410. """Send a warning message to both JSON and the log.
  411. """
  412. info_data['parse_warnings'].append(message)
  413. cli.log.warning('%s: %s', info_data.get('keyboard_folder', 'Unknown Keyboard!'), message)
  414. def arm_processor_rules(info_data, rules):
  415. """Setup the default info for an ARM board.
  416. """
  417. info_data['processor_type'] = 'arm'
  418. info_data['protocol'] = 'ChibiOS'
  419. if 'MCU' in rules:
  420. if 'processor' in info_data:
  421. _log_warning(info_data, 'Processor/MCU is specified in both info.json and rules.mk, the rules.mk value wins.')
  422. info_data['processor'] = rules['MCU']
  423. elif 'processor' not in info_data:
  424. info_data['processor'] = 'unknown'
  425. if 'BOOTLOADER' in rules:
  426. # FIXME(skullydazed/anyone): need to remove the massive amounts of duplication first
  427. # if 'bootloader' in info_data:
  428. # _log_warning(info_data, 'Bootloader is specified in both info.json and rules.mk, the rules.mk value wins.')
  429. info_data['bootloader'] = rules['BOOTLOADER']
  430. else:
  431. if 'STM32' in info_data['processor']:
  432. info_data['bootloader'] = 'stm32-dfu'
  433. else:
  434. info_data['bootloader'] = 'unknown'
  435. if 'STM32' in info_data['processor']:
  436. info_data['platform'] = 'STM32'
  437. elif 'MCU_SERIES' in rules:
  438. info_data['platform'] = rules['MCU_SERIES']
  439. elif 'ARM_ATSAM' in rules:
  440. info_data['platform'] = 'ARM_ATSAM'
  441. if 'BOARD' in rules:
  442. if 'board' in info_data:
  443. _log_warning(info_data, 'Board is specified in both info.json and rules.mk, the rules.mk value wins.')
  444. info_data['board'] = rules['BOARD']
  445. return info_data
  446. def avr_processor_rules(info_data, rules):
  447. """Setup the default info for an AVR board.
  448. """
  449. info_data['processor_type'] = 'avr'
  450. info_data['bootloader'] = rules['BOOTLOADER'] if 'BOOTLOADER' in rules else 'atmel-dfu'
  451. info_data['platform'] = rules['ARCH'] if 'ARCH' in rules else 'unknown'
  452. info_data['protocol'] = 'V-USB' if rules.get('MCU') in VUSB_PROCESSORS else 'LUFA'
  453. if 'MCU' in rules:
  454. if 'processor' in info_data:
  455. _log_warning(info_data, 'Processor/MCU is specified in both info.json and rules.mk, the rules.mk value wins.')
  456. info_data['processor'] = rules['MCU']
  457. elif 'processor' not in info_data:
  458. info_data['processor'] = 'unknown'
  459. if 'BOOTLOADER' in rules:
  460. # FIXME(skullydazed/anyone): need to remove the massive amounts of duplication first
  461. # if 'bootloader' in info_data:
  462. # _log_warning(info_data, 'Bootloader is specified in both info.json and rules.mk, the rules.mk value wins.')
  463. info_data['bootloader'] = rules['BOOTLOADER']
  464. else:
  465. info_data['bootloader'] = 'atmel-dfu'
  466. # FIXME(fauxpark/anyone): Eventually we should detect the protocol by looking at PROTOCOL inherited from mcu_selection.mk:
  467. # info_data['protocol'] = 'V-USB' if rules.get('PROTOCOL') == 'VUSB' else 'LUFA'
  468. return info_data
  469. def unknown_processor_rules(info_data, rules):
  470. """Setup the default keyboard info for unknown boards.
  471. """
  472. info_data['bootloader'] = 'unknown'
  473. info_data['platform'] = 'unknown'
  474. info_data['processor'] = 'unknown'
  475. info_data['processor_type'] = 'unknown'
  476. info_data['protocol'] = 'unknown'
  477. return info_data
  478. def deep_update(origdict, newdict):
  479. """Update a dictionary in place, recursing to do a deep copy.
  480. """
  481. for key, value in newdict.items():
  482. if isinstance(value, Mapping):
  483. origdict[key] = deep_update(origdict.get(key, {}), value)
  484. else:
  485. origdict[key] = value
  486. return origdict
  487. def merge_info_jsons(keyboard, info_data):
  488. """Return a merged copy of all the info.json files for a keyboard.
  489. """
  490. for info_file in find_info_json(keyboard):
  491. # Load and validate the JSON data
  492. new_info_data = _json_load(info_file)
  493. if not isinstance(new_info_data, dict):
  494. _log_error(info_data, "Invalid file %s, root object should be a dictionary." % (str(info_file),))
  495. continue
  496. try:
  497. keyboard_validate(new_info_data)
  498. except jsonschema.ValidationError as e:
  499. json_path = '.'.join([str(p) for p in e.absolute_path])
  500. cli.log.error('Not including data from file: %s', info_file)
  501. cli.log.error('\t%s: %s', json_path, e.message)
  502. continue
  503. # Mark the layouts as coming from json
  504. for layout in new_info_data.get('layouts', {}).values():
  505. layout['c_macro'] = False
  506. # Update info_data with the new data
  507. deep_update(info_data, new_info_data)
  508. return info_data
  509. def find_info_json(keyboard):
  510. """Finds all the info.json files associated with a keyboard.
  511. """
  512. # Find the most specific first
  513. base_path = Path('keyboards')
  514. keyboard_path = base_path / keyboard
  515. keyboard_parent = keyboard_path.parent
  516. info_jsons = [keyboard_path / 'info.json']
  517. # Add DEFAULT_FOLDER before parents, if present
  518. rules = rules_mk(keyboard)
  519. if 'DEFAULT_FOLDER' in rules:
  520. info_jsons.append(Path(rules['DEFAULT_FOLDER']) / 'info.json')
  521. # Add in parent folders for least specific
  522. for _ in range(5):
  523. info_jsons.append(keyboard_parent / 'info.json')
  524. if keyboard_parent.parent == base_path:
  525. break
  526. keyboard_parent = keyboard_parent.parent
  527. # Return a list of the info.json files that actually exist
  528. return [info_json for info_json in info_jsons if info_json.exists()]