summaryrefslogtreecommitdiff
path: root/pylint/config/argument.py
blob: d826cbd3e6d4f87d4beac8228914b8c502e579cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt

"""Definition of an Argument class and transformers for various argument types.

An Argument instance represents a pylint option to be handled by an argparse.ArgumentParser
"""

from __future__ import annotations

import argparse
import os
import pathlib
import re
from collections.abc import Callable
from glob import glob
from typing import Any, Literal, Pattern, Sequence, Tuple, Union

from pylint import interfaces
from pylint import utils as pylint_utils
from pylint.config.callback_actions import _CallbackAction, _ExtendAction
from pylint.config.deprecation_actions import _NewNamesAction, _OldNamesAction
from pylint.constants import PY38_PLUS

_ArgumentTypes = Union[
    str,
    int,
    float,
    bool,
    Pattern[str],
    Sequence[str],
    Sequence[Pattern[str]],
    Tuple[int, ...],
]
"""List of possible argument types."""


def _confidence_transformer(value: str) -> Sequence[str]:
    """Transforms a comma separated string of confidence values."""
    if not value:
        return interfaces.CONFIDENCE_LEVEL_NAMES
    values = pylint_utils._check_csv(value)
    for confidence in values:
        if confidence not in interfaces.CONFIDENCE_LEVEL_NAMES:
            raise argparse.ArgumentTypeError(
                f"{value} should be in {*interfaces.CONFIDENCE_LEVEL_NAMES,}"
            )
    return values


def _csv_transformer(value: str) -> Sequence[str]:
    """Transforms a comma separated string."""
    return pylint_utils._check_csv(value)


YES_VALUES = {"y", "yes", "true"}
NO_VALUES = {"n", "no", "false"}


def _yn_transformer(value: str) -> bool:
    """Transforms a yes/no or stringified bool into a bool."""
    value = value.lower()
    if value in YES_VALUES:
        return True
    if value in NO_VALUES:
        return False
    raise argparse.ArgumentTypeError(
        None, f"Invalid yn value '{value}', should be in {*YES_VALUES, *NO_VALUES}"
    )


def _non_empty_string_transformer(value: str) -> str:
    """Check that a string is not empty and remove quotes."""
    if not value:
        raise argparse.ArgumentTypeError("Option cannot be an empty string.")
    return pylint_utils._unquote(value)


def _path_transformer(value: str) -> str:
    """Expand user and variables in a path."""
    return os.path.expandvars(os.path.expanduser(value))


def _glob_paths_csv_transformer(value: str) -> Sequence[str]:
    """Transforms a comma separated list of paths while expanding user and
    variables and glob patterns.
    """
    paths: list[str] = []
    for path in _csv_transformer(value):
        paths.extend(glob(_path_transformer(path), recursive=True))
    return paths


def _py_version_transformer(value: str) -> tuple[int, ...]:
    """Transforms a version string into a version tuple."""
    try:
        version = tuple(int(val) for val in value.replace(",", ".").split("."))
    except ValueError:
        raise argparse.ArgumentTypeError(
            f"{value} has an invalid format, should be a version string. E.g., '3.8'"
        ) from None
    return version


def _regex_transformer(value: str) -> Pattern[str]:
    """Return `re.compile(value)`."""
    try:
        return re.compile(value)
    except re.error as e:
        msg = f"Error in provided regular expression: {value} beginning at index {e.pos}: {e.msg}"
        raise argparse.ArgumentTypeError(msg) from e


def _regexp_csv_transfomer(value: str) -> Sequence[Pattern[str]]:
    """Transforms a comma separated list of regular expressions."""
    patterns: list[Pattern[str]] = []
    for pattern in _csv_transformer(value):
        patterns.append(_regex_transformer(pattern))
    return patterns


def _regexp_paths_csv_transfomer(value: str) -> Sequence[Pattern[str]]:
    """Transforms a comma separated list of regular expressions paths."""
    patterns: list[Pattern[str]] = []
    for pattern in _csv_transformer(value):
        patterns.append(
            re.compile(
                str(pathlib.PureWindowsPath(pattern)).replace("\\", "\\\\")
                + "|"
                + pathlib.PureWindowsPath(pattern).as_posix()
            )
        )
    return patterns


_TYPE_TRANSFORMERS: dict[str, Callable[[str], _ArgumentTypes]] = {
    "choice": str,
    "csv": _csv_transformer,
    "float": float,
    "int": int,
    "confidence": _confidence_transformer,
    "non_empty_string": _non_empty_string_transformer,
    "path": _path_transformer,
    "glob_paths_csv": _glob_paths_csv_transformer,
    "py_version": _py_version_transformer,
    "regexp": _regex_transformer,
    "regexp_csv": _regexp_csv_transfomer,
    "regexp_paths_csv": _regexp_paths_csv_transfomer,
    "string": pylint_utils._unquote,
    "yn": _yn_transformer,
}
"""Type transformers for all argument types.

A transformer should accept a string and return one of the supported
Argument types. It will only be called when parsing 1) command-line,
2) configuration files and 3) a string default value.
Non-string default values are assumed to be of the correct type.
"""


class _Argument:
    """Class representing an argument to be parsed by an argparse.ArgumentsParser.

    This is based on the parameters passed to argparse.ArgumentsParser.add_message.
    See:
    https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument
    """

    def __init__(
        self,
        *,
        flags: list[str],
        arg_help: str,
        hide_help: bool,
        section: str | None,
    ) -> None:
        self.flags = flags
        """The name of the argument."""

        self.hide_help = hide_help
        """Whether to hide this argument in the help message."""

        # argparse uses % formatting on help strings, so a % needs to be escaped
        self.help = arg_help.replace("%", "%%")
        """The description of the argument."""

        if hide_help:
            self.help = argparse.SUPPRESS

        self.section = section
        """The section to add this argument to."""


class _BaseStoreArgument(_Argument):
    """Base class for store arguments to be parsed by an argparse.ArgumentsParser.

    This is based on the parameters passed to argparse.ArgumentsParser.add_message.
    See:
    https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument
    """

    def __init__(
        self,
        *,
        flags: list[str],
        action: str,
        default: _ArgumentTypes,
        arg_help: str,
        hide_help: bool,
        section: str | None,
    ) -> None:
        super().__init__(
            flags=flags, arg_help=arg_help, hide_help=hide_help, section=section
        )

        self.action = action
        """The action to perform with the argument."""

        self.default = default
        """The default value of the argument."""


class _StoreArgument(_BaseStoreArgument):
    """Class representing a store argument to be parsed by an argparse.ArgumentsParser.

    This is based on the parameters passed to argparse.ArgumentsParser.add_message.
    See:
    https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument
    """

    def __init__(
        self,
        *,
        flags: list[str],
        action: str,
        default: _ArgumentTypes,
        arg_type: str,
        choices: list[str] | None,
        arg_help: str,
        metavar: str,
        hide_help: bool,
        section: str | None,
    ) -> None:
        super().__init__(
            flags=flags,
            action=action,
            default=default,
            arg_help=arg_help,
            hide_help=hide_help,
            section=section,
        )

        self.type = _TYPE_TRANSFORMERS[arg_type]
        """A transformer function that returns a transformed type of the argument."""

        self.choices = choices
        """A list of possible choices for the argument.

        None if there are no restrictions.
        """

        self.metavar = metavar
        """The metavar of the argument.

        See:
        https://docs.python.org/3/library/argparse.html#metavar
        """


class _StoreTrueArgument(_BaseStoreArgument):
    """Class representing a 'store_true' argument to be parsed by an
    argparse.ArgumentsParser.

    This is based on the parameters passed to argparse.ArgumentsParser.add_message.
    See:
    https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument
    """

    # pylint: disable-next=useless-parent-delegation # We narrow down the type of action
    def __init__(
        self,
        *,
        flags: list[str],
        action: Literal["store_true"],
        default: _ArgumentTypes,
        arg_help: str,
        hide_help: bool,
        section: str | None,
    ) -> None:
        super().__init__(
            flags=flags,
            action=action,
            default=default,
            arg_help=arg_help,
            hide_help=hide_help,
            section=section,
        )


class _DeprecationArgument(_Argument):
    """Store arguments while also handling deprecation warnings for old and new names.

    This is based on the parameters passed to argparse.ArgumentsParser.add_message.
    See:
    https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument
    """

    def __init__(
        self,
        *,
        flags: list[str],
        action: type[argparse.Action],
        default: _ArgumentTypes,
        arg_type: str,
        choices: list[str] | None,
        arg_help: str,
        metavar: str,
        hide_help: bool,
        section: str | None,
    ) -> None:
        super().__init__(
            flags=flags, arg_help=arg_help, hide_help=hide_help, section=section
        )

        self.action = action
        """The action to perform with the argument."""

        self.default = default
        """The default value of the argument."""

        self.type = _TYPE_TRANSFORMERS[arg_type]
        """A transformer function that returns a transformed type of the argument."""

        self.choices = choices
        """A list of possible choices for the argument.

        None if there are no restrictions.
        """

        self.metavar = metavar
        """The metavar of the argument.

        See:
        https://docs.python.org/3/library/argparse.html#metavar
        """


class _ExtendArgument(_DeprecationArgument):
    """Class for extend arguments to be parsed by an argparse.ArgumentsParser.

    This is based on the parameters passed to argparse.ArgumentsParser.add_message.
    See:
    https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument
    """

    def __init__(
        self,
        *,
        flags: list[str],
        action: Literal["extend"],
        default: _ArgumentTypes,
        arg_type: str,
        metavar: str,
        arg_help: str,
        hide_help: bool,
        section: str | None,
        choices: list[str] | None,
        dest: str | None,
    ) -> None:
        # The extend action is included in the stdlib from 3.8+
        if PY38_PLUS:
            action_class = argparse._ExtendAction
        else:
            action_class = _ExtendAction  # type: ignore[assignment]

        self.dest = dest
        """The destination of the argument."""

        super().__init__(
            flags=flags,
            action=action_class,
            default=default,
            arg_type=arg_type,
            choices=choices,
            arg_help=arg_help,
            metavar=metavar,
            hide_help=hide_help,
            section=section,
        )


class _StoreOldNamesArgument(_DeprecationArgument):
    """Store arguments while also handling old names.

    This is based on the parameters passed to argparse.ArgumentsParser.add_message.
    See:
    https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument
    """

    def __init__(
        self,
        *,
        flags: list[str],
        default: _ArgumentTypes,
        arg_type: str,
        choices: list[str] | None,
        arg_help: str,
        metavar: str,
        hide_help: bool,
        kwargs: dict[str, Any],
        section: str | None,
    ) -> None:
        super().__init__(
            flags=flags,
            action=_OldNamesAction,
            default=default,
            arg_type=arg_type,
            choices=choices,
            arg_help=arg_help,
            metavar=metavar,
            hide_help=hide_help,
            section=section,
        )

        self.kwargs = kwargs
        """Any additional arguments passed to the action."""


class _StoreNewNamesArgument(_DeprecationArgument):
    """Store arguments while also emitting deprecation warnings.

    This is based on the parameters passed to argparse.ArgumentsParser.add_message.
    See:
    https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument
    """

    def __init__(
        self,
        *,
        flags: list[str],
        default: _ArgumentTypes,
        arg_type: str,
        choices: list[str] | None,
        arg_help: str,
        metavar: str,
        hide_help: bool,
        kwargs: dict[str, Any],
        section: str | None,
    ) -> None:
        super().__init__(
            flags=flags,
            action=_NewNamesAction,
            default=default,
            arg_type=arg_type,
            choices=choices,
            arg_help=arg_help,
            metavar=metavar,
            hide_help=hide_help,
            section=section,
        )

        self.kwargs = kwargs
        """Any additional arguments passed to the action."""


class _CallableArgument(_Argument):
    """Class representing an callable argument to be parsed by an
    argparse.ArgumentsParser.

    This is based on the parameters passed to argparse.ArgumentsParser.add_message.
    See:
    https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument
    """

    def __init__(
        self,
        *,
        flags: list[str],
        action: type[_CallbackAction],
        arg_help: str,
        kwargs: dict[str, Any],
        hide_help: bool,
        section: str | None,
        metavar: str,
    ) -> None:
        super().__init__(
            flags=flags, arg_help=arg_help, hide_help=hide_help, section=section
        )

        self.action = action
        """The action to perform with the argument."""

        self.kwargs = kwargs
        """Any additional arguments passed to the action."""

        self.metavar = metavar
        """The metavar of the argument.

        See:
        https://docs.python.org/3/library/argparse.html#metavar
        """