Coverage for src/su6/core.py: 100%
214 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-05 12:28 +0200
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-05 12:28 +0200
1"""
2This file contains internal helpers used by cli.py.
3"""
4import enum
5import functools
6import inspect
7import json
8import operator
9import os
10import sys
11import tomllib
12import types
13import typing
14from dataclasses import dataclass, field, replace
16import black.files
17import plumbum.commands.processes as pb
18import typer
19from plumbum import local
20from plumbum.machines import LocalCommand
21from rich import print
22from typeguard import TypeCheckError
23from typeguard import check_type as _check_type
25GREEN_CIRCLE = "🟢"
26YELLOW_CIRCLE = "🟡"
27RED_CIRCLE = "🔴"
29EXIT_CODE_SUCCESS = 0
30EXIT_CODE_ERROR = 1
31EXIT_CODE_COMMAND_NOT_FOUND = 127
33PlumbumError = (pb.ProcessExecutionError, pb.ProcessTimedOut, pb.ProcessLineTimedOut, pb.CommandNotFound)
35# a Command can return these:
36T_Command_Return = bool | int | None
37# ... here indicates any number of args/kwargs:
38# t command is any @app.command() method, which can have anything as input and bool or int as output
39T_Command: typing.TypeAlias = typing.Callable[..., T_Command_Return]
40# t inner wrapper calls t_command and handles its output. This wrapper gets the same (kw)args as above so ... again
41T_Inner_Wrapper: typing.TypeAlias = typing.Callable[..., int | None]
42# outer wrapper gets the t_command method as input and outputs the inner wrapper,
43# so that gets called() with args and kwargs when that method is used from the cli
44T_Outer_Wrapper: typing.TypeAlias = typing.Callable[[T_Command], T_Inner_Wrapper]
47def print_json(data: typing.Any) -> None:
48 """
49 Take a dict of {command: output} or the State and print it.
50 """
51 print(json.dumps(data, default=str))
54def dump_tools_with_results(tools: list[T_Command], results: list[int | bool | None]) -> None:
55 """
56 When using format = json, dump the success of each tool in tools (-> exit code == 0).
58 This method is used in `all` and `fix` (with a list of tools) and in 'with_exit_code' (with one tool).
59 'with_exit_code' does NOT use this method if the return value was a bool, because that's the return value of
60 'all' and 'fix' and those already dump a dict output themselves.
62 Args:
63 tools: list of commands that ran
64 results: list of return values from these commands
65 """
66 print_json({tool.__name__: not result for tool, result in zip(tools, results)})
69def with_exit_code() -> T_Outer_Wrapper:
70 """
71 Convert the return value of an app.command (bool or int) to an typer Exit with return code, \
72 Unless the return value is Falsey, in which case the default exit happens (with exit code 0 indicating success).
74 Usage:
75 > @app.command()
76 > @with_exit_code()
77 def some_command(): ...
79 When calling a command from a different command, _suppress=True can be added to not raise an Exit exception.
80 """
82 def outer_wrapper(func: T_Command) -> T_Inner_Wrapper:
83 @functools.wraps(func)
84 def inner_wrapper(*args: typing.Any, **kwargs: typing.Any) -> int:
85 _suppress = kwargs.pop("_suppress", False)
86 _ignore_exit_codes = kwargs.pop("_ignore", set())
88 result = func(*args, **kwargs)
89 if state.output_format == "json" and not _suppress and result is not None and not isinstance(result, bool):
90 # isinstance(True, int) -> True so not isinstance(result, bool)
91 # print {tool: success}
92 # but only if a retcode is returned,
93 # otherwise (True, False) assume the function handled printing itself.
94 dump_tools_with_results([func], [result])
96 if result is None:
97 # assume no issue then
98 result = 0
100 if (retcode := int(result)) and not _suppress:
101 raise typer.Exit(code=retcode)
103 if retcode in _ignore_exit_codes: # pragma: no cover
104 # there is an error code, but we choose to ignore it -> return 0
105 return EXIT_CODE_SUCCESS
107 return retcode
109 return inner_wrapper
111 return outer_wrapper
114def run_tool(tool: str, *args: str) -> int:
115 """
116 Abstraction to run one of the cli checking tools and process its output.
118 Args:
119 tool: the (bash) name of the tool to run.
120 args: cli args to pass to the cli bash tool
121 """
122 try:
123 cmd = local[tool]
125 if state.verbosity >= 3:
126 log_command(cmd, args)
128 result = cmd(*args)
130 if state.output_format == "text":
131 print(GREEN_CIRCLE, tool)
133 if state.verbosity > 2: # pragma: no cover
134 log_cmd_output(result)
136 return EXIT_CODE_SUCCESS # success
137 except pb.CommandNotFound: # pragma: no cover
138 if state.verbosity > 2:
139 warn(f"Tool {tool} not installed!")
141 if state.output_format == "text":
142 print(YELLOW_CIRCLE, tool)
144 return EXIT_CODE_COMMAND_NOT_FOUND # command not found
145 except pb.ProcessExecutionError as e:
146 if state.output_format == "text":
147 print(RED_CIRCLE, tool)
149 if state.verbosity > 1:
150 log_cmd_output(e.stdout, e.stderr)
151 return EXIT_CODE_ERROR # general error
154class Verbosity(enum.Enum):
155 """
156 Verbosity is used with the --verbose argument of the cli commands.
157 """
159 # typer enum can only be string
160 quiet = "1"
161 normal = "2"
162 verbose = "3"
163 debug = "4" # only for internal use
165 @staticmethod
166 def _compare(
167 self: "Verbosity",
168 other: "Verbosity_Comparable",
169 _operator: typing.Callable[["Verbosity_Comparable", "Verbosity_Comparable"], bool],
170 ) -> bool:
171 """
172 Abstraction using 'operator' to have shared functionality between <, <=, ==, >=, >.
174 This enum can be compared with integers, strings and other Verbosity instances.
176 Args:
177 self: the first Verbosity
178 other: the second Verbosity (or other thing to compare)
179 _operator: a callable operator (from 'operators') that takes two of the same types as input.
180 """
181 match other:
182 case Verbosity():
183 return _operator(self.value, other.value)
184 case int():
185 return _operator(int(self.value), other)
186 case str():
187 return _operator(int(self.value), int(other))
189 def __gt__(self, other: "Verbosity_Comparable") -> bool:
190 """
191 Magic method for self > other.
192 """
193 return self._compare(self, other, operator.gt)
195 def __ge__(self, other: "Verbosity_Comparable") -> bool:
196 """
197 Method magic for self >= other.
198 """
199 return self._compare(self, other, operator.ge)
201 def __lt__(self, other: "Verbosity_Comparable") -> bool:
202 """
203 Magic method for self < other.
204 """
205 return self._compare(self, other, operator.lt)
207 def __le__(self, other: "Verbosity_Comparable") -> bool:
208 """
209 Magic method for self <= other.
210 """
211 return self._compare(self, other, operator.le)
213 def __eq__(self, other: typing.Union["Verbosity", str, int, object]) -> bool:
214 """
215 Magic method for self == other.
217 'eq' is a special case because 'other' MUST be object according to mypy
218 """
219 if other is Ellipsis or other is inspect._empty:
220 # both instances of object; can't use Ellipsis or type(ELlipsis) = ellipsis as a type hint in mypy
221 # special cases where Typer instanciates its cli arguments,
222 # return False or it will crash
223 return False
224 if not isinstance(other, (str, int, Verbosity)):
225 raise TypeError(f"Object of type {type(other)} can not be compared with Verbosity")
226 return self._compare(self, other, operator.eq)
228 def __hash__(self) -> int:
229 """
230 Magic method for `hash(self)`, also required for Typer to work.
231 """
232 return hash(self.value)
235Verbosity_Comparable = Verbosity | str | int
237DEFAULT_VERBOSITY = Verbosity.normal
240class Format(enum.Enum):
241 """
242 Options for su6 --format.
243 """
245 text = "text"
246 json = "json"
248 def __eq__(self, other: object) -> bool:
249 """
250 Magic method for self == other.
252 'eq' is a special case because 'other' MUST be object according to mypy
253 """
254 if other is Ellipsis or other is inspect._empty:
255 # both instances of object; can't use Ellipsis or type(ELlipsis) = ellipsis as a type hint in mypy
256 # special cases where Typer instanciates its cli arguments,
257 # return False or it will crash
258 return False
259 return self.value == other
261 def __hash__(self) -> int:
262 """
263 Magic method for `hash(self)`, also required for Typer to work.
264 """
265 return hash(self.value)
268DEFAULT_FORMAT = Format.text
270C = typing.TypeVar("C", bound=T_Command)
272DEFAULT_BADGE = "coverage.svg"
275@dataclass
276class Config:
277 """
278 Used as typed version of the [tool.su6] part of pyproject.toml.
280 Also accessible via state.config
281 """
283 directory: str = "."
284 pyproject: str = "pyproject.toml"
285 include: list[str] = field(default_factory=list)
286 exclude: list[str] = field(default_factory=list)
287 stop_after_first_failure: bool = False
289 ### pytest ###
290 coverage: typing.Optional[float] = None # only relevant for pytest
291 badge: bool | str = False # only relevant for pytest
293 def __post_init__(self) -> None:
294 """
295 Update the value of badge to the default path.
296 """
297 if self.badge is True: # pragma: no cover
298 # no cover because pytest can't test pytest :C
299 self.badge = DEFAULT_BADGE
301 def determine_which_to_run(self, options: list[C]) -> list[C]:
302 """
303 Filter out any includes/excludes from pyproject.toml (first check include, then exclude).
304 """
305 if self.include:
306 tools = [_ for _ in options if _.__name__ in self.include]
307 tools.sort(key=lambda f: self.include.index(f.__name__))
308 return tools
309 elif self.exclude:
310 return [_ for _ in options if _.__name__ not in self.exclude]
311 # if no include or excludes passed, just run all!
312 return options
315MaybeConfig: typing.TypeAlias = typing.Optional[Config]
317T_typelike: typing.TypeAlias = type | types.UnionType | types.UnionType
320def check_type(value: typing.Any, expected_type: T_typelike) -> bool:
321 """
322 Given a variable, check if it matches 'expected_type' (which can be a Union, parameterized generic etc.).
324 Based on typeguard but this returns a boolean instead of returning the value or throwing a TypeCheckError
325 """
326 try:
327 _check_type(value, expected_type)
328 return True
329 except TypeCheckError:
330 return False
333@dataclass
334class ConfigError(Exception):
335 """
336 Raised if pyproject.toml [su6.tool] contains a variable of \
337 which the type does not match that of the corresponding key in Config.
338 """
340 key: str
341 value: typing.Any
342 expected_type: type
344 def __post_init__(self) -> None:
345 """
346 Store the actual type of the config variable.
347 """
348 self.actual_type = type(self.value)
350 def __str__(self) -> str:
351 """
352 Custom error message based on dataclass values and calculated actual type.
353 """
354 return (
355 f"Config key '{self.key}' had a value ('{self.value}') with a type (`{self.actual_type}`) "
356 f"that was not expected: `{self.expected_type}` is the required type."
357 )
360T = typing.TypeVar("T")
363def _ensure_types(data: dict[str, T], annotations: dict[str, type]) -> dict[str, T | None]:
364 """
365 Make sure all values in 'data' are in line with the ones stored in 'annotations'.
367 If an annotated key in missing from data, it will be filled with None for convenience.
368 """
369 final: dict[str, T | None] = {}
370 for key, _type in annotations.items():
371 compare = data.get(key)
372 if compare is None:
373 # skip!
374 continue
375 if not check_type(compare, _type):
376 raise ConfigError(key, value=compare, expected_type=_type)
378 final[key] = compare
379 return final
382def _convert_config(items: dict[str, T]) -> dict[str, T]:
383 """
384 Converts the config dict (from toml) or 'overwrites' dict in two ways.
386 1. removes any items where the value is None, since in that case the default should be used;
387 2. replaces '-' in keys with '_' so it can be mapped to the Config properties.
388 """
389 return {k.replace("-", "_"): v for k, v in items.items() if v is not None}
392def _get_su6_config(overwrites: dict[str, typing.Any], toml_path: str = None) -> MaybeConfig:
393 """
394 Parse the users pyproject.toml (found using black's logic) and extract the tool.su6 part.
396 The types as entered in the toml are checked using _ensure_types,
397 to make sure there isn't a string implicitly converted to a list of characters or something.
399 Args:
400 overwrites: cli arguments can overwrite the config toml.
401 toml_path: by default, black will search for a relevant pyproject.toml.
402 If a toml_path is provided, that file will be used instead.
403 """
404 if toml_path is None:
405 toml_path = black.files.find_pyproject_toml((os.getcwd(),))
407 if not toml_path:
408 return None
410 with open(toml_path, "rb") as f:
411 full_config = tomllib.load(f)
413 su6_config_dict = full_config["tool"]["su6"]
414 su6_config_dict |= overwrites
416 su6_config_dict["pyproject"] = toml_path
417 # first convert the keys, then ensure types. Otherwise, non-matching keys may be removed!
418 su6_config_dict = _convert_config(su6_config_dict)
419 su6_config_dict = _ensure_types(su6_config_dict, Config.__annotations__)
421 return Config(**su6_config_dict)
424def get_su6_config(verbosity: Verbosity = DEFAULT_VERBOSITY, toml_path: str = None, **overwrites: typing.Any) -> Config:
425 """
426 Load the relevant pyproject.toml config settings.
428 Args:
429 verbosity: if something goes wrong, level 3+ will show a warning and 4+ will raise the exception.
430 toml_path: --config can be used to use a different file than ./pyproject.toml
431 overwrites (dict[str, typing.Any): cli arguments can overwrite the config toml.
432 If a value is None, the key is not overwritten.
433 """
434 # strip out any 'overwrites' with None as value
435 overwrites = _convert_config(overwrites)
437 try:
438 if config := _get_su6_config(overwrites, toml_path=toml_path):
439 return config
440 raise ValueError("Falsey config?")
441 except Exception as e:
442 # something went wrong parsing config, use defaults
443 if verbosity > 3:
444 # verbosity = debug
445 raise e
446 elif verbosity > 2:
447 # verbosity = verbose
448 print("Error parsing pyproject.toml, falling back to defaults.", file=sys.stderr)
449 return Config(**overwrites)
452def info(*args: str) -> None:
453 """
454 'print' but with blue text.
455 """
456 print(f"[blue]{' '.join(args)}[/blue]", file=sys.stderr)
459def warn(*args: str) -> None:
460 """
461 'print' but with yellow text.
462 """
463 print(f"[yellow]{' '.join(args)}[/yellow]", file=sys.stderr)
466def danger(*args: str) -> None:
467 """
468 'print' but with red text.
469 """
470 print(f"[red]{' '.join(args)}[/red]", file=sys.stderr)
473def log_command(command: LocalCommand, args: typing.Iterable[str]) -> None:
474 """
475 Print a Plumbum command in blue, prefixed with > to indicate it's a shell command.
476 """
477 info(f"> {command[*args]}")
480def log_cmd_output(stdout: str = "", stderr: str = "") -> None:
481 """
482 Print stdout in yellow and stderr in red.
483 """
484 # if you are logging stdout, it's probably because it's not a successful run.
485 # However, it's not stderr so we make it warning-yellow
486 warn(stdout)
487 # probably more important error stuff, so stderr goes last:
488 danger(stderr)
491@dataclass()
492class ApplicationState:
493 """
494 Application State - global user defined variables.
496 State contains generic variables passed BEFORE the subcommand (so --verbosity, --config, ...),
497 whereas Config contains settings from the config toml file, updated with arguments AFTER the subcommand
498 (e.g. su6 subcommand <directory> --flag), directory and flag will be updated in the config and not the state.
500 To summarize: 'state' is applicable to all commands and config only to specific ones.
501 """
503 verbosity: Verbosity = DEFAULT_VERBOSITY
504 output_format: Format = DEFAULT_FORMAT
505 config_file: typing.Optional[str] = None # will be filled with black's search logic
506 config: MaybeConfig = None
508 def load_config(self, **overwrites: typing.Any) -> Config:
509 """
510 Load the su6 config from pyproject.toml (or other config_file) with optional overwriting settings.
511 """
512 if "verbosity" in overwrites:
513 self.verbosity = overwrites["verbosity"]
514 if "config_file" in overwrites:
515 self.config_file = overwrites.pop("config_file")
516 if "output_format" in overwrites:
517 self.output_format = overwrites.pop("output_format")
519 self.config = get_su6_config(toml_path=self.config_file, **overwrites)
520 return self.config
522 def update_config(self, **values: typing.Any) -> Config:
523 """
524 Overwrite default/toml settings with cli values.
526 Example:
527 `config = state.update_config(directory='src')`
528 This will update the state's config and return the same object with the updated settings.
529 """
530 existing_config = self.load_config() if self.config is None else self.config
532 values = _convert_config(values)
533 # replace is dataclass' update function
534 self.config = replace(existing_config, **values)
535 return self.config
538state = ApplicationState()