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