3 ## This file is part of the sigrok-util project.
5 ## Copyright (C) 2015 Daniel Elstner <daniel.kitta@gmail.com>
7 ## This program is free software: you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation, either version 3 of the License, or
10 ## (at your option) any later version.
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ## GNU General Public License for more details.
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program. If not, see <http://www.gnu.org/licenses/>.
28 Make sure that every source file has <config.h> as first include, and that
29 no header file includes <config.h>. Pass the source directories to process
30 as command-line arguments.
33 file_patterns = ["*.[ch]", "*.cc", "*.hh", "*.[ch]pp", "*.[ch]xx", "*.h.in"]
34 source_regex = re.compile(r'\.c[^.]*$')
36 config_include = "#include <config.h>\n"
37 config_h_regex = re.compile(r'\s*#\s*include\s+[<"]config\.h[>"]')
39 def create_tmpfile(tmpdir):
40 return tempfile.NamedTemporaryFile('w', dir=tmpdir, delete=False)
42 def process_file(filename, tmpdir, is_source):
44 with open(filename, 'r') as srcfile, create_tmpfile(tmpdir) as tmpfile:
45 tmpfilename = tmpfile.name
47 if is_source and not changed and line.startswith("#"):
48 if line == config_include:
50 tmpfile.write(config_include)
52 if config_h_regex.match(line) is None:
57 os.replace(tmpfilename, filename)
59 os.remove(tmpfilename)
62 def process_directory(srcdir):
63 filelist = subprocess.check_output(["git",
64 "-C", srcdir, "ls-files"] + file_patterns).decode()
65 with tempfile.TemporaryDirectory(dir=srcdir) as tmpdir:
66 for filename in filelist.splitlines():
67 if process_file(os.path.join(srcdir, filename), tmpdir,
68 source_regex.search(filename) is not None):
69 print("Rewrote file", filename)
72 sys.exit("Usage: include-config-header DIRECTORY...")
74 for arg in sys.argv[1:]:
75 process_directory(arg)