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