Coverage for typer / _click / decorators.py: 100%

26 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-11-18 11:12 +0000

1from collections.abc import Callable 1abcdefghij

2from typing import TYPE_CHECKING, Any, ParamSpec, TypeVar 1abcdefghij

3 

4from .core import Command, Context, Parameter 1abcdefghij

5from .utils import echo 1abcdefghij

6 

7if TYPE_CHECKING: 1abcdefghij

8 from ..core import TyperGroup, TyperOption 

9 

10 GrpType = TypeVar("GrpType", bound=TyperGroup) 

11 

12 

13P = ParamSpec("P") 1abcdefghij

14 

15R = TypeVar("R") 1abcdefghij

16T = TypeVar("T") 1abcdefghij

17_AnyCallable = Callable[..., Any] 1abcdefghij

18 

19 

20CmdType = TypeVar("CmdType", bound=Command) 1abcdefghij

21 

22 

23def option( 1abcdefghij

24 param_decls: list[str], cls: type["TyperOption"] | None = None, **attrs: Any 

25) -> Callable[[Command], Command]: 

26 """Attaches an option to the command.""" 

27 if cls is None: 1abcdefghij

28 # avoid circular imports 

29 from ..core import TyperOption 1abcdefghij

30 

31 cls = TyperOption 1abcdefghij

32 

33 def decorator(f: Command) -> Command: 1abcdefghij

34 param = cls(param_decls=param_decls, **attrs) 1abcdefghij

35 f.params.append(param) 1abcdefghij

36 return f 1abcdefghij

37 

38 return decorator 1abcdefghij

39 

40 

41def help_option(param_decls: list[str]) -> Callable[[Command], Command]: 1abcdefghij

42 """Help option which prints the help page and exits the program.""" 

43 from .._coercion import bool_flag_type_descriptor 1abcdefghij

44 

45 def show_help(ctx: Context, param: Parameter, value: bool) -> None: 1abcdefghij

46 """Callback that print the help page on ``<stdout>`` and exits.""" 

47 if value and not ctx.resilient_parsing: 1abcdefghij

48 echo(ctx.get_help(), color=ctx.color) 1abcdefghij

49 ctx.exit() 1abcdefghij

50 

51 assert len(param_decls) > 0, "At least one help option should be provided" 1abcdefghij

52 

53 return option( 1abcdefghij

54 param_decls, 

55 is_flag=True, 

56 expose_value=False, 

57 is_eager=True, 

58 help="Show this message and exit.", 

59 callback=show_help, 

60 required=False, 

61 type_descriptor=bool_flag_type_descriptor(), 

62 )