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.
@@ -0,0 +1,15 @@
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
+ """Main module for cmake-pre-commit-hooks."""
@@ -0,0 +1,332 @@
1
+ # Copyright 2023 Damien Nguyen <ngn.damien@gmail.com>
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
+ """Custom argument parser to support parsing from TOML config files."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import logging
21
+ import os
22
+ import sys
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ import toml
27
+
28
+ log = logging.getLogger(__name__)
29
+
30
+ # ==============================================================================
31
+
32
+
33
+ class InvalidExecutablePathError(argparse.ArgumentTypeError):
34
+ """Exception raised when a path to an executable is invalid."""
35
+
36
+ def __init__(self, path: Path) -> None:
37
+ """Initialize an InvalidExecutablePathError."""
38
+ super().__init__(f'{path} is not a valid file and/or does not appear executable')
39
+
40
+
41
+ class TOMLFileNotFoundError(FileNotFoundError):
42
+ """Exception raised when a TOML file cannot be found."""
43
+
44
+ def __init__(self, path: Path) -> None:
45
+ """Initialize a TOMLFileNotFoundError object."""
46
+ super().__init__(f'Unable to locate TOML file {path}')
47
+
48
+
49
+ class TOMLSectionKeyError(KeyError):
50
+ """Exception raised when a TOML key cannot be found."""
51
+
52
+ def __init__(self, section: str, path: Path) -> None:
53
+ """Initialize a TOMLSectionKeyError object."""
54
+ super().__init__(f'Unable to locate section {section} in TOML file {path}')
55
+
56
+
57
+ class TOMLTypeError(argparse.ArgumentTypeError):
58
+ """Exception raised when a TOML key does not match the type of a default value."""
59
+
60
+ def __init__(self, value_type: type, default_value_type: type, toml_key: str) -> None:
61
+ """Initialize a TOMLSectionKeyError object."""
62
+ super().__init__(
63
+ f'TOML value type {value_type} not compatible with parser argument '
64
+ f'{default_value_type} for key "{toml_key}"'
65
+ )
66
+
67
+
68
+ # ==============================================================================
69
+
70
+
71
+ def _append_in_namespace(namespace, key, values):
72
+ current = getattr(namespace, key, [])
73
+ if current is None:
74
+ current = []
75
+ current.append(values)
76
+ setattr(namespace, key, current)
77
+
78
+
79
+ class OSSpecificAction(argparse.Action):
80
+ """Custom action to support platform-specific arguments."""
81
+
82
+ def __call__(self, parser, namespace, values, options_string=None): # ruff: ignore[unused-method-argument]
83
+ if self.dest == 'unix':
84
+ _append_in_namespace(namespace, 'linux', values)
85
+ _append_in_namespace(namespace, 'mac', values)
86
+
87
+ _append_in_namespace(namespace, self.dest, values)
88
+
89
+
90
+ # ==============================================================================
91
+
92
+
93
+ def executable_path(path: str) -> Path:
94
+ """
95
+ Argparse validation function.
96
+
97
+ Args:
98
+ path: Path to some file or directory
99
+
100
+ Returns:
101
+ True if `path` points to a file that is executable, False otherwise
102
+
103
+ Raises:
104
+ argparse.ArgumentTypeError if path does not point to an executable file.
105
+ """
106
+ if Path(path).is_file() and os.access(path, os.X_OK):
107
+ return path
108
+ raise InvalidExecutablePathError(path)
109
+
110
+
111
+ # ==============================================================================
112
+
113
+
114
+ def _load_data_from_toml(
115
+ path: Path,
116
+ section: str,
117
+ *,
118
+ path_must_exist: bool = True,
119
+ section_must_exist: bool = True,
120
+ ) -> dict:
121
+ """
122
+ Load a TOML file and return the corresponding config dictionary.
123
+
124
+ Note:
125
+ If no section is specified, this function will only return the dictionary containing the first level of
126
+ elements (ie. no nested sections).
127
+
128
+ Args:
129
+ path: Path to TOML file
130
+ section: Name of section to load in TOML file
131
+ path_must_exist: Whether a missing TOML file is considered an error or not
132
+ section_must_exist: Whether a missing section in the TOML file is considered an error or not
133
+ """
134
+ try:
135
+ with path.open(mode='r', encoding='utf-8') as fd:
136
+ config = toml.load(fd)
137
+ except FileNotFoundError as err:
138
+ if path_must_exist:
139
+ raise TOMLFileNotFoundError(path) from err
140
+ log.debug('TOML file %s does not exist (not an error)', path)
141
+ return {}
142
+
143
+ if not section:
144
+ log.debug('Loading data from root table of %s', path)
145
+ return {key: value for key, value in config.items() if not isinstance(value, dict)}
146
+
147
+ try:
148
+ for sub_section in section.split('.'):
149
+ config = config[sub_section]
150
+ except KeyError as err:
151
+ if section_must_exist:
152
+ raise TOMLSectionKeyError(section, path) from err
153
+ log.debug('TOML file %s does not have a %s section (not an error)', path, section)
154
+ return {}
155
+
156
+ log.debug('Loading data from %s table of %s', section, path)
157
+ return config
158
+
159
+
160
+ # ==============================================================================
161
+
162
+
163
+ class ArgumentParser(argparse.ArgumentParser):
164
+ """
165
+ A wrapper of the argparse.ArgumentParser class that supports loading from TOML files.
166
+
167
+ This class extends the functionality of the standard argparse.ArgumentParser by allowing users to specify default
168
+ values for arguments in a TOML file, in addition to the command line.
169
+
170
+ Argument are parsed from either the CLI or an optional TOML file using the following hierarchy:
171
+ 1. Arguments passed through the command line are selected over TOML
172
+ arguments, even if both are passed
173
+ 2. Arguments from a TOML file if specified using the --config CLI argument
174
+ 3. Arguments from a default TOML config file location
175
+ 4. Arguments from an existing pyproject.toml file location
176
+ """
177
+
178
+ def __init__(
179
+ self,
180
+ *args: Any,
181
+ default_config_name: str | None = None,
182
+ pyproject_section_name: str | None = None,
183
+ args_groups: list[dict] | None = None,
184
+ **kwargs: Any,
185
+ ) -> None:
186
+ """
187
+ Initialize an instance of ArgumentParser.
188
+
189
+ Keyword Args:
190
+ default_config_name (str): Default name for a TOML configuration file
191
+ pyproject_section_name (str): Name of section to look for in pyproject.toml file
192
+ args_groups: List of argument groups to create. Items are dictionaries with keywords to pass onto
193
+ add_argument_group()
194
+ args: Same as for argparse.ArgumentParser()
195
+ kwargs: Same as for argparse.ArgumentParser()
196
+ """
197
+ self._default_config_name = default_config_name
198
+ self._pyproject_section_name = pyproject_section_name
199
+ self.groups = []
200
+
201
+ super().__init__(*args, **kwargs)
202
+
203
+ if args_groups is not None:
204
+ for arg_group in args_groups:
205
+ self.groups.append(self.add_argument_group(**arg_group))
206
+
207
+ group = self.add_argument_group(title='TOML options')
208
+ group.add_argument(
209
+ '--config',
210
+ type=str,
211
+ default='',
212
+ help='Path to a TOML configuration file.',
213
+ )
214
+ group.add_argument(
215
+ '--dump-toml',
216
+ action='store_true',
217
+ help='Dump the current set of CLI arguments as TOML-formatted output',
218
+ )
219
+ self._default_args = {}
220
+
221
+ def parse_known_args(
222
+ self, args: list | None = None, namespace: argparse.Namespace | None = None
223
+ ) -> argparse.Namespace:
224
+ """
225
+ Convert argument strings to objects and assign them as attributes of the namespace.
226
+
227
+ Args:
228
+ args: List of strings to parse. The default is taken from sys.argv.
229
+ namespace: An object to take the attributes. The default is a new empty Namespace object.
230
+
231
+ Return:
232
+ The populated namespace.
233
+ """
234
+ # 1. Attempt to parse from pyproject.toml
235
+ # 2. Attempt to parse from default config file
236
+ # 3. Attempt to parse from TOML config file from CLI
237
+ # 4. Use CLI arguments or default values
238
+
239
+ tmp, _ = super().parse_known_args([])
240
+ self._default_args = vars(tmp)
241
+
242
+ if namespace is None:
243
+ namespace = argparse.Namespace()
244
+
245
+ if self._pyproject_section_name is not None:
246
+ namespace = self._load_from_toml(
247
+ namespace=namespace,
248
+ path=Path('pyproject.toml'),
249
+ section=self._pyproject_section_name,
250
+ path_must_exist=False,
251
+ section_must_exist=False,
252
+ )
253
+
254
+ if self._default_config_name is not None:
255
+ namespace = self._load_from_toml(
256
+ namespace=namespace,
257
+ path=Path(self._default_config_name),
258
+ path_must_exist=False,
259
+ )
260
+
261
+ namespace, args = super().parse_known_args(args=args, namespace=namespace)
262
+ if namespace.config:
263
+ overridable_keys = set()
264
+ for key, value in vars(namespace).items():
265
+ default_value = self._default_args[key]
266
+ if value == default_value:
267
+ overridable_keys.add(key)
268
+ namespace = self._load_from_toml(
269
+ namespace=namespace,
270
+ path=Path(namespace.config),
271
+ path_must_exist=True,
272
+ overridable_keys=overridable_keys,
273
+ )
274
+
275
+ if namespace.dump_toml:
276
+ exclude_keys = {'positionals', 'dump_toml'}
277
+ print(
278
+ toml.dumps(
279
+ {
280
+ key: value
281
+ for key, value in vars(namespace).items()
282
+ if value != self._default_args[key] and key not in exclude_keys
283
+ }
284
+ )
285
+ )
286
+ sys.exit(0)
287
+
288
+ return namespace, args
289
+
290
+ def _load_from_toml( # ruff: ignore[too-many-arguments]
291
+ self,
292
+ namespace: argparse.Namespace,
293
+ path: Path,
294
+ section: str = '',
295
+ *,
296
+ path_must_exist: bool = True,
297
+ section_must_exist: bool = True,
298
+ overridable_keys: set | None = None,
299
+ ) -> argparse.Namespace:
300
+ """
301
+ Load a TOML file and set the attributes within the argparse namespace object.
302
+
303
+ Args:
304
+ namespace: Namespace to store results into
305
+ path: Path to TOML file
306
+ section: Name of section to load in TOML file
307
+ path_must_exist: Whether a missing TOML file is considered an error or not
308
+ section_must_exist: Whether a missing section in the TOML file is considered an error or not
309
+ overridable_keys: List of keys that can be overridden by values in the TOML file
310
+ """
311
+ config = _load_data_from_toml(
312
+ path,
313
+ section,
314
+ path_must_exist=path_must_exist,
315
+ section_must_exist=section_must_exist,
316
+ )
317
+
318
+ for key, value in config.items():
319
+ if key not in self._default_args:
320
+ self.error(f'unrecognized arguments: "{key}"')
321
+
322
+ # NB: we can only do proper type check if the default value is given...
323
+ default_value = self._default_args[key]
324
+ if default_value is not None and not isinstance(value, type(default_value)):
325
+ raise TOMLTypeError(type(value), type(default_value), key)
326
+ if overridable_keys is not None and key not in overridable_keys:
327
+ log.debug(' skipping non-overridable key: "%s"', key)
328
+ continue
329
+
330
+ log.debug(' setting %s = %s', key, value)
331
+ setattr(namespace, key, value)
332
+ return namespace
@@ -0,0 +1,74 @@
1
+ # Copyright 2023 Damien Nguyen <ngn.damien@gmail.com>
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
+ """Sub-process handling classes and functions."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import logging
20
+ import subprocess as sp
21
+ import sys
22
+
23
+ import attrs
24
+
25
+ log = logging.getLogger(__name__)
26
+
27
+
28
+ @attrs.define(slots=True)
29
+ class History:
30
+ """Process execution data."""
31
+
32
+ stdout: str
33
+ stderr: str
34
+ returncode: int
35
+ _print_output: bool = True
36
+
37
+ def disable_print_output(self) -> None:
38
+ """Disable output printing."""
39
+ self._print_output = False
40
+
41
+ def to_stdout_and_stderr(self) -> None:
42
+ """Copy the relevant content to the standard output and error streams."""
43
+ if not self._print_output:
44
+ return
45
+ sys.stdout.write(self.stdout)
46
+ sys.stdout.flush()
47
+ sys.stderr.write(self.stderr)
48
+ sys.stderr.flush()
49
+
50
+
51
+ def call_process(args: list, **kwargs: any) -> History:
52
+ """
53
+ Call a process using subprocess and save the output for later use.
54
+
55
+ Args:
56
+ args: Arguments to pass onto subprocess.run()
57
+ kwargs: Keyword arguments to pass onto subprocess.run()
58
+
59
+ Returns:
60
+ A History object instance.
61
+ """
62
+ try:
63
+ sp_child = sp.run(args, check=True, capture_output=True, **kwargs)
64
+ except sp.CalledProcessError as err:
65
+ ret = History(err.stdout.decode(), err.stderr.decode(), err.returncode)
66
+ else:
67
+ ret = History(sp_child.stdout.decode(), sp_child.stderr.decode(), sp_child.returncode)
68
+
69
+ log.debug('command `%s` exited with %d', ' '.join(args), ret.returncode)
70
+ for line in ret.stdout.split('\n'):
71
+ log.debug('(stdout) %s', line)
72
+ for line in ret.stderr.split('\n'):
73
+ log.debug('(stderr) %s', line)
74
+ return ret