diff options
author | Laurent Pinchart <laurent.pinchart@ideasonboard.com> | 2020-03-22 13:31:32 +0200 |
---|---|---|
committer | Laurent Pinchart <laurent.pinchart@ideasonboard.com> | 2020-03-23 13:51:00 +0200 |
commit | 5849dd0b1761f8729b81bed8235e76e5b4e39b39 (patch) | |
tree | a657ab426afdbcde5de358f6c233a48289f07888 /utils | |
parent | 3f97be923c11df4324f20a94591dc5562a05c7ba (diff) |
utils: checkstyle: Add formatter to sort #include statements
Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
Reviewed-by: Kieran Bingham <kieran.bingham@ideasonboard.com>
Diffstat (limited to 'utils')
-rwxr-xr-x | utils/checkstyle.py | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/utils/checkstyle.py b/utils/checkstyle.py index 0827a1e6..b594a19a 100755 --- a/utils/checkstyle.py +++ b/utils/checkstyle.py @@ -481,6 +481,47 @@ class DoxygenFormatter(Formatter): return '\n'.join(lines) +class IncludeOrderFormatter(Formatter): + patterns = ('*.cpp', '*.h') + + include_regex = re.compile('^#include ["<]([^">]*)[">]') + + @classmethod + def format(cls, filename, data): + lines = [] + includes = [] + + # Parse blocks of #include statements, and output them as a sorted list + # when we reach a non #include statement. + for line in data.split('\n'): + match = IncludeOrderFormatter.include_regex.match(line) + if match: + # If the current line is an #include statement, add it to the + # includes group and continue to the next line. + includes.append((line, match.group(1))) + continue + + # The current line is not an #include statement, output the sorted + # stashed includes first, and then the current line. + if len(includes): + includes.sort(key=lambda i: i[1]) + for include in includes: + lines.append(include[0]) + includes = [] + + lines.append(line) + + # In the unlikely case the file ends with an #include statement, make + # sure we output the stashed includes. + if len(includes): + includes.sort(key=lambda i: i[1]) + for include in includes: + lines.append(include[0]) + includes = [] + + return '\n'.join(lines) + + class StripTrailingSpaceFormatter(Formatter): patterns = ('*.c', '*.cpp', '*.h', '*.py', 'meson.build') |