cmake-pre-commit-hooks 1.10.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cmake_pc_hooks/__init__.py +15 -0
- cmake_pc_hooks/_argparse.py +332 -0
- cmake_pc_hooks/_call_process.py +74 -0
- cmake_pc_hooks/_cmake.py +659 -0
- cmake_pc_hooks/_utils.py +242 -0
- cmake_pc_hooks/clang_format.py +59 -0
- cmake_pc_hooks/clang_tidy.py +82 -0
- cmake_pc_hooks/cppcheck.py +87 -0
- cmake_pc_hooks/cpplint.py +20 -0
- cmake_pc_hooks/include_what_you_use.py +141 -0
- cmake_pc_hooks/lizard.py +72 -0
- cmake_pre_commit_hooks-1.10.0.dist-info/METADATA +396 -0
- cmake_pre_commit_hooks-1.10.0.dist-info/RECORD +17 -0
- cmake_pre_commit_hooks-1.10.0.dist-info/WHEEL +5 -0
- cmake_pre_commit_hooks-1.10.0.dist-info/entry_points.txt +7 -0
- cmake_pre_commit_hooks-1.10.0.dist-info/licenses/LICENSE +201 -0
- cmake_pre_commit_hooks-1.10.0.dist-info/top_level.txt +1 -0
cmake_pc_hooks/_utils.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
# Copyright 2021 Damien Nguyen
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Base classes and functions for C/C++ linters and formatters."""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import logging
|
|
21
|
+
import os
|
|
22
|
+
import sys
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
import hooks.utils
|
|
26
|
+
|
|
27
|
+
from . import _argparse, _call_process
|
|
28
|
+
from ._cmake import CMakeCommand
|
|
29
|
+
|
|
30
|
+
_LOGLEVEL = os.environ.get('LOGLEVEL', 'INFO').upper()
|
|
31
|
+
logging.basicConfig(level=_LOGLEVEL, format='%(levelname)-5s:cmake-pc-hooks:%(message)s')
|
|
32
|
+
|
|
33
|
+
log = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class CMakePresetError(Exception):
|
|
37
|
+
"""Exception raised if a command line incompatibility with --preset is detected."""
|
|
38
|
+
|
|
39
|
+
def __init__(self) -> None:
|
|
40
|
+
super().__init__('You *must* specify -B|--build-dir if you pass --preset as a CMake argument!')
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _read_compile_commands_json(compile_db: Path) -> list[str]:
|
|
44
|
+
"""Read a JSON compile database and return the list of files contained within."""
|
|
45
|
+
if compile_db.exists():
|
|
46
|
+
with compile_db.open(encoding='utf-8') as fd:
|
|
47
|
+
data = json.load(fd)
|
|
48
|
+
return [entry['file'] for entry in data]
|
|
49
|
+
return []
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Command(hooks.utils.Command):
|
|
53
|
+
"""Super class that all commands inherit."""
|
|
54
|
+
|
|
55
|
+
setup_cmake = True
|
|
56
|
+
|
|
57
|
+
def __init__(self, command, look_behind, args):
|
|
58
|
+
"""Initialize a Command object."""
|
|
59
|
+
super().__init__(command, look_behind, args)
|
|
60
|
+
self.ddash_args = []
|
|
61
|
+
self.cmake = CMakeCommand()
|
|
62
|
+
self.clean_build = False
|
|
63
|
+
self.all_at_once = False
|
|
64
|
+
self.read_json_db = False
|
|
65
|
+
self.build_dir_list = ['.', CMakeCommand.DEFAULT_BUILD_DIR]
|
|
66
|
+
|
|
67
|
+
self.history = []
|
|
68
|
+
|
|
69
|
+
def parse_args(self, args):
|
|
70
|
+
"""
|
|
71
|
+
Parse some arguments into some usable variables.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
args (:obj:`list` of :obj:`str`): list of arguments
|
|
75
|
+
"""
|
|
76
|
+
parser = _argparse.ArgumentParser(
|
|
77
|
+
default_config_name='cmake_pc_hooks.toml',
|
|
78
|
+
pyproject_section_name='tool.cmake_pc_hooks',
|
|
79
|
+
args_groups=[{'title': 'Hook options'}],
|
|
80
|
+
)
|
|
81
|
+
self.cmake.add_cmake_arguments_to_parser(parser)
|
|
82
|
+
hook_options = parser.groups[0]
|
|
83
|
+
hook_options.add_argument(
|
|
84
|
+
'--all-at-once',
|
|
85
|
+
action='store_true',
|
|
86
|
+
help='Pass all filenames at once to the linter/formatter instead of calling the command once for each file',
|
|
87
|
+
)
|
|
88
|
+
hook_options.add_argument(
|
|
89
|
+
'--read-json-db',
|
|
90
|
+
action='store_true',
|
|
91
|
+
help=(
|
|
92
|
+
'Run hooks on files found in compile_commands.json (if found and in addition to files specified on CLI)'
|
|
93
|
+
),
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
# Other options
|
|
97
|
+
hook_options.add_argument('--version', type=str, help='Perform a version check')
|
|
98
|
+
hook_options.add_argument('positionals', metavar='filenames', nargs='*', help='Filenames to check')
|
|
99
|
+
|
|
100
|
+
known_args, self.args = parser.parse_known_args(args[1:])
|
|
101
|
+
|
|
102
|
+
self.all_at_once = known_args.all_at_once
|
|
103
|
+
self.read_json_db = known_args.read_json_db
|
|
104
|
+
self.clean_build = known_args.clean
|
|
105
|
+
self.build_dir_list.extend(known_args.build_dir or [])
|
|
106
|
+
|
|
107
|
+
if not known_args.build_dir and known_args.preset:
|
|
108
|
+
raise CMakePresetError
|
|
109
|
+
|
|
110
|
+
if self.setup_cmake:
|
|
111
|
+
self.cmake.setup_cmake_args(known_args)
|
|
112
|
+
|
|
113
|
+
if not self.cmake.source_dir.exists() and not self.cmake.source_dir.is_dir():
|
|
114
|
+
sys.stderr.write(f'{self.cmake.source_dir} is not a valid source directory\n')
|
|
115
|
+
sys.exit(1)
|
|
116
|
+
|
|
117
|
+
if known_args.version:
|
|
118
|
+
actual_version = self.get_version_str()
|
|
119
|
+
self.assert_version(actual_version, known_args.version)
|
|
120
|
+
|
|
121
|
+
# NB: if '--' may be present on the command line, the command class for that particular command needs to call
|
|
122
|
+
# handle_ddash_args() in order to properly handle the filenames in those cases.
|
|
123
|
+
self.files = known_args.positionals
|
|
124
|
+
|
|
125
|
+
def run(self):
|
|
126
|
+
"""Run the command."""
|
|
127
|
+
self.cmake.configure(self.command, clean_build=self.clean_build)
|
|
128
|
+
self.files.extend(self.cmake.cmake_configured_files)
|
|
129
|
+
|
|
130
|
+
compile_db = self._resolve_compilation_database(self.cmake.build_dir, self.build_dir_list)
|
|
131
|
+
if self.read_json_db and compile_db:
|
|
132
|
+
self.files.extend(set(_read_compile_commands_json(compile_db)) - set(self.files))
|
|
133
|
+
|
|
134
|
+
if self.all_at_once:
|
|
135
|
+
self.run_command(self.files)
|
|
136
|
+
elif self.files:
|
|
137
|
+
for filename in self.files:
|
|
138
|
+
self.run_command([filename])
|
|
139
|
+
else:
|
|
140
|
+
log.error('No files to process!')
|
|
141
|
+
sys.exit(1)
|
|
142
|
+
|
|
143
|
+
has_errors = False
|
|
144
|
+
for res in self.history:
|
|
145
|
+
has_errors |= self._parse_output(res)
|
|
146
|
+
res.to_stdout_and_stderr()
|
|
147
|
+
|
|
148
|
+
if has_errors:
|
|
149
|
+
sys.exit(1)
|
|
150
|
+
|
|
151
|
+
def run_command(self, filenames):
|
|
152
|
+
"""Run the command and check for errors."""
|
|
153
|
+
self.history.append(_call_process.call_process([self.command, *filenames, *self.args, *self.ddash_args]))
|
|
154
|
+
self._clinters_compat()
|
|
155
|
+
|
|
156
|
+
def _clinters_compat(self):
|
|
157
|
+
"""Compatibility with CLinters."""
|
|
158
|
+
self.stdout = self.history[-1].stdout.encode()
|
|
159
|
+
self.stderr = self.history[-1].stderr.encode()
|
|
160
|
+
self.returncode = self.history[-1].returncode
|
|
161
|
+
|
|
162
|
+
def _parse_output(self, result): # ruff: ignore[unused-method-argument, no-self-use]
|
|
163
|
+
return NotImplemented
|
|
164
|
+
|
|
165
|
+
@staticmethod
|
|
166
|
+
def _resolve_compilation_database(cmake_build_dir: Path, build_dir_list: list[Path]) -> Path | None:
|
|
167
|
+
"""Locate a compilation database based on internal list of directories."""
|
|
168
|
+
if cmake_build_dir and cmake_build_dir / 'compile_commands.json':
|
|
169
|
+
return cmake_build_dir / 'compile_commands.json'
|
|
170
|
+
|
|
171
|
+
build_dir_list = [] if build_dir_list is None else [Path(path) for path in build_dir_list]
|
|
172
|
+
for build_dir in build_dir_list:
|
|
173
|
+
path = Path(build_dir, 'compile_commands.json')
|
|
174
|
+
if build_dir.exists() and path.exists():
|
|
175
|
+
log.debug('Located valid compilation database at: %s', path)
|
|
176
|
+
return path
|
|
177
|
+
log.debug('No valid compilation database located')
|
|
178
|
+
return None
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class ClangAnalyzerCmd(Command):
|
|
182
|
+
"""Commands that statically analyze code: clang-tidy, oclint."""
|
|
183
|
+
|
|
184
|
+
def handle_ddash_args(self):
|
|
185
|
+
"""
|
|
186
|
+
Handle arguments after a '--'.
|
|
187
|
+
|
|
188
|
+
Pre-commit sends a list of files as the last argument which may cause problems with -- and some programs such as
|
|
189
|
+
clang-tidy. This function converts the filename arguments in order to make everything work as expected.
|
|
190
|
+
|
|
191
|
+
Example:
|
|
192
|
+
clang-tidy --checks=* -- -std=c++17 file1.cpp file2.cpp
|
|
193
|
+
will be turned into:
|
|
194
|
+
clang-tidy file1.cpp file2.cpp --checks=* -- -std=c++17
|
|
195
|
+
|
|
196
|
+
In the case above, the content of self.files would be: ['-std=c++17', 'file1.cpp', 'file2.cpp'] which needs
|
|
197
|
+
to be converted to: ['file1.cpp', 'file2.cpp'] while ['--', '-std=c++17'] should be added to `self.args`.
|
|
198
|
+
"""
|
|
199
|
+
files = []
|
|
200
|
+
other_args = []
|
|
201
|
+
for _, fname in enumerate(reversed(self.files)):
|
|
202
|
+
if Path(fname).is_file():
|
|
203
|
+
files.append(fname)
|
|
204
|
+
else:
|
|
205
|
+
other_args.append(fname)
|
|
206
|
+
|
|
207
|
+
if other_args:
|
|
208
|
+
self.ddash_args.extend(['--', *other_args])
|
|
209
|
+
self.files = list(reversed(files))
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class FormatterCmd(Command, hooks.utils.FormatterCmd):
|
|
213
|
+
"""Commands that format code: clang-format, uncrustify."""
|
|
214
|
+
|
|
215
|
+
setup_cmake = False
|
|
216
|
+
|
|
217
|
+
def __init__(self, command: str, look_behind: str, args: list[str]):
|
|
218
|
+
super().__init__(command, look_behind, args)
|
|
219
|
+
self.dry_run = '-n' in self.args or '--dry-run' in self.args
|
|
220
|
+
|
|
221
|
+
def get_formatted_lines(self, filename: bytes) -> list: # pragma: nocover
|
|
222
|
+
"""Get the expected output for a command applied to a file."""
|
|
223
|
+
filename_opts = self.get_filename_opts(filename)
|
|
224
|
+
args = [self.command, *self.args, *filename_opts]
|
|
225
|
+
# NB: only change w.r.t original method to handle both bytes and string argument types
|
|
226
|
+
child = _call_process.call_process([arg.decode() if isinstance(arg, bytes) else arg for arg in args])
|
|
227
|
+
if len(child.stderr) > 0 or child.returncode != 0:
|
|
228
|
+
problem = f'Unexpected Stderr/return code received when analyzing {filename}.\nArgs: {args}'
|
|
229
|
+
self.raise_error(problem, child.stdout + child.stderr)
|
|
230
|
+
|
|
231
|
+
if self.dry_run:
|
|
232
|
+
# clang-format dry-run mode is '-n'
|
|
233
|
+
# If dry-run mode then we only look at the return code -> read the lines
|
|
234
|
+
self.returncode = 0
|
|
235
|
+
return self.get_filelines(filename)
|
|
236
|
+
if not child.stdout:
|
|
237
|
+
return []
|
|
238
|
+
return child.stdout.encode().split(b'\x0a')
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class StaticAnalyzerCmd(Command, hooks.utils.StaticAnalyzerCmd):
|
|
242
|
+
"""Commands that analyze code and are not formatters."""
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Copyright 2021 Damien Nguyen
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Wrapper script for clang-format."""
|
|
16
|
+
|
|
17
|
+
import sys
|
|
18
|
+
|
|
19
|
+
from ._utils import FormatterCmd
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ClangFormatCmd(FormatterCmd):
|
|
23
|
+
"""Class for the ClangFormat command."""
|
|
24
|
+
|
|
25
|
+
command = 'clang-format'
|
|
26
|
+
lookbehind = 'clang-format version '
|
|
27
|
+
|
|
28
|
+
def __init__(self, args):
|
|
29
|
+
"""Initialize a ClangFormatCmd object."""
|
|
30
|
+
super().__init__(self.command, self.lookbehind, args)
|
|
31
|
+
self.check_installed()
|
|
32
|
+
self.parse_args(args)
|
|
33
|
+
self.set_diff_flag()
|
|
34
|
+
self.edit_in_place = '-i' in self.args
|
|
35
|
+
|
|
36
|
+
def run(self):
|
|
37
|
+
"""Run clang-format. Error if diff is incorrect."""
|
|
38
|
+
for filename in self.files:
|
|
39
|
+
self.compare_to_formatted(filename)
|
|
40
|
+
if self.returncode != 0:
|
|
41
|
+
sys.stdout.buffer.write(self.stderr)
|
|
42
|
+
sys.exit(self.returncode)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def main(argv=None):
|
|
46
|
+
"""
|
|
47
|
+
Run command.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
argv (:obj:`list` of :obj:`str`): list of arguments
|
|
51
|
+
"""
|
|
52
|
+
if argv is None:
|
|
53
|
+
argv = sys.argv
|
|
54
|
+
cmd = ClangFormatCmd(argv)
|
|
55
|
+
cmd.run()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
if __name__ == '__main__': # pragma: nocover
|
|
59
|
+
main()
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# Copyright 2021 Damien Nguyen
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Wrapper script for clang-tidy."""
|
|
16
|
+
|
|
17
|
+
import logging
|
|
18
|
+
import sys
|
|
19
|
+
|
|
20
|
+
from ._utils import ClangAnalyzerCmd
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ClangTidyCmd(ClangAnalyzerCmd):
|
|
24
|
+
"""Class for the clang-tidy command."""
|
|
25
|
+
|
|
26
|
+
command = 'clang-tidy'
|
|
27
|
+
lookbehind = 'LLVM version '
|
|
28
|
+
|
|
29
|
+
def __init__(self, args):
|
|
30
|
+
"""Initialize a ClangTidyCmd object."""
|
|
31
|
+
super().__init__(self.command, self.lookbehind, args)
|
|
32
|
+
self.parse_args(args)
|
|
33
|
+
self.edit_in_place = '-fix' in self.args or '--fix-errors' in self.args
|
|
34
|
+
self.handle_ddash_args()
|
|
35
|
+
self.log = logging.getLogger(__name__)
|
|
36
|
+
|
|
37
|
+
compile_db = self._resolve_compilation_database(self.cmake.build_dir, self.build_dir_list)
|
|
38
|
+
if not self.cmake.no_cmake_configure or compile_db:
|
|
39
|
+
self.add_if_missing([f'-p={compile_db}'])
|
|
40
|
+
|
|
41
|
+
def _parse_output(self, result):
|
|
42
|
+
"""
|
|
43
|
+
Parse output and check whether some errors occurred.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
result (namedtuple): Result from calling a command
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
False if no errors were detected, True in all other cases.
|
|
50
|
+
"""
|
|
51
|
+
# Reset stderr if it's complaining about problems in system files
|
|
52
|
+
if not result.stdout or 'non-user code' in result.stderr:
|
|
53
|
+
result.stderr = ''
|
|
54
|
+
|
|
55
|
+
self.log.debug('returncode %d', result.returncode)
|
|
56
|
+
self.log.debug('parsing output from %s', result.stderr)
|
|
57
|
+
return result.returncode != 0 or any(
|
|
58
|
+
msg in result.stderr
|
|
59
|
+
for msg in (
|
|
60
|
+
'error generated.',
|
|
61
|
+
'errors generated.',
|
|
62
|
+
'warning treated as error',
|
|
63
|
+
'warnings treated as errors',
|
|
64
|
+
)
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def main(argv=None):
|
|
69
|
+
"""
|
|
70
|
+
Run command.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
argv (:obj:`list` of :obj:`str`): list of arguments
|
|
74
|
+
"""
|
|
75
|
+
if argv is None:
|
|
76
|
+
argv = sys.argv
|
|
77
|
+
cmd = ClangTidyCmd(argv)
|
|
78
|
+
cmd.run()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
if __name__ == '__main__': # pragma: nocover
|
|
82
|
+
main()
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# Copyright 2021 Damien Nguyen
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Wrapper script for cppcheck."""
|
|
16
|
+
|
|
17
|
+
import logging
|
|
18
|
+
import sys
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from . import _call_process
|
|
22
|
+
from ._utils import Command
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class CppcheckCmd(Command):
|
|
26
|
+
"""Class for the cppcheck command."""
|
|
27
|
+
|
|
28
|
+
command = 'cppcheck'
|
|
29
|
+
lookbehind = 'Cppcheck '
|
|
30
|
+
|
|
31
|
+
def __init__(self, args):
|
|
32
|
+
"""Initialize a CppcheckCmd object."""
|
|
33
|
+
super().__init__(self.command, self.lookbehind, args)
|
|
34
|
+
self.parse_args(args)
|
|
35
|
+
# quiet for stdout purposes
|
|
36
|
+
self.add_if_missing(['-q'])
|
|
37
|
+
# make cppcheck behave as expected for pre-commit
|
|
38
|
+
self.add_if_missing(['--error-exitcode=1'])
|
|
39
|
+
# Enable all of the checks
|
|
40
|
+
self.add_if_missing(['--enable=all'])
|
|
41
|
+
self.log = logging.getLogger(__name__)
|
|
42
|
+
|
|
43
|
+
compile_db = self._resolve_compilation_database(self.cmake.build_dir, self.build_dir_list)
|
|
44
|
+
if not self.cmake.no_cmake_configure or compile_db:
|
|
45
|
+
self.add_if_missing([f'--project={compile_db}'])
|
|
46
|
+
|
|
47
|
+
def run_command(self, filenames):
|
|
48
|
+
"""Run the command and check for errors."""
|
|
49
|
+
filter_args = [f'--file-filter=*{Path(filename).parent.name}/{Path(filename).name}' for filename in filenames]
|
|
50
|
+
self.history.append(_call_process.call_process([self.command, *filter_args, *self.args, *self.ddash_args]))
|
|
51
|
+
self._clinters_compat()
|
|
52
|
+
|
|
53
|
+
def _parse_output(self, result):
|
|
54
|
+
"""
|
|
55
|
+
Parse output and check whether some errors occurred.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
result (namedtuple): Result from calling a command
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
False if no errors were detected, True in all other cases.
|
|
62
|
+
"""
|
|
63
|
+
# Useless error see https://stackoverflow.com/questions/6986033
|
|
64
|
+
self.log.debug('parsing output from %s', result.stderr)
|
|
65
|
+
useless_error_part = 'Cppcheck cannot find all the include files'
|
|
66
|
+
result.stderr = ''.join(
|
|
67
|
+
[line for line in result.stderr.splitlines(keepends=True) if useless_error_part not in line]
|
|
68
|
+
)
|
|
69
|
+
self._clinters_compat()
|
|
70
|
+
return result.returncode != 0
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def main(argv=None):
|
|
74
|
+
"""
|
|
75
|
+
Run command.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
argv (:obj:`list` of :obj:`str`): list of arguments
|
|
79
|
+
"""
|
|
80
|
+
if argv is None:
|
|
81
|
+
argv = sys.argv
|
|
82
|
+
cmd = CppcheckCmd(argv)
|
|
83
|
+
cmd.run()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
if __name__ == '__main__': # pragma: nocover
|
|
87
|
+
main()
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Copyright 2021 Damien Nguyen
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Wrapper script for cpplint."""
|
|
16
|
+
|
|
17
|
+
from hooks.cpplint import main
|
|
18
|
+
|
|
19
|
+
if __name__ == '__main__': # pragma: nocover
|
|
20
|
+
main()
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# Copyright 2021 Damien Nguyen
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Wrapper script for include-what-you-use."""
|
|
16
|
+
|
|
17
|
+
import logging
|
|
18
|
+
import shutil
|
|
19
|
+
import sys
|
|
20
|
+
|
|
21
|
+
from ._utils import ClangAnalyzerCmd
|
|
22
|
+
|
|
23
|
+
log = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def get_iwyu_tool_command(iwyu_tool_names=None):
|
|
27
|
+
"""
|
|
28
|
+
Get the path to the iwyu-tool.py executable on the PATH or in the virtual environment.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
iwyu_tool_names (:obj:`list` of :obj:`str`): Names for the CMake command
|
|
32
|
+
Defaults to ['iwyu_tool.py', 'iwyu-tool']
|
|
33
|
+
"""
|
|
34
|
+
if not iwyu_tool_names:
|
|
35
|
+
iwyu_tool_names = ['iwyu_tool.py', 'iwyu-tool', 'iwyu_tool']
|
|
36
|
+
|
|
37
|
+
for iwyu_tool in iwyu_tool_names:
|
|
38
|
+
fname = shutil.which(iwyu_tool)
|
|
39
|
+
if fname:
|
|
40
|
+
log.debug('found iwyu-tool command at %s', fname)
|
|
41
|
+
return fname
|
|
42
|
+
|
|
43
|
+
# Nothing worked -> give up!
|
|
44
|
+
return None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def get_iwyu_command(iwyu_names=None):
|
|
48
|
+
"""
|
|
49
|
+
Get the path to the include-what-you-use executable on the PATH or in the virtual environment.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
iwyu_names (:obj:`list` of :obj:`str`): Names for the CMake command
|
|
53
|
+
Defaults to ['include-what-you-use']
|
|
54
|
+
"""
|
|
55
|
+
if not iwyu_names:
|
|
56
|
+
iwyu_names = ['include-what-you-use']
|
|
57
|
+
|
|
58
|
+
for iwyu in iwyu_names:
|
|
59
|
+
fname = shutil.which(iwyu)
|
|
60
|
+
if fname:
|
|
61
|
+
log.debug('found iwyu command at %s', fname)
|
|
62
|
+
return fname
|
|
63
|
+
|
|
64
|
+
# Nothing worked -> give up!
|
|
65
|
+
return None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class IWYUToolCmd(ClangAnalyzerCmd):
|
|
69
|
+
"""Class for the iwyu_tool.py command."""
|
|
70
|
+
|
|
71
|
+
command = None
|
|
72
|
+
command_for_version = None
|
|
73
|
+
lookbehind = 'include-what-you-use '
|
|
74
|
+
|
|
75
|
+
def __init__(self, args):
|
|
76
|
+
"""Initialize an IWYUToolCmd object."""
|
|
77
|
+
IWYUToolCmd.command = get_iwyu_tool_command()
|
|
78
|
+
IWYUToolCmd.command_for_version = get_iwyu_command()
|
|
79
|
+
|
|
80
|
+
if IWYUToolCmd.command is None:
|
|
81
|
+
msg = 'Unable to locate path to iwyu-tool'
|
|
82
|
+
raise FileNotFoundError(msg)
|
|
83
|
+
if IWYUToolCmd.command_for_version is None:
|
|
84
|
+
msg = 'Unable to locate path to include-what-you-use executable!'
|
|
85
|
+
raise FileNotFoundError(msg)
|
|
86
|
+
|
|
87
|
+
super().__init__(self.command, self.lookbehind, args)
|
|
88
|
+
self.check_installed()
|
|
89
|
+
self.parse_args(args)
|
|
90
|
+
self.handle_ddash_args()
|
|
91
|
+
self.log = logging.getLogger(__name__)
|
|
92
|
+
|
|
93
|
+
# Force location of compile database
|
|
94
|
+
compile_db = self._resolve_compilation_database(self.cmake.build_dir, self.build_dir_list)
|
|
95
|
+
if compile_db:
|
|
96
|
+
self.add_if_missing([f'-p={compile_db}'])
|
|
97
|
+
|
|
98
|
+
def get_version_str(self):
|
|
99
|
+
"""Get the version string of include-what-you-use (iwyu-tool itself does not have any)."""
|
|
100
|
+
command, self.command = self.command, self.command_for_version
|
|
101
|
+
try:
|
|
102
|
+
return super().get_version_str()
|
|
103
|
+
finally:
|
|
104
|
+
self.command = command
|
|
105
|
+
|
|
106
|
+
def _parse_output(self, result):
|
|
107
|
+
"""
|
|
108
|
+
Parse output and check whether some errors occurred.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
result (namedtuple): Result from calling a command
|
|
112
|
+
|
|
113
|
+
Returns:
|
|
114
|
+
False if no errors were detected, True in all other cases.
|
|
115
|
+
|
|
116
|
+
Notes:
|
|
117
|
+
Include-What-You-Use return code is never 0
|
|
118
|
+
"""
|
|
119
|
+
self.log.debug('parsing output from %s', result.stdout)
|
|
120
|
+
is_correct = 'has correct #includes/fwd-decls' in result.stdout
|
|
121
|
+
# NB: when several files are processed at once, the output may contain a mix of correct and incorrect files
|
|
122
|
+
has_suggestions = any(msg in result.stdout for msg in ('should add these lines:', 'should remove these lines:'))
|
|
123
|
+
|
|
124
|
+
return has_suggestions or (bool(result.stdout) and not is_correct)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def main(argv=None):
|
|
128
|
+
"""
|
|
129
|
+
Run command.
|
|
130
|
+
|
|
131
|
+
Args:
|
|
132
|
+
argv (:obj:`list` of :obj:`str`): list of arguments
|
|
133
|
+
"""
|
|
134
|
+
if argv is None:
|
|
135
|
+
argv = sys.argv
|
|
136
|
+
cmd = IWYUToolCmd(argv)
|
|
137
|
+
cmd.run()
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
if __name__ == '__main__': # pragma: nocover
|
|
141
|
+
main()
|