makefile.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. """ Functions for working with Makefiles
  2. """
  3. import os
  4. import qmk.path
  5. from qmk.errors import NoSuchKeyboardError
  6. def parse_rules_mk_file(file, rules_mk=None):
  7. """Turn a rules.mk file into a dictionary.
  8. Args:
  9. file: path to the rules.mk file
  10. rules_mk: already parsed rules.mk the new file should be merged with
  11. Returns:
  12. a dictionary with the file's content
  13. """
  14. if not rules_mk:
  15. rules_mk = {}
  16. if os.path.exists(file):
  17. rules_mk_lines = qmk.path.file_lines(file)
  18. for line in rules_mk_lines:
  19. # Filter out comments
  20. if line.strip().startswith("#"):
  21. continue
  22. # Strip in-line comments
  23. if '#' in line:
  24. line = line[:line.index('#')].strip()
  25. if '=' in line:
  26. # Append
  27. if '+=' in line:
  28. key, value = line.split('+=', 1)
  29. if key.strip() not in rules_mk:
  30. rules_mk[key.strip()] = value.strip()
  31. else:
  32. rules_mk[key.strip()] += ' ' + value.strip()
  33. # Set if absent
  34. elif "?=" in line:
  35. key, value = line.split('?=', 1)
  36. if key.strip() not in rules_mk:
  37. rules_mk[key.strip()] = value.strip()
  38. else:
  39. if ":=" in line:
  40. line.replace(":","")
  41. key, value = line.split('=', 1)
  42. rules_mk[key.strip()] = value.strip()
  43. return rules_mk
  44. def get_rules_mk(keyboard):
  45. """ Get a rules.mk for a keyboard
  46. Args:
  47. keyboard: name of the keyboard
  48. Raises:
  49. NoSuchKeyboardError: when the keyboard does not exists
  50. Returns:
  51. a dictionary with the content of the rules.mk file
  52. """
  53. # Start with qmk_firmware/keyboards
  54. kb_path = os.path.join(os.getcwd(), "keyboards")
  55. # walk down the directory tree
  56. # and collect all rules.mk files
  57. if os.path.exists(os.path.join(kb_path, keyboard)):
  58. rules_mk = dict()
  59. for directory in keyboard.split(os.path.sep):
  60. kb_path = os.path.join(kb_path, directory)
  61. rules_mk_path = os.path.join(kb_path, "rules.mk")
  62. if os.path.exists(rules_mk_path):
  63. rules_mk = parse_rules_mk_file(rules_mk_path, rules_mk)
  64. else:
  65. raise NoSuchKeyboardError("The requested keyboard and/or revision does not exist.")
  66. return rules_mk