makefile.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """ Functions for working with Makefiles
  2. """
  3. from pathlib import Path
  4. from qmk.errors import NoSuchKeyboardError
  5. def parse_rules_mk_file(file, rules_mk=None):
  6. """Turn a rules.mk file into a dictionary.
  7. Args:
  8. file: path to the rules.mk file
  9. rules_mk: already parsed rules.mk the new file should be merged with
  10. Returns:
  11. a dictionary with the file's content
  12. """
  13. if not rules_mk:
  14. rules_mk = {}
  15. file = Path(file)
  16. if file.exists():
  17. rules_mk_lines = file.read_text().split("\n")
  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 = Path.cwd() / "keyboards"
  55. # walk down the directory tree
  56. # and collect all rules.mk files
  57. kb_dir = kb_path / keyboard
  58. if kb_dir.exists():
  59. rules_mk = dict()
  60. for directory in Path(keyboard).parts:
  61. kb_path = kb_path / directory
  62. rules_mk_path = kb_path / "rules.mk"
  63. if rules_mk_path.exists():
  64. rules_mk = parse_rules_mk_file(rules_mk_path, rules_mk)
  65. else:
  66. raise NoSuchKeyboardError("The requested keyboard and/or revision does not exist.")
  67. return rules_mk