Skip to content

Commit 94fec4b

Browse files
committed
Fix pre-commit issues
1 parent bb2a942 commit 94fec4b

12 files changed

Lines changed: 219 additions & 147 deletions

File tree

cmake_pc_hooks/_argparse.py

Lines changed: 28 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525

2626
import toml
2727

28+
log = logging.getLogger(__name__)
29+
2830
# ==============================================================================
2931

3032

@@ -110,7 +112,11 @@ def executable_path(path: str) -> Path:
110112

111113

112114
def _load_data_from_toml(
113-
path: Path, section: str, *, path_must_exist: bool = True, section_must_exist: bool = True
115+
path: Path,
116+
section: str,
117+
*,
118+
path_must_exist: bool = True,
119+
section_must_exist: bool = True,
114120
) -> dict:
115121
"""
116122
Load a TOML file and return the corresponding config dictionary.
@@ -127,23 +133,23 @@ def _load_data_from_toml(
127133
section_must_exist: Whether a missing section in the TOML file is considered an error or not
128134
"""
129135
try:
130-
with path.open(mode='r') as fd:
136+
with path.open(mode='r', encoding='utf-8') as fd:
131137
config = toml.load(fd)
132138
if section:
133139
for sub_section in section.split('.'):
134140
config = config[sub_section]
135-
logging.debug('Loading data from %s table of %s', section, path)
141+
log.debug('Loading data from %s table of %s', section, path)
136142
else:
137143
config = {key: value for key, value in config.items() if not isinstance(value, dict)}
138-
logging.debug('Loading data from root table of %s', path)
144+
log.debug('Loading data from root table of %s', path)
139145
except FileNotFoundError as err:
140146
if path_must_exist:
141147
raise TOMLFileNotFoundError(path) from err
142-
logging.debug('TOML file %s does not exist (not an error)', str(path))
148+
log.debug('TOML file %s does not exist (not an error)', str(path))
143149
except KeyError as err:
144150
if section_must_exist:
145151
raise TOMLSectionKeyError(section, path) from err
146-
logging.debug('TOML file %s does not have a %s section (not an error)', str(path), section)
152+
log.debug('TOML file %s does not have a %s section (not an error)', str(path), section)
147153
else:
148154
return config
149155
return {}
@@ -245,7 +251,9 @@ def parse_known_args(
245251

246252
if self._default_config_name is not None:
247253
namespace = self._load_from_toml(
248-
namespace=namespace, path=Path(self._default_config_name), path_must_exist=False
254+
namespace=namespace,
255+
path=Path(self._default_config_name),
256+
path_must_exist=False,
249257
)
250258

251259
namespace, args = super().parse_known_args(args=args, namespace=namespace)
@@ -265,11 +273,13 @@ def parse_known_args(
265273
if namespace.dump_toml:
266274
exclude_keys = {'positionals', 'dump_toml'}
267275
print(
268-
toml.dumps({
269-
key: value
270-
for key, value in vars(namespace).items()
271-
if value != self._default_args[key] and key not in exclude_keys
272-
})
276+
toml.dumps(
277+
{
278+
key: value
279+
for key, value in vars(namespace).items()
280+
if value != self._default_args[key] and key not in exclude_keys
281+
}
282+
)
273283
)
274284
sys.exit(0)
275285

@@ -297,7 +307,10 @@ def _load_from_toml( # noqa: PLR0913
297307
overridable_keys: List of keys that can be overridden by values in the TOML file
298308
"""
299309
config = _load_data_from_toml(
300-
path, section, path_must_exist=path_must_exist, section_must_exist=section_must_exist
310+
path,
311+
section,
312+
path_must_exist=path_must_exist,
313+
section_must_exist=section_must_exist,
301314
)
302315

303316
for key, value in config.items():
@@ -309,9 +322,9 @@ def _load_from_toml( # noqa: PLR0913
309322
if default_value is not None and not isinstance(value, type(default_value)):
310323
raise TOMLTypeError(type(value), type(default_value), key)
311324
if overridable_keys is not None and key not in overridable_keys:
312-
logging.debug(' skipping non-overridable key: "%s"', key)
325+
log.debug(' skipping non-overridable key: "%s"', key)
313326
continue
314327

315-
logging.debug(' setting %s = %s', key, value)
328+
log.debug(' setting %s = %s', key, value)
316329
setattr(namespace, key, value)
317330
return namespace

cmake_pc_hooks/_call_process.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222

2323
import attrs
2424

25+
log = logging.getLogger(__name__)
26+
2527

2628
@attrs.define(slots=True)
2729
class History: # pylint: disable=too-few-public-methods
@@ -64,9 +66,9 @@ def call_process(args: list, **kwargs: any) -> History:
6466
else:
6567
ret = History(sp_child.stdout.decode(), sp_child.stderr.decode(), sp_child.returncode)
6668

67-
logging.debug('command `%s` exited with %d', ' '.join(args), ret.returncode)
69+
log.debug('command `%s` exited with %d', ' '.join(args), ret.returncode)
6870
for line in ret.stdout.split('\n'):
69-
logging.debug('(stdout) %s', line)
71+
log.debug('(stdout) %s', line)
7072
for line in ret.stderr.split('\n'):
71-
logging.debug('(stderr) %s', line)
73+
log.debug('(stderr) %s', line)
7274
return ret

cmake_pc_hooks/_cmake.py

Lines changed: 32 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@
3232

3333
from . import _argparse, _call_process
3434

35+
log = logging.getLogger(__name__)
36+
3537
# ==============================================================================
3638

3739

@@ -267,7 +269,7 @@ def resolve_build_directory(self, build_dir_list=None, *, automatic_discovery=Tr
267269
build_dir_list = [] if build_dir_list is None else [Path(path) for path in build_dir_list]
268270
for build_dir in build_dir_list:
269271
if build_dir.exists() and Path(build_dir, 'CMakeCache.txt').exists():
270-
logging.debug(
272+
log.debug(
271273
'Located valid build directory with CMakeCache.txt at: %s',
272274
str(build_dir),
273275
)
@@ -278,20 +280,20 @@ def resolve_build_directory(self, build_dir_list=None, *, automatic_discovery=Tr
278280
if automatic_discovery:
279281
for path in sorted(self.source_dir.glob('*')):
280282
if path.is_dir() and (path / 'CMakeCache.txt').exists():
281-
logging.info('Automatic build dir discovery resulted in: %s', str(path))
283+
log.info('Automatic build dir discovery resulted in: %s', str(path))
282284
self.build_dir = path
283285
return
284286

285287
if self.no_cmake_configure:
286-
logging.info('Unable to locate a valid build directory. Will not be creating one')
288+
log.info('Unable to locate a valid build directory. Will not be creating one')
287289
self.build_dir = None
288290
return
289291

290292
if not build_dir_list:
291293
self.build_dir = self.source_dir / self.DEFAULT_BUILD_DIR
292294
else:
293295
self.build_dir = Path(build_dir_list[0]).resolve()
294-
logging.info(
296+
log.info(
295297
'Unable to locate a valid build directory. Will be creating one at %s',
296298
str(self.build_dir),
297299
)
@@ -379,11 +381,11 @@ def configure(self, command, *, clean_build=False):
379381
clean_build (bool): Clean build directory before calling CMake configure
380382
"""
381383
if self.no_cmake_configure:
382-
logging.debug('Not calling CMake configure')
384+
log.debug('Not calling CMake configure')
383385
return
384386

385387
if self.source_dir is None:
386-
logging.error('No source dir was for CMake! Did you call `setup_cmake_args()`?')
388+
log.error('No source dir was for CMake! Did you call `setup_cmake_args()`?')
387389
sys.exit(1)
388390

389391
cmake_configure_lock_file = Path(self.build_dir, '_cmake_configure_lock')
@@ -396,7 +398,7 @@ def configure(self, command, *, clean_build=False):
396398
try:
397399
with cmake_configure_try_lock.acquire(blocking=False): # noqa: SIM117
398400
with cmake_configure_lock.write_lock():
399-
logging.debug(
401+
log.debug(
400402
'Command %s with id %s is running CMake configure',
401403
command,
402404
os.getpid(),
@@ -408,23 +410,23 @@ def configure(self, command, *, clean_build=False):
408410
),
409411
clean_build=clean_build,
410412
)
411-
logging.debug(
413+
log.debug(
412414
'Command %s with id %s is done running CMake configure',
413415
command,
414416
os.getpid(),
415417
)
416418
except filelock.Timeout:
417-
logging.debug(
419+
log.debug(
418420
'Command %s with id %s is not running CMake configure and waiting',
419421
command,
420422
os.getpid(),
421423
)
422424
with cmake_configure_lock.read_lock():
423-
logging.debug('Command %s with id %s is done waiting', command, os.getpid())
425+
log.debug('Command %s with id %s is done waiting', command, os.getpid())
424426
returncode = 0
425427

426428
if returncode != 0:
427-
logging.error('CMake configure step failed. See output for more information.')
429+
log.error('CMake configure step failed. See output for more information.')
428430
sys.exit(returncode)
429431

430432
if self.cmake_trace_log is not None:
@@ -439,12 +441,14 @@ def _call_cmake(self, extra_args=None):
439441
[*command, str(self.source_dir), *self.cmake_args, *extra_args],
440442
cwd=str(self.build_dir),
441443
)
442-
result.stdout = '\n'.join([
443-
f'Running CMake with: {[*command, str(self.source_dir), *self.cmake_args]}',
444-
f' from within {self.build_dir}',
445-
result.stdout,
446-
'',
447-
])
444+
result.stdout = '\n'.join(
445+
[
446+
f'Running CMake with: {[*command, str(self.source_dir), *self.cmake_args]}',
447+
f' from within {self.build_dir}',
448+
result.stdout,
449+
'',
450+
]
451+
)
448452

449453
return result
450454

@@ -461,11 +465,13 @@ def _configure(self, lock_files, clean_build):
461465

462466
extra_args = []
463467
if self.cmake_trace_log:
464-
extra_args.extend([
465-
'--trace-expand',
466-
'--trace-format=json-v1',
467-
f'--trace-redirect={self.cmake_trace_log}',
468-
])
468+
extra_args.extend(
469+
[
470+
'--trace-expand',
471+
'--trace-format=json-v1',
472+
f'--trace-redirect={self.cmake_trace_log}',
473+
]
474+
)
469475

470476
result = self._call_cmake(extra_args=extra_args)
471477

@@ -480,16 +486,16 @@ def _configure(self, lock_files, clean_build):
480486
return result.returncode
481487

482488
def _parse_cmake_trace_log(self):
483-
logging.info('attempting to parse CMake trace log to detect calls to configure_file()')
489+
log.info('attempting to parse CMake trace log to detect calls to configure_file()')
484490
self.cmake_configured_files = []
485491

486492
if not self.cmake_trace_log:
487-
logging.info('no trace log provided, aborting.')
493+
log.info('no trace log provided, aborting.')
488494
return
489495

490496
result = self._call_cmake(extra_args=['-N', '-LA'])
491497
if result.returncode != 0:
492-
logging.error('failed to retrieve CMake cache variables')
498+
log.error('failed to retrieve CMake cache variables')
493499
return
494500

495501
cmake_cache_variables = {}
@@ -524,7 +530,7 @@ def _is_relevant_configure_file_call(json_data):
524530
input_file, configured_file = (Path(arg) for arg in configure_file_call['args'][:2])
525531
if not configured_file.is_absolute():
526532
configured_file = self.build_dir / configured_file
527-
logging.debug(
533+
log.debug(
528534
'detected call to configure_file(%s %s [...])',
529535
str(input_file),
530536
str(configured_file),

cmake_pc_hooks/_utils.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@
3131
logging.basicConfig(level=_LOGLEVEL, format='%(levelname)-5s:cmake-pc-hooks:%(message)s')
3232
logging.getLogger('filelock').setLevel(logging.WARNING)
3333

34+
log = logging.getLogger(__name__)
35+
3436

3537
class CMakePresetError(Exception):
3638
"""Exception raised if a command line incompatibility with --preset is detected."""
@@ -88,8 +90,7 @@ def parse_args(self, args):
8890
'--read-json-db',
8991
action='store_true',
9092
help=(
91-
'Run hooks on files found in compile_commands.json '
92-
'(if found and in addition to files specified on CLI)'
93+
'Run hooks on files found in compile_commands.json (if found and in addition to files specified on CLI)'
9394
),
9495
)
9596

@@ -137,7 +138,7 @@ def run(self):
137138
for filename in self.files:
138139
self.run_command([filename])
139140
else:
140-
logging.error('No files to process!')
141+
log.error('No files to process!')
141142
sys.exit(1)
142143

143144
has_errors = False
@@ -172,9 +173,9 @@ def _resolve_compilation_database(cmake_build_dir: Path, build_dir_list: list[Pa
172173
for build_dir in build_dir_list:
173174
path = Path(build_dir, 'compile_commands.json')
174175
if build_dir.exists() and path.exists():
175-
logging.debug('Located valid compilation database at: %s', str(path))
176+
log.debug('Located valid compilation database at: %s', str(path))
176177
return path
177-
logging.debug('No valid compilation database located')
178+
log.debug('No valid compilation database located')
178179
return None
179180

180181

cmake_pc_hooks/clang_tidy.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,13 @@ def __init__(self, args):
3232
self.parse_args(args)
3333
self.edit_in_place = '-fix' in self.args or '--fix-errors' in self.args
3434
self.handle_ddash_args()
35+
self.log = logging.getLogger(__name__)
3536

3637
compile_db = self._resolve_compilation_database(self.cmake.build_dir, self.build_dir_list)
3738
if not self.cmake.no_cmake_configure or compile_db:
3839
self.add_if_missing([f'-p={compile_db}'])
3940

40-
def _parse_output(self, result): # noqa: PLR6301
41+
def _parse_output(self, result):
4142
"""
4243
Parse output and check whether some errors occurred.
4344
@@ -51,8 +52,8 @@ def _parse_output(self, result): # noqa: PLR6301
5152
if not result.stdout or 'non-user code' in result.stderr:
5253
result.stderr = ''
5354

54-
logging.debug('returncode %d', result.returncode)
55-
logging.debug('parsing output from %s', result.stderr)
55+
self.log.debug('returncode %d', result.returncode)
56+
self.log.debug('parsing output from %s', result.stderr)
5657
return result.returncode != 0 or any(
5758
msg in result.stderr
5859
for msg in (

cmake_pc_hooks/cppcheck.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ def __init__(self, args):
3838
self.add_if_missing(['--error-exitcode=1'])
3939
# Enable all of the checks
4040
self.add_if_missing(['--enable=all'])
41+
self.log = logging.getLogger(__name__)
4142

4243
compile_db = self._resolve_compilation_database(self.cmake.build_dir, self.build_dir_list)
4344
if not self.cmake.no_cmake_configure or compile_db:
@@ -60,11 +61,11 @@ def _parse_output(self, result):
6061
False if no errors were detected, True in all other cases.
6162
"""
6263
# Useless error see https://stackoverflow.com/questions/6986033
63-
logging.debug('parsing output from %s', result.stderr)
64+
self.log.debug('parsing output from %s', result.stderr)
6465
useless_error_part = 'Cppcheck cannot find all the include files'
65-
result.stderr = ''.join([
66-
line for line in result.stderr.splitlines(keepends=True) if useless_error_part not in line
67-
])
66+
result.stderr = ''.join(
67+
[line for line in result.stderr.splitlines(keepends=True) if useless_error_part not in line]
68+
)
6869
self._clinters_compat()
6970
return result.returncode != 0
7071

0 commit comments

Comments
 (0)