/ test / lint / lint-include-guards.py
lint-include-guards.py
 1  #!/usr/bin/env python3
 2  #
 3  # Copyright (c) 2018-present The Bitcoin Core developers
 4  # Distributed under the MIT software license, see the accompanying
 5  # file COPYING or http://www.opensource.org/licenses/mit-license.php.
 6  
 7  """
 8  Check include guards.
 9  """
10  
11  import re
12  import sys
13  from subprocess import check_output
14  
15  from lint_ignore_dirs import SHARED_EXCLUDED_SUBTREES
16  
17  
18  HEADER_ID_PREFIX = 'BITCOIN_'
19  HEADER_ID_SUFFIX = '_H'
20  
21  EXCLUDE_FILES_WITH_PREFIX = ['contrib/devtools/bitcoin-tidy',
22                               'src/tinyformat.h',
23                               'src/bench/nanobench.h',
24                               'src/test/fuzz/FuzzedDataProvider.h'] + SHARED_EXCLUDED_SUBTREES
25  
26  
27  def _get_header_file_lst() -> list[str]:
28      """ Helper function to get a list of header filepaths to be
29          checked for include guards.
30      """
31      git_cmd_lst = ['git', 'ls-files', '--', '*.h']
32      header_file_lst = check_output(
33          git_cmd_lst, text=True).splitlines()
34  
35      header_file_lst = [hf for hf in header_file_lst
36                         if not any(ef in hf for ef
37                                    in EXCLUDE_FILES_WITH_PREFIX)]
38  
39      return header_file_lst
40  
41  
42  def _get_header_id(header_file: str) -> str:
43      """ Helper function to get the header id from a header file
44          string.
45  
46          eg: 'src/wallet/walletdb.h' -> 'BITCOIN_WALLET_WALLETDB_H'
47  
48      Args:
49          header_file: Filepath to header file.
50  
51      Returns:
52          The header id.
53      """
54      header_id_base = header_file.split('/')[1:]
55      header_id_base = '_'.join(header_id_base)
56      header_id_base = header_id_base.replace('.h', '').replace('-', '_')
57      header_id_base = header_id_base.upper()
58  
59      header_id = f'{HEADER_ID_PREFIX}{header_id_base}{HEADER_ID_SUFFIX}'
60  
61      return header_id
62  
63  
64  def main():
65      exit_code = 0
66  
67      header_file_lst = _get_header_file_lst()
68      for header_file in header_file_lst:
69          header_id = _get_header_id(header_file)
70  
71          regex_pattern = f'^#(ifndef|define|endif //) {header_id}'
72  
73          with open(header_file, 'r') as f:
74              header_file_contents = f.readlines()
75  
76          count = 0
77          for header_file_contents_string in header_file_contents:
78              include_guard_lst = re.findall(
79                  regex_pattern, header_file_contents_string)
80  
81              count += len(include_guard_lst)
82  
83          if count != 3:
84              print(f'{header_file} seems to be missing the expected '
85                    'include guard to prevent the double inclusion problem:')
86              print(f'  #ifndef {header_id}')
87              print(f'  #define {header_id}')
88              print('  ...')
89              print(f'  #endif // {header_id}\n')
90              exit_code = 1
91  
92      sys.exit(exit_code)
93  
94  
95  if __name__ == '__main__':
96      main()