blob: b80bcf6a0be9d9959e4577350ce0297bef2a35b3 [file] [log] [blame]
Lei Zhangac975fb2021-04-21 03:51:061#!/usr/bin/env python3
2# Copyright 2021 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5"""Applies cpplint build/header_guard recommendations.
6
7Reads cpplint build/header_guard recommendations from stdin and applies them.
8
9Run cpplint for a single header:
10cpplint.py --filter=-,+build/header_guard foo.h 2>&1 | grep build/header_guard
11
12Run cpplint for all headers in dir foo in parallel:
13find foo -name '*.h' | \
14 xargs parallel cpplint.py --filter=-,+build/header_guard -- 2>&1 | \
15 grep build/header_guard
16"""
17
18import sys
19
20IFNDEF_MSG = ' #ifndef header guard has wrong style, please use'
21ENDIF_MSG_START = ' #endif line should be "'
22ENDIF_MSG_END = '" [build/header_guard] [5]'
23NO_GUARD_MSG = ' No #ifndef header guard found, suggested CPP variable is'
24
25
26def process_cpplint_recommendations(cpplint_data):
27 for entry in cpplint_data:
28 entry = entry.split(':')
29 header = entry[0]
30 line = entry[1]
31 index = int(line) - 1
32 msg = entry[2].rstrip()
33 if msg == IFNDEF_MSG:
34 assert len(entry) == 4
35
36 with open(header, 'rb') as f:
37 content = f.readlines()
38
39 if not content[index + 1].startswith(b'#define '):
40 raise Exception('Missing #define: %s:%d' % (header, index + 2))
41
42 guard = entry[3].split(' ')[1]
43 content[index] = ('#ifndef %s\n' % guard).encode('utf-8')
44 # Since cpplint does not print messages for the #define line, just
45 # blindly overwrite the #define that was here.
46 content[index + 1] = ('#define %s\n' % guard).encode('utf-8')
47 elif msg.startswith(ENDIF_MSG_START):
48 assert len(entry) == 3
49 assert msg.endswith(ENDIF_MSG_END)
50
51 with open(header, 'rb') as f:
52 content = f.readlines()
53 endif = msg[len(ENDIF_MSG_START):-len(ENDIF_MSG_END)]
54 content[index] = ('%s\n' % endif).encode('utf-8')
55 elif msg == NO_GUARD_MSG:
56 assert index == -1
57 continue
58 else:
59 raise Exception('Unknown cpplint message: %s for %s:%s' %
60 (msg, header, line))
61
62 with open(header, 'wb') as f:
63 f.writelines(content)
64
65
66if __name__ == '__main__':
67 process_cpplint_recommendations(sys.stdin)