makefile.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. """ Functions for working with Makefiles
  2. """
  3. from functools import lru_cache
  4. from pathlib import Path
  5. @lru_cache(maxsize=0)
  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. file = Path(file)
  17. if file.exists():
  18. rules_mk_lines = file.read_text().split("\n")
  19. for line in rules_mk_lines:
  20. # Filter out comments
  21. if line.strip().startswith("#"):
  22. continue
  23. # Strip in-line comments
  24. if '#' in line:
  25. line = line[:line.index('#')].strip()
  26. if '=' in line:
  27. # Append
  28. if '+=' in line:
  29. key, value = line.split('+=', 1)
  30. if key.strip() not in rules_mk:
  31. rules_mk[key.strip()] = value.strip()
  32. else:
  33. rules_mk[key.strip()] += ' ' + value.strip()
  34. # Set if absent
  35. elif "?=" in line:
  36. key, value = line.split('?=', 1)
  37. if key.strip() not in rules_mk:
  38. rules_mk[key.strip()] = value.strip()
  39. else:
  40. if ":=" in line:
  41. line.replace(":", "")
  42. key, value = line.split('=', 1)
  43. rules_mk[key.strip()] = value.strip()
  44. return rules_mk