makeutils.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import re
  2. def filterLines(lines, regex):
  3. '''Filters each line of the given line iterator using the given regular
  4. expression string. For each match, a tuple containing the text matching
  5. each capture group from the regular expression is yielded.
  6. '''
  7. matcher = re.compile(regex)
  8. for line in lines:
  9. if line.endswith('\n'):
  10. line = line[ : -1]
  11. match = matcher.match(line)
  12. if match:
  13. yield match.groups()
  14. def filterFile(filePath, regex):
  15. '''Filters each line of the given text file using the given regular
  16. expression string. For each match, a tuple containing the text matching
  17. each capture group from the regular expression is yielded.
  18. '''
  19. inp = open(filePath, 'r')
  20. try:
  21. for groups in filterLines(inp, regex):
  22. yield groups
  23. finally:
  24. inp.close()
  25. def joinContinuedLines(lines):
  26. '''Iterates through the given lines, replacing lines that are continued
  27. using a trailing backslash with a single line.
  28. '''
  29. buf = ''
  30. for line in lines:
  31. if line.endswith('\\\n'):
  32. buf += line[ : -2]
  33. elif line.endswith('\\'):
  34. buf += line[ : -1]
  35. else:
  36. yield buf + line
  37. buf = ''
  38. if buf:
  39. raise ValueError('Continuation on last line')
  40. def extractMakeVariables(filePath):
  41. '''Extract all variable definitions from the given Makefile.
  42. Returns a dictionary that maps each variable name to its value.
  43. '''
  44. makeVars = {}
  45. inp = open(filePath, 'r')
  46. try:
  47. for name, value in filterLines(
  48. joinContinuedLines(inp),
  49. r'[ ]*([A-Za-z0-9_]+)[ ]*:=(.*)'
  50. ):
  51. makeVars[name] = value.strip()
  52. finally:
  53. inp.close()
  54. return makeVars
  55. def parseBool(valueStr):
  56. '''Parses a string containing a boolean value.
  57. Accepted values are "true" and "false"; anything else raises ValueError.
  58. '''
  59. if valueStr == 'true':
  60. return True
  61. elif valueStr == 'false':
  62. return False
  63. else:
  64. raise ValueError('Invalid boolean "%s"' % valueStr)