jarbin-c-coding-style 2.0.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.
- jarbin_c_coding_style-2.0.0.dist-info/METADATA +150 -0
- jarbin_c_coding_style-2.0.0.dist-info/RECORD +186 -0
- jarbin_c_coding_style-2.0.0.dist-info/WHEEL +4 -0
- jarbin_c_coding_style-2.0.0.dist-info/entry_points.txt +2 -0
- jarbin_c_coding_style-2.0.0.dist-info/licenses/LICENSE +674 -0
- sources/__init__.py +0 -0
- sources/__main__.py +6 -0
- sources/analysis/__init__.py +0 -0
- sources/analysis/directives.py +258 -0
- sources/analysis/lexer.py +288 -0
- sources/analysis/parser.py +1754 -0
- sources/analysis/project.py +286 -0
- sources/analysis/source.py +326 -0
- sources/analysis/syntax.py +238 -0
- sources/analysis/tokens.py +116 -0
- sources/analysis/unit.py +700 -0
- sources/application.py +118 -0
- sources/build_info.json +6 -0
- sources/cli/__init__.py +0 -0
- sources/cli/arguments.py +507 -0
- sources/cli/completion.py +610 -0
- sources/cli/context.py +258 -0
- sources/cli/converters.py +204 -0
- sources/cli/help.py +162 -0
- sources/cli/parser.py +659 -0
- sources/configs/__init__.py +0 -0
- sources/configs/editor.py +207 -0
- sources/configs/ini.py +327 -0
- sources/configs/project.py +735 -0
- sources/configs/schema/__init__.py +0 -0
- sources/configs/schema/project.py +68 -0
- sources/constants.py +801 -0
- sources/diagnostics/__init__.py +0 -0
- sources/diagnostics/fingerprint.py +82 -0
- sources/diagnostics/model.py +146 -0
- sources/engine/__init__.py +0 -0
- sources/engine/api.py +355 -0
- sources/engine/examples.py +157 -0
- sources/engine/outcome.py +114 -0
- sources/engine/plan.py +440 -0
- sources/engine/runner.py +345 -0
- sources/engine/scanner.py +179 -0
- sources/enums.py +838 -0
- sources/errors/__init__.py +0 -0
- sources/errors/exceptions.py +727 -0
- sources/fixers/__init__.py +0 -0
- sources/fixers/base.py +209 -0
- sources/fixers/conflicts.py +129 -0
- sources/fixers/diff.py +73 -0
- sources/fixers/engine.py +434 -0
- sources/fixers/journal.py +290 -0
- sources/fixers/kinds.py +30 -0
- sources/fixers/layout.py +411 -0
- sources/fixers/model.py +151 -0
- sources/fixers/registry.py +54 -0
- sources/fixers/text.py +353 -0
- sources/fixers/verify.py +123 -0
- sources/fixers/writer.py +88 -0
- sources/integrations/__init__.py +0 -0
- sources/integrations/ci/__init__.py +0 -0
- sources/integrations/ci/github.py +183 -0
- sources/integrations/editors/__init__.py +0 -0
- sources/integrations/git/__init__.py +0 -0
- sources/integrations/git/repository.py +176 -0
- sources/integrations/update/__init__.py +0 -0
- sources/integrations/update/installers.py +529 -0
- sources/integrations/update/releases.py +397 -0
- sources/integrations/update/state.py +143 -0
- sources/outputs/__init__.py +0 -0
- sources/outputs/github/__init__.py +0 -0
- sources/outputs/github/renderer.py +135 -0
- sources/outputs/html/__init__.py +0 -0
- sources/outputs/html/renderer.py +694 -0
- sources/outputs/json/__init__.py +0 -0
- sources/outputs/json/renderer.py +154 -0
- sources/outputs/json/report.schema.json +121 -0
- sources/outputs/junit/__init__.py +0 -0
- sources/outputs/junit/renderer.py +151 -0
- sources/outputs/registry.py +135 -0
- sources/outputs/report.py +224 -0
- sources/outputs/sarif/__init__.py +0 -0
- sources/outputs/sarif/renderer.py +182 -0
- sources/outputs/terminal/__init__.py +0 -0
- sources/outputs/terminal/renderer.py +184 -0
- sources/outputs/terminal/style.py +159 -0
- sources/rules/__init__.py +0 -0
- sources/rules/arguments.py +362 -0
- sources/rules/catalog.py +227 -0
- sources/rules/categories/advanced/constant_pointers.ini +46 -0
- sources/rules/categories/advanced/line_break_at_end_of_file.ini +44 -0
- sources/rules/categories/advanced/static.ini +65 -0
- sources/rules/categories/advanced/typing.ini +47 -0
- sources/rules/categories/control_structures/conditional_branching.ini +89 -0
- sources/rules/categories/control_structures/goto.ini +45 -0
- sources/rules/categories/control_structures/ternary_operators.ini +57 -0
- sources/rules/categories/extensions/language_extensions.ini +71 -0
- sources/rules/categories/files_organization/contents_of_the_repository.ini +85 -0
- sources/rules/categories/files_organization/file_coherence.ini +166 -0
- sources/rules/categories/files_organization/file_extension.ini +68 -0
- sources/rules/categories/files_organization/fixtures/program +0 -0
- sources/rules/categories/files_organization/naming_files_and_folders.ini +74 -0
- sources/rules/categories/functions/coherence_of_functions.ini +45 -0
- sources/rules/categories/functions/comments_inside_a_function.ini +45 -0
- sources/rules/categories/functions/functions_without_parameters.ini +39 -0
- sources/rules/categories/functions/naming_functions.ini +79 -0
- sources/rules/categories/functions/number_of_columns.ini +61 -0
- sources/rules/categories/functions/number_of_lines.ini +70 -0
- sources/rules/categories/functions/number_of_parameters.ini +64 -0
- sources/rules/categories/functions/structures_as_parameters.ini +44 -0
- sources/rules/categories/global_scope/constant_values.ini +49 -0
- sources/rules/categories/global_scope/file_header.ini +92 -0
- sources/rules/categories/global_scope/global_variables.ini +53 -0
- sources/rules/categories/global_scope/include.ini +39 -0
- sources/rules/categories/global_scope/indentation_of_preprocessor.ini +62 -0
- sources/rules/categories/global_scope/inline_assembly.ini +43 -0
- sources/rules/categories/global_scope/leading_trailing_lines.ini +58 -0
- sources/rules/categories/global_scope/line_endings.ini +53 -0
- sources/rules/categories/global_scope/separation_of_functions.ini +61 -0
- sources/rules/categories/global_scope/trailing_spaces.ini +45 -0
- sources/rules/categories/header_files/content.ini +104 -0
- sources/rules/categories/header_files/include_guard.ini +47 -0
- sources/rules/categories/header_files/macros.ini +57 -0
- sources/rules/categories/layout_inside_a_function_scope/blank_lines.ini +71 -0
- sources/rules/categories/layout_inside_a_function_scope/code_line_content.ini +112 -0
- sources/rules/categories/layout_inside_a_function_scope/curly_brackets.ini +94 -0
- sources/rules/categories/layout_inside_a_function_scope/indentation.ini +96 -0
- sources/rules/categories/layout_inside_a_function_scope/spaces.ini +113 -0
- sources/rules/categories/layout_inside_a_function_scope/variable_declarations.ini +65 -0
- sources/rules/categories/variables_and_types/naming_identifiers.ini +74 -0
- sources/rules/categories/variables_and_types/pointers.ini +67 -0
- sources/rules/categories/variables_and_types/structures.ini +47 -0
- sources/rules/data/verbs.txt +182 -0
- sources/rules/definition.py +430 -0
- sources/rules/loader.py +925 -0
- sources/rules/paths.py +6 -0
- sources/rules/primitives/__init__.py +0 -0
- sources/rules/primitives/base.py +297 -0
- sources/rules/primitives/braces.py +211 -0
- sources/rules/primitives/directives.py +203 -0
- sources/rules/primitives/indentation.py +376 -0
- sources/rules/primitives/layout.py +199 -0
- sources/rules/primitives/naming.py +277 -0
- sources/rules/primitives/project.py +62 -0
- sources/rules/primitives/registry.py +49 -0
- sources/rules/primitives/repository.py +129 -0
- sources/rules/primitives/review.py +87 -0
- sources/rules/primitives/semantic.py +319 -0
- sources/rules/primitives/spacing.py +210 -0
- sources/rules/primitives/structure.py +586 -0
- sources/rules/primitives/syntax.py +200 -0
- sources/rules/primitives/text.py +408 -0
- sources/rules/primitives/tokens.py +84 -0
- sources/rules/template.py +138 -0
- sources/selftest/__init__.py +0 -0
- sources/selftest/cases.py +292 -0
- sources/services.py +90 -0
- sources/subcommands/__init__.py +0 -0
- sources/subcommands/base.py +45 -0
- sources/subcommands/check/__init__.py +0 -0
- sources/subcommands/check/command.py +45 -0
- sources/subcommands/check/fixing.py +224 -0
- sources/subcommands/check/handler.py +757 -0
- sources/subcommands/info/__init__.py +0 -0
- sources/subcommands/info/command.py +45 -0
- sources/subcommands/info/handler.py +527 -0
- sources/subcommands/registry.py +37 -0
- sources/subcommands/rule/__init__.py +0 -0
- sources/subcommands/rule/command.py +45 -0
- sources/subcommands/rule/handler.py +1067 -0
- sources/subcommands/rule/render.py +273 -0
- sources/subcommands/runner.py +124 -0
- sources/subcommands/test/__init__.py +0 -0
- sources/subcommands/test/command.py +45 -0
- sources/subcommands/test/handler.py +166 -0
- sources/subcommands/test/render.py +219 -0
- sources/subcommands/test/runner.py +430 -0
- sources/subcommands/update/__init__.py +0 -0
- sources/subcommands/update/command.py +45 -0
- sources/subcommands/update/handler.py +408 -0
- sources/utils/__init__.py +0 -0
- sources/utils/build_info.py +188 -0
- sources/utils/git.py +73 -0
- sources/utils/globs.py +98 -0
- sources/utils/logging.py +154 -0
- sources/utils/schema.py +77 -0
- sources/utils/versions.py +87 -0
sources/application.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import traceback
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
from typing import NoReturn
|
|
5
|
+
|
|
6
|
+
from sources.cli.parser import ArgumentParser
|
|
7
|
+
from sources.constants import PROGRAM_NAME, ROOT_COMMAND
|
|
8
|
+
from sources.enums import ExitCode
|
|
9
|
+
from sources.errors.exceptions import JccsError
|
|
10
|
+
from sources.services import Services
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
# Environment variable that makes internal errors print their Python traceback.
|
|
14
|
+
DEBUG_VARIABLE: str = "JCCS_DEBUG"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _error_parts(error: JccsError) -> tuple[str, str | None]:
|
|
18
|
+
"""
|
|
19
|
+
Description and hint of an error (JccsError stores them joined by a newline).
|
|
20
|
+
|
|
21
|
+
Parameters
|
|
22
|
+
----------
|
|
23
|
+
error : JccsError
|
|
24
|
+
The error.
|
|
25
|
+
|
|
26
|
+
Returns
|
|
27
|
+
----------
|
|
28
|
+
tuple[str, str | None]
|
|
29
|
+
The description and the hint.
|
|
30
|
+
"""
|
|
31
|
+
message: str = str(getattr(error, "message", "") or (error.args[0] if error.args else ""))
|
|
32
|
+
hint: str | None = error.hint
|
|
33
|
+
if hint and message.endswith("\n" + hint):
|
|
34
|
+
message = message[:-len(hint) - 1]
|
|
35
|
+
return message, hint
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def report_error(services: Services, error: JccsError) -> None:
|
|
39
|
+
"""
|
|
40
|
+
Print an error the way the CLI contract says (plan 02, section 8): `jccs: error: <message>`, then an
|
|
41
|
+
optional `hint:` line, on stderr.
|
|
42
|
+
|
|
43
|
+
Parameters
|
|
44
|
+
----------
|
|
45
|
+
services : Services
|
|
46
|
+
Process seams.
|
|
47
|
+
error : JccsError
|
|
48
|
+
The error.
|
|
49
|
+
|
|
50
|
+
Returns
|
|
51
|
+
----------
|
|
52
|
+
None
|
|
53
|
+
Nothing.
|
|
54
|
+
"""
|
|
55
|
+
from sources.outputs.terminal.style import Style
|
|
56
|
+
|
|
57
|
+
style: Style = Style(services.color_enabled(services.stderr))
|
|
58
|
+
message, hint = _error_parts(error)
|
|
59
|
+
services.stderr.write(f"{PROGRAM_NAME}: {style.error('error')}: {message}\n")
|
|
60
|
+
if hint:
|
|
61
|
+
for line in hint.split("\n"):
|
|
62
|
+
services.stderr.write(f"{style.notice('hint')}: {line}\n")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def main(argv: Sequence[str] | None = None, services: Services | None = None) -> int:
|
|
66
|
+
"""
|
|
67
|
+
Process entry point: parse the command line, dispatch it, and turn every error into its exit code. This
|
|
68
|
+
is the only place that translates exceptions (plan 01, ARCH-05); nothing below it prints errors or exits.
|
|
69
|
+
|
|
70
|
+
Parameters
|
|
71
|
+
----------
|
|
72
|
+
argv : Sequence[str] | None
|
|
73
|
+
Command-line arguments without the program name (default: sys.argv[1:]).
|
|
74
|
+
services : Services | None
|
|
75
|
+
Process seams (default: the real process).
|
|
76
|
+
|
|
77
|
+
Returns
|
|
78
|
+
----------
|
|
79
|
+
int
|
|
80
|
+
The exit code.
|
|
81
|
+
"""
|
|
82
|
+
services = services or Services.from_process()
|
|
83
|
+
tokens: Sequence[str] = sys.argv[1:] if argv is None else argv
|
|
84
|
+
try:
|
|
85
|
+
from sources.subcommands.runner import dispatch
|
|
86
|
+
|
|
87
|
+
return int(dispatch(ArgumentParser(ROOT_COMMAND).parse(tokens), services))
|
|
88
|
+
except JccsError as error:
|
|
89
|
+
report_error(services, error)
|
|
90
|
+
return int(error.exit_code)
|
|
91
|
+
except KeyboardInterrupt:
|
|
92
|
+
services.stderr.write(f"{PROGRAM_NAME}: interrupted\n")
|
|
93
|
+
return int(ExitCode.INTERRUPTED)
|
|
94
|
+
except Exception as error:
|
|
95
|
+
services.stderr.write(f"{PROGRAM_NAME}: internal error: {type(error).__name__}: {error}\n")
|
|
96
|
+
if services.env.get(DEBUG_VARIABLE):
|
|
97
|
+
services.stderr.write(traceback.format_exc())
|
|
98
|
+
else:
|
|
99
|
+
services.stderr.write(f"hint: set {DEBUG_VARIABLE}=1 to print the traceback, and please report the issue.\n")
|
|
100
|
+
return int(ExitCode.INTERNAL)
|
|
101
|
+
finally:
|
|
102
|
+
try:
|
|
103
|
+
services.stdout.flush()
|
|
104
|
+
services.stderr.flush()
|
|
105
|
+
except (OSError, ValueError):
|
|
106
|
+
pass
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def run() -> NoReturn:
|
|
110
|
+
"""
|
|
111
|
+
Run JCCS as a process: the single place that calls sys.exit.
|
|
112
|
+
|
|
113
|
+
Returns
|
|
114
|
+
----------
|
|
115
|
+
NoReturn
|
|
116
|
+
Never returns.
|
|
117
|
+
"""
|
|
118
|
+
sys.exit(main())
|
sources/build_info.json
ADDED
sources/cli/__init__.py
ADDED
|
File without changes
|
sources/cli/arguments.py
ADDED
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from collections.abc import Callable, Iterator, Mapping
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from enum import Enum
|
|
7
|
+
from types import MappingProxyType
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from sources.enums import RepeatPolicy
|
|
11
|
+
from sources.errors.exceptions import FlagDefinitionError, ValueConversionError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
# Callable turning one raw command-line string into a typed value; must raise ValueError or TypeError on bad input.
|
|
15
|
+
type Converter = Callable[[str], Any]
|
|
16
|
+
|
|
17
|
+
# Valid short flag token: one dash followed by one letter or digit (e.g. "-o").
|
|
18
|
+
SHORT_FLAG_PATTERN: re.Pattern[str] = re.compile(r"-[A-Za-z0-9]")
|
|
19
|
+
|
|
20
|
+
# Valid long flag token: two dashes followed by a lowercase kebab-case word (e.g. "--no-color").
|
|
21
|
+
LONG_FLAG_PATTERN: re.Pattern[str] = re.compile(r"--[a-z0-9][a-z0-9-]*")
|
|
22
|
+
|
|
23
|
+
# Valid flag identifier used in code and in results: lowercase snake_case (e.g. "no_color").
|
|
24
|
+
FLAG_NAME_PATTERN: re.Pattern[str] = re.compile(r"[a-z][a-z0-9_]*")
|
|
25
|
+
|
|
26
|
+
# Valid command name as typed on the command line: lowercase kebab-case (e.g. "check").
|
|
27
|
+
COMMAND_NAME_PATTERN: re.Pattern[str] = re.compile(r"[a-z][a-z0-9-]*")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class ValueSpec:
|
|
32
|
+
"""
|
|
33
|
+
Definition of one value taken by a flag.
|
|
34
|
+
(dataclass)
|
|
35
|
+
|
|
36
|
+
Attributes
|
|
37
|
+
----------
|
|
38
|
+
metavar : str
|
|
39
|
+
Name of the value shown in usage and errors, e.g. "path" for "<path>".
|
|
40
|
+
converter : Converter
|
|
41
|
+
Callable converting the raw string; an Enum subclass is accepted and its values become the choices.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
metavar: str
|
|
45
|
+
converter: Converter = str
|
|
46
|
+
|
|
47
|
+
def __post_init__(self) -> None:
|
|
48
|
+
"""
|
|
49
|
+
Validate the definition.
|
|
50
|
+
|
|
51
|
+
Returns
|
|
52
|
+
----------
|
|
53
|
+
None
|
|
54
|
+
Nothing.
|
|
55
|
+
|
|
56
|
+
Raises
|
|
57
|
+
----------
|
|
58
|
+
FlagDefinitionError
|
|
59
|
+
The metavar is empty or the converter is not callable.
|
|
60
|
+
"""
|
|
61
|
+
if not self.metavar:
|
|
62
|
+
raise FlagDefinitionError("A flag value must have a non-empty metavar.")
|
|
63
|
+
if not callable(self.converter):
|
|
64
|
+
raise FlagDefinitionError(f"Converter of value <{self.metavar}> is not callable.")
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def choices(self) -> tuple[str, ...] | None:
|
|
68
|
+
"""
|
|
69
|
+
Accepted raw values when the converter is an Enum subclass.
|
|
70
|
+
|
|
71
|
+
Returns
|
|
72
|
+
----------
|
|
73
|
+
tuple[str, ...] | None
|
|
74
|
+
The accepted values, or None when any value may be accepted.
|
|
75
|
+
"""
|
|
76
|
+
if isinstance(self.converter, type) and issubclass(self.converter, Enum):
|
|
77
|
+
return tuple(str(member.value) for member in self.converter)
|
|
78
|
+
return None
|
|
79
|
+
|
|
80
|
+
def display(self) -> str:
|
|
81
|
+
"""
|
|
82
|
+
Render the value for usage lines, e.g. "<path>" or "<text|json>".
|
|
83
|
+
|
|
84
|
+
Returns
|
|
85
|
+
----------
|
|
86
|
+
str
|
|
87
|
+
The rendered value.
|
|
88
|
+
"""
|
|
89
|
+
choices: tuple[str, ...] | None = self.choices
|
|
90
|
+
if choices:
|
|
91
|
+
return "<" + "|".join(choices) + ">"
|
|
92
|
+
return f"<{self.metavar}>"
|
|
93
|
+
|
|
94
|
+
def convert(self, raw: str) -> Any:
|
|
95
|
+
"""
|
|
96
|
+
Convert one raw string with the converter. Converters should raise ValueConversionError;
|
|
97
|
+
plain ValueError/TypeError (e.g. from `int` or an Enum) are normalised into it.
|
|
98
|
+
|
|
99
|
+
Parameters
|
|
100
|
+
----------
|
|
101
|
+
raw : str
|
|
102
|
+
The value as typed by the user.
|
|
103
|
+
|
|
104
|
+
Returns
|
|
105
|
+
----------
|
|
106
|
+
Any
|
|
107
|
+
The converted value.
|
|
108
|
+
|
|
109
|
+
Raises
|
|
110
|
+
----------
|
|
111
|
+
ValueConversionError
|
|
112
|
+
The converter rejected the value.
|
|
113
|
+
"""
|
|
114
|
+
try:
|
|
115
|
+
return self.converter(raw)
|
|
116
|
+
except (ValueError, TypeError) as error:
|
|
117
|
+
raise ValueConversionError(str(error), raw) from error
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@dataclass(frozen=True, slots=True)
|
|
121
|
+
class FlagSpec:
|
|
122
|
+
"""
|
|
123
|
+
Definition of one command-line flag. Pure data: it never parses anything by itself.
|
|
124
|
+
|
|
125
|
+
Value shape returned by the parser when the flag is called:
|
|
126
|
+
switch (no values) -> True
|
|
127
|
+
1 value -> the converted value
|
|
128
|
+
n values -> tuple of n converted values
|
|
129
|
+
variadic, 1 value per group -> tuple of converted values
|
|
130
|
+
variadic, n values per group -> tuple of n-tuples
|
|
131
|
+
RepeatPolicy.ACCUMULATE -> tuple of the above, one per occurrence (variadic ones are flattened)
|
|
132
|
+
(dataclass)
|
|
133
|
+
|
|
134
|
+
Attributes
|
|
135
|
+
----------
|
|
136
|
+
name : str
|
|
137
|
+
Identifier used in code and in parse results (snake_case, unique within its command).
|
|
138
|
+
description : str
|
|
139
|
+
One-line description used by help output.
|
|
140
|
+
short : str | None
|
|
141
|
+
Short token, e.g. "-o".
|
|
142
|
+
long : str | None
|
|
143
|
+
Long token, e.g. "--output".
|
|
144
|
+
values : tuple[ValueSpec, ...]
|
|
145
|
+
Values taken by one occurrence (or by one group when variadic); empty for a switch.
|
|
146
|
+
variadic : bool
|
|
147
|
+
Whether the group of values may repeat one or more times after a single flag token.
|
|
148
|
+
repeat : RepeatPolicy
|
|
149
|
+
Behaviour when the flag appears several times.
|
|
150
|
+
default : Any
|
|
151
|
+
Value reported when the flag is not called (switches always default to False).
|
|
152
|
+
inherited : bool
|
|
153
|
+
Whether subcommands also accept this flag (e.g. "--no-color" given after the subcommand).
|
|
154
|
+
conflicts : tuple[str, ...]
|
|
155
|
+
Names of flags that cannot be called together with this one.
|
|
156
|
+
requires : tuple[str, ...]
|
|
157
|
+
Names of flags that must also be called when this one is.
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
name: str
|
|
161
|
+
description: str
|
|
162
|
+
short: str | None = None
|
|
163
|
+
long: str | None = None
|
|
164
|
+
values: tuple[ValueSpec, ...] = ()
|
|
165
|
+
variadic: bool = False
|
|
166
|
+
repeat: RepeatPolicy = RepeatPolicy.FORBID
|
|
167
|
+
default: Any = None
|
|
168
|
+
inherited: bool = False
|
|
169
|
+
conflicts: tuple[str, ...] = ()
|
|
170
|
+
requires: tuple[str, ...] = ()
|
|
171
|
+
|
|
172
|
+
def __post_init__(self) -> None:
|
|
173
|
+
"""
|
|
174
|
+
Validate the definition.
|
|
175
|
+
|
|
176
|
+
Returns
|
|
177
|
+
----------
|
|
178
|
+
None
|
|
179
|
+
Nothing.
|
|
180
|
+
|
|
181
|
+
Raises
|
|
182
|
+
----------
|
|
183
|
+
FlagDefinitionError
|
|
184
|
+
The definition is inconsistent (see messages).
|
|
185
|
+
"""
|
|
186
|
+
if not FLAG_NAME_PATTERN.fullmatch(self.name):
|
|
187
|
+
raise FlagDefinitionError(f"Invalid flag name '{self.name}': expected snake_case.")
|
|
188
|
+
if not self.description:
|
|
189
|
+
raise FlagDefinitionError(f"Flag '{self.name}' has no description.")
|
|
190
|
+
if self.short is None and self.long is None:
|
|
191
|
+
raise FlagDefinitionError(f"Flag '{self.name}' needs a short or a long token.")
|
|
192
|
+
if self.short is not None and not SHORT_FLAG_PATTERN.fullmatch(self.short):
|
|
193
|
+
raise FlagDefinitionError(f"Invalid short token '{self.short}' for flag '{self.name}'.")
|
|
194
|
+
if self.long is not None and not LONG_FLAG_PATTERN.fullmatch(self.long):
|
|
195
|
+
raise FlagDefinitionError(f"Invalid long token '{self.long}' for flag '{self.name}'.")
|
|
196
|
+
if self.variadic and not self.values:
|
|
197
|
+
raise FlagDefinitionError(f"Variadic flag '{self.name}' must declare at least one value.")
|
|
198
|
+
if self.is_switch and self.repeat is RepeatPolicy.ACCUMULATE:
|
|
199
|
+
raise FlagDefinitionError(f"Switch '{self.name}' cannot accumulate; use LAST_WINS and read the count.")
|
|
200
|
+
if self.is_switch and self.default is not None:
|
|
201
|
+
raise FlagDefinitionError(f"Switch '{self.name}' cannot have a default (it is always False).")
|
|
202
|
+
if self.name in self.conflicts or self.name in self.requires:
|
|
203
|
+
raise FlagDefinitionError(f"Flag '{self.name}' cannot conflict with or require itself.")
|
|
204
|
+
overlap: set[str] = set(self.conflicts) & set(self.requires)
|
|
205
|
+
if overlap:
|
|
206
|
+
raise FlagDefinitionError(f"Flag '{self.name}' both conflicts with and requires {sorted(overlap)}.")
|
|
207
|
+
|
|
208
|
+
@property
|
|
209
|
+
def is_switch(self) -> bool:
|
|
210
|
+
"""
|
|
211
|
+
Whether the flag takes no value.
|
|
212
|
+
|
|
213
|
+
Returns
|
|
214
|
+
----------
|
|
215
|
+
bool
|
|
216
|
+
True for a switch.
|
|
217
|
+
"""
|
|
218
|
+
return not self.values
|
|
219
|
+
|
|
220
|
+
@property
|
|
221
|
+
def arity(self) -> int:
|
|
222
|
+
"""
|
|
223
|
+
Number of values taken by one occurrence (or by one group when variadic).
|
|
224
|
+
|
|
225
|
+
Returns
|
|
226
|
+
----------
|
|
227
|
+
int
|
|
228
|
+
The number of values.
|
|
229
|
+
"""
|
|
230
|
+
return len(self.values)
|
|
231
|
+
|
|
232
|
+
@property
|
|
233
|
+
def tokens(self) -> tuple[str, ...]:
|
|
234
|
+
"""
|
|
235
|
+
Every token that calls the flag, short first.
|
|
236
|
+
|
|
237
|
+
Returns
|
|
238
|
+
----------
|
|
239
|
+
tuple[str, ...]
|
|
240
|
+
The tokens.
|
|
241
|
+
"""
|
|
242
|
+
return tuple(token for token in (self.short, self.long) if token is not None)
|
|
243
|
+
|
|
244
|
+
@property
|
|
245
|
+
def display_name(self) -> str:
|
|
246
|
+
"""
|
|
247
|
+
Preferred token to show in messages (long when available).
|
|
248
|
+
|
|
249
|
+
Returns
|
|
250
|
+
----------
|
|
251
|
+
str
|
|
252
|
+
The token.
|
|
253
|
+
"""
|
|
254
|
+
return self.long if self.long is not None else str(self.short)
|
|
255
|
+
|
|
256
|
+
@property
|
|
257
|
+
def default_value(self) -> Any:
|
|
258
|
+
"""
|
|
259
|
+
Value reported when the flag is not called.
|
|
260
|
+
|
|
261
|
+
Returns
|
|
262
|
+
----------
|
|
263
|
+
Any
|
|
264
|
+
False for a switch, the declared default otherwise.
|
|
265
|
+
"""
|
|
266
|
+
return False if self.is_switch else self.default
|
|
267
|
+
|
|
268
|
+
def usage(self) -> str:
|
|
269
|
+
"""
|
|
270
|
+
Render the usage line of the flag, e.g. "-R, --only <category> <rule> ...".
|
|
271
|
+
|
|
272
|
+
Returns
|
|
273
|
+
----------
|
|
274
|
+
str
|
|
275
|
+
The usage line.
|
|
276
|
+
"""
|
|
277
|
+
parts: list[str] = [", ".join(self.tokens)]
|
|
278
|
+
parts.extend(value.display() for value in self.values)
|
|
279
|
+
if self.variadic:
|
|
280
|
+
parts.append("...")
|
|
281
|
+
return " ".join(parts)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
@dataclass(frozen=True, slots=True)
|
|
285
|
+
class CommandSpec:
|
|
286
|
+
"""
|
|
287
|
+
Definition of a command: its flags and its subcommands. The program itself is the root command.
|
|
288
|
+
(dataclass)
|
|
289
|
+
|
|
290
|
+
Attributes
|
|
291
|
+
----------
|
|
292
|
+
name : str
|
|
293
|
+
Command name as typed on the command line (the program name for the root).
|
|
294
|
+
description : str
|
|
295
|
+
One-line description used by help output.
|
|
296
|
+
flags : tuple[FlagSpec, ...]
|
|
297
|
+
Flags owned by the command.
|
|
298
|
+
subcommands : tuple[CommandSpec, ...]
|
|
299
|
+
Nested commands; at most one of them is selected per level.
|
|
300
|
+
exclusive_groups : tuple[tuple[str, ...], ...]
|
|
301
|
+
Groups of flag names of which at most one may be called.
|
|
302
|
+
operands : ValueSpec | None
|
|
303
|
+
Positional arguments taken by the command (any number of them, each converted by this spec), or None
|
|
304
|
+
when the command takes none. A command cannot have both operands and subcommands.
|
|
305
|
+
"""
|
|
306
|
+
|
|
307
|
+
name: str
|
|
308
|
+
description: str
|
|
309
|
+
flags: tuple[FlagSpec, ...] = ()
|
|
310
|
+
subcommands: tuple[CommandSpec, ...] = ()
|
|
311
|
+
exclusive_groups: tuple[tuple[str, ...], ...] = ()
|
|
312
|
+
operands: ValueSpec | None = None
|
|
313
|
+
_flags_by_name: Mapping[str, FlagSpec] = field(init=False, repr=False, compare=False)
|
|
314
|
+
_flags_by_token: Mapping[str, FlagSpec] = field(init=False, repr=False, compare=False)
|
|
315
|
+
_subcommands_by_name: Mapping[str, CommandSpec] = field(init=False, repr=False, compare=False)
|
|
316
|
+
|
|
317
|
+
def __post_init__(self) -> None:
|
|
318
|
+
"""
|
|
319
|
+
Validate the definition and build the lookup tables.
|
|
320
|
+
|
|
321
|
+
Returns
|
|
322
|
+
----------
|
|
323
|
+
None
|
|
324
|
+
Nothing.
|
|
325
|
+
|
|
326
|
+
Raises
|
|
327
|
+
----------
|
|
328
|
+
FlagDefinitionError
|
|
329
|
+
Invalid name, duplicate flag name/token, duplicate subcommand, invalid exclusive group, or operands
|
|
330
|
+
together with subcommands.
|
|
331
|
+
"""
|
|
332
|
+
if not COMMAND_NAME_PATTERN.fullmatch(self.name):
|
|
333
|
+
raise FlagDefinitionError(f"Invalid command name '{self.name}': expected kebab-case.")
|
|
334
|
+
if not self.description:
|
|
335
|
+
raise FlagDefinitionError(f"Command '{self.name}' has no description.")
|
|
336
|
+
by_name: dict[str, FlagSpec] = {}
|
|
337
|
+
by_token: dict[str, FlagSpec] = {}
|
|
338
|
+
for flag in self.flags:
|
|
339
|
+
if flag.name in by_name:
|
|
340
|
+
raise FlagDefinitionError(f"Duplicate flag name '{flag.name}' in command '{self.name}'.")
|
|
341
|
+
by_name[flag.name] = flag
|
|
342
|
+
for token in flag.tokens:
|
|
343
|
+
if token in by_token:
|
|
344
|
+
raise FlagDefinitionError(
|
|
345
|
+
f"Token '{token}' used by both '{by_token[token].name}' and '{flag.name}' in '{self.name}'."
|
|
346
|
+
)
|
|
347
|
+
by_token[token] = flag
|
|
348
|
+
subcommands: dict[str, CommandSpec] = {}
|
|
349
|
+
for subcommand in self.subcommands:
|
|
350
|
+
if subcommand.name in subcommands:
|
|
351
|
+
raise FlagDefinitionError(f"Duplicate subcommand '{subcommand.name}' in command '{self.name}'.")
|
|
352
|
+
subcommands[subcommand.name] = subcommand
|
|
353
|
+
for group in self.exclusive_groups:
|
|
354
|
+
if len(group) < 2 or len(set(group)) != len(group):
|
|
355
|
+
raise FlagDefinitionError(f"Invalid exclusive group {group} in command '{self.name}'.")
|
|
356
|
+
if self.operands is not None and self.subcommands:
|
|
357
|
+
raise FlagDefinitionError(f"Command '{self.name}' cannot take both operands and subcommands.")
|
|
358
|
+
object.__setattr__(self, "_flags_by_name", MappingProxyType(by_name))
|
|
359
|
+
object.__setattr__(self, "_flags_by_token", MappingProxyType(by_token))
|
|
360
|
+
object.__setattr__(self, "_subcommands_by_name", MappingProxyType(subcommands))
|
|
361
|
+
|
|
362
|
+
def get_flag(self, name: str) -> FlagSpec | None:
|
|
363
|
+
"""
|
|
364
|
+
Find an owned flag by name.
|
|
365
|
+
|
|
366
|
+
Parameters
|
|
367
|
+
----------
|
|
368
|
+
name : str
|
|
369
|
+
Flag name, e.g. "no_color".
|
|
370
|
+
|
|
371
|
+
Returns
|
|
372
|
+
----------
|
|
373
|
+
FlagSpec | None
|
|
374
|
+
The flag, or None if this command does not own it.
|
|
375
|
+
"""
|
|
376
|
+
return self._flags_by_name.get(name)
|
|
377
|
+
|
|
378
|
+
def find_flag(self, token: str) -> FlagSpec | None:
|
|
379
|
+
"""
|
|
380
|
+
Find an owned flag by token.
|
|
381
|
+
|
|
382
|
+
Parameters
|
|
383
|
+
----------
|
|
384
|
+
token : str
|
|
385
|
+
Flag token, e.g. "-o" or "--output".
|
|
386
|
+
|
|
387
|
+
Returns
|
|
388
|
+
----------
|
|
389
|
+
FlagSpec | None
|
|
390
|
+
The flag, or None if this command does not own it.
|
|
391
|
+
"""
|
|
392
|
+
return self._flags_by_token.get(token)
|
|
393
|
+
|
|
394
|
+
def find_subcommand(self, name: str) -> CommandSpec | None:
|
|
395
|
+
"""
|
|
396
|
+
Find a direct subcommand by name.
|
|
397
|
+
|
|
398
|
+
Parameters
|
|
399
|
+
----------
|
|
400
|
+
name : str
|
|
401
|
+
Subcommand name, e.g. "check".
|
|
402
|
+
|
|
403
|
+
Returns
|
|
404
|
+
----------
|
|
405
|
+
CommandSpec | None
|
|
406
|
+
The subcommand, or None if it does not exist.
|
|
407
|
+
"""
|
|
408
|
+
return self._subcommands_by_name.get(name)
|
|
409
|
+
|
|
410
|
+
@property
|
|
411
|
+
def flag_tokens(self) -> tuple[str, ...]:
|
|
412
|
+
"""
|
|
413
|
+
Every token owned by this command.
|
|
414
|
+
|
|
415
|
+
Returns
|
|
416
|
+
----------
|
|
417
|
+
tuple[str, ...]
|
|
418
|
+
The tokens.
|
|
419
|
+
"""
|
|
420
|
+
return tuple(self._flags_by_token)
|
|
421
|
+
|
|
422
|
+
@property
|
|
423
|
+
def subcommand_names(self) -> tuple[str, ...]:
|
|
424
|
+
"""
|
|
425
|
+
Names of the direct subcommands.
|
|
426
|
+
|
|
427
|
+
Returns
|
|
428
|
+
----------
|
|
429
|
+
tuple[str, ...]
|
|
430
|
+
The names, in definition order.
|
|
431
|
+
"""
|
|
432
|
+
return tuple(self._subcommands_by_name)
|
|
433
|
+
|
|
434
|
+
def walk(self, parents: tuple[CommandSpec, ...] = ()) -> Iterator[tuple[CommandSpec, ...]]:
|
|
435
|
+
"""
|
|
436
|
+
Iterate over this command and all its descendants, depth first.
|
|
437
|
+
|
|
438
|
+
Parameters
|
|
439
|
+
----------
|
|
440
|
+
parents : tuple[CommandSpec, ...]
|
|
441
|
+
Ancestors of this command (used by the recursion).
|
|
442
|
+
|
|
443
|
+
Returns
|
|
444
|
+
----------
|
|
445
|
+
Iterator[tuple[CommandSpec, ...]]
|
|
446
|
+
For each command, its chain from the root (the command itself is last).
|
|
447
|
+
"""
|
|
448
|
+
chain: tuple[CommandSpec, ...] = (*parents, self)
|
|
449
|
+
yield chain
|
|
450
|
+
for subcommand in self.subcommands:
|
|
451
|
+
yield from subcommand.walk(chain)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def resolve_flag_name(chain: tuple[CommandSpec, ...], name: str) -> FlagSpec | None:
|
|
455
|
+
"""
|
|
456
|
+
Resolve a flag name as seen from the last command of a chain: its own flags first,
|
|
457
|
+
then the inherited flags of its ancestors, nearest first.
|
|
458
|
+
|
|
459
|
+
Parameters
|
|
460
|
+
----------
|
|
461
|
+
chain : tuple[CommandSpec, ...]
|
|
462
|
+
Commands from the root to the current one.
|
|
463
|
+
name : str
|
|
464
|
+
Flag name to resolve.
|
|
465
|
+
|
|
466
|
+
Returns
|
|
467
|
+
----------
|
|
468
|
+
FlagSpec | None
|
|
469
|
+
The visible flag, or None if no visible flag has this name.
|
|
470
|
+
"""
|
|
471
|
+
for depth, command in enumerate(reversed(chain)):
|
|
472
|
+
flag: FlagSpec | None = command.get_flag(name)
|
|
473
|
+
if flag is not None and (depth == 0 or flag.inherited):
|
|
474
|
+
return flag
|
|
475
|
+
return None
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def validate_command_tree(root: CommandSpec) -> None:
|
|
479
|
+
"""
|
|
480
|
+
Check cross-command consistency that a single CommandSpec cannot check on its own:
|
|
481
|
+
every name used in `conflicts`, `requires` and `exclusive_groups` must be visible from its command.
|
|
482
|
+
|
|
483
|
+
Parameters
|
|
484
|
+
----------
|
|
485
|
+
root : CommandSpec
|
|
486
|
+
Root of the command tree.
|
|
487
|
+
|
|
488
|
+
Returns
|
|
489
|
+
----------
|
|
490
|
+
None
|
|
491
|
+
Nothing.
|
|
492
|
+
|
|
493
|
+
Raises
|
|
494
|
+
----------
|
|
495
|
+
FlagDefinitionError
|
|
496
|
+
A referenced flag name is not visible from where it is used.
|
|
497
|
+
"""
|
|
498
|
+
for chain in root.walk():
|
|
499
|
+
command: CommandSpec = chain[-1]
|
|
500
|
+
references: list[tuple[str, str]] = []
|
|
501
|
+
for flag in command.flags:
|
|
502
|
+
references.extend((flag.name, name) for name in (*flag.conflicts, *flag.requires))
|
|
503
|
+
for group in command.exclusive_groups:
|
|
504
|
+
references.extend(("exclusive group", name) for name in group)
|
|
505
|
+
for owner, name in references:
|
|
506
|
+
if resolve_flag_name(chain, name) is None:
|
|
507
|
+
raise FlagDefinitionError(f"'{owner}' in command '{command.name}' references unknown flag '{name}'.")
|