]> git.proxmox.com Git - mirror_frr.git/blob - python/firstheader.py
Merge pull request #12205 from proelbtn/fix-ipv4-vpn-nexthop-over-ipv6-peer
[mirror_frr.git] / python / firstheader.py
1 # check that the first header included in C files is either
2 # zebra.h or config.h
3 #
4 # Copyright (C) 2020 David Lamparter for NetDEF, Inc.
5 #
6 # This program is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by the Free
8 # Software Foundation; either version 2 of the License, or (at your option)
9 # any later version.
10 #
11 # This program is distributed in the hope that it will be useful, but WITHOUT
12 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 # more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with this program; see the file COPYING; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19
20 import sys
21 import os
22 import re
23 import subprocess
24 import argparse
25
26 argp = argparse.ArgumentParser(description="include fixer")
27 argp.add_argument("--autofix", action="store_const", const=True)
28 argp.add_argument("--warn-empty", action="store_const", const=True)
29 argp.add_argument("--pipe", action="store_const", const=True)
30
31 include_re = re.compile('^#\s*include\s+["<]([^ ">]+)[">]', re.M)
32
33 ignore = [
34 lambda fn: fn.startswith("tools/"),
35 lambda fn: fn
36 in [
37 "lib/elf_py.c",
38 ],
39 ]
40
41
42 def run(args):
43 out = []
44
45 files = subprocess.check_output(["git", "ls-files"]).decode("ASCII")
46 for fn in files.splitlines():
47 if not fn.endswith(".c"):
48 continue
49 if max([i(fn) for i in ignore]):
50 continue
51
52 with open(fn, "r") as fd:
53 data = fd.read()
54
55 m = include_re.search(data)
56 if m is None:
57 if args.warn_empty:
58 sys.stderr.write("no #include in %s?\n" % (fn))
59 continue
60 if m.group(1) in ["config.h", "zebra.h", "lib/zebra.h"]:
61 continue
62
63 if args.autofix:
64 sys.stderr.write("%s: %s - fixing\n" % (fn, m.group(0)))
65 if fn.startswith("pceplib/"):
66 insert = '#ifdef HAVE_CONFIG_H\n#include "config.h"\n#endif\n\n'
67 else:
68 insert = "#include <zebra.h>\n\n"
69
70 pos = m.span()[0]
71
72 data = data[:pos] + insert + data[pos:]
73 with open(fn + ".new", "w") as fd:
74 fd.write(data)
75 os.rename(fn + ".new", fn)
76 else:
77 sys.stderr.write("%s: %s\n" % (fn, m.group(0)))
78 out.append(fn)
79
80 if len(out):
81 if args.pipe:
82 # for "vim `firstheader.py`"
83 print("\n".join(out))
84 return 1
85 return 0
86
87
88 if __name__ == "__main__":
89 args = argp.parse_args()
90 sys.exit(run(args))