summarylogtreecommitdiffstats
path: root/makedeps.py
blob: 634c8464e05455fef1520813fa38b422dd9d8370 (plain)
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
#!/usr/bin/env python3
# A quick n dirty script to compute Fortran module dependencies for a Makefile.
#
#     ./makedeps.py fres/source >deps.mk
#
import os, re, sys

def obj_path(f_path):
    return os.path.splitext(f_path)[0] + ".o"

root_dir = sys.argv[1]

module_paths = []
use_path_by_module = {}
for dirpath, _, filenames in os.walk(root_dir):
    for filename in filenames:
        if not filename.endswith(".f") or filename.startswith("._"):
            continue
        path = os.path.relpath(os.path.join(dirpath, filename), root_dir)
        with open(os.path.join(root_dir, path)) as f:
            for line in f:
                line = line.lower().strip()
                if match := re.search(r"^use\s+(\w+)", line):
                    [module] = match.groups()
                    use_path_by_module.setdefault(module, set()).add(path)
                elif match := re.search(r"^module\s+(\w+)", line):
                    [module] = match.groups()
                    module_paths.append((module, path))

targets_by_prerequisite = {}
for module, module_path in module_paths:
    for use_path in use_path_by_module[module]:
        if use_path == module_path:
            continue
        targets_by_prerequisite.setdefault(
            obj_path(module_path),
            set(),
        ).add(obj_path(use_path))

print('# Autogenerated by ./makedeps.py')
for prerequisite, targets in sorted(targets_by_prerequisite.items()):
    print(f"{' '.join(sorted(targets))}: {prerequisite}")