]> sigrok.org Git - sigrok-util.git/blame - source/include-config-header
sigrok-cross-mingw: Lower Python version to 3.4 (Win XP support).
[sigrok-util.git] / source / include-config-header
CommitLineData
f6229138
DE
1#!/usr/bin/env python3
2##
3## This file is part of the sigrok-util project.
4##
5## Copyright (C) 2015 Daniel Elstner <daniel.kitta@gmail.com>
6##
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.
11##
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.
16##
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/>.
19##
20
21import os
22import sys
23import subprocess
24import tempfile
25import re
26
27"""
28Make sure that every source file has <config.h> as first include, and that
29no header file includes <config.h>. Pass the source directories to process
30as command-line arguments.
31"""
32
33file_patterns = ["*.[ch]", "*.cc", "*.hh", "*.[ch]pp", "*.[ch]xx", "*.h.in"]
34source_regex = re.compile(r'\.c[^.]*$')
35
36config_include = "#include <config.h>\n"
37config_h_regex = re.compile(r'\s*#\s*include\s+[<"]config\.h[>"]')
38
39def create_tmpfile(tmpdir):
40 return tempfile.NamedTemporaryFile('w', dir=tmpdir, delete=False)
41
42def process_file(filename, tmpdir, is_source):
43 changed = False
44 with open(filename, 'r') as srcfile, create_tmpfile(tmpdir) as tmpfile:
45 tmpfilename = tmpfile.name
46 for line in srcfile:
47 if is_source and not changed and line.startswith("#"):
48 if line == config_include:
49 break
50 tmpfile.write(config_include)
51 changed = True
52 if config_h_regex.match(line) is None:
53 tmpfile.write(line)
54 else:
55 changed = True
56 if changed:
57 os.replace(tmpfilename, filename)
58 else:
59 os.remove(tmpfilename)
60 return changed
61
62def 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)
70
71if len(sys.argv) < 2:
72 sys.exit("Usage: include-config-header DIRECTORY...")
73
74for arg in sys.argv[1:]:
75 process_directory(arg)