Guido van Rossum | 00ff433 | 1994-10-03 16:33:08 +0000 | [diff] [blame] | 1 | # Parse Makefiles and Python Setup(.in) files. |
| 2 | |
| 3 | import regex |
| 4 | import string |
| 5 | |
| 6 | |
| 7 | # Extract variable definitions from a Makefile. |
| 8 | # Return a dictionary mapping names to values. |
| 9 | # May raise IOError. |
| 10 | |
| 11 | makevardef = regex.compile('^\([a-zA-Z0-9_]+\)[ \t]*=\(.*\)') |
| 12 | |
| 13 | def getmakevars(filename): |
| 14 | variables = {} |
| 15 | fp = open(filename) |
| 16 | try: |
| 17 | while 1: |
| 18 | line = fp.readline() |
| 19 | if not line: |
| 20 | break |
| 21 | if makevardef.match(line) < 0: |
| 22 | continue |
| 23 | name, value = makevardef.group(1, 2) |
| 24 | # Strip trailing comment |
| 25 | i = string.find(value, '#') |
| 26 | if i >= 0: |
| 27 | value = value[:i] |
| 28 | value = string.strip(value) |
| 29 | variables[name] = value |
| 30 | finally: |
| 31 | fp.close() |
| 32 | return variables |
| 33 | |
| 34 | |
| 35 | # Parse a Python Setup(.in) file. |
| 36 | # Return two dictionaries, the first mapping modules to their |
| 37 | # definitions, the second mapping variable names to their values. |
| 38 | # May raise IOError. |
| 39 | |
| 40 | setupvardef = regex.compile('^\([a-zA-Z0-9_]+\)=\(.*\)') |
| 41 | |
| 42 | def getsetupinfo(filename): |
| 43 | modules = {} |
| 44 | variables = {} |
| 45 | fp = open(filename) |
| 46 | try: |
| 47 | while 1: |
| 48 | line = fp.readline() |
| 49 | if not line: |
| 50 | break |
| 51 | # Strip comments |
| 52 | i = string.find(line, '#') |
| 53 | if i >= 0: |
| 54 | line = line[:i] |
| 55 | if setupvardef.match(line) >= 0: |
| 56 | name, value = setupvardef.group(1, 2) |
| 57 | variables[name] = string.strip(value) |
| 58 | else: |
| 59 | words = string.split(line) |
| 60 | if words: |
| 61 | modules[words[0]] = words[1:] |
| 62 | finally: |
| 63 | fp.close() |
| 64 | return modules, variables |
| 65 | |
| 66 | |
| 67 | # Test the above functions. |
| 68 | |
| 69 | def test(): |
| 70 | import sys |
| 71 | import os |
| 72 | if not sys.argv[1:]: |
| 73 | print 'usage: python parsesetup.py Makefile*|Setup* ...' |
| 74 | sys.exit(2) |
| 75 | for arg in sys.argv[1:]: |
| 76 | base = os.path.basename(arg) |
| 77 | if base[:8] == 'Makefile': |
| 78 | print 'Make style parsing:', arg |
| 79 | v = getmakevars(arg) |
| 80 | prdict(v) |
| 81 | elif base[:5] == 'Setup': |
| 82 | print 'Setup style parsing:', arg |
| 83 | m, v = getsetupinfo(arg) |
| 84 | prdict(m) |
| 85 | prdict(v) |
| 86 | else: |
| 87 | print arg, 'is neither a Makefile nor a Setup file' |
| 88 | print '(name must begin with "Makefile" or "Setup")' |
| 89 | |
| 90 | def prdict(d): |
| 91 | keys = d.keys() |
| 92 | keys.sort() |
| 93 | for key in keys: |
| 94 | value = d[key] |
| 95 | print "%-15s" % key, str(value) |
| 96 | |
| 97 | if __name__ == '__main__': |
| 98 | test() |