-
Notifications
You must be signed in to change notification settings - Fork 0
/
makemake90.py
executable file
·289 lines (216 loc) · 7.32 KB
/
makemake90.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#!/usr/bin/env python3
'''Usage: makemake90 [src=...] [obj=...] [mod=...] [bin=...]
Optional arguments specify places for source (.f90), object (.o), module
(.mod), and executable files. They all default to the currect directory.
There is no need to specify them again when updating existing makefiles.
'''
__version__ = '0.3'
import os
import re
import sys
def parameters(*filenames, **args):
"""Fetch parameters from existing makefile and command arguments.
Parameters
----------
*filenames : str
Possible names of makefile.
**args : str
Default command arguments.
Returns
-------
str
Name of makefile.
str
Static makefile header.
str
Static makefile footer.
dict of str
Command arguments.
"""
if not filenames:
filenames = ['GNUmakefile', 'makefile', 'Makefile']
preamble = ''
epilogue = ''
for filename in filenames:
if os.path.exists(filename):
with open(filename) as makefile:
for line in makefile:
if 'generated by makemake' in line:
for arg in re.findall(r'\w+=[^\s:=]+', line):
sys.argv.insert(1, arg)
break
preamble += line
else:
raise SystemExit('Unknown Makefile already exists')
for line in makefile:
if 'not generated by makemake' in line:
break
for line in makefile:
epilogue += line
break
for arg in sys.argv[1:]:
if '=' in arg:
key, value = arg.split('=')
args[key] = value
else:
raise SystemExit(__doc__.rstrip())
preamble = preamble.strip()
epilogue = epilogue.strip()
return filename, preamble, epilogue, args
def dependencies(src='.', obj='.', bin='.', **ignore):
"""Determine dependencies of Fortran project.
Parameters
----------
src : str, default '.'
Directory with source files.
obj : str, default '.'
Directory for object files.
bin : str, default '.'
Directory for executable binary files.
Returns
-------
dict of set
Programs with direct and indirect dependencies.
dict of set
Objects with direct dependencies.
set
All objects used.
"""
references = {}
companions = {}
components = {}
folders = [src]
for folder in folders:
for file in os.listdir(folder):
if file.startswith('.'):
continue
path = folder + '/' + file
if os.path.isdir(path):
folders.append(path)
elif path.endswith('.f90'):
doto = re.sub('^%s/' % src, '%s/' % obj, path)
doto = re.sub(r'\.f90$', '.o', doto)
references[doto] = set()
with open(path) as code:
for line in code:
match = re.match(r'\s*(use|program|module)'
r'\s+(\w+)\s*(?:$|,)', line, re.I)
if match:
statement, name = match.groups()
if statement == 'use':
references[doto].add(name)
elif statement == 'module':
companions[name] = doto
elif statement == 'program':
components['%s/%s' % (bin,
name.replace('_dot_', '.'))] = {doto}
for target, modules in references.items():
references[target] = set(companions[name]
for name in modules if name in companions)
related = set()
for doto in components.values():
todo = list(doto)
for target in todo:
new = references[target] - doto
doto |= new
todo += new
related |= doto
for target in list(references.keys()):
if target not in related:
del references[target]
return components, references, related
def makefile(filename='Makefile', components={}, references={}, related=None,
preamble='', epilogue='', src='.', obj='.', mod='.', bin='.', **ignore):
"""Create makefile.
Parameters
----------
filename : str, default 'Makefile'
Name of makefile.
components : dict of set, default {}
Programs with direct and indirect dependencies.
references : dict of set, default {}
Objects with direct dependencies.
related : set, default None
All objects used. Inferred from `components` if absent.
preamble : str, default ''
Static makefile header.
epilogue : str, default ''
Static makefile footer.
src : str, default '.'
Directory with source files.
obj : str, default '.'
Directory for object files.
mod : str, default '.'
Directory for module files.
bin : str, default '.'
Directory for executable binary files.
"""
if related is None:
related = set().union(*components.values())
args = dict(src=src, obj=obj, mod=mod, bin=bin)
def join(these):
return ' '.join(sorted(these))
programs = join(components)
adjuncts = join(related)
def listing(dependencies):
return '\n'.join(target + ': ' + join(doto)
for target, doto in sorted(dependencies.items()) if doto)
components = listing(components)
references = listing(references)
arguments = ''.join(' %s=%s' % (key, value)
for key, value in sorted(args.items()) if value != '.')
modules_flag = '' if mod == '.' else '''
modules_gfortran = -J{0}
modules_ifort = -module {0}
modules_ifx = ${{modules_ifort}}
override FFLAGS += ${{modules_$(FC)}}
'''.format(mod)
content = '''
# generated by makemake90{arguments}:
{modules_flag}
needless += {adjuncts} {mod}/*.mod
programs = {programs}
.PHONY: all clean cleaner
all: $(programs)
clean:
\trm -f $(needless)
cleaner: clean
\trm -f $(programs)
$(programs):
\t$(FC) $(FFLAGS) -o $@ $^ $(LDLIBS)
{obj}/%.o: {src}/%.f90
\t$(FC) $(FFLAGS) -c $< -o $@
{components}
{references}
'''.format(**vars())
content = re.sub(r'(^|\s)\./', r'\1', content)
with open(filename, 'w') as makefile:
if preamble:
makefile.write(preamble)
else:
makefile.write('''
FC = gfortran
flags_gfortran = -std=f2008 -pedantic -Wall -Wno-maybe-uninitialized
flags_ifort = -O0 -stand f08 -warn all
flags_ifx = ${flags_ifort}
FFLAGS = ${flags_$(FC)}
# dependent_program: LDLIBS = -llapack -lblas
'''.strip())
makefile.write(content)
if epilogue:
makefile.write('''
# not generated by makemake90:
{epilogue}
'''.format(**vars()))
for mkdir in set(args.values()) | set(map(os.path.dirname, related)):
if not os.path.isdir(mkdir):
os.makedirs(os.path.realpath(mkdir))
print('Created folder "%s" required to make project'
% os.path.normpath(mkdir))
def main():
filename, preamble, epilogue, args = parameters()
components, references, related = dependencies(**args)
makefile(filename, components, references, related, preamble, epilogue,
**args)
if __name__ == '__main__':
main()