techprotrade commited on
Commit
8de2ea3
·
verified ·
1 Parent(s): 0d24195

Add loan-advisor-agent

Browse files
loan-advisor-agent/.venv/Lib/site-packages/typer/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Typer, build great CLIs. Easy to code. Based on Python type hints."""
2
+
3
+ __version__ = "0.24.1"
4
+
5
+ from shutil import get_terminal_size as get_terminal_size
6
+
7
+ from click.exceptions import Abort as Abort
8
+ from click.exceptions import BadParameter as BadParameter
9
+ from click.exceptions import Exit as Exit
10
+ from click.termui import clear as clear
11
+ from click.termui import confirm as confirm
12
+ from click.termui import echo_via_pager as echo_via_pager
13
+ from click.termui import edit as edit
14
+ from click.termui import getchar as getchar
15
+ from click.termui import pause as pause
16
+ from click.termui import progressbar as progressbar
17
+ from click.termui import prompt as prompt
18
+ from click.termui import secho as secho
19
+ from click.termui import style as style
20
+ from click.termui import unstyle as unstyle
21
+ from click.utils import echo as echo
22
+ from click.utils import format_filename as format_filename
23
+ from click.utils import get_app_dir as get_app_dir
24
+ from click.utils import get_binary_stream as get_binary_stream
25
+ from click.utils import get_text_stream as get_text_stream
26
+ from click.utils import open_file as open_file
27
+
28
+ from . import colors as colors
29
+ from .main import Typer as Typer
30
+ from .main import launch as launch
31
+ from .main import run as run
32
+ from .models import CallbackParam as CallbackParam
33
+ from .models import Context as Context
34
+ from .models import FileBinaryRead as FileBinaryRead
35
+ from .models import FileBinaryWrite as FileBinaryWrite
36
+ from .models import FileText as FileText
37
+ from .models import FileTextWrite as FileTextWrite
38
+ from .params import Argument as Argument
39
+ from .params import Option as Option
loan-advisor-agent/.venv/Lib/site-packages/typer/__main__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .cli import main
2
+
3
+ main()
loan-advisor-agent/.venv/Lib/site-packages/typer/_completion_classes.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.util
2
+ import os
3
+ import re
4
+ import sys
5
+ from typing import Any
6
+
7
+ import click
8
+ import click.parser
9
+ import click.shell_completion
10
+ from click.shell_completion import split_arg_string as click_split_arg_string
11
+
12
+ from ._completion_shared import (
13
+ COMPLETION_SCRIPT_BASH,
14
+ COMPLETION_SCRIPT_FISH,
15
+ COMPLETION_SCRIPT_POWER_SHELL,
16
+ COMPLETION_SCRIPT_ZSH,
17
+ Shells,
18
+ )
19
+
20
+
21
+ def _sanitize_help_text(text: str) -> str:
22
+ """Sanitizes the help text by removing rich tags"""
23
+ if not importlib.util.find_spec("rich"):
24
+ return text
25
+ from . import rich_utils
26
+
27
+ return rich_utils.rich_render_text(text)
28
+
29
+
30
+ class BashComplete(click.shell_completion.BashComplete):
31
+ name = Shells.bash.value
32
+ source_template = COMPLETION_SCRIPT_BASH
33
+
34
+ def source_vars(self) -> dict[str, Any]:
35
+ return {
36
+ "complete_func": self.func_name,
37
+ "autocomplete_var": self.complete_var,
38
+ "prog_name": self.prog_name,
39
+ }
40
+
41
+ def get_completion_args(self) -> tuple[list[str], str]:
42
+ cwords = click_split_arg_string(os.environ["COMP_WORDS"])
43
+ cword = int(os.environ["COMP_CWORD"])
44
+ args = cwords[1:cword]
45
+
46
+ try:
47
+ incomplete = cwords[cword]
48
+ except IndexError:
49
+ incomplete = ""
50
+
51
+ return args, incomplete
52
+
53
+ def format_completion(self, item: click.shell_completion.CompletionItem) -> str:
54
+ # TODO: Explore replicating the new behavior from Click, with item types and
55
+ # triggering completion for files and directories
56
+ # return f"{item.type},{item.value}"
57
+ return f"{item.value}"
58
+
59
+ def complete(self) -> str:
60
+ args, incomplete = self.get_completion_args()
61
+ completions = self.get_completions(args, incomplete)
62
+ out = [self.format_completion(item) for item in completions]
63
+ return "\n".join(out)
64
+
65
+
66
+ class ZshComplete(click.shell_completion.ZshComplete):
67
+ name = Shells.zsh.value
68
+ source_template = COMPLETION_SCRIPT_ZSH
69
+
70
+ def source_vars(self) -> dict[str, Any]:
71
+ return {
72
+ "complete_func": self.func_name,
73
+ "autocomplete_var": self.complete_var,
74
+ "prog_name": self.prog_name,
75
+ }
76
+
77
+ def get_completion_args(self) -> tuple[list[str], str]:
78
+ completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")
79
+ cwords = click_split_arg_string(completion_args)
80
+ args = cwords[1:]
81
+ if args and not completion_args.endswith(" "):
82
+ incomplete = args[-1]
83
+ args = args[:-1]
84
+ else:
85
+ incomplete = ""
86
+ return args, incomplete
87
+
88
+ def format_completion(self, item: click.shell_completion.CompletionItem) -> str:
89
+ def escape(s: str) -> str:
90
+ return (
91
+ s.replace('"', '""')
92
+ .replace("'", "''")
93
+ .replace("$", "\\$")
94
+ .replace("`", "\\`")
95
+ .replace(":", r"\\:")
96
+ )
97
+
98
+ # TODO: Explore replicating the new behavior from Click, pay attention to
99
+ # the difference with and without escape
100
+ # return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"
101
+ if item.help:
102
+ return f'"{escape(item.value)}":"{_sanitize_help_text(escape(item.help))}"'
103
+ else:
104
+ return f'"{escape(item.value)}"'
105
+
106
+ def complete(self) -> str:
107
+ args, incomplete = self.get_completion_args()
108
+ completions = self.get_completions(args, incomplete)
109
+ res = [self.format_completion(item) for item in completions]
110
+ if res:
111
+ args_str = "\n".join(res)
112
+ return f"_arguments '*: :(({args_str}))'"
113
+ else:
114
+ return "_files"
115
+
116
+
117
+ class FishComplete(click.shell_completion.FishComplete):
118
+ name = Shells.fish.value
119
+ source_template = COMPLETION_SCRIPT_FISH
120
+
121
+ def source_vars(self) -> dict[str, Any]:
122
+ return {
123
+ "complete_func": self.func_name,
124
+ "autocomplete_var": self.complete_var,
125
+ "prog_name": self.prog_name,
126
+ }
127
+
128
+ def get_completion_args(self) -> tuple[list[str], str]:
129
+ completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")
130
+ cwords = click_split_arg_string(completion_args)
131
+ args = cwords[1:]
132
+ if args and not completion_args.endswith(" "):
133
+ incomplete = args[-1]
134
+ args = args[:-1]
135
+ else:
136
+ incomplete = ""
137
+ return args, incomplete
138
+
139
+ def format_completion(self, item: click.shell_completion.CompletionItem) -> str:
140
+ # TODO: Explore replicating the new behavior from Click, pay attention to
141
+ # the difference with and without formatted help
142
+ # if item.help:
143
+ # return f"{item.type},{item.value}\t{item.help}"
144
+
145
+ # return f"{item.type},{item.value}
146
+ if item.help:
147
+ formatted_help = re.sub(r"\s", " ", item.help)
148
+ return f"{item.value}\t{_sanitize_help_text(formatted_help)}"
149
+ else:
150
+ return f"{item.value}"
151
+
152
+ def complete(self) -> str:
153
+ complete_action = os.getenv("_TYPER_COMPLETE_FISH_ACTION", "")
154
+ args, incomplete = self.get_completion_args()
155
+ completions = self.get_completions(args, incomplete)
156
+ show_args = [self.format_completion(item) for item in completions]
157
+ if complete_action == "get-args":
158
+ if show_args:
159
+ return "\n".join(show_args)
160
+ elif complete_action == "is-args":
161
+ if show_args:
162
+ # Activate complete args (no files)
163
+ sys.exit(0)
164
+ else:
165
+ # Deactivate complete args (allow files)
166
+ sys.exit(1)
167
+ return "" # pragma: no cover
168
+
169
+
170
+ class PowerShellComplete(click.shell_completion.ShellComplete):
171
+ name = Shells.powershell.value
172
+ source_template = COMPLETION_SCRIPT_POWER_SHELL
173
+
174
+ def source_vars(self) -> dict[str, Any]:
175
+ return {
176
+ "complete_func": self.func_name,
177
+ "autocomplete_var": self.complete_var,
178
+ "prog_name": self.prog_name,
179
+ }
180
+
181
+ def get_completion_args(self) -> tuple[list[str], str]:
182
+ completion_args = os.getenv("_TYPER_COMPLETE_ARGS", "")
183
+ incomplete = os.getenv("_TYPER_COMPLETE_WORD_TO_COMPLETE", "")
184
+ cwords = click_split_arg_string(completion_args)
185
+ args = cwords[1:-1] if incomplete else cwords[1:]
186
+ return args, incomplete
187
+
188
+ def format_completion(self, item: click.shell_completion.CompletionItem) -> str:
189
+ return f"{item.value}:::{_sanitize_help_text(item.help) if item.help else ' '}"
190
+
191
+
192
+ def completion_init() -> None:
193
+ click.shell_completion.add_completion_class(BashComplete, Shells.bash.value)
194
+ click.shell_completion.add_completion_class(ZshComplete, Shells.zsh.value)
195
+ click.shell_completion.add_completion_class(FishComplete, Shells.fish.value)
196
+ click.shell_completion.add_completion_class(
197
+ PowerShellComplete, Shells.powershell.value
198
+ )
199
+ click.shell_completion.add_completion_class(PowerShellComplete, Shells.pwsh.value)
loan-advisor-agent/.venv/Lib/site-packages/typer/_completion_shared.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import subprocess
4
+ from enum import Enum
5
+ from pathlib import Path
6
+
7
+ import click
8
+ import shellingham
9
+
10
+
11
+ class Shells(str, Enum):
12
+ bash = "bash"
13
+ zsh = "zsh"
14
+ fish = "fish"
15
+ powershell = "powershell"
16
+ pwsh = "pwsh"
17
+
18
+
19
+ COMPLETION_SCRIPT_BASH = """
20
+ %(complete_func)s() {
21
+ local IFS=$'\n'
22
+ COMPREPLY=( $( env COMP_WORDS="${COMP_WORDS[*]}" \\
23
+ COMP_CWORD=$COMP_CWORD \\
24
+ %(autocomplete_var)s=complete_bash $1 ) )
25
+ return 0
26
+ }
27
+
28
+ complete -o default -F %(complete_func)s %(prog_name)s
29
+ """
30
+
31
+ COMPLETION_SCRIPT_ZSH = """
32
+ #compdef %(prog_name)s
33
+
34
+ %(complete_func)s() {
35
+ eval $(env _TYPER_COMPLETE_ARGS="${words[1,$CURRENT]}" %(autocomplete_var)s=complete_zsh %(prog_name)s)
36
+ }
37
+
38
+ compdef %(complete_func)s %(prog_name)s
39
+ """
40
+
41
+ COMPLETION_SCRIPT_FISH = 'complete --command %(prog_name)s --no-files --arguments "(env %(autocomplete_var)s=complete_fish _TYPER_COMPLETE_FISH_ACTION=get-args _TYPER_COMPLETE_ARGS=(commandline -cp) %(prog_name)s)" --condition "env %(autocomplete_var)s=complete_fish _TYPER_COMPLETE_FISH_ACTION=is-args _TYPER_COMPLETE_ARGS=(commandline -cp) %(prog_name)s"'
42
+
43
+ COMPLETION_SCRIPT_POWER_SHELL = """
44
+ Import-Module PSReadLine
45
+ Set-PSReadLineKeyHandler -Chord Tab -Function MenuComplete
46
+ $scriptblock = {
47
+ param($wordToComplete, $commandAst, $cursorPosition)
48
+ $Env:%(autocomplete_var)s = "complete_powershell"
49
+ $Env:_TYPER_COMPLETE_ARGS = $commandAst.ToString()
50
+ $Env:_TYPER_COMPLETE_WORD_TO_COMPLETE = $wordToComplete
51
+ %(prog_name)s | ForEach-Object {
52
+ $commandArray = $_ -Split ":::"
53
+ $command = $commandArray[0]
54
+ $helpString = $commandArray[1]
55
+ [System.Management.Automation.CompletionResult]::new(
56
+ $command, $command, 'ParameterValue', $helpString)
57
+ }
58
+ $Env:%(autocomplete_var)s = ""
59
+ $Env:_TYPER_COMPLETE_ARGS = ""
60
+ $Env:_TYPER_COMPLETE_WORD_TO_COMPLETE = ""
61
+ }
62
+ Register-ArgumentCompleter -Native -CommandName %(prog_name)s -ScriptBlock $scriptblock
63
+ """
64
+
65
+ _completion_scripts = {
66
+ "bash": COMPLETION_SCRIPT_BASH,
67
+ "zsh": COMPLETION_SCRIPT_ZSH,
68
+ "fish": COMPLETION_SCRIPT_FISH,
69
+ "powershell": COMPLETION_SCRIPT_POWER_SHELL,
70
+ "pwsh": COMPLETION_SCRIPT_POWER_SHELL,
71
+ }
72
+
73
+ # TODO: Probably refactor this, copied from Click 7.x
74
+ _invalid_ident_char_re = re.compile(r"[^a-zA-Z0-9_]")
75
+
76
+
77
+ def get_completion_script(*, prog_name: str, complete_var: str, shell: str) -> str:
78
+ cf_name = _invalid_ident_char_re.sub("", prog_name.replace("-", "_"))
79
+ script = _completion_scripts.get(shell)
80
+ if script is None:
81
+ click.echo(f"Shell {shell} not supported.", err=True)
82
+ raise click.exceptions.Exit(1)
83
+ return (
84
+ script
85
+ % {
86
+ "complete_func": f"_{cf_name}_completion",
87
+ "prog_name": prog_name,
88
+ "autocomplete_var": complete_var,
89
+ }
90
+ ).strip()
91
+
92
+
93
+ def install_bash(*, prog_name: str, complete_var: str, shell: str) -> Path:
94
+ # Ref: https://github.com/scop/bash-completion#faq
95
+ # It seems bash-completion is the official completion system for bash:
96
+ # Ref: https://www.gnu.org/software/bash/manual/html_node/A-Programmable-Completion-Example.html
97
+ # But installing in the locations from the docs doesn't seem to have effect
98
+ completion_path = Path.home() / ".bash_completions" / f"{prog_name}.sh"
99
+ rc_path = Path.home() / ".bashrc"
100
+ rc_path.parent.mkdir(parents=True, exist_ok=True)
101
+ rc_content = ""
102
+ if rc_path.is_file():
103
+ rc_content = rc_path.read_text()
104
+ completion_init_lines = [f"source '{completion_path}'"]
105
+ for line in completion_init_lines:
106
+ if line not in rc_content: # pragma: no cover
107
+ rc_content += f"\n{line}"
108
+ rc_content += "\n"
109
+ rc_path.write_text(rc_content)
110
+ # Install completion
111
+ completion_path.parent.mkdir(parents=True, exist_ok=True)
112
+ script_content = get_completion_script(
113
+ prog_name=prog_name, complete_var=complete_var, shell=shell
114
+ )
115
+ completion_path.write_text(script_content)
116
+ return completion_path
117
+
118
+
119
+ def install_zsh(*, prog_name: str, complete_var: str, shell: str) -> Path:
120
+ # Setup Zsh and load ~/.zfunc
121
+ zshrc_path = Path.home() / ".zshrc"
122
+ zshrc_path.parent.mkdir(parents=True, exist_ok=True)
123
+ zshrc_content = ""
124
+ if zshrc_path.is_file():
125
+ zshrc_content = zshrc_path.read_text()
126
+ completion_line = "fpath+=~/.zfunc; autoload -Uz compinit; compinit"
127
+ if completion_line not in zshrc_content:
128
+ zshrc_content += f"\n{completion_line}\n"
129
+ style_line = "zstyle ':completion:*' menu select"
130
+ # TODO: consider setting the style only for the current program
131
+ # style_line = f"zstyle ':completion:*:*:{prog_name}:*' menu select"
132
+ # Install zstyle completion config only if the user doesn't have a customization
133
+ if "zstyle" not in zshrc_content:
134
+ zshrc_content += f"\n{style_line}\n"
135
+ zshrc_content = f"{zshrc_content.strip()}\n"
136
+ zshrc_path.write_text(zshrc_content)
137
+ # Install completion under ~/.zfunc/
138
+ path_obj = Path.home() / f".zfunc/_{prog_name}"
139
+ path_obj.parent.mkdir(parents=True, exist_ok=True)
140
+ script_content = get_completion_script(
141
+ prog_name=prog_name, complete_var=complete_var, shell=shell
142
+ )
143
+ path_obj.write_text(script_content)
144
+ return path_obj
145
+
146
+
147
+ def install_fish(*, prog_name: str, complete_var: str, shell: str) -> Path:
148
+ path_obj = Path.home() / f".config/fish/completions/{prog_name}.fish"
149
+ parent_dir: Path = path_obj.parent
150
+ parent_dir.mkdir(parents=True, exist_ok=True)
151
+ script_content = get_completion_script(
152
+ prog_name=prog_name, complete_var=complete_var, shell=shell
153
+ )
154
+ path_obj.write_text(f"{script_content}\n")
155
+ return path_obj
156
+
157
+
158
+ def install_powershell(*, prog_name: str, complete_var: str, shell: str) -> Path:
159
+ subprocess.run(
160
+ [
161
+ shell,
162
+ "-Command",
163
+ "Set-ExecutionPolicy",
164
+ "Unrestricted",
165
+ "-Scope",
166
+ "CurrentUser",
167
+ ]
168
+ )
169
+ result = subprocess.run(
170
+ [shell, "-NoProfile", "-Command", "echo", "$profile"],
171
+ check=True,
172
+ stdout=subprocess.PIPE,
173
+ )
174
+ if result.returncode != 0: # pragma: no cover
175
+ click.echo("Couldn't get PowerShell user profile", err=True)
176
+ raise click.exceptions.Exit(result.returncode)
177
+ path_str = ""
178
+ if isinstance(result.stdout, str): # pragma: no cover
179
+ path_str = result.stdout
180
+ if isinstance(result.stdout, bytes):
181
+ for encoding in ["windows-1252", "utf8", "cp850"]:
182
+ try:
183
+ path_str = result.stdout.decode(encoding)
184
+ break
185
+ except UnicodeDecodeError: # pragma: no cover
186
+ pass
187
+ if not path_str: # pragma: no cover
188
+ click.echo("Couldn't decode the path automatically", err=True)
189
+ raise click.exceptions.Exit(1)
190
+ path_obj = Path(path_str.strip())
191
+ parent_dir: Path = path_obj.parent
192
+ parent_dir.mkdir(parents=True, exist_ok=True)
193
+ script_content = get_completion_script(
194
+ prog_name=prog_name, complete_var=complete_var, shell=shell
195
+ )
196
+ with path_obj.open(mode="a") as f:
197
+ f.write(f"{script_content}\n")
198
+ return path_obj
199
+
200
+
201
+ def install(
202
+ shell: str | None = None,
203
+ prog_name: str | None = None,
204
+ complete_var: str | None = None,
205
+ ) -> tuple[str, Path]:
206
+ prog_name = prog_name or click.get_current_context().find_root().info_name
207
+ assert prog_name
208
+ if complete_var is None:
209
+ complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())
210
+ test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")
211
+ if shell is None and not test_disable_detection:
212
+ shell = _get_shell_name()
213
+ if shell == "bash":
214
+ installed_path = install_bash(
215
+ prog_name=prog_name, complete_var=complete_var, shell=shell
216
+ )
217
+ return shell, installed_path
218
+ elif shell == "zsh":
219
+ installed_path = install_zsh(
220
+ prog_name=prog_name, complete_var=complete_var, shell=shell
221
+ )
222
+ return shell, installed_path
223
+ elif shell == "fish":
224
+ installed_path = install_fish(
225
+ prog_name=prog_name, complete_var=complete_var, shell=shell
226
+ )
227
+ return shell, installed_path
228
+ elif shell in {"powershell", "pwsh"}:
229
+ installed_path = install_powershell(
230
+ prog_name=prog_name, complete_var=complete_var, shell=shell
231
+ )
232
+ return shell, installed_path
233
+ else:
234
+ click.echo(f"Shell {shell} is not supported.")
235
+ raise click.exceptions.Exit(1)
236
+
237
+
238
+ def _get_shell_name() -> str | None:
239
+ """Get the current shell name, if available.
240
+
241
+ The name will always be lowercase. If the shell cannot be detected, None is
242
+ returned.
243
+ """
244
+ name: str | None # N.B. shellingham is untyped
245
+ try:
246
+ # N.B. detect_shell returns a tuple of (shell name, shell command).
247
+ # We only need the name.
248
+ name, _cmd = shellingham.detect_shell() # noqa: TID251
249
+ except shellingham.ShellDetectionFailure: # pragma: no cover
250
+ name = None
251
+
252
+ return name
loan-advisor-agent/.venv/Lib/site-packages/typer/_types.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum
2
+ from typing import TypeVar
3
+
4
+ import click
5
+
6
+ ParamTypeValue = TypeVar("ParamTypeValue")
7
+
8
+
9
+ class TyperChoice(click.Choice[ParamTypeValue]):
10
+ def normalize_choice(
11
+ self, choice: ParamTypeValue, ctx: click.Context | None
12
+ ) -> str:
13
+ # Click 8.2.0 added a new method `normalize_choice` to the `Choice` class
14
+ # to support enums, but it uses the enum names, while Typer has always used the
15
+ # enum values.
16
+ # This class overrides that method to maintain the previous behavior.
17
+ # In Click:
18
+ # normed_value = choice.name if isinstance(choice, Enum) else str(choice)
19
+ normed_value = str(choice.value) if isinstance(choice, Enum) else str(choice)
20
+
21
+ if ctx is not None and ctx.token_normalize_func is not None:
22
+ normed_value = ctx.token_normalize_func(normed_value)
23
+
24
+ if not self.case_sensitive:
25
+ normed_value = normed_value.casefold()
26
+
27
+ return normed_value
loan-advisor-agent/.venv/Lib/site-packages/typer/_typing.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from pydantic 1.9.2 (the latest version to support python 3.6.)
2
+ # https://github.com/pydantic/pydantic/blob/v1.9.2/pydantic/typing.py
3
+ # Reduced drastically to only include Typer-specific 3.9+ functionality
4
+ # mypy: ignore-errors
5
+
6
+ import types
7
+ from collections.abc import Callable
8
+ from typing import (
9
+ Annotated,
10
+ Any,
11
+ Literal,
12
+ Union,
13
+ get_args,
14
+ get_origin,
15
+ get_type_hints,
16
+ )
17
+
18
+
19
+ def is_union(tp: type[Any] | None) -> bool:
20
+ return tp is Union or tp is types.UnionType # noqa: E721
21
+
22
+
23
+ __all__ = (
24
+ "NoneType",
25
+ "is_none_type",
26
+ "is_callable_type",
27
+ "is_literal_type",
28
+ "all_literal_values",
29
+ "is_union",
30
+ "Annotated",
31
+ "Literal",
32
+ "get_args",
33
+ "get_origin",
34
+ "get_type_hints",
35
+ )
36
+
37
+
38
+ NoneType = None.__class__
39
+
40
+
41
+ NONE_TYPES: tuple[Any, Any, Any] = (None, NoneType, Literal[None])
42
+
43
+
44
+ def is_none_type(type_: Any) -> bool:
45
+ for none_type in NONE_TYPES:
46
+ if type_ is none_type:
47
+ return True
48
+ return False
49
+
50
+
51
+ def is_callable_type(type_: type[Any]) -> bool:
52
+ return type_ is Callable or get_origin(type_) is Callable
53
+
54
+
55
+ def is_literal_type(type_: type[Any]) -> bool:
56
+ return get_origin(type_) is Literal
57
+
58
+
59
+ def literal_values(type_: type[Any]) -> tuple[Any, ...]:
60
+ return get_args(type_)
61
+
62
+
63
+ def all_literal_values(type_: type[Any]) -> tuple[Any, ...]:
64
+ """
65
+ This method is used to retrieve all Literal values as
66
+ Literal can be used recursively (see https://www.python.org/dev/peps/pep-0586)
67
+ e.g. `Literal[Literal[Literal[1, 2, 3], "foo"], 5, None]`
68
+ """
69
+ if not is_literal_type(type_):
70
+ return (type_,)
71
+
72
+ values = literal_values(type_)
73
+ return tuple(x for value in values for x in all_literal_values(value))
loan-advisor-agent/.venv/Lib/site-packages/typer/cli.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.util
2
+ import re
3
+ import sys
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ import click
8
+ import typer
9
+ import typer.core
10
+ from click import Command, Group, Option
11
+
12
+ from . import __version__
13
+ from .core import HAS_RICH, MARKUP_MODE_KEY
14
+
15
+ default_app_names = ("app", "cli", "main")
16
+ default_func_names = ("main", "cli", "app")
17
+
18
+ app = typer.Typer()
19
+ utils_app = typer.Typer(help="Extra utility commands for Typer apps.")
20
+ app.add_typer(utils_app, name="utils")
21
+
22
+
23
+ class State:
24
+ def __init__(self) -> None:
25
+ self.app: str | None = None
26
+ self.func: str | None = None
27
+ self.file: Path | None = None
28
+ self.module: str | None = None
29
+
30
+
31
+ state = State()
32
+
33
+
34
+ def maybe_update_state(ctx: click.Context) -> None:
35
+ path_or_module = ctx.params.get("path_or_module")
36
+ if path_or_module:
37
+ file_path = Path(path_or_module)
38
+ if file_path.exists() and file_path.is_file():
39
+ state.file = file_path
40
+ else:
41
+ if not re.fullmatch(r"[a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*", path_or_module):
42
+ typer.echo(
43
+ f"Not a valid file or Python module: {path_or_module}", err=True
44
+ )
45
+ sys.exit(1)
46
+ state.module = path_or_module
47
+ app_name = ctx.params.get("app")
48
+ if app_name:
49
+ state.app = app_name
50
+ func_name = ctx.params.get("func")
51
+ if func_name:
52
+ state.func = func_name
53
+
54
+
55
+ class TyperCLIGroup(typer.core.TyperGroup):
56
+ def list_commands(self, ctx: click.Context) -> list[str]:
57
+ self.maybe_add_run(ctx)
58
+ return super().list_commands(ctx)
59
+
60
+ def get_command(self, ctx: click.Context, name: str) -> Command | None: # ty: ignore[invalid-method-override]
61
+ self.maybe_add_run(ctx)
62
+ return super().get_command(ctx, name)
63
+
64
+ def invoke(self, ctx: click.Context) -> Any:
65
+ self.maybe_add_run(ctx)
66
+ return super().invoke(ctx)
67
+
68
+ def maybe_add_run(self, ctx: click.Context) -> None:
69
+ maybe_update_state(ctx)
70
+ maybe_add_run_to_cli(self)
71
+
72
+
73
+ def get_typer_from_module(module: Any) -> typer.Typer | None:
74
+ # Try to get defined app
75
+ if state.app:
76
+ obj = getattr(module, state.app, None)
77
+ if not isinstance(obj, typer.Typer):
78
+ typer.echo(f"Not a Typer object: --app {state.app}", err=True)
79
+ sys.exit(1)
80
+ return obj
81
+ # Try to get defined function
82
+ if state.func:
83
+ func_obj = getattr(module, state.func, None)
84
+ if not callable(func_obj):
85
+ typer.echo(f"Not a function: --func {state.func}", err=True)
86
+ raise typer.Exit(1)
87
+ sub_app = typer.Typer()
88
+ sub_app.command()(func_obj)
89
+ return sub_app
90
+ # Iterate and get a default object to use as CLI
91
+ local_names = dir(module)
92
+ local_names_set = set(local_names)
93
+ # Try to get a default Typer app
94
+ for name in default_app_names:
95
+ if name in local_names_set:
96
+ obj = getattr(module, name, None)
97
+ if isinstance(obj, typer.Typer):
98
+ return obj
99
+ # Try to get any Typer app
100
+ for name in local_names_set - set(default_app_names):
101
+ obj = getattr(module, name)
102
+ if isinstance(obj, typer.Typer):
103
+ return obj
104
+ # Try to get a default function
105
+ for func_name in default_func_names:
106
+ func_obj = getattr(module, func_name, None)
107
+ if callable(func_obj):
108
+ sub_app = typer.Typer()
109
+ sub_app.command()(func_obj)
110
+ return sub_app
111
+ # Try to get any func app
112
+ for func_name in local_names_set - set(default_func_names):
113
+ func_obj = getattr(module, func_name)
114
+ if callable(func_obj):
115
+ sub_app = typer.Typer()
116
+ sub_app.command()(func_obj)
117
+ return sub_app
118
+ return None
119
+
120
+
121
+ def get_typer_from_state() -> typer.Typer | None:
122
+ spec = None
123
+ if state.file:
124
+ module_name = state.file.name
125
+ spec = importlib.util.spec_from_file_location(module_name, str(state.file))
126
+ elif state.module:
127
+ spec = importlib.util.find_spec(state.module)
128
+ if spec is None:
129
+ if state.file:
130
+ typer.echo(f"Could not import as Python file: {state.file}", err=True)
131
+ else:
132
+ typer.echo(f"Could not import as Python module: {state.module}", err=True)
133
+ sys.exit(1)
134
+ module = importlib.util.module_from_spec(spec)
135
+ spec.loader.exec_module(module) # type: ignore
136
+ obj = get_typer_from_module(module)
137
+ return obj
138
+
139
+
140
+ def maybe_add_run_to_cli(cli: click.Group) -> None:
141
+ if "run" not in cli.commands:
142
+ if state.file or state.module:
143
+ obj = get_typer_from_state()
144
+ if obj:
145
+ obj._add_completion = False
146
+ click_obj = typer.main.get_command(obj)
147
+ click_obj.name = "run"
148
+ if not click_obj.help:
149
+ click_obj.help = "Run the provided Typer app."
150
+ cli.add_command(click_obj)
151
+
152
+
153
+ def print_version(ctx: click.Context, param: Option, value: bool) -> None:
154
+ if not value or ctx.resilient_parsing:
155
+ return
156
+ typer.echo(f"Typer version: {__version__}")
157
+ raise typer.Exit()
158
+
159
+
160
+ @app.callback(cls=TyperCLIGroup, no_args_is_help=True)
161
+ def callback(
162
+ ctx: typer.Context,
163
+ *,
164
+ path_or_module: str = typer.Argument(None),
165
+ app: str = typer.Option(None, help="The typer app object/variable to use."),
166
+ func: str = typer.Option(None, help="The function to convert to Typer."),
167
+ version: bool = typer.Option(
168
+ False,
169
+ "--version",
170
+ help="Print version and exit.",
171
+ callback=print_version,
172
+ ),
173
+ ) -> None:
174
+ """
175
+ Run Typer scripts with completion, without having to create a package.
176
+
177
+ You probably want to install completion for the typer command:
178
+
179
+ $ typer --install-completion
180
+
181
+ https://typer.tiangolo.com/
182
+ """
183
+ maybe_update_state(ctx)
184
+
185
+
186
+ def get_docs_for_click(
187
+ *,
188
+ obj: Command,
189
+ ctx: typer.Context,
190
+ indent: int = 0,
191
+ name: str = "",
192
+ call_prefix: str = "",
193
+ title: str | None = None,
194
+ ) -> str:
195
+ docs = "#" * (1 + indent)
196
+ command_name = name or obj.name
197
+ if call_prefix:
198
+ command_name = f"{call_prefix} {command_name}"
199
+ if not title:
200
+ title = f"`{command_name}`" if command_name else "CLI"
201
+ docs += f" {title}\n\n"
202
+ rich_markup_mode = None
203
+ if hasattr(ctx, "obj") and isinstance(ctx.obj, dict):
204
+ rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None)
205
+ to_parse: bool = bool(HAS_RICH and (rich_markup_mode == "rich"))
206
+ if obj.help:
207
+ docs += f"{_parse_html(to_parse, obj.help)}\n\n"
208
+ usage_pieces = obj.collect_usage_pieces(ctx)
209
+ if usage_pieces:
210
+ docs += "**Usage**:\n\n"
211
+ docs += "```console\n"
212
+ docs += "$ "
213
+ if command_name:
214
+ docs += f"{command_name} "
215
+ docs += f"{' '.join(usage_pieces)}\n"
216
+ docs += "```\n\n"
217
+ args = []
218
+ opts = []
219
+ for param in obj.get_params(ctx):
220
+ rv = param.get_help_record(ctx)
221
+ if rv is not None:
222
+ if param.param_type_name == "argument":
223
+ args.append(rv)
224
+ elif param.param_type_name == "option":
225
+ opts.append(rv)
226
+ if args:
227
+ docs += "**Arguments**:\n\n"
228
+ for arg_name, arg_help in args:
229
+ docs += f"* `{arg_name}`"
230
+ if arg_help:
231
+ docs += f": {_parse_html(to_parse, arg_help)}"
232
+ docs += "\n"
233
+ docs += "\n"
234
+ if opts:
235
+ docs += "**Options**:\n\n"
236
+ for opt_name, opt_help in opts:
237
+ docs += f"* `{opt_name}`"
238
+ if opt_help:
239
+ docs += f": {_parse_html(to_parse, opt_help)}"
240
+ docs += "\n"
241
+ docs += "\n"
242
+ if obj.epilog:
243
+ docs += f"{obj.epilog}\n\n"
244
+ if isinstance(obj, Group):
245
+ group = obj
246
+ commands = group.list_commands(ctx)
247
+ if commands:
248
+ docs += "**Commands**:\n\n"
249
+ for command in commands:
250
+ command_obj = group.get_command(ctx, command)
251
+ assert command_obj
252
+ docs += f"* `{command_obj.name}`"
253
+ command_help = command_obj.get_short_help_str()
254
+ if command_help:
255
+ docs += f": {_parse_html(to_parse, command_help)}"
256
+ docs += "\n"
257
+ docs += "\n"
258
+ for command in commands:
259
+ command_obj = group.get_command(ctx, command)
260
+ assert command_obj
261
+ use_prefix = ""
262
+ if command_name:
263
+ use_prefix += f"{command_name}"
264
+ docs += get_docs_for_click(
265
+ obj=command_obj, ctx=ctx, indent=indent + 1, call_prefix=use_prefix
266
+ )
267
+ return docs
268
+
269
+
270
+ def _parse_html(to_parse: bool, input_text: str) -> str:
271
+ if not to_parse:
272
+ return input_text
273
+ from . import rich_utils
274
+
275
+ return rich_utils.rich_to_html(input_text)
276
+
277
+
278
+ @utils_app.command()
279
+ def docs(
280
+ ctx: typer.Context,
281
+ name: str = typer.Option("", help="The name of the CLI program to use in docs."),
282
+ output: Path | None = typer.Option(
283
+ None,
284
+ help="An output file to write docs to, like README.md.",
285
+ file_okay=True,
286
+ dir_okay=False,
287
+ ),
288
+ title: str | None = typer.Option(
289
+ None,
290
+ help="The title for the documentation page. If not provided, the name of "
291
+ "the program is used.",
292
+ ),
293
+ ) -> None:
294
+ """
295
+ Generate Markdown docs for a Typer app.
296
+ """
297
+ typer_obj = get_typer_from_state()
298
+ if not typer_obj:
299
+ typer.echo("No Typer app found", err=True)
300
+ raise typer.Abort()
301
+ if hasattr(typer_obj, "rich_markup_mode"):
302
+ if not hasattr(ctx, "obj") or ctx.obj is None:
303
+ ctx.ensure_object(dict)
304
+ if isinstance(ctx.obj, dict):
305
+ ctx.obj[MARKUP_MODE_KEY] = typer_obj.rich_markup_mode
306
+ click_obj = typer.main.get_command(typer_obj)
307
+ docs = get_docs_for_click(obj=click_obj, ctx=ctx, name=name, title=title)
308
+ clean_docs = f"{docs.strip()}\n"
309
+ if output:
310
+ output.write_text(clean_docs)
311
+ typer.echo(f"Docs saved to: {output}")
312
+ else:
313
+ typer.echo(clean_docs)
314
+
315
+
316
+ def main() -> Any:
317
+ return app()
loan-advisor-agent/.venv/Lib/site-packages/typer/colors.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Variable names to colors, just for completion
2
+ BLACK = "black"
3
+ RED = "red"
4
+ GREEN = "green"
5
+ YELLOW = "yellow"
6
+ BLUE = "blue"
7
+ MAGENTA = "magenta"
8
+ CYAN = "cyan"
9
+ WHITE = "white"
10
+
11
+ RESET = "reset"
12
+
13
+ BRIGHT_BLACK = "bright_black"
14
+ BRIGHT_RED = "bright_red"
15
+ BRIGHT_GREEN = "bright_green"
16
+ BRIGHT_YELLOW = "bright_yellow"
17
+ BRIGHT_BLUE = "bright_blue"
18
+ BRIGHT_MAGENTA = "bright_magenta"
19
+ BRIGHT_CYAN = "bright_cyan"
20
+ BRIGHT_WHITE = "bright_white"
loan-advisor-agent/.venv/Lib/site-packages/typer/completion.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from collections.abc import MutableMapping
4
+ from typing import Any
5
+
6
+ import click
7
+
8
+ from ._completion_classes import completion_init
9
+ from ._completion_shared import Shells, _get_shell_name, get_completion_script, install
10
+ from .models import ParamMeta
11
+ from .params import Option
12
+ from .utils import get_params_from_function
13
+
14
+ _click_patched = False
15
+
16
+
17
+ def get_completion_inspect_parameters() -> tuple[ParamMeta, ParamMeta]:
18
+ completion_init()
19
+ test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")
20
+ if not test_disable_detection:
21
+ parameters = get_params_from_function(_install_completion_placeholder_function)
22
+ else:
23
+ parameters = get_params_from_function(
24
+ _install_completion_no_auto_placeholder_function
25
+ )
26
+ install_param, show_param = parameters.values()
27
+ return install_param, show_param
28
+
29
+
30
+ def install_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
31
+ if not value or ctx.resilient_parsing:
32
+ return value # pragma: no cover
33
+ if isinstance(value, str):
34
+ shell, path = install(shell=value)
35
+ else:
36
+ shell, path = install()
37
+ click.secho(f"{shell} completion installed in {path}", fg="green")
38
+ click.echo("Completion will take effect once you restart the terminal")
39
+ sys.exit(0)
40
+
41
+
42
+ def show_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
43
+ if not value or ctx.resilient_parsing:
44
+ return value # pragma: no cover
45
+ prog_name = ctx.find_root().info_name
46
+ assert prog_name
47
+ complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())
48
+ shell = ""
49
+ test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")
50
+ if isinstance(value, str):
51
+ shell = value
52
+ elif not test_disable_detection:
53
+ detected_shell = _get_shell_name()
54
+ if detected_shell is not None:
55
+ shell = detected_shell
56
+ script_content = get_completion_script(
57
+ prog_name=prog_name, complete_var=complete_var, shell=shell
58
+ )
59
+ click.echo(script_content)
60
+ sys.exit(0)
61
+
62
+
63
+ # Create a fake command function to extract the completion parameters
64
+ def _install_completion_placeholder_function(
65
+ install_completion: bool = Option(
66
+ None,
67
+ "--install-completion",
68
+ callback=install_callback,
69
+ expose_value=False,
70
+ help="Install completion for the current shell.",
71
+ ),
72
+ show_completion: bool = Option(
73
+ None,
74
+ "--show-completion",
75
+ callback=show_callback,
76
+ expose_value=False,
77
+ help="Show completion for the current shell, to copy it or customize the installation.",
78
+ ),
79
+ ) -> Any:
80
+ pass # pragma: no cover
81
+
82
+
83
+ def _install_completion_no_auto_placeholder_function(
84
+ install_completion: Shells = Option(
85
+ None,
86
+ callback=install_callback,
87
+ expose_value=False,
88
+ help="Install completion for the specified shell.",
89
+ ),
90
+ show_completion: Shells = Option(
91
+ None,
92
+ callback=show_callback,
93
+ expose_value=False,
94
+ help="Show completion for the specified shell, to copy it or customize the installation.",
95
+ ),
96
+ ) -> Any:
97
+ pass # pragma: no cover
98
+
99
+
100
+ # Re-implement Click's shell_complete to add error message with:
101
+ # Invalid completion instruction
102
+ # To use 7.x instruction style for compatibility
103
+ # And to add extra error messages, for compatibility with Typer in previous versions
104
+ # This is only called in new Command method, only used by Click 8.x+
105
+ def shell_complete(
106
+ cli: click.Command,
107
+ ctx_args: MutableMapping[str, Any],
108
+ prog_name: str,
109
+ complete_var: str,
110
+ instruction: str,
111
+ ) -> int:
112
+ import click
113
+ import click.shell_completion
114
+
115
+ if "_" not in instruction:
116
+ click.echo("Invalid completion instruction.", err=True)
117
+ return 1
118
+
119
+ # Click 8 changed the order/style of shell instructions from e.g.
120
+ # source_bash to bash_source
121
+ # Typer override to preserve the old style for compatibility
122
+ # Original in Click 8.x commented:
123
+ # shell, _, instruction = instruction.partition("_")
124
+ instruction, _, shell = instruction.partition("_")
125
+ # Typer override end
126
+
127
+ comp_cls = click.shell_completion.get_completion_class(shell)
128
+
129
+ if comp_cls is None:
130
+ click.echo(f"Shell {shell} not supported.", err=True)
131
+ return 1
132
+
133
+ comp = comp_cls(cli, ctx_args, prog_name, complete_var)
134
+
135
+ if instruction == "source":
136
+ click.echo(comp.source())
137
+ return 0
138
+
139
+ # Typer override to print the completion help msg with Rich
140
+ if instruction == "complete":
141
+ click.echo(comp.complete())
142
+ return 0
143
+ # Typer override end
144
+
145
+ click.echo(f'Completion instruction "{instruction}" not supported.', err=True)
146
+ return 1
loan-advisor-agent/.venv/Lib/site-packages/typer/core.py ADDED
@@ -0,0 +1,821 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import errno
2
+ import inspect
3
+ import os
4
+ import sys
5
+ from collections.abc import Callable, MutableMapping, Sequence
6
+ from difflib import get_close_matches
7
+ from enum import Enum
8
+ from gettext import gettext as _
9
+ from typing import (
10
+ Any,
11
+ TextIO,
12
+ Union,
13
+ cast,
14
+ )
15
+
16
+ import click
17
+ import click.core
18
+ import click.formatting
19
+ import click.shell_completion
20
+ import click.types
21
+ import click.utils
22
+
23
+ from ._typing import Literal
24
+ from .utils import parse_boolean_env_var
25
+
26
+ MarkupMode = Literal["markdown", "rich", None]
27
+ MARKUP_MODE_KEY = "TYPER_RICH_MARKUP_MODE"
28
+
29
+ HAS_RICH = parse_boolean_env_var(os.getenv("TYPER_USE_RICH"), default=True)
30
+
31
+ if HAS_RICH:
32
+ DEFAULT_MARKUP_MODE: MarkupMode = "rich"
33
+ else:
34
+ DEFAULT_MARKUP_MODE = None
35
+
36
+
37
+ # Copy from click.parser._split_opt
38
+ def _split_opt(opt: str) -> tuple[str, str]:
39
+ first = opt[:1]
40
+ if first.isalnum():
41
+ return "", opt
42
+ if opt[1:2] == first:
43
+ return opt[:2], opt[2:]
44
+ return first, opt[1:]
45
+
46
+
47
+ def _typer_param_setup_autocompletion_compat(
48
+ self: click.Parameter,
49
+ *,
50
+ autocompletion: Callable[
51
+ [click.Context, list[str], str], list[tuple[str, str] | str]
52
+ ]
53
+ | None = None,
54
+ ) -> None:
55
+ if self._custom_shell_complete is not None:
56
+ import warnings
57
+
58
+ warnings.warn(
59
+ "In Typer, only the parameter 'autocompletion' is supported. "
60
+ "The support for 'shell_complete' is deprecated and will be removed in upcoming versions. ",
61
+ DeprecationWarning,
62
+ stacklevel=2,
63
+ )
64
+
65
+ if autocompletion is not None:
66
+
67
+ def compat_autocompletion(
68
+ ctx: click.Context, param: click.core.Parameter, incomplete: str
69
+ ) -> list["click.shell_completion.CompletionItem"]:
70
+ from click.shell_completion import CompletionItem
71
+
72
+ out = []
73
+
74
+ for c in autocompletion(ctx, [], incomplete):
75
+ if isinstance(c, tuple):
76
+ use_completion = CompletionItem(c[0], help=c[1])
77
+ else:
78
+ assert isinstance(c, str)
79
+ use_completion = CompletionItem(c)
80
+
81
+ if use_completion.value.startswith(incomplete):
82
+ out.append(use_completion)
83
+
84
+ return out
85
+
86
+ self._custom_shell_complete = compat_autocompletion
87
+
88
+
89
+ def _get_default_string(
90
+ obj: Union["TyperArgument", "TyperOption"],
91
+ *,
92
+ ctx: click.Context,
93
+ show_default_is_str: bool,
94
+ default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any,
95
+ ) -> str:
96
+ # Extracted from click.core.Option.get_help_record() to be reused by
97
+ # rich_utils avoiding RegEx hacks
98
+ if show_default_is_str:
99
+ default_string = f"({obj.show_default})"
100
+ elif isinstance(default_value, (list, tuple)):
101
+ default_string = ", ".join(
102
+ _get_default_string(
103
+ obj, ctx=ctx, show_default_is_str=show_default_is_str, default_value=d
104
+ )
105
+ for d in default_value
106
+ )
107
+ elif isinstance(default_value, Enum):
108
+ default_string = str(default_value.value)
109
+ elif inspect.isfunction(default_value):
110
+ default_string = _("(dynamic)")
111
+ elif isinstance(obj, TyperOption) and obj.is_bool_flag and obj.secondary_opts:
112
+ # For boolean flags that have distinct True/False opts,
113
+ # use the opt without prefix instead of the value.
114
+ # Typer override, original commented
115
+ # default_string = click.parser.split_opt(
116
+ # (self.opts if self.default else self.secondary_opts)[0]
117
+ # )[1]
118
+ if obj.default:
119
+ if obj.opts:
120
+ default_string = _split_opt(obj.opts[0])[1]
121
+ else:
122
+ default_string = str(default_value)
123
+ else:
124
+ default_string = _split_opt(obj.secondary_opts[0])[1]
125
+ # Typer override end
126
+ elif (
127
+ isinstance(obj, TyperOption)
128
+ and obj.is_bool_flag
129
+ and not obj.secondary_opts
130
+ and not default_value
131
+ ):
132
+ default_string = ""
133
+ else:
134
+ default_string = str(default_value)
135
+ return default_string
136
+
137
+
138
+ def _extract_default_help_str(
139
+ obj: Union["TyperArgument", "TyperOption"], *, ctx: click.Context
140
+ ) -> Any | Callable[[], Any] | None:
141
+ # Extracted from click.core.Option.get_help_record() to be reused by
142
+ # rich_utils avoiding RegEx hacks
143
+ # Temporarily enable resilient parsing to avoid type casting
144
+ # failing for the default. Might be possible to extend this to
145
+ # help formatting in general.
146
+ resilient = ctx.resilient_parsing
147
+ ctx.resilient_parsing = True
148
+
149
+ try:
150
+ default_value = obj.get_default(ctx, call=False)
151
+ finally:
152
+ ctx.resilient_parsing = resilient
153
+ return default_value
154
+
155
+
156
+ def _main(
157
+ self: click.Command,
158
+ *,
159
+ args: Sequence[str] | None = None,
160
+ prog_name: str | None = None,
161
+ complete_var: str | None = None,
162
+ standalone_mode: bool = True,
163
+ windows_expand_args: bool = True,
164
+ rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,
165
+ **extra: Any,
166
+ ) -> Any:
167
+ # Typer override, duplicated from click.main() to handle custom rich exceptions
168
+ # Verify that the environment is configured correctly, or reject
169
+ # further execution to avoid a broken script.
170
+ if args is None:
171
+ args = sys.argv[1:]
172
+
173
+ # Covered in Click tests
174
+ if os.name == "nt" and windows_expand_args: # pragma: no cover
175
+ args = click.utils._expand_args(args)
176
+ else:
177
+ args = list(args)
178
+
179
+ if prog_name is None:
180
+ prog_name = click.utils._detect_program_name()
181
+
182
+ # Process shell completion requests and exit early.
183
+ self._main_shell_completion(extra, prog_name, complete_var)
184
+
185
+ try:
186
+ try:
187
+ with self.make_context(prog_name, args, **extra) as ctx:
188
+ rv = self.invoke(ctx)
189
+ if not standalone_mode:
190
+ return rv
191
+ # it's not safe to `ctx.exit(rv)` here!
192
+ # note that `rv` may actually contain data like "1" which
193
+ # has obvious effects
194
+ # more subtle case: `rv=[None, None]` can come out of
195
+ # chained commands which all returned `None` -- so it's not
196
+ # even always obvious that `rv` indicates success/failure
197
+ # by its truthiness/falsiness
198
+ ctx.exit()
199
+ except EOFError as e:
200
+ click.echo(file=sys.stderr)
201
+ raise click.Abort() from e
202
+ except KeyboardInterrupt as e:
203
+ raise click.exceptions.Exit(130) from e
204
+ except click.ClickException as e:
205
+ if not standalone_mode:
206
+ raise
207
+ # Typer override
208
+ if HAS_RICH and rich_markup_mode is not None:
209
+ from . import rich_utils
210
+
211
+ rich_utils.rich_format_error(e)
212
+ else:
213
+ e.show()
214
+ # Typer override end
215
+ sys.exit(e.exit_code)
216
+ except OSError as e:
217
+ if e.errno == errno.EPIPE:
218
+ sys.stdout = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stdout))
219
+ sys.stderr = cast(TextIO, click.utils.PacifyFlushWrapper(sys.stderr))
220
+ sys.exit(1)
221
+ else:
222
+ raise
223
+ except click.exceptions.Exit as e:
224
+ if standalone_mode:
225
+ sys.exit(e.exit_code)
226
+ else:
227
+ # in non-standalone mode, return the exit code
228
+ # note that this is only reached if `self.invoke` above raises
229
+ # an Exit explicitly -- thus bypassing the check there which
230
+ # would return its result
231
+ # the results of non-standalone execution may therefore be
232
+ # somewhat ambiguous: if there are codepaths which lead to
233
+ # `ctx.exit(1)` and to `return 1`, the caller won't be able to
234
+ # tell the difference between the two
235
+ return e.exit_code
236
+ except click.Abort:
237
+ if not standalone_mode:
238
+ raise
239
+ # Typer override
240
+ if HAS_RICH and rich_markup_mode is not None:
241
+ from . import rich_utils
242
+
243
+ rich_utils.rich_abort_error()
244
+ else:
245
+ click.echo(_("Aborted!"), file=sys.stderr)
246
+ # Typer override end
247
+ sys.exit(1)
248
+
249
+
250
+ class TyperArgument(click.core.Argument):
251
+ def __init__(
252
+ self,
253
+ *,
254
+ # Parameter
255
+ param_decls: list[str],
256
+ type: Any | None = None,
257
+ required: bool | None = None,
258
+ default: Any | None = None,
259
+ callback: Callable[..., Any] | None = None,
260
+ nargs: int | None = None,
261
+ metavar: str | None = None,
262
+ expose_value: bool = True,
263
+ is_eager: bool = False,
264
+ envvar: str | list[str] | None = None,
265
+ # Note that shell_complete is not fully supported and will be removed in future versions
266
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
267
+ shell_complete: Callable[
268
+ [click.Context, click.Parameter, str],
269
+ list["click.shell_completion.CompletionItem"] | list[str],
270
+ ]
271
+ | None = None,
272
+ autocompletion: Callable[..., Any] | None = None,
273
+ # TyperArgument
274
+ show_default: bool | str = True,
275
+ show_choices: bool = True,
276
+ show_envvar: bool = True,
277
+ help: str | None = None,
278
+ hidden: bool = False,
279
+ # Rich settings
280
+ rich_help_panel: str | None = None,
281
+ ):
282
+ self.help = help
283
+ self.show_default = show_default
284
+ self.show_choices = show_choices
285
+ self.show_envvar = show_envvar
286
+ self.hidden = hidden
287
+ self.rich_help_panel = rich_help_panel
288
+
289
+ super().__init__(
290
+ param_decls=param_decls,
291
+ type=type,
292
+ required=required,
293
+ default=default,
294
+ callback=callback,
295
+ nargs=nargs,
296
+ metavar=metavar,
297
+ expose_value=expose_value,
298
+ is_eager=is_eager,
299
+ envvar=envvar,
300
+ shell_complete=shell_complete,
301
+ )
302
+ _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion)
303
+
304
+ def _get_default_string(
305
+ self,
306
+ *,
307
+ ctx: click.Context,
308
+ show_default_is_str: bool,
309
+ default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any,
310
+ ) -> str:
311
+ return _get_default_string(
312
+ self,
313
+ ctx=ctx,
314
+ show_default_is_str=show_default_is_str,
315
+ default_value=default_value,
316
+ )
317
+
318
+ def _extract_default_help_str(
319
+ self, *, ctx: click.Context
320
+ ) -> Any | Callable[[], Any] | None:
321
+ return _extract_default_help_str(self, ctx=ctx)
322
+
323
+ def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None:
324
+ # Modified version of click.core.Option.get_help_record()
325
+ # to support Arguments
326
+ if self.hidden:
327
+ return None
328
+ name = self.make_metavar(ctx=ctx)
329
+ help = self.help or ""
330
+ extra = []
331
+ if self.show_envvar:
332
+ envvar = self.envvar
333
+ # allow_from_autoenv is currently not supported in Typer for CLI Arguments
334
+ if envvar is not None:
335
+ var_str = (
336
+ ", ".join(str(d) for d in envvar)
337
+ if isinstance(envvar, (list, tuple))
338
+ else envvar
339
+ )
340
+ extra.append(f"env var: {var_str}")
341
+
342
+ # Typer override:
343
+ # Extracted to _extract_default_help_str() to allow re-using it in rich_utils
344
+ default_value = self._extract_default_help_str(ctx=ctx)
345
+ # Typer override end
346
+
347
+ show_default_is_str = isinstance(self.show_default, str)
348
+
349
+ if show_default_is_str or (
350
+ default_value is not None and (self.show_default or ctx.show_default)
351
+ ):
352
+ # Typer override:
353
+ # Extracted to _get_default_string() to allow re-using it in rich_utils
354
+ default_string = self._get_default_string(
355
+ ctx=ctx,
356
+ show_default_is_str=show_default_is_str,
357
+ default_value=default_value,
358
+ )
359
+ # Typer override end
360
+ if default_string:
361
+ extra.append(_("default: {default}").format(default=default_string))
362
+ if self.required:
363
+ extra.append(_("required"))
364
+ if extra:
365
+ extra_str = "; ".join(extra)
366
+ extra_str = f"[{extra_str}]"
367
+ rich_markup_mode = None
368
+ if hasattr(ctx, "obj") and isinstance(ctx.obj, dict):
369
+ rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None)
370
+ if HAS_RICH and rich_markup_mode == "rich":
371
+ # This is needed for when we want to export to HTML
372
+ from . import rich_utils
373
+
374
+ extra_str = rich_utils.escape_before_html_export(extra_str)
375
+
376
+ help = f"{help} {extra_str}" if help else f"{extra_str}"
377
+ return name, help
378
+
379
+ def make_metavar(self, ctx: click.Context | None = None) -> str:
380
+ # Modified version of click.core.Argument.make_metavar()
381
+ # to include Argument name
382
+ if self.metavar is not None:
383
+ var = self.metavar
384
+ if not self.required and not var.startswith("["):
385
+ var = f"[{var}]"
386
+ return var
387
+ var = (self.name or "").upper()
388
+ if not self.required:
389
+ var = f"[{var}]"
390
+ type_var = self.type.get_metavar(self, ctx=ctx) # type: ignore[arg-type]
391
+ # type_var = self.type.get_metavar(self, ctx=ctx)
392
+ if type_var:
393
+ var += f":{type_var}"
394
+ if self.nargs != 1:
395
+ var += "..."
396
+ return var
397
+
398
+ def value_is_missing(self, value: Any) -> bool:
399
+ return _value_is_missing(self, value)
400
+
401
+
402
+ class TyperOption(click.core.Option):
403
+ def __init__(
404
+ self,
405
+ *,
406
+ # Parameter
407
+ param_decls: list[str],
408
+ type: click.types.ParamType | Any | None = None,
409
+ required: bool | None = None,
410
+ default: Any | None = None,
411
+ callback: Callable[..., Any] | None = None,
412
+ nargs: int | None = None,
413
+ metavar: str | None = None,
414
+ expose_value: bool = True,
415
+ is_eager: bool = False,
416
+ envvar: str | list[str] | None = None,
417
+ # Note that shell_complete is not fully supported and will be removed in future versions
418
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
419
+ shell_complete: Callable[
420
+ [click.Context, click.Parameter, str],
421
+ list["click.shell_completion.CompletionItem"] | list[str],
422
+ ]
423
+ | None = None,
424
+ autocompletion: Callable[..., Any] | None = None,
425
+ # Option
426
+ show_default: bool | str = False,
427
+ prompt: bool | str = False,
428
+ confirmation_prompt: bool | str = False,
429
+ prompt_required: bool = True,
430
+ hide_input: bool = False,
431
+ is_flag: bool | None = None,
432
+ multiple: bool = False,
433
+ count: bool = False,
434
+ allow_from_autoenv: bool = True,
435
+ help: str | None = None,
436
+ hidden: bool = False,
437
+ show_choices: bool = True,
438
+ show_envvar: bool = False,
439
+ # Rich settings
440
+ rich_help_panel: str | None = None,
441
+ ):
442
+ super().__init__(
443
+ param_decls=param_decls,
444
+ type=type,
445
+ required=required,
446
+ default=default,
447
+ callback=callback,
448
+ nargs=nargs,
449
+ metavar=metavar,
450
+ expose_value=expose_value,
451
+ is_eager=is_eager,
452
+ envvar=envvar,
453
+ show_default=show_default,
454
+ prompt=prompt,
455
+ confirmation_prompt=confirmation_prompt,
456
+ hide_input=hide_input,
457
+ is_flag=is_flag,
458
+ multiple=multiple,
459
+ count=count,
460
+ allow_from_autoenv=allow_from_autoenv,
461
+ help=help,
462
+ hidden=hidden,
463
+ show_choices=show_choices,
464
+ show_envvar=show_envvar,
465
+ prompt_required=prompt_required,
466
+ shell_complete=shell_complete,
467
+ )
468
+ _typer_param_setup_autocompletion_compat(self, autocompletion=autocompletion)
469
+ self.rich_help_panel = rich_help_panel
470
+
471
+ def _get_default_string(
472
+ self,
473
+ *,
474
+ ctx: click.Context,
475
+ show_default_is_str: bool,
476
+ default_value: list[Any] | tuple[Any, ...] | str | Callable[..., Any] | Any,
477
+ ) -> str:
478
+ return _get_default_string(
479
+ self,
480
+ ctx=ctx,
481
+ show_default_is_str=show_default_is_str,
482
+ default_value=default_value,
483
+ )
484
+
485
+ def _extract_default_help_str(
486
+ self, *, ctx: click.Context
487
+ ) -> Any | Callable[[], Any] | None:
488
+ return _extract_default_help_str(self, ctx=ctx)
489
+
490
+ def make_metavar(self, ctx: click.Context | None = None) -> str:
491
+ return super().make_metavar(ctx=ctx) # type: ignore[arg-type]
492
+
493
+ def get_help_record(self, ctx: click.Context) -> tuple[str, str] | None:
494
+ # Duplicate all of Click's logic only to modify a single line, to allow boolean
495
+ # flags with only names for False values as it's currently supported by Typer
496
+ # Ref: https://typer.tiangolo.com/tutorial/parameter-types/bool/#only-names-for-false
497
+ if self.hidden:
498
+ return None
499
+
500
+ any_prefix_is_slash = False
501
+
502
+ def _write_opts(opts: Sequence[str]) -> str:
503
+ nonlocal any_prefix_is_slash
504
+
505
+ rv, any_slashes = click.formatting.join_options(opts)
506
+
507
+ if any_slashes:
508
+ any_prefix_is_slash = True
509
+
510
+ if not self.is_flag and not self.count:
511
+ rv += f" {self.make_metavar(ctx=ctx)}"
512
+
513
+ return rv
514
+
515
+ rv = [_write_opts(self.opts)]
516
+
517
+ if self.secondary_opts:
518
+ rv.append(_write_opts(self.secondary_opts))
519
+
520
+ help = self.help or ""
521
+ extra = []
522
+
523
+ if self.show_envvar:
524
+ envvar = self.envvar
525
+
526
+ if envvar is None:
527
+ if (
528
+ self.allow_from_autoenv
529
+ and ctx.auto_envvar_prefix is not None
530
+ and self.name is not None
531
+ ):
532
+ envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
533
+
534
+ if envvar is not None:
535
+ var_str = (
536
+ envvar
537
+ if isinstance(envvar, str)
538
+ else ", ".join(str(d) for d in envvar)
539
+ )
540
+ extra.append(_("env var: {var}").format(var=var_str))
541
+
542
+ # Typer override:
543
+ # Extracted to _extract_default() to allow re-using it in rich_utils
544
+ default_value = self._extract_default_help_str(ctx=ctx)
545
+ # Typer override end
546
+
547
+ show_default_is_str = isinstance(self.show_default, str)
548
+
549
+ if show_default_is_str or (
550
+ default_value is not None and (self.show_default or ctx.show_default)
551
+ ):
552
+ # Typer override:
553
+ # Extracted to _get_default_string() to allow re-using it in rich_utils
554
+ default_string = self._get_default_string(
555
+ ctx=ctx,
556
+ show_default_is_str=show_default_is_str,
557
+ default_value=default_value,
558
+ )
559
+ # Typer override end
560
+ if default_string:
561
+ extra.append(_("default: {default}").format(default=default_string))
562
+
563
+ if isinstance(self.type, click.types._NumberRangeBase):
564
+ range_str = self.type._describe_range()
565
+
566
+ if range_str:
567
+ extra.append(range_str)
568
+
569
+ if self.required:
570
+ extra.append(_("required"))
571
+
572
+ if extra:
573
+ extra_str = "; ".join(extra)
574
+ extra_str = f"[{extra_str}]"
575
+ rich_markup_mode = None
576
+ if hasattr(ctx, "obj") and isinstance(ctx.obj, dict):
577
+ rich_markup_mode = ctx.obj.get(MARKUP_MODE_KEY, None)
578
+ if HAS_RICH and rich_markup_mode == "rich":
579
+ # This is needed for when we want to export to HTML
580
+ from . import rich_utils
581
+
582
+ extra_str = rich_utils.escape_before_html_export(extra_str)
583
+
584
+ help = f"{help} {extra_str}" if help else f"{extra_str}"
585
+
586
+ return ("; " if any_prefix_is_slash else " / ").join(rv), help
587
+
588
+ def value_is_missing(self, value: Any) -> bool:
589
+ return _value_is_missing(self, value)
590
+
591
+
592
+ def _value_is_missing(param: click.Parameter, value: Any) -> bool:
593
+ if value is None:
594
+ return True
595
+
596
+ # Click 8.3 and beyond
597
+ # if value is UNSET:
598
+ # return True
599
+
600
+ if (param.nargs != 1 or param.multiple) and value == ():
601
+ return True # pragma: no cover
602
+
603
+ return False
604
+
605
+
606
+ def _typer_format_options(
607
+ self: click.core.Command, *, ctx: click.Context, formatter: click.HelpFormatter
608
+ ) -> None:
609
+ args = []
610
+ opts = []
611
+ for param in self.get_params(ctx):
612
+ rv = param.get_help_record(ctx)
613
+ if rv is not None:
614
+ if param.param_type_name == "argument":
615
+ args.append(rv)
616
+ elif param.param_type_name == "option":
617
+ opts.append(rv)
618
+
619
+ if args:
620
+ with formatter.section(_("Arguments")):
621
+ formatter.write_dl(args)
622
+ if opts:
623
+ with formatter.section(_("Options")):
624
+ formatter.write_dl(opts)
625
+
626
+
627
+ def _typer_main_shell_completion(
628
+ self: click.core.Command,
629
+ *,
630
+ ctx_args: MutableMapping[str, Any],
631
+ prog_name: str,
632
+ complete_var: str | None = None,
633
+ ) -> None:
634
+ if complete_var is None:
635
+ complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()
636
+
637
+ instruction = os.environ.get(complete_var)
638
+
639
+ if not instruction:
640
+ return
641
+
642
+ from .completion import shell_complete
643
+
644
+ rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)
645
+ sys.exit(rv)
646
+
647
+
648
+ class TyperCommand(click.core.Command):
649
+ def __init__(
650
+ self,
651
+ name: str | None,
652
+ *,
653
+ context_settings: dict[str, Any] | None = None,
654
+ callback: Callable[..., Any] | None = None,
655
+ params: list[click.Parameter] | None = None,
656
+ help: str | None = None,
657
+ epilog: str | None = None,
658
+ short_help: str | None = None,
659
+ options_metavar: str | None = "[OPTIONS]",
660
+ add_help_option: bool = True,
661
+ no_args_is_help: bool = False,
662
+ hidden: bool = False,
663
+ deprecated: bool = False,
664
+ # Rich settings
665
+ rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,
666
+ rich_help_panel: str | None = None,
667
+ ) -> None:
668
+ super().__init__(
669
+ name=name,
670
+ context_settings=context_settings,
671
+ callback=callback,
672
+ params=params,
673
+ help=help,
674
+ epilog=epilog,
675
+ short_help=short_help,
676
+ options_metavar=options_metavar,
677
+ add_help_option=add_help_option,
678
+ no_args_is_help=no_args_is_help,
679
+ hidden=hidden,
680
+ deprecated=deprecated,
681
+ )
682
+ self.rich_markup_mode: MarkupMode = rich_markup_mode
683
+ self.rich_help_panel = rich_help_panel
684
+
685
+ def format_options(
686
+ self, ctx: click.Context, formatter: click.HelpFormatter
687
+ ) -> None:
688
+ _typer_format_options(self, ctx=ctx, formatter=formatter)
689
+
690
+ def _main_shell_completion(
691
+ self,
692
+ ctx_args: MutableMapping[str, Any],
693
+ prog_name: str,
694
+ complete_var: str | None = None,
695
+ ) -> None:
696
+ _typer_main_shell_completion(
697
+ self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var
698
+ )
699
+
700
+ def main(
701
+ self,
702
+ args: Sequence[str] | None = None,
703
+ prog_name: str | None = None,
704
+ complete_var: str | None = None,
705
+ standalone_mode: bool = True,
706
+ windows_expand_args: bool = True,
707
+ **extra: Any,
708
+ ) -> Any:
709
+ return _main(
710
+ self,
711
+ args=args,
712
+ prog_name=prog_name,
713
+ complete_var=complete_var,
714
+ standalone_mode=standalone_mode,
715
+ windows_expand_args=windows_expand_args,
716
+ rich_markup_mode=self.rich_markup_mode,
717
+ **extra,
718
+ )
719
+
720
+ def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
721
+ if not HAS_RICH or self.rich_markup_mode is None:
722
+ if not hasattr(ctx, "obj") or ctx.obj is None:
723
+ ctx.ensure_object(dict)
724
+ if isinstance(ctx.obj, dict):
725
+ ctx.obj[MARKUP_MODE_KEY] = self.rich_markup_mode
726
+ return super().format_help(ctx, formatter)
727
+ from . import rich_utils
728
+
729
+ return rich_utils.rich_format_help(
730
+ obj=self,
731
+ ctx=ctx,
732
+ markup_mode=self.rich_markup_mode,
733
+ )
734
+
735
+
736
+ class TyperGroup(click.core.Group):
737
+ def __init__(
738
+ self,
739
+ *,
740
+ name: str | None = None,
741
+ commands: dict[str, click.Command] | Sequence[click.Command] | None = None,
742
+ # Rich settings
743
+ rich_markup_mode: MarkupMode = DEFAULT_MARKUP_MODE,
744
+ rich_help_panel: str | None = None,
745
+ suggest_commands: bool = True,
746
+ **attrs: Any,
747
+ ) -> None:
748
+ super().__init__(name=name, commands=commands, **attrs)
749
+ self.rich_markup_mode: MarkupMode = rich_markup_mode
750
+ self.rich_help_panel = rich_help_panel
751
+ self.suggest_commands = suggest_commands
752
+
753
+ def format_options(
754
+ self, ctx: click.Context, formatter: click.HelpFormatter
755
+ ) -> None:
756
+ _typer_format_options(self, ctx=ctx, formatter=formatter)
757
+ self.format_commands(ctx, formatter)
758
+
759
+ def _main_shell_completion(
760
+ self,
761
+ ctx_args: MutableMapping[str, Any],
762
+ prog_name: str,
763
+ complete_var: str | None = None,
764
+ ) -> None:
765
+ _typer_main_shell_completion(
766
+ self, ctx_args=ctx_args, prog_name=prog_name, complete_var=complete_var
767
+ )
768
+
769
+ def resolve_command(
770
+ self, ctx: click.Context, args: list[str]
771
+ ) -> tuple[str | None, click.Command | None, list[str]]:
772
+ try:
773
+ return super().resolve_command(ctx, args)
774
+ except click.UsageError as e:
775
+ if self.suggest_commands:
776
+ available_commands = list(self.commands.keys())
777
+ if available_commands and args:
778
+ typo = args[0]
779
+ matches = get_close_matches(typo, available_commands)
780
+ if matches:
781
+ suggestions = ", ".join(f"{m!r}" for m in matches)
782
+ message = e.message.rstrip(".")
783
+ e.message = f"{message}. Did you mean {suggestions}?"
784
+ raise
785
+
786
+ def main(
787
+ self,
788
+ args: Sequence[str] | None = None,
789
+ prog_name: str | None = None,
790
+ complete_var: str | None = None,
791
+ standalone_mode: bool = True,
792
+ windows_expand_args: bool = True,
793
+ **extra: Any,
794
+ ) -> Any:
795
+ return _main(
796
+ self,
797
+ args=args,
798
+ prog_name=prog_name,
799
+ complete_var=complete_var,
800
+ standalone_mode=standalone_mode,
801
+ windows_expand_args=windows_expand_args,
802
+ rich_markup_mode=self.rich_markup_mode,
803
+ **extra,
804
+ )
805
+
806
+ def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
807
+ if not HAS_RICH or self.rich_markup_mode is None:
808
+ return super().format_help(ctx, formatter)
809
+ from . import rich_utils
810
+
811
+ return rich_utils.rich_format_help(
812
+ obj=self,
813
+ ctx=ctx,
814
+ markup_mode=self.rich_markup_mode,
815
+ )
816
+
817
+ def list_commands(self, ctx: click.Context) -> list[str]:
818
+ """Returns a list of subcommand names.
819
+ Note that in Click's Group class, these are sorted.
820
+ In Typer, we wish to maintain the original order of creation (cf Issue #933)"""
821
+ return [n for n, c in self.commands.items()]
loan-advisor-agent/.venv/Lib/site-packages/typer/main.py ADDED
@@ -0,0 +1,2013 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import os
3
+ import platform
4
+ import shutil
5
+ import subprocess
6
+ import sys
7
+ import traceback
8
+ from collections.abc import Callable, Sequence
9
+ from datetime import datetime
10
+ from enum import Enum
11
+ from functools import update_wrapper
12
+ from pathlib import Path
13
+ from traceback import FrameSummary, StackSummary
14
+ from types import TracebackType
15
+ from typing import Annotated, Any
16
+ from uuid import UUID
17
+
18
+ import click
19
+ from annotated_doc import Doc
20
+ from typer._types import TyperChoice
21
+
22
+ from ._typing import get_args, get_origin, is_literal_type, is_union, literal_values
23
+ from .completion import get_completion_inspect_parameters
24
+ from .core import (
25
+ DEFAULT_MARKUP_MODE,
26
+ HAS_RICH,
27
+ MarkupMode,
28
+ TyperArgument,
29
+ TyperCommand,
30
+ TyperGroup,
31
+ TyperOption,
32
+ )
33
+ from .models import (
34
+ AnyType,
35
+ ArgumentInfo,
36
+ CommandFunctionType,
37
+ CommandInfo,
38
+ Default,
39
+ DefaultPlaceholder,
40
+ DeveloperExceptionConfig,
41
+ FileBinaryRead,
42
+ FileBinaryWrite,
43
+ FileText,
44
+ FileTextWrite,
45
+ NoneType,
46
+ OptionInfo,
47
+ ParameterInfo,
48
+ ParamMeta,
49
+ Required,
50
+ TyperInfo,
51
+ TyperPath,
52
+ )
53
+ from .utils import get_params_from_function
54
+
55
+ _original_except_hook = sys.excepthook
56
+ _typer_developer_exception_attr_name = "__typer_developer_exception__"
57
+
58
+
59
+ def except_hook(
60
+ exc_type: type[BaseException], exc_value: BaseException, tb: TracebackType | None
61
+ ) -> None:
62
+ exception_config: DeveloperExceptionConfig | None = getattr(
63
+ exc_value, _typer_developer_exception_attr_name, None
64
+ )
65
+ standard_traceback = os.getenv(
66
+ "TYPER_STANDARD_TRACEBACK", os.getenv("_TYPER_STANDARD_TRACEBACK")
67
+ )
68
+ if (
69
+ standard_traceback
70
+ or not exception_config
71
+ or not exception_config.pretty_exceptions_enable
72
+ ):
73
+ _original_except_hook(exc_type, exc_value, tb)
74
+ return
75
+ typer_path = os.path.dirname(__file__)
76
+ click_path = os.path.dirname(click.__file__)
77
+ internal_dir_names = [typer_path, click_path]
78
+ exc = exc_value
79
+ if HAS_RICH:
80
+ from . import rich_utils
81
+
82
+ rich_tb = rich_utils.get_traceback(exc, exception_config, internal_dir_names)
83
+ console_stderr = rich_utils._get_rich_console(stderr=True)
84
+ console_stderr.print(rich_tb)
85
+ return
86
+ tb_exc = traceback.TracebackException.from_exception(exc)
87
+ stack: list[FrameSummary] = []
88
+ for frame in tb_exc.stack:
89
+ if any(frame.filename.startswith(path) for path in internal_dir_names):
90
+ if not exception_config.pretty_exceptions_short:
91
+ # Hide the line for internal libraries, Typer and Click
92
+ stack.append(
93
+ traceback.FrameSummary(
94
+ filename=frame.filename,
95
+ lineno=frame.lineno,
96
+ name=frame.name,
97
+ line="",
98
+ )
99
+ )
100
+ else:
101
+ stack.append(frame)
102
+ # Type ignore ref: https://github.com/python/typeshed/pull/8244
103
+ final_stack_summary = StackSummary.from_list(stack)
104
+ tb_exc.stack = final_stack_summary
105
+ for line in tb_exc.format():
106
+ print(line, file=sys.stderr)
107
+ return
108
+
109
+
110
+ def get_install_completion_arguments() -> tuple[click.Parameter, click.Parameter]:
111
+ install_param, show_param = get_completion_inspect_parameters()
112
+ click_install_param, _ = get_click_param(install_param)
113
+ click_show_param, _ = get_click_param(show_param)
114
+ return click_install_param, click_show_param
115
+
116
+
117
+ class Typer:
118
+ """
119
+ `Typer` main class, the main entrypoint to use Typer.
120
+
121
+ Read more in the
122
+ [Typer docs for First Steps](https://typer.tiangolo.com/tutorial/typer-app/).
123
+
124
+ ## Example
125
+
126
+ ```python
127
+ import typer
128
+
129
+ app = typer.Typer()
130
+ ```
131
+ """
132
+
133
+ def __init__(
134
+ self,
135
+ *,
136
+ name: Annotated[
137
+ str | None,
138
+ Doc(
139
+ """
140
+ The name of this application.
141
+ Mostly used to set the name for [subcommands](https://typer.tiangolo.com/tutorial/subcommands/), in which case it can be overridden by `add_typer(name=...)`.
142
+
143
+ **Example**
144
+
145
+ ```python
146
+ import typer
147
+
148
+ app = typer.Typer(name="users")
149
+ ```
150
+ """
151
+ ),
152
+ ] = Default(None),
153
+ cls: Annotated[
154
+ type[TyperGroup] | None,
155
+ Doc(
156
+ """
157
+ The class of this app. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`.
158
+ Otherwise, should be a subtype of `TyperGroup`.
159
+
160
+ **Example**
161
+
162
+ ```python
163
+ import typer
164
+
165
+ app = typer.Typer(cls=TyperGroup)
166
+ ```
167
+ """
168
+ ),
169
+ ] = Default(None),
170
+ invoke_without_command: Annotated[
171
+ bool,
172
+ Doc(
173
+ """
174
+ By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided.
175
+
176
+ **Example**
177
+
178
+ ```python
179
+ import typer
180
+
181
+ app = typer.Typer(invoke_without_command=True)
182
+ ```
183
+ """
184
+ ),
185
+ ] = Default(False),
186
+ no_args_is_help: Annotated[
187
+ bool,
188
+ Doc(
189
+ """
190
+ If this is set to `True`, running a command without any arguments will automatically show the help page.
191
+
192
+ **Example**
193
+
194
+ ```python
195
+ import typer
196
+
197
+ app = typer.Typer(no_args_is_help=True)
198
+ ```
199
+ """
200
+ ),
201
+ ] = Default(False),
202
+ subcommand_metavar: Annotated[
203
+ str | None,
204
+ Doc(
205
+ """
206
+ **Note**: you probably shouldn't use this parameter, it is inherited
207
+ from Click and supported for compatibility.
208
+
209
+ ---
210
+
211
+ How to represent the subcommand argument in help.
212
+ """
213
+ ),
214
+ ] = Default(None),
215
+ chain: Annotated[
216
+ bool,
217
+ Doc(
218
+ """
219
+ **Note**: you probably shouldn't use this parameter, it is inherited
220
+ from Click and supported for compatibility.
221
+
222
+ ---
223
+
224
+ Allow passing more than one subcommand argument.
225
+ """
226
+ ),
227
+ ] = Default(False),
228
+ result_callback: Annotated[
229
+ Callable[..., Any] | None,
230
+ Doc(
231
+ """
232
+ **Note**: you probably shouldn't use this parameter, it is inherited
233
+ from Click and supported for compatibility.
234
+
235
+ ---
236
+
237
+ A function to call after the group's and subcommand's callbacks.
238
+ """
239
+ ),
240
+ ] = Default(None),
241
+ # Command
242
+ context_settings: Annotated[
243
+ dict[Any, Any] | None,
244
+ Doc(
245
+ """
246
+ Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).
247
+ Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).
248
+
249
+ **Example**
250
+
251
+ ```python
252
+ import typer
253
+
254
+ app = typer.Typer(context_settings={"help_option_names": ["-h", "--help"]})
255
+ ```
256
+ """
257
+ ),
258
+ ] = Default(None),
259
+ callback: Annotated[
260
+ Callable[..., Any] | None,
261
+ Doc(
262
+ """
263
+ Add a callback to the main Typer app. Can be overridden with `@app.callback()`.
264
+ See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/commands/callback/) for more details.
265
+
266
+ **Example**
267
+
268
+ ```python
269
+ import typer
270
+
271
+ def callback():
272
+ print("Running a command")
273
+
274
+ app = typer.Typer(callback=callback)
275
+ ```
276
+ """
277
+ ),
278
+ ] = Default(None),
279
+ help: Annotated[
280
+ str | None,
281
+ Doc(
282
+ """
283
+ Help text for the main Typer app.
284
+ See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help,
285
+ and which one takes priority.
286
+
287
+ **Example**
288
+
289
+ ```python
290
+ import typer
291
+
292
+ app = typer.Typer(help="Some help.")
293
+ ```
294
+ """
295
+ ),
296
+ ] = Default(None),
297
+ epilog: Annotated[
298
+ str | None,
299
+ Doc(
300
+ """
301
+ Text that will be printed right after the help text.
302
+
303
+ **Example**
304
+
305
+ ```python
306
+ import typer
307
+
308
+ app = typer.Typer(epilog="May the force be with you")
309
+ ```
310
+ """
311
+ ),
312
+ ] = Default(None),
313
+ short_help: Annotated[
314
+ str | None,
315
+ Doc(
316
+ """
317
+ A shortened version of the help text that can be used e.g. in the help table listing subcommands.
318
+ When not defined, the normal `help` text will be used instead.
319
+
320
+ **Example**
321
+
322
+ ```python
323
+ import typer
324
+
325
+ app = typer.Typer(help="A lot of explanation about user management", short_help="user management")
326
+ ```
327
+ """
328
+ ),
329
+ ] = Default(None),
330
+ options_metavar: Annotated[
331
+ str,
332
+ Doc(
333
+ """
334
+ In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.
335
+ Set `options_metavar` to change this into a different string.
336
+
337
+ **Example**
338
+
339
+ ```python
340
+ import typer
341
+
342
+ app = typer.Typer(options_metavar="[OPTS]")
343
+ ```
344
+ """
345
+ ),
346
+ ] = Default("[OPTIONS]"),
347
+ add_help_option: Annotated[
348
+ bool,
349
+ Doc(
350
+ """
351
+ **Note**: you probably shouldn't use this parameter, it is inherited
352
+ from Click and supported for compatibility.
353
+
354
+ ---
355
+
356
+ By default each command registers a `--help` option. This can be disabled by this parameter.
357
+ """
358
+ ),
359
+ ] = Default(True),
360
+ hidden: Annotated[
361
+ bool,
362
+ Doc(
363
+ """
364
+ Hide this command from help outputs. `False` by default.
365
+
366
+ **Example**
367
+
368
+ ```python
369
+ import typer
370
+
371
+ app = typer.Typer(hidden=True)
372
+ ```
373
+ """
374
+ ),
375
+ ] = Default(False),
376
+ deprecated: Annotated[
377
+ bool,
378
+ Doc(
379
+ """
380
+ Mark this command as being deprecated in the help text. `False` by default.
381
+
382
+ **Example**
383
+
384
+ ```python
385
+ import typer
386
+
387
+ app = typer.Typer(deprecated=True)
388
+ ```
389
+ """
390
+ ),
391
+ ] = Default(False),
392
+ add_completion: Annotated[
393
+ bool,
394
+ Doc(
395
+ """
396
+ Toggle whether or not to add the `--install-completion` and `--show-completion` options to the app.
397
+ Set to `True` by default.
398
+
399
+ **Example**
400
+
401
+ ```python
402
+ import typer
403
+
404
+ app = typer.Typer(add_completion=False)
405
+ ```
406
+ """
407
+ ),
408
+ ] = True,
409
+ # Rich settings
410
+ rich_markup_mode: Annotated[
411
+ MarkupMode,
412
+ Doc(
413
+ """
414
+ Enable markup text if you have Rich installed. This can be set to `"markdown"`, `"rich"`, or `None`.
415
+ By default, `rich_markup_mode` is `None` if Rich is not installed, and `"rich"` if it is installed.
416
+ See [the tutorial on help formatting](https://typer.tiangolo.com/tutorial/commands/help/#rich-markdown-and-markup) for more information.
417
+
418
+ **Example**
419
+
420
+ ```python
421
+ import typer
422
+
423
+ app = typer.Typer(rich_markup_mode="rich")
424
+ ```
425
+ """
426
+ ),
427
+ ] = DEFAULT_MARKUP_MODE,
428
+ rich_help_panel: Annotated[
429
+ str | None,
430
+ Doc(
431
+ """
432
+ Set the panel name of the command when the help is printed with Rich.
433
+
434
+ **Example**
435
+
436
+ ```python
437
+ import typer
438
+
439
+ app = typer.Typer(rich_help_panel="Utils and Configs")
440
+ ```
441
+ """
442
+ ),
443
+ ] = Default(None),
444
+ suggest_commands: Annotated[
445
+ bool,
446
+ Doc(
447
+ """
448
+ As of version 0.20.0, Typer provides [support for mistyped command names](https://typer.tiangolo.com/tutorial/commands/help/#suggest-commands) by printing helpful suggestions.
449
+ You can turn this setting off with `suggest_commands`:
450
+
451
+ **Example**
452
+
453
+ ```python
454
+ import typer
455
+
456
+ app = typer.Typer(suggest_commands=False)
457
+ ```
458
+ """
459
+ ),
460
+ ] = True,
461
+ pretty_exceptions_enable: Annotated[
462
+ bool,
463
+ Doc(
464
+ """
465
+ If you want to disable [pretty exceptions with Rich](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-with-rich),
466
+ you can set `pretty_exceptions_enable` to `False`. When doing so, you will see the usual standard exception trace.
467
+
468
+ **Example**
469
+
470
+ ```python
471
+ import typer
472
+
473
+ app = typer.Typer(pretty_exceptions_enable=False)
474
+ ```
475
+ """
476
+ ),
477
+ ] = True,
478
+ pretty_exceptions_show_locals: Annotated[
479
+ bool,
480
+ Doc(
481
+ """
482
+ If Rich is installed, [error messages](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-and-errors)
483
+ will be nicely printed.
484
+
485
+ If you set `pretty_exceptions_show_locals=True` it will also include the values of local variables for easy debugging.
486
+
487
+ However, if such a variable contains delicate information, you should consider leaving `pretty_exceptions_show_locals=False`
488
+ (the default) to `False` to enhance security.
489
+
490
+ **Example**
491
+
492
+ ```python
493
+ import typer
494
+
495
+ app = typer.Typer(pretty_exceptions_show_locals=True)
496
+ ```
497
+ """
498
+ ),
499
+ ] = False,
500
+ pretty_exceptions_short: Annotated[
501
+ bool,
502
+ Doc(
503
+ """
504
+ By default, [pretty exceptions formatted with Rich](https://typer.tiangolo.com/tutorial/exceptions/#exceptions-with-rich) hide the long stack trace.
505
+ If you want to show the full trace instead, you can set the parameter `pretty_exceptions_short` to `False`:
506
+
507
+ **Example**
508
+
509
+ ```python
510
+ import typer
511
+
512
+ app = typer.Typer(pretty_exceptions_short=False)
513
+ ```
514
+ """
515
+ ),
516
+ ] = True,
517
+ ):
518
+ self._add_completion = add_completion
519
+ self.rich_markup_mode: MarkupMode = rich_markup_mode
520
+ self.rich_help_panel = rich_help_panel
521
+ self.suggest_commands = suggest_commands
522
+ self.pretty_exceptions_enable = pretty_exceptions_enable
523
+ self.pretty_exceptions_show_locals = pretty_exceptions_show_locals
524
+ self.pretty_exceptions_short = pretty_exceptions_short
525
+ self.info = TyperInfo(
526
+ name=name,
527
+ cls=cls,
528
+ invoke_without_command=invoke_without_command,
529
+ no_args_is_help=no_args_is_help,
530
+ subcommand_metavar=subcommand_metavar,
531
+ chain=chain,
532
+ result_callback=result_callback,
533
+ context_settings=context_settings,
534
+ callback=callback,
535
+ help=help,
536
+ epilog=epilog,
537
+ short_help=short_help,
538
+ options_metavar=options_metavar,
539
+ add_help_option=add_help_option,
540
+ hidden=hidden,
541
+ deprecated=deprecated,
542
+ )
543
+ self.registered_groups: list[TyperInfo] = []
544
+ self.registered_commands: list[CommandInfo] = []
545
+ self.registered_callback: TyperInfo | None = None
546
+
547
+ def callback(
548
+ self,
549
+ *,
550
+ cls: Annotated[
551
+ type[TyperGroup] | None,
552
+ Doc(
553
+ """
554
+ The class of this app. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`.
555
+ Otherwise, should be a subtype of `TyperGroup`.
556
+ """
557
+ ),
558
+ ] = Default(None),
559
+ invoke_without_command: Annotated[
560
+ bool,
561
+ Doc(
562
+ """
563
+ By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided.
564
+ """
565
+ ),
566
+ ] = Default(False),
567
+ no_args_is_help: Annotated[
568
+ bool,
569
+ Doc(
570
+ """
571
+ If this is set to `True`, running a command without any arguments will automatically show the help page.
572
+ """
573
+ ),
574
+ ] = Default(False),
575
+ subcommand_metavar: Annotated[
576
+ str | None,
577
+ Doc(
578
+ """
579
+ **Note**: you probably shouldn't use this parameter, it is inherited
580
+ from Click and supported for compatibility.
581
+
582
+ ---
583
+
584
+ How to represent the subcommand argument in help.
585
+ """
586
+ ),
587
+ ] = Default(None),
588
+ chain: Annotated[
589
+ bool,
590
+ Doc(
591
+ """
592
+ **Note**: you probably shouldn't use this parameter, it is inherited
593
+ from Click and supported for compatibility.
594
+
595
+ ---
596
+
597
+ Allow passing more than one subcommand argument.
598
+ """
599
+ ),
600
+ ] = Default(False),
601
+ result_callback: Annotated[
602
+ Callable[..., Any] | None,
603
+ Doc(
604
+ """
605
+ **Note**: you probably shouldn't use this parameter, it is inherited
606
+ from Click and supported for compatibility.
607
+
608
+ ---
609
+
610
+ A function to call after the group's and subcommand's callbacks.
611
+ """
612
+ ),
613
+ ] = Default(None),
614
+ # Command
615
+ context_settings: Annotated[
616
+ dict[Any, Any] | None,
617
+ Doc(
618
+ """
619
+ Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).
620
+ Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).
621
+ """
622
+ ),
623
+ ] = Default(None),
624
+ help: Annotated[
625
+ str | None,
626
+ Doc(
627
+ """
628
+ Help text for the command.
629
+ See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help,
630
+ and which one takes priority.
631
+ """
632
+ ),
633
+ ] = Default(None),
634
+ epilog: Annotated[
635
+ str | None,
636
+ Doc(
637
+ """
638
+ Text that will be printed right after the help text.
639
+ """
640
+ ),
641
+ ] = Default(None),
642
+ short_help: Annotated[
643
+ str | None,
644
+ Doc(
645
+ """
646
+ A shortened version of the help text that can be used e.g. in the help table listing subcommands.
647
+ When not defined, the normal `help` text will be used instead.
648
+ """
649
+ ),
650
+ ] = Default(None),
651
+ options_metavar: Annotated[
652
+ str | None,
653
+ Doc(
654
+ """
655
+ In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.
656
+ Set `options_metavar` to change this into a different string. When `None`, the default value will be used.
657
+ """
658
+ ),
659
+ ] = Default(None),
660
+ add_help_option: Annotated[
661
+ bool,
662
+ Doc(
663
+ """
664
+ **Note**: you probably shouldn't use this parameter, it is inherited
665
+ from Click and supported for compatibility.
666
+
667
+ ---
668
+
669
+ By default each command registers a `--help` option. This can be disabled by this parameter.
670
+ """
671
+ ),
672
+ ] = Default(True),
673
+ hidden: Annotated[
674
+ bool,
675
+ Doc(
676
+ """
677
+ Hide this command from help outputs. `False` by default.
678
+ """
679
+ ),
680
+ ] = Default(False),
681
+ deprecated: Annotated[
682
+ bool,
683
+ Doc(
684
+ """
685
+ Mark this command as deprecated in the help text. `False` by default.
686
+ """
687
+ ),
688
+ ] = Default(False),
689
+ # Rich settings
690
+ rich_help_panel: Annotated[
691
+ str | None,
692
+ Doc(
693
+ """
694
+ Set the panel name of the command when the help is printed with Rich.
695
+ """
696
+ ),
697
+ ] = Default(None),
698
+ ) -> Callable[[CommandFunctionType], CommandFunctionType]:
699
+ """
700
+ Using the decorator `@app.callback`, you can declare the CLI parameters for the main CLI application.
701
+
702
+ Read more in the
703
+ [Typer docs for Callbacks](https://typer.tiangolo.com/tutorial/commands/callback/).
704
+
705
+ ## Example
706
+
707
+ ```python
708
+ import typer
709
+
710
+ app = typer.Typer()
711
+ state = {"verbose": False}
712
+
713
+ @app.callback()
714
+ def main(verbose: bool = False):
715
+ if verbose:
716
+ print("Will write verbose output")
717
+ state["verbose"] = True
718
+
719
+ @app.command()
720
+ def delete(username: str):
721
+ # define subcommand
722
+ ...
723
+ ```
724
+ """
725
+
726
+ def decorator(f: CommandFunctionType) -> CommandFunctionType:
727
+ self.registered_callback = TyperInfo(
728
+ cls=cls,
729
+ invoke_without_command=invoke_without_command,
730
+ no_args_is_help=no_args_is_help,
731
+ subcommand_metavar=subcommand_metavar,
732
+ chain=chain,
733
+ result_callback=result_callback,
734
+ context_settings=context_settings,
735
+ callback=f,
736
+ help=help,
737
+ epilog=epilog,
738
+ short_help=short_help,
739
+ options_metavar=(
740
+ options_metavar or self._info_val_str("options_metavar")
741
+ ),
742
+ add_help_option=add_help_option,
743
+ hidden=hidden,
744
+ deprecated=deprecated,
745
+ rich_help_panel=rich_help_panel,
746
+ )
747
+ return f
748
+
749
+ return decorator
750
+
751
+ def command(
752
+ self,
753
+ name: Annotated[
754
+ str | None,
755
+ Doc(
756
+ """
757
+ The name of this command.
758
+ """
759
+ ),
760
+ ] = None,
761
+ *,
762
+ cls: Annotated[
763
+ type[TyperCommand] | None,
764
+ Doc(
765
+ """
766
+ The class of this command. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`.
767
+ Otherwise, should be a subtype of `TyperCommand`.
768
+ """
769
+ ),
770
+ ] = None,
771
+ context_settings: Annotated[
772
+ dict[Any, Any] | None,
773
+ Doc(
774
+ """
775
+ Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).
776
+ Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).
777
+ """
778
+ ),
779
+ ] = None,
780
+ help: Annotated[
781
+ str | None,
782
+ Doc(
783
+ """
784
+ Help text for the command.
785
+ See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help,
786
+ and which one takes priority.
787
+ """
788
+ ),
789
+ ] = None,
790
+ epilog: Annotated[
791
+ str | None,
792
+ Doc(
793
+ """
794
+ Text that will be printed right after the help text.
795
+ """
796
+ ),
797
+ ] = None,
798
+ short_help: Annotated[
799
+ str | None,
800
+ Doc(
801
+ """
802
+ A shortened version of the help text that can be used e.g. in the help table listing subcommands.
803
+ When not defined, the normal `help` text will be used instead.
804
+ """
805
+ ),
806
+ ] = None,
807
+ options_metavar: Annotated[
808
+ str | None,
809
+ Doc(
810
+ """
811
+ In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.
812
+ Set `options_metavar` to change this into a different string. When `None`, the default value will be used.
813
+ """
814
+ ),
815
+ ] = Default(None),
816
+ add_help_option: Annotated[
817
+ bool,
818
+ Doc(
819
+ """
820
+ **Note**: you probably shouldn't use this parameter, it is inherited
821
+ from Click and supported for compatibility.
822
+
823
+ ---
824
+
825
+ By default each command registers a `--help` option. This can be disabled by this parameter.
826
+ """
827
+ ),
828
+ ] = True,
829
+ no_args_is_help: Annotated[
830
+ bool,
831
+ Doc(
832
+ """
833
+ If this is set to `True`, running a command without any arguments will automatically show the help page.
834
+ """
835
+ ),
836
+ ] = False,
837
+ hidden: Annotated[
838
+ bool,
839
+ Doc(
840
+ """
841
+ Hide this command from help outputs. `False` by default.
842
+ """
843
+ ),
844
+ ] = False,
845
+ deprecated: Annotated[
846
+ bool,
847
+ Doc(
848
+ """
849
+ Mark this command as deprecated in the help outputs. `False` by default.
850
+ """
851
+ ),
852
+ ] = False,
853
+ # Rich settings
854
+ rich_help_panel: Annotated[
855
+ str | None,
856
+ Doc(
857
+ """
858
+ Set the panel name of the command when the help is printed with Rich.
859
+ """
860
+ ),
861
+ ] = Default(None),
862
+ ) -> Callable[[CommandFunctionType], CommandFunctionType]:
863
+ """
864
+ Using the decorator `@app.command`, you can define a subcommand of the previously defined Typer app.
865
+
866
+ Read more in the
867
+ [Typer docs for Commands](https://typer.tiangolo.com/tutorial/commands/).
868
+
869
+ ## Example
870
+
871
+ ```python
872
+ import typer
873
+
874
+ app = typer.Typer()
875
+
876
+ @app.command()
877
+ def create():
878
+ print("Creating user: Hiro Hamada")
879
+
880
+ @app.command()
881
+ def delete():
882
+ print("Deleting user: Hiro Hamada")
883
+ ```
884
+ """
885
+ if cls is None:
886
+ cls = TyperCommand
887
+
888
+ def decorator(f: CommandFunctionType) -> CommandFunctionType:
889
+ self.registered_commands.append(
890
+ CommandInfo(
891
+ name=name,
892
+ cls=cls,
893
+ context_settings=context_settings,
894
+ callback=f,
895
+ help=help,
896
+ epilog=epilog,
897
+ short_help=short_help,
898
+ options_metavar=(
899
+ options_metavar or self._info_val_str("options_metavar")
900
+ ),
901
+ add_help_option=add_help_option,
902
+ no_args_is_help=no_args_is_help,
903
+ hidden=hidden,
904
+ deprecated=deprecated,
905
+ # Rich settings
906
+ rich_help_panel=rich_help_panel,
907
+ )
908
+ )
909
+ return f
910
+
911
+ return decorator
912
+
913
+ def add_typer(
914
+ self,
915
+ typer_instance: "Typer",
916
+ *,
917
+ name: Annotated[
918
+ str | None,
919
+ Doc(
920
+ """
921
+ The name of this subcommand.
922
+ See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's name,
923
+ and which one takes priority.
924
+ """
925
+ ),
926
+ ] = Default(None),
927
+ cls: Annotated[
928
+ type[TyperGroup] | None,
929
+ Doc(
930
+ """
931
+ The class of this subcommand. Mainly used when [using the Click library underneath](https://typer.tiangolo.com/tutorial/using-click/). Can usually be left at the default value `None`.
932
+ Otherwise, should be a subtype of `TyperGroup`.
933
+ """
934
+ ),
935
+ ] = Default(None),
936
+ invoke_without_command: Annotated[
937
+ bool,
938
+ Doc(
939
+ """
940
+ By setting this to `True`, you can make sure a callback is executed even when no subcommand is provided.
941
+ """
942
+ ),
943
+ ] = Default(False),
944
+ no_args_is_help: Annotated[
945
+ bool,
946
+ Doc(
947
+ """
948
+ If this is set to `True`, running a command without any arguments will automatically show the help page.
949
+ """
950
+ ),
951
+ ] = Default(False),
952
+ subcommand_metavar: Annotated[
953
+ str | None,
954
+ Doc(
955
+ """
956
+ **Note**: you probably shouldn't use this parameter, it is inherited
957
+ from Click and supported for compatibility.
958
+
959
+ ---
960
+
961
+ How to represent the subcommand argument in help.
962
+ """
963
+ ),
964
+ ] = Default(None),
965
+ chain: Annotated[
966
+ bool,
967
+ Doc(
968
+ """
969
+ **Note**: you probably shouldn't use this parameter, it is inherited
970
+ from Click and supported for compatibility.
971
+
972
+ ---
973
+
974
+ Allow passing more than one subcommand argument.
975
+ """
976
+ ),
977
+ ] = Default(False),
978
+ result_callback: Annotated[
979
+ Callable[..., Any] | None,
980
+ Doc(
981
+ """
982
+ **Note**: you probably shouldn't use this parameter, it is inherited
983
+ from Click and supported for compatibility.
984
+
985
+ ---
986
+
987
+ A function to call after the group's and subcommand's callbacks.
988
+ """
989
+ ),
990
+ ] = Default(None),
991
+ # Command
992
+ context_settings: Annotated[
993
+ dict[Any, Any] | None,
994
+ Doc(
995
+ """
996
+ Pass configurations for the [context](https://typer.tiangolo.com/tutorial/commands/context/).
997
+ Available configurations can be found in the docs for Click's `Context` [here](https://click.palletsprojects.com/en/stable/api/#context).
998
+ """
999
+ ),
1000
+ ] = Default(None),
1001
+ callback: Annotated[
1002
+ Callable[..., Any] | None,
1003
+ Doc(
1004
+ """
1005
+ Add a callback to this app.
1006
+ See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/commands/callback/) for more details.
1007
+ """
1008
+ ),
1009
+ ] = Default(None),
1010
+ help: Annotated[
1011
+ str | None,
1012
+ Doc(
1013
+ """
1014
+ Help text for the subcommand.
1015
+ See [the tutorial about name and help](https://typer.tiangolo.com/tutorial/subcommands/name-and-help) for different ways of setting a command's help,
1016
+ and which one takes priority.
1017
+ """
1018
+ ),
1019
+ ] = Default(None),
1020
+ epilog: Annotated[
1021
+ str | None,
1022
+ Doc(
1023
+ """
1024
+ Text that will be printed right after the help text.
1025
+ """
1026
+ ),
1027
+ ] = Default(None),
1028
+ short_help: Annotated[
1029
+ str | None,
1030
+ Doc(
1031
+ """
1032
+ A shortened version of the help text that can be used e.g. in the help table listing subcommands.
1033
+ When not defined, the normal `help` text will be used instead.
1034
+ """
1035
+ ),
1036
+ ] = Default(None),
1037
+ options_metavar: Annotated[
1038
+ str | None,
1039
+ Doc(
1040
+ """
1041
+ In the example usage string of the help text for a command, the default placeholder for various arguments is `[OPTIONS]`.
1042
+ Set `options_metavar` to change this into a different string. When `None`, the default value will be used.
1043
+ """
1044
+ ),
1045
+ ] = Default(None),
1046
+ add_help_option: Annotated[
1047
+ bool,
1048
+ Doc(
1049
+ """
1050
+ **Note**: you probably shouldn't use this parameter, it is inherited
1051
+ from Click and supported for compatibility.
1052
+
1053
+ ---
1054
+
1055
+ By default each command registers a `--help` option. This can be disabled by this parameter.
1056
+ """
1057
+ ),
1058
+ ] = Default(True),
1059
+ hidden: Annotated[
1060
+ bool,
1061
+ Doc(
1062
+ """
1063
+ Hide this command from help outputs. `False` by default.
1064
+ """
1065
+ ),
1066
+ ] = Default(False),
1067
+ deprecated: Annotated[
1068
+ bool,
1069
+ Doc(
1070
+ """
1071
+ Mark this command as deprecated in the help outputs. `False` by default.
1072
+ """
1073
+ ),
1074
+ ] = False,
1075
+ # Rich settings
1076
+ rich_help_panel: Annotated[
1077
+ str | None,
1078
+ Doc(
1079
+ """
1080
+ Set the panel name of the command when the help is printed with Rich.
1081
+ """
1082
+ ),
1083
+ ] = Default(None),
1084
+ ) -> None:
1085
+ """
1086
+ Add subcommands to the main app using `app.add_typer()`.
1087
+ Subcommands may be defined in separate modules, ensuring clean separation of code by functionality.
1088
+
1089
+ Read more in the
1090
+ [Typer docs for SubCommands](https://typer.tiangolo.com/tutorial/subcommands/add-typer/).
1091
+
1092
+ ## Example
1093
+
1094
+ ```python
1095
+ import typer
1096
+
1097
+ from .add import app as add_app
1098
+ from .delete import app as delete_app
1099
+
1100
+ app = typer.Typer()
1101
+
1102
+ app.add_typer(add_app)
1103
+ app.add_typer(delete_app)
1104
+ ```
1105
+ """
1106
+ self.registered_groups.append(
1107
+ TyperInfo(
1108
+ typer_instance,
1109
+ name=name,
1110
+ cls=cls,
1111
+ invoke_without_command=invoke_without_command,
1112
+ no_args_is_help=no_args_is_help,
1113
+ subcommand_metavar=subcommand_metavar,
1114
+ chain=chain,
1115
+ result_callback=result_callback,
1116
+ context_settings=context_settings,
1117
+ callback=callback,
1118
+ help=help,
1119
+ epilog=epilog,
1120
+ short_help=short_help,
1121
+ options_metavar=(
1122
+ options_metavar or self._info_val_str("options_metavar")
1123
+ ),
1124
+ add_help_option=add_help_option,
1125
+ hidden=hidden,
1126
+ deprecated=deprecated,
1127
+ rich_help_panel=rich_help_panel,
1128
+ )
1129
+ )
1130
+
1131
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
1132
+ if sys.excepthook != except_hook:
1133
+ sys.excepthook = except_hook
1134
+ try:
1135
+ return get_command(self)(*args, **kwargs)
1136
+ except Exception as e:
1137
+ # Set a custom attribute to tell the hook to show nice exceptions for user
1138
+ # code. An alternative/first implementation was a custom exception with
1139
+ # raise custom_exc from e
1140
+ # but that means the last error shown is the custom exception, not the
1141
+ # actual error. This trick improves developer experience by showing the
1142
+ # actual error last.
1143
+ setattr(
1144
+ e,
1145
+ _typer_developer_exception_attr_name,
1146
+ DeveloperExceptionConfig(
1147
+ pretty_exceptions_enable=self.pretty_exceptions_enable,
1148
+ pretty_exceptions_show_locals=self.pretty_exceptions_show_locals,
1149
+ pretty_exceptions_short=self.pretty_exceptions_short,
1150
+ ),
1151
+ )
1152
+ raise e
1153
+
1154
+ def _info_val_str(self, name: str) -> str:
1155
+ val = getattr(self.info, name)
1156
+ val_str = val.value if isinstance(val, DefaultPlaceholder) else val
1157
+ assert isinstance(val_str, str)
1158
+ return val_str
1159
+
1160
+
1161
+ def get_group(typer_instance: Typer) -> TyperGroup:
1162
+ group = get_group_from_info(
1163
+ TyperInfo(typer_instance),
1164
+ pretty_exceptions_short=typer_instance.pretty_exceptions_short,
1165
+ rich_markup_mode=typer_instance.rich_markup_mode,
1166
+ suggest_commands=typer_instance.suggest_commands,
1167
+ )
1168
+ return group
1169
+
1170
+
1171
+ def get_command(typer_instance: Typer) -> click.Command:
1172
+ if typer_instance._add_completion:
1173
+ click_install_param, click_show_param = get_install_completion_arguments()
1174
+ if (
1175
+ typer_instance.registered_callback
1176
+ or typer_instance.info.callback
1177
+ or typer_instance.registered_groups
1178
+ or len(typer_instance.registered_commands) > 1
1179
+ ):
1180
+ # Create a Group
1181
+ click_command: click.Command = get_group(typer_instance)
1182
+ if typer_instance._add_completion:
1183
+ click_command.params.append(click_install_param)
1184
+ click_command.params.append(click_show_param)
1185
+ return click_command
1186
+ elif len(typer_instance.registered_commands) == 1:
1187
+ # Create a single Command
1188
+ single_command = typer_instance.registered_commands[0]
1189
+
1190
+ if not single_command.context_settings and not isinstance(
1191
+ typer_instance.info.context_settings, DefaultPlaceholder
1192
+ ):
1193
+ single_command.context_settings = typer_instance.info.context_settings
1194
+
1195
+ click_command = get_command_from_info(
1196
+ single_command,
1197
+ pretty_exceptions_short=typer_instance.pretty_exceptions_short,
1198
+ rich_markup_mode=typer_instance.rich_markup_mode,
1199
+ )
1200
+ if typer_instance._add_completion:
1201
+ click_command.params.append(click_install_param)
1202
+ click_command.params.append(click_show_param)
1203
+ return click_command
1204
+ raise RuntimeError(
1205
+ "Could not get a command for this Typer instance"
1206
+ ) # pragma: no cover
1207
+
1208
+
1209
+ def solve_typer_info_help(typer_info: TyperInfo) -> str:
1210
+ # Priority 1: Explicit value was set in app.add_typer()
1211
+ if not isinstance(typer_info.help, DefaultPlaceholder):
1212
+ return inspect.cleandoc(typer_info.help or "")
1213
+ # Priority 2: Explicit value was set in sub_app.callback()
1214
+ if typer_info.typer_instance and typer_info.typer_instance.registered_callback:
1215
+ callback_help = typer_info.typer_instance.registered_callback.help
1216
+ if not isinstance(callback_help, DefaultPlaceholder):
1217
+ return inspect.cleandoc(callback_help or "")
1218
+ # Priority 3: Explicit value was set in sub_app = typer.Typer()
1219
+ if typer_info.typer_instance and typer_info.typer_instance.info:
1220
+ instance_help = typer_info.typer_instance.info.help
1221
+ if not isinstance(instance_help, DefaultPlaceholder):
1222
+ return inspect.cleandoc(instance_help or "")
1223
+ # Priority 4: Implicit inference from callback docstring in app.add_typer()
1224
+ if typer_info.callback:
1225
+ doc = inspect.getdoc(typer_info.callback)
1226
+ if doc:
1227
+ return doc
1228
+ # Priority 5: Implicit inference from callback docstring in @app.callback()
1229
+ if typer_info.typer_instance and typer_info.typer_instance.registered_callback:
1230
+ callback = typer_info.typer_instance.registered_callback.callback
1231
+ if not isinstance(callback, DefaultPlaceholder):
1232
+ doc = inspect.getdoc(callback or "")
1233
+ if doc:
1234
+ return doc
1235
+ # Priority 6: Implicit inference from callback docstring in typer.Typer()
1236
+ if typer_info.typer_instance and typer_info.typer_instance.info:
1237
+ instance_callback = typer_info.typer_instance.info.callback
1238
+ if not isinstance(instance_callback, DefaultPlaceholder):
1239
+ doc = inspect.getdoc(instance_callback)
1240
+ if doc:
1241
+ return doc
1242
+ # Value not set, use the default
1243
+ return typer_info.help.value
1244
+
1245
+
1246
+ def solve_typer_info_defaults(typer_info: TyperInfo) -> TyperInfo:
1247
+ values: dict[str, Any] = {}
1248
+ for name, value in typer_info.__dict__.items():
1249
+ # Priority 1: Value was set in app.add_typer()
1250
+ if not isinstance(value, DefaultPlaceholder):
1251
+ values[name] = value
1252
+ continue
1253
+ # Priority 2: Value was set in @subapp.callback()
1254
+ try:
1255
+ callback_value = getattr(
1256
+ typer_info.typer_instance.registered_callback, # type: ignore
1257
+ name,
1258
+ )
1259
+ if not isinstance(callback_value, DefaultPlaceholder):
1260
+ values[name] = callback_value
1261
+ continue
1262
+ except AttributeError:
1263
+ pass
1264
+ # Priority 3: Value set in subapp = typer.Typer()
1265
+ try:
1266
+ instance_value = getattr(
1267
+ typer_info.typer_instance.info, # type: ignore
1268
+ name,
1269
+ )
1270
+ if not isinstance(instance_value, DefaultPlaceholder):
1271
+ values[name] = instance_value
1272
+ continue
1273
+ except AttributeError:
1274
+ pass
1275
+ # Value not set, use the default
1276
+ values[name] = value.value
1277
+ values["help"] = solve_typer_info_help(typer_info)
1278
+ return TyperInfo(**values)
1279
+
1280
+
1281
+ def get_group_from_info(
1282
+ group_info: TyperInfo,
1283
+ *,
1284
+ pretty_exceptions_short: bool,
1285
+ suggest_commands: bool,
1286
+ rich_markup_mode: MarkupMode,
1287
+ ) -> TyperGroup:
1288
+ assert group_info.typer_instance, (
1289
+ "A Typer instance is needed to generate a Click Group"
1290
+ )
1291
+ commands: dict[str, click.Command] = {}
1292
+ for command_info in group_info.typer_instance.registered_commands:
1293
+ command = get_command_from_info(
1294
+ command_info=command_info,
1295
+ pretty_exceptions_short=pretty_exceptions_short,
1296
+ rich_markup_mode=rich_markup_mode,
1297
+ )
1298
+ if command.name:
1299
+ commands[command.name] = command
1300
+ for sub_group_info in group_info.typer_instance.registered_groups:
1301
+ sub_group = get_group_from_info(
1302
+ sub_group_info,
1303
+ pretty_exceptions_short=pretty_exceptions_short,
1304
+ rich_markup_mode=rich_markup_mode,
1305
+ suggest_commands=suggest_commands,
1306
+ )
1307
+ if sub_group.name:
1308
+ commands[sub_group.name] = sub_group
1309
+ else:
1310
+ if sub_group.callback:
1311
+ import warnings
1312
+
1313
+ warnings.warn(
1314
+ "The 'callback' parameter is not supported by Typer when using `add_typer` without a name",
1315
+ stacklevel=5,
1316
+ )
1317
+ for sub_command_name, sub_command in sub_group.commands.items():
1318
+ commands[sub_command_name] = sub_command
1319
+ solved_info = solve_typer_info_defaults(group_info)
1320
+ (
1321
+ params,
1322
+ convertors,
1323
+ context_param_name,
1324
+ ) = get_params_convertors_ctx_param_name_from_function(solved_info.callback)
1325
+ cls = solved_info.cls or TyperGroup
1326
+ assert issubclass(cls, TyperGroup), f"{cls} should be a subclass of {TyperGroup}"
1327
+ group = cls(
1328
+ name=solved_info.name or "",
1329
+ commands=commands,
1330
+ invoke_without_command=solved_info.invoke_without_command,
1331
+ no_args_is_help=solved_info.no_args_is_help,
1332
+ subcommand_metavar=solved_info.subcommand_metavar,
1333
+ chain=solved_info.chain,
1334
+ result_callback=solved_info.result_callback,
1335
+ context_settings=solved_info.context_settings,
1336
+ callback=get_callback(
1337
+ callback=solved_info.callback,
1338
+ params=params,
1339
+ convertors=convertors,
1340
+ context_param_name=context_param_name,
1341
+ pretty_exceptions_short=pretty_exceptions_short,
1342
+ ),
1343
+ params=params,
1344
+ help=solved_info.help,
1345
+ epilog=solved_info.epilog,
1346
+ short_help=solved_info.short_help,
1347
+ options_metavar=solved_info.options_metavar,
1348
+ add_help_option=solved_info.add_help_option,
1349
+ hidden=solved_info.hidden,
1350
+ deprecated=solved_info.deprecated,
1351
+ rich_markup_mode=rich_markup_mode,
1352
+ # Rich settings
1353
+ rich_help_panel=solved_info.rich_help_panel,
1354
+ suggest_commands=suggest_commands,
1355
+ )
1356
+ return group
1357
+
1358
+
1359
+ def get_command_name(name: str) -> str:
1360
+ return name.lower().replace("_", "-")
1361
+
1362
+
1363
+ def get_params_convertors_ctx_param_name_from_function(
1364
+ callback: Callable[..., Any] | None,
1365
+ ) -> tuple[list[click.Argument | click.Option], dict[str, Any], str | None]:
1366
+ params = []
1367
+ convertors = {}
1368
+ context_param_name = None
1369
+ if callback:
1370
+ parameters = get_params_from_function(callback)
1371
+ for param_name, param in parameters.items():
1372
+ if lenient_issubclass(param.annotation, click.Context):
1373
+ context_param_name = param_name
1374
+ continue
1375
+ click_param, convertor = get_click_param(param)
1376
+ if convertor:
1377
+ convertors[param_name] = convertor
1378
+ params.append(click_param)
1379
+ return params, convertors, context_param_name
1380
+
1381
+
1382
+ def get_command_from_info(
1383
+ command_info: CommandInfo,
1384
+ *,
1385
+ pretty_exceptions_short: bool,
1386
+ rich_markup_mode: MarkupMode,
1387
+ ) -> click.Command:
1388
+ assert command_info.callback, "A command must have a callback function"
1389
+ name = command_info.name or get_command_name(command_info.callback.__name__) # ty:ignore[unresolved-attribute]
1390
+ use_help = command_info.help
1391
+ if use_help is None:
1392
+ use_help = inspect.getdoc(command_info.callback)
1393
+ else:
1394
+ use_help = inspect.cleandoc(use_help)
1395
+ (
1396
+ params,
1397
+ convertors,
1398
+ context_param_name,
1399
+ ) = get_params_convertors_ctx_param_name_from_function(command_info.callback)
1400
+ cls = command_info.cls or TyperCommand
1401
+ command = cls(
1402
+ name=name,
1403
+ context_settings=command_info.context_settings,
1404
+ callback=get_callback(
1405
+ callback=command_info.callback,
1406
+ params=params,
1407
+ convertors=convertors,
1408
+ context_param_name=context_param_name,
1409
+ pretty_exceptions_short=pretty_exceptions_short,
1410
+ ),
1411
+ params=params, # type: ignore
1412
+ help=use_help,
1413
+ epilog=command_info.epilog,
1414
+ short_help=command_info.short_help,
1415
+ options_metavar=command_info.options_metavar,
1416
+ add_help_option=command_info.add_help_option,
1417
+ no_args_is_help=command_info.no_args_is_help,
1418
+ hidden=command_info.hidden,
1419
+ deprecated=command_info.deprecated,
1420
+ rich_markup_mode=rich_markup_mode,
1421
+ # Rich settings
1422
+ rich_help_panel=command_info.rich_help_panel,
1423
+ )
1424
+ return command
1425
+
1426
+
1427
+ def determine_type_convertor(type_: Any) -> Callable[[Any], Any] | None:
1428
+ convertor: Callable[[Any], Any] | None = None
1429
+ if lenient_issubclass(type_, Path):
1430
+ convertor = param_path_convertor
1431
+ if lenient_issubclass(type_, Enum):
1432
+ convertor = generate_enum_convertor(type_)
1433
+ return convertor
1434
+
1435
+
1436
+ def param_path_convertor(value: str | None = None) -> Path | None:
1437
+ if value is not None:
1438
+ # allow returning any subclass of Path created by an annotated parser without converting
1439
+ # it back to a Path
1440
+ return value if isinstance(value, Path) else Path(value)
1441
+ return None
1442
+
1443
+
1444
+ def generate_enum_convertor(enum: type[Enum]) -> Callable[[Any], Any]:
1445
+ val_map = {str(val.value): val for val in enum}
1446
+
1447
+ def convertor(value: Any) -> Any:
1448
+ if value is not None:
1449
+ val = str(value)
1450
+ if val in val_map:
1451
+ key = val_map[val]
1452
+ return enum(key)
1453
+
1454
+ return convertor
1455
+
1456
+
1457
+ def generate_list_convertor(
1458
+ convertor: Callable[[Any], Any] | None, default_value: Any | None
1459
+ ) -> Callable[[Sequence[Any] | None], list[Any] | None]:
1460
+ def internal_convertor(value: Sequence[Any] | None) -> list[Any] | None:
1461
+ if (value is None) or (default_value is None and len(value) == 0):
1462
+ return None
1463
+ return [convertor(v) if convertor else v for v in value]
1464
+
1465
+ return internal_convertor
1466
+
1467
+
1468
+ def generate_tuple_convertor(
1469
+ types: Sequence[Any],
1470
+ ) -> Callable[[tuple[Any, ...] | None], tuple[Any, ...] | None]:
1471
+ convertors = [determine_type_convertor(type_) for type_ in types]
1472
+
1473
+ def internal_convertor(
1474
+ param_args: tuple[Any, ...] | None,
1475
+ ) -> tuple[Any, ...] | None:
1476
+ if param_args is None:
1477
+ return None
1478
+ return tuple(
1479
+ convertor(arg) if convertor else arg
1480
+ for (convertor, arg) in zip(convertors, param_args, strict=False)
1481
+ )
1482
+
1483
+ return internal_convertor
1484
+
1485
+
1486
+ def get_callback(
1487
+ *,
1488
+ callback: Callable[..., Any] | None = None,
1489
+ params: Sequence[click.Parameter] = [],
1490
+ convertors: dict[str, Callable[[str], Any]] | None = None,
1491
+ context_param_name: str | None = None,
1492
+ pretty_exceptions_short: bool,
1493
+ ) -> Callable[..., Any] | None:
1494
+ use_convertors = convertors or {}
1495
+ if not callback:
1496
+ return None
1497
+ parameters = get_params_from_function(callback)
1498
+ use_params: dict[str, Any] = {}
1499
+ for param_name in parameters:
1500
+ use_params[param_name] = None
1501
+ for param in params:
1502
+ if param.name:
1503
+ use_params[param.name] = param.default
1504
+
1505
+ def wrapper(**kwargs: Any) -> Any:
1506
+ _rich_traceback_guard = pretty_exceptions_short # noqa: F841
1507
+ for k, v in kwargs.items():
1508
+ if k in use_convertors:
1509
+ use_params[k] = use_convertors[k](v)
1510
+ else:
1511
+ use_params[k] = v
1512
+ if context_param_name:
1513
+ use_params[context_param_name] = click.get_current_context()
1514
+ return callback(**use_params)
1515
+
1516
+ update_wrapper(wrapper, callback)
1517
+ return wrapper
1518
+
1519
+
1520
+ def get_click_type(
1521
+ *, annotation: Any, parameter_info: ParameterInfo
1522
+ ) -> click.ParamType:
1523
+ if parameter_info.click_type is not None:
1524
+ return parameter_info.click_type
1525
+
1526
+ elif parameter_info.parser is not None:
1527
+ return click.types.FuncParamType(parameter_info.parser)
1528
+
1529
+ elif annotation is str:
1530
+ return click.STRING
1531
+ elif annotation is int:
1532
+ if parameter_info.min is not None or parameter_info.max is not None:
1533
+ min_ = None
1534
+ max_ = None
1535
+ if parameter_info.min is not None:
1536
+ min_ = int(parameter_info.min)
1537
+ if parameter_info.max is not None:
1538
+ max_ = int(parameter_info.max)
1539
+ return click.IntRange(min=min_, max=max_, clamp=parameter_info.clamp)
1540
+ else:
1541
+ return click.INT
1542
+ elif annotation is float:
1543
+ if parameter_info.min is not None or parameter_info.max is not None:
1544
+ return click.FloatRange(
1545
+ min=parameter_info.min,
1546
+ max=parameter_info.max,
1547
+ clamp=parameter_info.clamp,
1548
+ )
1549
+ else:
1550
+ return click.FLOAT
1551
+ elif annotation is bool:
1552
+ return click.BOOL
1553
+ elif annotation == UUID:
1554
+ return click.UUID
1555
+ elif annotation == datetime:
1556
+ return click.DateTime(formats=parameter_info.formats)
1557
+ elif (
1558
+ annotation == Path
1559
+ or parameter_info.allow_dash
1560
+ or parameter_info.path_type
1561
+ or parameter_info.resolve_path
1562
+ ):
1563
+ return TyperPath(
1564
+ exists=parameter_info.exists,
1565
+ file_okay=parameter_info.file_okay,
1566
+ dir_okay=parameter_info.dir_okay,
1567
+ writable=parameter_info.writable,
1568
+ readable=parameter_info.readable,
1569
+ resolve_path=parameter_info.resolve_path,
1570
+ allow_dash=parameter_info.allow_dash,
1571
+ path_type=parameter_info.path_type,
1572
+ )
1573
+ elif lenient_issubclass(annotation, FileTextWrite):
1574
+ return click.File(
1575
+ mode=parameter_info.mode or "w",
1576
+ encoding=parameter_info.encoding,
1577
+ errors=parameter_info.errors,
1578
+ lazy=parameter_info.lazy,
1579
+ atomic=parameter_info.atomic,
1580
+ )
1581
+ elif lenient_issubclass(annotation, FileText):
1582
+ return click.File(
1583
+ mode=parameter_info.mode or "r",
1584
+ encoding=parameter_info.encoding,
1585
+ errors=parameter_info.errors,
1586
+ lazy=parameter_info.lazy,
1587
+ atomic=parameter_info.atomic,
1588
+ )
1589
+ elif lenient_issubclass(annotation, FileBinaryRead):
1590
+ return click.File(
1591
+ mode=parameter_info.mode or "rb",
1592
+ encoding=parameter_info.encoding,
1593
+ errors=parameter_info.errors,
1594
+ lazy=parameter_info.lazy,
1595
+ atomic=parameter_info.atomic,
1596
+ )
1597
+ elif lenient_issubclass(annotation, FileBinaryWrite):
1598
+ return click.File(
1599
+ mode=parameter_info.mode or "wb",
1600
+ encoding=parameter_info.encoding,
1601
+ errors=parameter_info.errors,
1602
+ lazy=parameter_info.lazy,
1603
+ atomic=parameter_info.atomic,
1604
+ )
1605
+ elif lenient_issubclass(annotation, Enum):
1606
+ # The custom TyperChoice is only needed for Click < 8.2.0, to parse the
1607
+ # command line values matching them to the enum values. Click 8.2.0 added
1608
+ # support for enum values but reading enum names.
1609
+ # Passing here the list of enum values (instead of just the enum) accounts for
1610
+ # Click < 8.2.0.
1611
+ return TyperChoice(
1612
+ [item.value for item in annotation],
1613
+ case_sensitive=parameter_info.case_sensitive,
1614
+ )
1615
+ elif is_literal_type(annotation):
1616
+ return click.Choice(
1617
+ literal_values(annotation),
1618
+ case_sensitive=parameter_info.case_sensitive,
1619
+ )
1620
+ raise RuntimeError(f"Type not yet supported: {annotation}") # pragma: no cover
1621
+
1622
+
1623
+ def lenient_issubclass(cls: Any, class_or_tuple: AnyType | tuple[AnyType, ...]) -> bool:
1624
+ return isinstance(cls, type) and issubclass(cls, class_or_tuple)
1625
+
1626
+
1627
+ def get_click_param(
1628
+ param: ParamMeta,
1629
+ ) -> tuple[click.Argument | click.Option, Any]:
1630
+ # First, find out what will be:
1631
+ # * ParamInfo (ArgumentInfo or OptionInfo)
1632
+ # * default_value
1633
+ # * required
1634
+ default_value = None
1635
+ required = False
1636
+ if isinstance(param.default, ParameterInfo):
1637
+ parameter_info = param.default
1638
+ if parameter_info.default == Required:
1639
+ required = True
1640
+ else:
1641
+ default_value = parameter_info.default
1642
+ elif param.default == Required or param.default is param.empty:
1643
+ required = True
1644
+ parameter_info = ArgumentInfo()
1645
+ else:
1646
+ default_value = param.default
1647
+ parameter_info = OptionInfo()
1648
+ annotation: Any
1649
+ if param.annotation is not param.empty:
1650
+ annotation = param.annotation
1651
+ else:
1652
+ annotation = str
1653
+ main_type = annotation
1654
+ is_list = False
1655
+ is_tuple = False
1656
+ parameter_type: Any = None
1657
+ is_flag = None
1658
+ origin = get_origin(main_type)
1659
+
1660
+ if origin is not None:
1661
+ # Handle SomeType | None and Optional[SomeType]
1662
+ if is_union(origin):
1663
+ types = []
1664
+ for type_ in get_args(main_type):
1665
+ if type_ is NoneType:
1666
+ continue
1667
+ types.append(type_)
1668
+ assert len(types) == 1, "Typer Currently doesn't support Union types"
1669
+ main_type = types[0]
1670
+ origin = get_origin(main_type)
1671
+ # Handle Tuples and Lists
1672
+ if lenient_issubclass(origin, list):
1673
+ main_type = get_args(main_type)[0]
1674
+ assert not get_origin(main_type), (
1675
+ "List types with complex sub-types are not currently supported"
1676
+ )
1677
+ is_list = True
1678
+ elif lenient_issubclass(origin, tuple):
1679
+ types = []
1680
+ for type_ in get_args(main_type):
1681
+ assert not get_origin(type_), (
1682
+ "Tuple types with complex sub-types are not currently supported"
1683
+ )
1684
+ types.append(
1685
+ get_click_type(annotation=type_, parameter_info=parameter_info)
1686
+ )
1687
+ parameter_type = tuple(types)
1688
+ is_tuple = True
1689
+ if parameter_type is None:
1690
+ parameter_type = get_click_type(
1691
+ annotation=main_type, parameter_info=parameter_info
1692
+ )
1693
+ convertor = determine_type_convertor(main_type)
1694
+ if is_list:
1695
+ convertor = generate_list_convertor(
1696
+ convertor=convertor, default_value=default_value
1697
+ )
1698
+ if is_tuple:
1699
+ convertor = generate_tuple_convertor(get_args(main_type))
1700
+ if isinstance(parameter_info, OptionInfo):
1701
+ if main_type is bool:
1702
+ is_flag = True
1703
+ # Click doesn't accept a flag of type bool, only None, and then it sets it
1704
+ # to bool internally
1705
+ parameter_type = None
1706
+ default_option_name = get_command_name(param.name)
1707
+ if is_flag:
1708
+ default_option_declaration = (
1709
+ f"--{default_option_name}/--no-{default_option_name}"
1710
+ )
1711
+ else:
1712
+ default_option_declaration = f"--{default_option_name}"
1713
+ param_decls = [param.name]
1714
+ if parameter_info.param_decls:
1715
+ param_decls.extend(parameter_info.param_decls)
1716
+ else:
1717
+ param_decls.append(default_option_declaration)
1718
+ return (
1719
+ TyperOption(
1720
+ # Option
1721
+ param_decls=param_decls,
1722
+ show_default=parameter_info.show_default,
1723
+ prompt=parameter_info.prompt,
1724
+ confirmation_prompt=parameter_info.confirmation_prompt,
1725
+ prompt_required=parameter_info.prompt_required,
1726
+ hide_input=parameter_info.hide_input,
1727
+ is_flag=is_flag,
1728
+ multiple=is_list,
1729
+ count=parameter_info.count,
1730
+ allow_from_autoenv=parameter_info.allow_from_autoenv,
1731
+ type=parameter_type,
1732
+ help=parameter_info.help,
1733
+ hidden=parameter_info.hidden,
1734
+ show_choices=parameter_info.show_choices,
1735
+ show_envvar=parameter_info.show_envvar,
1736
+ # Parameter
1737
+ required=required,
1738
+ default=default_value,
1739
+ callback=get_param_callback(
1740
+ callback=parameter_info.callback, convertor=convertor
1741
+ ),
1742
+ metavar=parameter_info.metavar,
1743
+ expose_value=parameter_info.expose_value,
1744
+ is_eager=parameter_info.is_eager,
1745
+ envvar=parameter_info.envvar,
1746
+ shell_complete=parameter_info.shell_complete,
1747
+ autocompletion=get_param_completion(parameter_info.autocompletion),
1748
+ # Rich settings
1749
+ rich_help_panel=parameter_info.rich_help_panel,
1750
+ ),
1751
+ convertor,
1752
+ )
1753
+ elif isinstance(parameter_info, ArgumentInfo):
1754
+ param_decls = [param.name]
1755
+ nargs = None
1756
+ if is_list:
1757
+ nargs = -1
1758
+ return (
1759
+ TyperArgument(
1760
+ # Argument
1761
+ param_decls=param_decls,
1762
+ type=parameter_type,
1763
+ required=required,
1764
+ nargs=nargs,
1765
+ # TyperArgument
1766
+ show_default=parameter_info.show_default,
1767
+ show_choices=parameter_info.show_choices,
1768
+ show_envvar=parameter_info.show_envvar,
1769
+ help=parameter_info.help,
1770
+ hidden=parameter_info.hidden,
1771
+ # Parameter
1772
+ default=default_value,
1773
+ callback=get_param_callback(
1774
+ callback=parameter_info.callback, convertor=convertor
1775
+ ),
1776
+ metavar=parameter_info.metavar,
1777
+ expose_value=parameter_info.expose_value,
1778
+ is_eager=parameter_info.is_eager,
1779
+ envvar=parameter_info.envvar,
1780
+ shell_complete=parameter_info.shell_complete,
1781
+ autocompletion=get_param_completion(parameter_info.autocompletion),
1782
+ # Rich settings
1783
+ rich_help_panel=parameter_info.rich_help_panel,
1784
+ ),
1785
+ convertor,
1786
+ )
1787
+ raise AssertionError("A click.Parameter should be returned") # pragma: no cover
1788
+
1789
+
1790
+ def get_param_callback(
1791
+ *,
1792
+ callback: Callable[..., Any] | None = None,
1793
+ convertor: Callable[..., Any] | None = None,
1794
+ ) -> Callable[..., Any] | None:
1795
+ if not callback:
1796
+ return None
1797
+ parameters = get_params_from_function(callback)
1798
+ ctx_name = None
1799
+ click_param_name = None
1800
+ value_name = None
1801
+ untyped_names: list[str] = []
1802
+ for param_name, param_sig in parameters.items():
1803
+ if lenient_issubclass(param_sig.annotation, click.Context):
1804
+ ctx_name = param_name
1805
+ elif lenient_issubclass(param_sig.annotation, click.Parameter):
1806
+ click_param_name = param_name
1807
+ else:
1808
+ untyped_names.append(param_name)
1809
+ # Extract value param name first
1810
+ if untyped_names:
1811
+ value_name = untyped_names.pop()
1812
+ # If context and Click param were not typed (old/Click callback style) extract them
1813
+ if untyped_names:
1814
+ if ctx_name is None:
1815
+ ctx_name = untyped_names.pop(0)
1816
+ if click_param_name is None:
1817
+ if untyped_names:
1818
+ click_param_name = untyped_names.pop(0)
1819
+ if untyped_names:
1820
+ raise click.ClickException(
1821
+ "Too many CLI parameter callback function parameters"
1822
+ )
1823
+
1824
+ def wrapper(ctx: click.Context, param: click.Parameter, value: Any) -> Any:
1825
+ use_params: dict[str, Any] = {}
1826
+ if ctx_name:
1827
+ use_params[ctx_name] = ctx
1828
+ if click_param_name:
1829
+ use_params[click_param_name] = param
1830
+ if value_name:
1831
+ if convertor:
1832
+ use_value = convertor(value)
1833
+ else:
1834
+ use_value = value
1835
+ use_params[value_name] = use_value
1836
+ return callback(**use_params)
1837
+
1838
+ update_wrapper(wrapper, callback)
1839
+ return wrapper
1840
+
1841
+
1842
+ def get_param_completion(
1843
+ callback: Callable[..., Any] | None = None,
1844
+ ) -> Callable[..., Any] | None:
1845
+ if not callback:
1846
+ return None
1847
+ parameters = get_params_from_function(callback)
1848
+ ctx_name = None
1849
+ args_name = None
1850
+ incomplete_name = None
1851
+ unassigned_params = list(parameters.values())
1852
+ for param_sig in unassigned_params[:]:
1853
+ origin = get_origin(param_sig.annotation)
1854
+ if lenient_issubclass(param_sig.annotation, click.Context):
1855
+ ctx_name = param_sig.name
1856
+ unassigned_params.remove(param_sig)
1857
+ elif lenient_issubclass(origin, list):
1858
+ args_name = param_sig.name
1859
+ unassigned_params.remove(param_sig)
1860
+ elif lenient_issubclass(param_sig.annotation, str):
1861
+ incomplete_name = param_sig.name
1862
+ unassigned_params.remove(param_sig)
1863
+ # If there are still unassigned parameters (not typed), extract by name
1864
+ for param_sig in unassigned_params[:]:
1865
+ if ctx_name is None and param_sig.name == "ctx":
1866
+ ctx_name = param_sig.name
1867
+ unassigned_params.remove(param_sig)
1868
+ elif args_name is None and param_sig.name == "args":
1869
+ args_name = param_sig.name
1870
+ unassigned_params.remove(param_sig)
1871
+ elif incomplete_name is None and param_sig.name == "incomplete":
1872
+ incomplete_name = param_sig.name
1873
+ unassigned_params.remove(param_sig)
1874
+ # Extract value param name first
1875
+ if unassigned_params:
1876
+ show_params = " ".join([param.name for param in unassigned_params])
1877
+ raise click.ClickException(
1878
+ f"Invalid autocompletion callback parameters: {show_params}"
1879
+ )
1880
+
1881
+ def wrapper(ctx: click.Context, args: list[str], incomplete: str | None) -> Any:
1882
+ use_params: dict[str, Any] = {}
1883
+ if ctx_name:
1884
+ use_params[ctx_name] = ctx
1885
+ if args_name:
1886
+ use_params[args_name] = args
1887
+ if incomplete_name:
1888
+ use_params[incomplete_name] = incomplete
1889
+ return callback(**use_params)
1890
+
1891
+ update_wrapper(wrapper, callback)
1892
+ return wrapper
1893
+
1894
+
1895
+ def run(
1896
+ function: Annotated[
1897
+ Callable[..., Any],
1898
+ Doc(
1899
+ """
1900
+ The function that should power this CLI application.
1901
+ """
1902
+ ),
1903
+ ],
1904
+ ) -> None:
1905
+ """
1906
+ This function converts a given function to a CLI application with `Typer()` and executes it.
1907
+
1908
+ ## Example
1909
+
1910
+ ```python
1911
+ import typer
1912
+
1913
+ def main(name: str):
1914
+ print(f"Hello {name}")
1915
+
1916
+ if __name__ == "__main__":
1917
+ typer.run(main)
1918
+ ```
1919
+ """
1920
+ app = Typer(add_completion=False)
1921
+ app.command()(function)
1922
+ app()
1923
+
1924
+
1925
+ def _is_macos() -> bool:
1926
+ return platform.system() == "Darwin"
1927
+
1928
+
1929
+ def _is_linux_or_bsd() -> bool:
1930
+ if platform.system() == "Linux":
1931
+ return True
1932
+
1933
+ return "BSD" in platform.system()
1934
+
1935
+
1936
+ def launch(
1937
+ url: Annotated[
1938
+ str,
1939
+ Doc(
1940
+ """
1941
+ URL or filename of the thing to launch.
1942
+ """
1943
+ ),
1944
+ ],
1945
+ wait: Annotated[
1946
+ bool,
1947
+ Doc(
1948
+ """
1949
+ Wait for the program to exit before returning. This only works if the launched program blocks.
1950
+ In particular, `xdg-open` on Linux does not block.
1951
+ """
1952
+ ),
1953
+ ] = False,
1954
+ locate: Annotated[
1955
+ bool,
1956
+ Doc(
1957
+ """
1958
+ If this is set to `True`, then instead of launching the application associated with the URL, it will attempt to
1959
+ launch a file manager with the file located. This might have weird effects if the URL does not point to the filesystem.
1960
+ """
1961
+ ),
1962
+ ] = False,
1963
+ ) -> int:
1964
+ """
1965
+ This function launches the given URL (or filename) in the default
1966
+ viewer application for this file type. If this is an executable, it
1967
+ might launch the executable in a new session. The return value is
1968
+ the exit code of the launched application. Usually, `0` indicates
1969
+ success.
1970
+
1971
+ This function handles url in different operating systems separately:
1972
+ - On macOS (Darwin), it uses the `open` command.
1973
+ - On Linux and BSD, it uses `xdg-open` if available.
1974
+ - On Windows (and other OSes), it uses the standard webbrowser module.
1975
+
1976
+ The function avoids, when possible, using the webbrowser module on Linux and macOS
1977
+ to prevent spammy terminal messages from some browsers (e.g., Chrome).
1978
+
1979
+ ## Examples
1980
+ ```python
1981
+ import typer
1982
+
1983
+ typer.launch("https://typer.tiangolo.com/")
1984
+ ```
1985
+
1986
+ ```python
1987
+ import typer
1988
+
1989
+ typer.launch("/my/downloaded/file", locate=True)
1990
+ ```
1991
+ """
1992
+
1993
+ if url.startswith("http://") or url.startswith("https://"):
1994
+ if _is_macos():
1995
+ return subprocess.Popen(
1996
+ ["open", url], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT
1997
+ ).wait()
1998
+
1999
+ has_xdg_open = _is_linux_or_bsd() and shutil.which("xdg-open") is not None
2000
+
2001
+ if has_xdg_open:
2002
+ return subprocess.Popen(
2003
+ ["xdg-open", url], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT
2004
+ ).wait()
2005
+
2006
+ import webbrowser
2007
+
2008
+ webbrowser.open(url)
2009
+
2010
+ return 0
2011
+
2012
+ else:
2013
+ return click.launch(url)
loan-advisor-agent/.venv/Lib/site-packages/typer/models.py ADDED
@@ -0,0 +1,651 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ import io
3
+ from collections.abc import Callable, Sequence
4
+ from typing import (
5
+ TYPE_CHECKING,
6
+ Any,
7
+ Optional,
8
+ TypeVar,
9
+ )
10
+
11
+ import click
12
+ import click.shell_completion
13
+
14
+ if TYPE_CHECKING: # pragma: no cover
15
+ from .core import TyperCommand, TyperGroup
16
+ from .main import Typer
17
+
18
+
19
+ NoneType = type(None)
20
+
21
+ AnyType = type[Any]
22
+
23
+ Required = ...
24
+
25
+
26
+ class Context(click.Context):
27
+ """
28
+ The [`Context`](https://click.palletsprojects.com/en/stable/api/#click.Context) has some additional data about the current execution of your program.
29
+ When declaring it in a [callback](https://typer.tiangolo.com/tutorial/options/callback-and-context/) function,
30
+ you can access this additional information.
31
+ """
32
+
33
+ pass
34
+
35
+
36
+ class FileText(io.TextIOWrapper):
37
+ """
38
+ Gives you a file-like object for reading text, and you will get a `str` data from it.
39
+ The default mode of this class is `mode="r"`.
40
+
41
+ **Example**
42
+
43
+ ```python
44
+ from typing import Annotated
45
+
46
+ import typer
47
+
48
+ app = typer.Typer()
49
+
50
+ @app.command()
51
+ def main(config: Annotated[typer.FileText, typer.Option()]):
52
+ for line in config:
53
+ print(f"Config line: {line}")
54
+
55
+ if __name__ == "__main__":
56
+ app()
57
+ ```
58
+ """
59
+
60
+ pass
61
+
62
+
63
+ class FileTextWrite(FileText):
64
+ """
65
+ You can use this class for writing text. Alternatively, you can use `FileText` with `mode="w"`.
66
+ The default mode of this class is `mode="w"`.
67
+
68
+ **Example**
69
+
70
+ ```python
71
+ from typing import Annotated
72
+
73
+ import typer
74
+
75
+ app = typer.Typer()
76
+
77
+ @app.command()
78
+ def main(config: Annotated[typer.FileTextWrite, typer.Option()]):
79
+ config.write("Some config written by the app")
80
+ print("Config written")
81
+
82
+ if __name__ == "__main__":
83
+ app()
84
+ ```
85
+ """
86
+
87
+ pass
88
+
89
+
90
+ class FileBinaryRead(io.BufferedReader):
91
+ """
92
+ You can use this class to read binary data, receiving `bytes`.
93
+ The default mode of this class is `mode="rb"`.
94
+ It is useful for reading binary files like images:
95
+
96
+ **Example**
97
+
98
+ ```python
99
+ from typing import Annotated
100
+
101
+ import typer
102
+
103
+ app = typer.Typer()
104
+
105
+ @app.command()
106
+ def main(file: Annotated[typer.FileBinaryRead, typer.Option()]):
107
+ processed_total = 0
108
+ for bytes_chunk in file:
109
+ # Process the bytes in bytes_chunk
110
+ processed_total += len(bytes_chunk)
111
+ print(f"Processed bytes total: {processed_total}")
112
+
113
+ if __name__ == "__main__":
114
+ app()
115
+ ```
116
+ """
117
+
118
+ pass
119
+
120
+
121
+ class FileBinaryWrite(io.BufferedWriter):
122
+ """
123
+ You can use this class to write binary data: you pass `bytes` to it instead of strings.
124
+ The default mode of this class is `mode="wb"`.
125
+ It is useful for writing binary files like images:
126
+
127
+ **Example**
128
+
129
+ ```python
130
+ from typing import Annotated
131
+
132
+ import typer
133
+
134
+ app = typer.Typer()
135
+
136
+ @app.command()
137
+ def main(file: Annotated[typer.FileBinaryWrite, typer.Option()]):
138
+ first_line_str = "some settings\\n"
139
+ # You cannot write str directly to a binary file; encode it first
140
+ first_line_bytes = first_line_str.encode("utf-8")
141
+ # Then you can write the bytes
142
+ file.write(first_line_bytes)
143
+ # This is already bytes, it starts with b"
144
+ second_line = b"la cig\xc3\xbce\xc3\xb1a trae al ni\xc3\xb1o"
145
+ file.write(second_line)
146
+ print("Binary file written")
147
+
148
+ if __name__ == "__main__":
149
+ app()
150
+ ```
151
+ """
152
+
153
+ pass
154
+
155
+
156
+ class CallbackParam(click.Parameter):
157
+ """
158
+ In a callback function, you can declare a function parameter with type `CallbackParam`
159
+ to access the specific Click [`Parameter`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) object.
160
+ """
161
+
162
+ pass
163
+
164
+
165
+ class DefaultPlaceholder:
166
+ """
167
+ You shouldn't use this class directly.
168
+
169
+ It's used internally to recognize when a default value has been overwritten, even
170
+ if the new value is `None`.
171
+ """
172
+
173
+ def __init__(self, value: Any):
174
+ self.value = value
175
+
176
+ def __bool__(self) -> bool:
177
+ return bool(self.value)
178
+
179
+
180
+ DefaultType = TypeVar("DefaultType")
181
+
182
+ CommandFunctionType = TypeVar("CommandFunctionType", bound=Callable[..., Any])
183
+
184
+
185
+ def Default(value: DefaultType) -> DefaultType:
186
+ """
187
+ You shouldn't use this function directly.
188
+
189
+ It's used internally to recognize when a default value has been overwritten, even
190
+ if the new value is `None`.
191
+ """
192
+ return DefaultPlaceholder(value) # type: ignore
193
+
194
+
195
+ class CommandInfo:
196
+ def __init__(
197
+ self,
198
+ name: str | None = None,
199
+ *,
200
+ cls: type["TyperCommand"] | None = None,
201
+ context_settings: dict[Any, Any] | None = None,
202
+ callback: Callable[..., Any] | None = None,
203
+ help: str | None = None,
204
+ epilog: str | None = None,
205
+ short_help: str | None = None,
206
+ options_metavar: str = "[OPTIONS]",
207
+ add_help_option: bool = True,
208
+ no_args_is_help: bool = False,
209
+ hidden: bool = False,
210
+ deprecated: bool = False,
211
+ # Rich settings
212
+ rich_help_panel: str | None = None,
213
+ ):
214
+ self.name = name
215
+ self.cls = cls
216
+ self.context_settings = context_settings
217
+ self.callback = callback
218
+ self.help = help
219
+ self.epilog = epilog
220
+ self.short_help = short_help
221
+ self.options_metavar = options_metavar
222
+ self.add_help_option = add_help_option
223
+ self.no_args_is_help = no_args_is_help
224
+ self.hidden = hidden
225
+ self.deprecated = deprecated
226
+ # Rich settings
227
+ self.rich_help_panel = rich_help_panel
228
+
229
+
230
+ class TyperInfo:
231
+ def __init__(
232
+ self,
233
+ typer_instance: Optional["Typer"] = Default(None),
234
+ *,
235
+ name: str | None = Default(None),
236
+ cls: type["TyperGroup"] | None = Default(None),
237
+ invoke_without_command: bool = Default(False),
238
+ no_args_is_help: bool = Default(False),
239
+ subcommand_metavar: str | None = Default(None),
240
+ chain: bool = Default(False),
241
+ result_callback: Callable[..., Any] | None = Default(None),
242
+ # Command
243
+ context_settings: dict[Any, Any] | None = Default(None),
244
+ callback: Callable[..., Any] | None = Default(None),
245
+ help: str | None = Default(None),
246
+ epilog: str | None = Default(None),
247
+ short_help: str | None = Default(None),
248
+ options_metavar: str = Default("[OPTIONS]"),
249
+ add_help_option: bool = Default(True),
250
+ hidden: bool = Default(False),
251
+ deprecated: bool = Default(False),
252
+ # Rich settings
253
+ rich_help_panel: str | None = Default(None),
254
+ ):
255
+ self.typer_instance = typer_instance
256
+ self.name = name
257
+ self.cls = cls
258
+ self.invoke_without_command = invoke_without_command
259
+ self.no_args_is_help = no_args_is_help
260
+ self.subcommand_metavar = subcommand_metavar
261
+ self.chain = chain
262
+ self.result_callback = result_callback
263
+ self.context_settings = context_settings
264
+ self.callback = callback
265
+ self.help = help
266
+ self.epilog = epilog
267
+ self.short_help = short_help
268
+ self.options_metavar = options_metavar
269
+ self.add_help_option = add_help_option
270
+ self.hidden = hidden
271
+ self.deprecated = deprecated
272
+ self.rich_help_panel = rich_help_panel
273
+
274
+
275
+ class ParameterInfo:
276
+ def __init__(
277
+ self,
278
+ *,
279
+ default: Any | None = None,
280
+ param_decls: Sequence[str] | None = None,
281
+ callback: Callable[..., Any] | None = None,
282
+ metavar: str | None = None,
283
+ expose_value: bool = True,
284
+ is_eager: bool = False,
285
+ envvar: str | list[str] | None = None,
286
+ # Note that shell_complete is not fully supported and will be removed in future versions
287
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
288
+ shell_complete: Callable[
289
+ [click.Context, click.Parameter, str],
290
+ list["click.shell_completion.CompletionItem"] | list[str],
291
+ ]
292
+ | None = None,
293
+ autocompletion: Callable[..., Any] | None = None,
294
+ default_factory: Callable[[], Any] | None = None,
295
+ # Custom type
296
+ parser: Callable[[str], Any] | None = None,
297
+ click_type: click.ParamType | None = None,
298
+ # TyperArgument
299
+ show_default: bool | str = True,
300
+ show_choices: bool = True,
301
+ show_envvar: bool = True,
302
+ help: str | None = None,
303
+ hidden: bool = False,
304
+ # Choice
305
+ case_sensitive: bool = True,
306
+ # Numbers
307
+ min: int | float | None = None,
308
+ max: int | float | None = None,
309
+ clamp: bool = False,
310
+ # DateTime
311
+ formats: list[str] | None = None,
312
+ # File
313
+ mode: str | None = None,
314
+ encoding: str | None = None,
315
+ errors: str | None = "strict",
316
+ lazy: bool | None = None,
317
+ atomic: bool = False,
318
+ # Path
319
+ exists: bool = False,
320
+ file_okay: bool = True,
321
+ dir_okay: bool = True,
322
+ writable: bool = False,
323
+ readable: bool = True,
324
+ resolve_path: bool = False,
325
+ allow_dash: bool = False,
326
+ path_type: None | type[str] | type[bytes] = None,
327
+ # Rich settings
328
+ rich_help_panel: str | None = None,
329
+ ):
330
+ # Check if user has provided multiple custom parsers
331
+ if parser and click_type:
332
+ raise ValueError(
333
+ "Multiple custom type parsers provided. "
334
+ "`parser` and `click_type` may not both be provided."
335
+ )
336
+
337
+ self.default = default
338
+ self.param_decls = param_decls
339
+ self.callback = callback
340
+ self.metavar = metavar
341
+ self.expose_value = expose_value
342
+ self.is_eager = is_eager
343
+ self.envvar = envvar
344
+ self.shell_complete = shell_complete
345
+ self.autocompletion = autocompletion
346
+ self.default_factory = default_factory
347
+ # Custom type
348
+ self.parser = parser
349
+ self.click_type = click_type
350
+ # TyperArgument
351
+ self.show_default = show_default
352
+ self.show_choices = show_choices
353
+ self.show_envvar = show_envvar
354
+ self.help = help
355
+ self.hidden = hidden
356
+ # Choice
357
+ self.case_sensitive = case_sensitive
358
+ # Numbers
359
+ self.min = min
360
+ self.max = max
361
+ self.clamp = clamp
362
+ # DateTime
363
+ self.formats = formats
364
+ # File
365
+ self.mode = mode
366
+ self.encoding = encoding
367
+ self.errors = errors
368
+ self.lazy = lazy
369
+ self.atomic = atomic
370
+ # Path
371
+ self.exists = exists
372
+ self.file_okay = file_okay
373
+ self.dir_okay = dir_okay
374
+ self.writable = writable
375
+ self.readable = readable
376
+ self.resolve_path = resolve_path
377
+ self.allow_dash = allow_dash
378
+ self.path_type = path_type
379
+ # Rich settings
380
+ self.rich_help_panel = rich_help_panel
381
+
382
+
383
+ class OptionInfo(ParameterInfo):
384
+ def __init__(
385
+ self,
386
+ *,
387
+ # ParameterInfo
388
+ default: Any | None = None,
389
+ param_decls: Sequence[str] | None = None,
390
+ callback: Callable[..., Any] | None = None,
391
+ metavar: str | None = None,
392
+ expose_value: bool = True,
393
+ is_eager: bool = False,
394
+ envvar: str | list[str] | None = None,
395
+ # Note that shell_complete is not fully supported and will be removed in future versions
396
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
397
+ shell_complete: Callable[
398
+ [click.Context, click.Parameter, str],
399
+ list["click.shell_completion.CompletionItem"] | list[str],
400
+ ]
401
+ | None = None,
402
+ autocompletion: Callable[..., Any] | None = None,
403
+ default_factory: Callable[[], Any] | None = None,
404
+ # Custom type
405
+ parser: Callable[[str], Any] | None = None,
406
+ click_type: click.ParamType | None = None,
407
+ # Option
408
+ show_default: bool | str = True,
409
+ prompt: bool | str = False,
410
+ confirmation_prompt: bool = False,
411
+ prompt_required: bool = True,
412
+ hide_input: bool = False,
413
+ # TODO: remove is_flag and flag_value in a future release
414
+ is_flag: bool | None = None,
415
+ flag_value: Any | None = None,
416
+ count: bool = False,
417
+ allow_from_autoenv: bool = True,
418
+ help: str | None = None,
419
+ hidden: bool = False,
420
+ show_choices: bool = True,
421
+ show_envvar: bool = True,
422
+ # Choice
423
+ case_sensitive: bool = True,
424
+ # Numbers
425
+ min: int | float | None = None,
426
+ max: int | float | None = None,
427
+ clamp: bool = False,
428
+ # DateTime
429
+ formats: list[str] | None = None,
430
+ # File
431
+ mode: str | None = None,
432
+ encoding: str | None = None,
433
+ errors: str | None = "strict",
434
+ lazy: bool | None = None,
435
+ atomic: bool = False,
436
+ # Path
437
+ exists: bool = False,
438
+ file_okay: bool = True,
439
+ dir_okay: bool = True,
440
+ writable: bool = False,
441
+ readable: bool = True,
442
+ resolve_path: bool = False,
443
+ allow_dash: bool = False,
444
+ path_type: None | type[str] | type[bytes] = None,
445
+ # Rich settings
446
+ rich_help_panel: str | None = None,
447
+ ):
448
+ super().__init__(
449
+ default=default,
450
+ param_decls=param_decls,
451
+ callback=callback,
452
+ metavar=metavar,
453
+ expose_value=expose_value,
454
+ is_eager=is_eager,
455
+ envvar=envvar,
456
+ shell_complete=shell_complete,
457
+ autocompletion=autocompletion,
458
+ default_factory=default_factory,
459
+ # Custom type
460
+ parser=parser,
461
+ click_type=click_type,
462
+ # TyperArgument
463
+ show_default=show_default,
464
+ show_choices=show_choices,
465
+ show_envvar=show_envvar,
466
+ help=help,
467
+ hidden=hidden,
468
+ # Choice
469
+ case_sensitive=case_sensitive,
470
+ # Numbers
471
+ min=min,
472
+ max=max,
473
+ clamp=clamp,
474
+ # DateTime
475
+ formats=formats,
476
+ # File
477
+ mode=mode,
478
+ encoding=encoding,
479
+ errors=errors,
480
+ lazy=lazy,
481
+ atomic=atomic,
482
+ # Path
483
+ exists=exists,
484
+ file_okay=file_okay,
485
+ dir_okay=dir_okay,
486
+ writable=writable,
487
+ readable=readable,
488
+ resolve_path=resolve_path,
489
+ allow_dash=allow_dash,
490
+ path_type=path_type,
491
+ # Rich settings
492
+ rich_help_panel=rich_help_panel,
493
+ )
494
+ if is_flag is not None or flag_value is not None:
495
+ import warnings
496
+
497
+ warnings.warn(
498
+ "The 'is_flag' and 'flag_value' parameters are not supported by Typer "
499
+ "and will be removed entirely in a future release.",
500
+ DeprecationWarning,
501
+ stacklevel=2,
502
+ )
503
+ self.prompt = prompt
504
+ self.confirmation_prompt = confirmation_prompt
505
+ self.prompt_required = prompt_required
506
+ self.hide_input = hide_input
507
+ self.count = count
508
+ self.allow_from_autoenv = allow_from_autoenv
509
+
510
+
511
+ class ArgumentInfo(ParameterInfo):
512
+ def __init__(
513
+ self,
514
+ *,
515
+ # ParameterInfo
516
+ default: Any | None = None,
517
+ param_decls: Sequence[str] | None = None,
518
+ callback: Callable[..., Any] | None = None,
519
+ metavar: str | None = None,
520
+ expose_value: bool = True,
521
+ is_eager: bool = False,
522
+ envvar: str | list[str] | None = None,
523
+ # Note that shell_complete is not fully supported and will be removed in future versions
524
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
525
+ shell_complete: Callable[
526
+ [click.Context, click.Parameter, str],
527
+ list["click.shell_completion.CompletionItem"] | list[str],
528
+ ]
529
+ | None = None,
530
+ autocompletion: Callable[..., Any] | None = None,
531
+ default_factory: Callable[[], Any] | None = None,
532
+ # Custom type
533
+ parser: Callable[[str], Any] | None = None,
534
+ click_type: click.ParamType | None = None,
535
+ # TyperArgument
536
+ show_default: bool | str = True,
537
+ show_choices: bool = True,
538
+ show_envvar: bool = True,
539
+ help: str | None = None,
540
+ hidden: bool = False,
541
+ # Choice
542
+ case_sensitive: bool = True,
543
+ # Numbers
544
+ min: int | float | None = None,
545
+ max: int | float | None = None,
546
+ clamp: bool = False,
547
+ # DateTime
548
+ formats: list[str] | None = None,
549
+ # File
550
+ mode: str | None = None,
551
+ encoding: str | None = None,
552
+ errors: str | None = "strict",
553
+ lazy: bool | None = None,
554
+ atomic: bool = False,
555
+ # Path
556
+ exists: bool = False,
557
+ file_okay: bool = True,
558
+ dir_okay: bool = True,
559
+ writable: bool = False,
560
+ readable: bool = True,
561
+ resolve_path: bool = False,
562
+ allow_dash: bool = False,
563
+ path_type: None | type[str] | type[bytes] = None,
564
+ # Rich settings
565
+ rich_help_panel: str | None = None,
566
+ ):
567
+ super().__init__(
568
+ default=default,
569
+ param_decls=param_decls,
570
+ callback=callback,
571
+ metavar=metavar,
572
+ expose_value=expose_value,
573
+ is_eager=is_eager,
574
+ envvar=envvar,
575
+ shell_complete=shell_complete,
576
+ autocompletion=autocompletion,
577
+ default_factory=default_factory,
578
+ # Custom type
579
+ parser=parser,
580
+ click_type=click_type,
581
+ # TyperArgument
582
+ show_default=show_default,
583
+ show_choices=show_choices,
584
+ show_envvar=show_envvar,
585
+ help=help,
586
+ hidden=hidden,
587
+ # Choice
588
+ case_sensitive=case_sensitive,
589
+ # Numbers
590
+ min=min,
591
+ max=max,
592
+ clamp=clamp,
593
+ # DateTime
594
+ formats=formats,
595
+ # File
596
+ mode=mode,
597
+ encoding=encoding,
598
+ errors=errors,
599
+ lazy=lazy,
600
+ atomic=atomic,
601
+ # Path
602
+ exists=exists,
603
+ file_okay=file_okay,
604
+ dir_okay=dir_okay,
605
+ writable=writable,
606
+ readable=readable,
607
+ resolve_path=resolve_path,
608
+ allow_dash=allow_dash,
609
+ path_type=path_type,
610
+ # Rich settings
611
+ rich_help_panel=rich_help_panel,
612
+ )
613
+
614
+
615
+ class ParamMeta:
616
+ empty = inspect.Parameter.empty
617
+
618
+ def __init__(
619
+ self,
620
+ *,
621
+ name: str,
622
+ default: Any = inspect.Parameter.empty,
623
+ annotation: Any = inspect.Parameter.empty,
624
+ ) -> None:
625
+ self.name = name
626
+ self.default = default
627
+ self.annotation = annotation
628
+
629
+
630
+ class DeveloperExceptionConfig:
631
+ def __init__(
632
+ self,
633
+ *,
634
+ pretty_exceptions_enable: bool = True,
635
+ pretty_exceptions_show_locals: bool = True,
636
+ pretty_exceptions_short: bool = True,
637
+ ) -> None:
638
+ self.pretty_exceptions_enable = pretty_exceptions_enable
639
+ self.pretty_exceptions_show_locals = pretty_exceptions_show_locals
640
+ self.pretty_exceptions_short = pretty_exceptions_short
641
+
642
+
643
+ class TyperPath(click.Path):
644
+ # Overwrite Click's behaviour to be compatible with Typer's autocompletion system
645
+ def shell_complete(
646
+ self, ctx: click.Context, param: click.Parameter, incomplete: str
647
+ ) -> list[click.shell_completion.CompletionItem]:
648
+ """Return an empty list so that the autocompletion functionality
649
+ will work properly from the commandline.
650
+ """
651
+ return []
loan-advisor-agent/.venv/Lib/site-packages/typer/params.py ADDED
@@ -0,0 +1,1831 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ from typing import TYPE_CHECKING, Annotated, Any, overload
3
+
4
+ import click
5
+ from annotated_doc import Doc
6
+
7
+ from .models import ArgumentInfo, OptionInfo
8
+
9
+ if TYPE_CHECKING: # pragma: no cover
10
+ import click.shell_completion
11
+
12
+
13
+ # Overload for Option created with custom type 'parser'
14
+ @overload
15
+ def Option(
16
+ # Parameter
17
+ default: Any | None = ...,
18
+ *param_decls: str,
19
+ callback: Callable[..., Any] | None = None,
20
+ metavar: str | None = None,
21
+ expose_value: bool = True,
22
+ is_eager: bool = False,
23
+ envvar: str | list[str] | None = None,
24
+ # Note that shell_complete is not fully supported and will be removed in future versions
25
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
26
+ shell_complete: Callable[
27
+ [click.Context, click.Parameter, str],
28
+ list["click.shell_completion.CompletionItem"] | list[str],
29
+ ]
30
+ | None = None,
31
+ autocompletion: Callable[..., Any] | None = None,
32
+ default_factory: Callable[[], Any] | None = None,
33
+ # Custom type
34
+ parser: Callable[[str], Any] | None = None,
35
+ # Option
36
+ show_default: bool | str = True,
37
+ prompt: bool | str = False,
38
+ confirmation_prompt: bool = False,
39
+ prompt_required: bool = True,
40
+ hide_input: bool = False,
41
+ # TODO: remove is_flag and flag_value in a future release
42
+ is_flag: bool | None = None,
43
+ flag_value: Any | None = None,
44
+ count: bool = False,
45
+ allow_from_autoenv: bool = True,
46
+ help: str | None = None,
47
+ hidden: bool = False,
48
+ show_choices: bool = True,
49
+ show_envvar: bool = True,
50
+ # Choice
51
+ case_sensitive: bool = True,
52
+ # Numbers
53
+ min: int | float | None = None,
54
+ max: int | float | None = None,
55
+ clamp: bool = False,
56
+ # DateTime
57
+ formats: list[str] | None = None,
58
+ # File
59
+ mode: str | None = None,
60
+ encoding: str | None = None,
61
+ errors: str | None = "strict",
62
+ lazy: bool | None = None,
63
+ atomic: bool = False,
64
+ # Path
65
+ exists: bool = False,
66
+ file_okay: bool = True,
67
+ dir_okay: bool = True,
68
+ writable: bool = False,
69
+ readable: bool = True,
70
+ resolve_path: bool = False,
71
+ allow_dash: bool = False,
72
+ path_type: None | type[str] | type[bytes] = None,
73
+ # Rich settings
74
+ rich_help_panel: str | None = None,
75
+ ) -> Any: ...
76
+
77
+
78
+ # Overload for Option created with custom type 'click_type'
79
+ @overload
80
+ def Option(
81
+ # Parameter
82
+ default: Any | None = ...,
83
+ *param_decls: str,
84
+ callback: Callable[..., Any] | None = None,
85
+ metavar: str | None = None,
86
+ expose_value: bool = True,
87
+ is_eager: bool = False,
88
+ envvar: str | list[str] | None = None,
89
+ # Note that shell_complete is not fully supported and will be removed in future versions
90
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
91
+ shell_complete: Callable[
92
+ [click.Context, click.Parameter, str],
93
+ list["click.shell_completion.CompletionItem"] | list[str],
94
+ ]
95
+ | None = None,
96
+ autocompletion: Callable[..., Any] | None = None,
97
+ default_factory: Callable[[], Any] | None = None,
98
+ # Custom type
99
+ click_type: click.ParamType | None = None,
100
+ # Option
101
+ show_default: bool | str = True,
102
+ prompt: bool | str = False,
103
+ confirmation_prompt: bool = False,
104
+ prompt_required: bool = True,
105
+ hide_input: bool = False,
106
+ # TODO: remove is_flag and flag_value in a future release
107
+ is_flag: bool | None = None,
108
+ flag_value: Any | None = None,
109
+ count: bool = False,
110
+ allow_from_autoenv: bool = True,
111
+ help: str | None = None,
112
+ hidden: bool = False,
113
+ show_choices: bool = True,
114
+ show_envvar: bool = True,
115
+ # Choice
116
+ case_sensitive: bool = True,
117
+ # Numbers
118
+ min: int | float | None = None,
119
+ max: int | float | None = None,
120
+ clamp: bool = False,
121
+ # DateTime
122
+ formats: list[str] | None = None,
123
+ # File
124
+ mode: str | None = None,
125
+ encoding: str | None = None,
126
+ errors: str | None = "strict",
127
+ lazy: bool | None = None,
128
+ atomic: bool = False,
129
+ # Path
130
+ exists: bool = False,
131
+ file_okay: bool = True,
132
+ dir_okay: bool = True,
133
+ writable: bool = False,
134
+ readable: bool = True,
135
+ resolve_path: bool = False,
136
+ allow_dash: bool = False,
137
+ path_type: None | type[str] | type[bytes] = None,
138
+ # Rich settings
139
+ rich_help_panel: str | None = None,
140
+ ) -> Any: ...
141
+
142
+
143
+ def Option(
144
+ # Parameter
145
+ default: Annotated[
146
+ Any | None,
147
+ Doc(
148
+ """
149
+ Usually, [CLI options](https://typer.tiangolo.com/tutorial/options/) are optional and have a default value, passed on like this:
150
+
151
+ **Example**
152
+
153
+ ```python
154
+ @app.command()
155
+ def main(network: str = typer.Option("CNN")):
156
+ print(f"Training neural network of type: {network}")
157
+ ```
158
+
159
+ Note that this usage is deprecated, and we recommend to use `Annotated` instead:
160
+ ```
161
+ @app.command()
162
+ def main(network: Annotated[str, typer.Option()] = "CNN"):
163
+ print(f"Hello {name}!")
164
+ ```
165
+
166
+ You can also use `...` ([Ellipsis](https://docs.python.org/3/library/constants.html#Ellipsis)) as the "default" value to clarify that this is a required CLI option.
167
+ """
168
+ ),
169
+ ] = ...,
170
+ *param_decls: Annotated[
171
+ str,
172
+ Doc(
173
+ """
174
+ Positional argument that defines how users can call this option on the command line. This may be one or multiple aliases, all strings.
175
+ If not defined, Typer will automatically use the function parameter as default name.
176
+ See [the tutorial about CLI Option Names](https://typer.tiangolo.com/tutorial/options/name/) for more details.
177
+
178
+ **Example**
179
+
180
+ ```python
181
+ @app.command()
182
+ def main(user_name: Annotated[str, typer.Option("--user", "-u", "-x")]):
183
+ print(f"Hello {user_name}")
184
+ ```
185
+ """
186
+ ),
187
+ ],
188
+ callback: Annotated[
189
+ Callable[..., Any] | None,
190
+ Doc(
191
+ """
192
+ Add a callback to this CLI Option, to execute additional logic after its value was received from the terminal.
193
+ See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/options/callback-and-context/) for more details.
194
+
195
+ **Example**
196
+
197
+ ```python
198
+ def name_callback(value: str):
199
+ if value != "Deadpool":
200
+ raise typer.BadParameter("Only Deadpool is allowed")
201
+ return value
202
+
203
+ @app.command()
204
+ def main(name: Annotated[str, typer.Option(callback=name_callback)]):
205
+ print(f"Hello {name}")
206
+ ```
207
+ """
208
+ ),
209
+ ] = None,
210
+ metavar: Annotated[
211
+ str | None,
212
+ Doc(
213
+ """
214
+ Customize the name displayed in the [help text](https://typer.tiangolo.com/tutorial/options/help/) to represent this CLI option.
215
+ Note that this doesn't influence the way the option must be called.
216
+
217
+ **Example**
218
+
219
+ ```python
220
+ @app.command()
221
+ def main(user: Annotated[str, typer.Option(metavar="User name")]):
222
+ print(f"Hello {user}")
223
+ ```
224
+ """
225
+ ),
226
+ ] = None,
227
+ expose_value: Annotated[
228
+ bool,
229
+ Doc(
230
+ """
231
+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
232
+
233
+ ---
234
+
235
+ If this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it’s skipped.
236
+ """
237
+ ),
238
+ ] = True,
239
+ is_eager: Annotated[
240
+ bool,
241
+ Doc(
242
+ """
243
+ Mark a CLI Option to be "eager", ensuring it gets processed before other CLI parameters. This could be relevant when there are other parameters with callbacks that could exit the program early.
244
+ For more information and an extended example, see the documentation [here](https://typer.tiangolo.com/tutorial/options/version/#fix-with-is_eager).
245
+ """
246
+ ),
247
+ ] = False,
248
+ envvar: Annotated[
249
+ str | list[str] | None,
250
+ Doc(
251
+ """
252
+ Configure a CLI Option to read its value from an environment variable if it is not provided in the command line.
253
+ For more information, see the [documentation on Environment Variables](https://typer.tiangolo.com/tutorial/arguments/envvar/).
254
+
255
+ **Example**
256
+
257
+ ```python
258
+ @app.command()
259
+ def main(user: Annotated[str, typer.Option(envvar="ME")]):
260
+ print(f"Hello {user}")
261
+ ```
262
+ """
263
+ ),
264
+ ] = None,
265
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
266
+ shell_complete: Annotated[
267
+ Callable[
268
+ [click.Context, click.Parameter, str],
269
+ list["click.shell_completion.CompletionItem"] | list[str],
270
+ ]
271
+ | None,
272
+ Doc(
273
+ """
274
+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
275
+ It is however not fully functional, and will likely be removed in future versions.
276
+ """
277
+ ),
278
+ ] = None,
279
+ autocompletion: Annotated[
280
+ Callable[..., Any] | None,
281
+ Doc(
282
+ """
283
+ Provide a custom function that helps to autocomplete the values of this CLI Option.
284
+ See [the tutorial on parameter autocompletion](https://typer.tiangolo.com/tutorial/options-autocompletion) for more details.
285
+
286
+ **Example**
287
+
288
+ ```python
289
+ def complete():
290
+ return ["Me", "Myself", "I"]
291
+
292
+ @app.command()
293
+ def main(name: Annotated[str, typer.Option(autocompletion=complete)]):
294
+ print(f"Hello {name}")
295
+ ```
296
+ """
297
+ ),
298
+ ] = None,
299
+ default_factory: Annotated[
300
+ Callable[[], Any] | None,
301
+ Doc(
302
+ """
303
+ Provide a custom function that dynamically generates a [default](https://typer.tiangolo.com/tutorial/arguments/default) for this CLI Option.
304
+
305
+ **Example**
306
+
307
+ ```python
308
+ def get_name():
309
+ return random.choice(["Me", "Myself", "I"])
310
+
311
+ @app.command()
312
+ def main(name: Annotated[str, typer.Option(default_factory=get_name)]):
313
+ print(f"Hello {name}")
314
+ ```
315
+ """
316
+ ),
317
+ ] = None,
318
+ # Custom type
319
+ parser: Annotated[
320
+ Callable[[str], Any] | None,
321
+ Doc(
322
+ """
323
+ Use your own custom types in Typer applications by defining a `parser` function that parses input into your own types:
324
+
325
+ **Example**
326
+
327
+ ```python
328
+ class CustomClass:
329
+ def __init__(self, value: str):
330
+ self.value = value
331
+
332
+ def __str__(self):
333
+ return f"<CustomClass: value={self.value}>"
334
+
335
+ def my_parser(value: str):
336
+ return CustomClass(value * 2)
337
+
338
+ @app.command()
339
+ def main(opt: Annotated[CustomClass, typer.Option(parser=my_parser)] = "Foo"):
340
+ print(f"--opt is {opt}")
341
+ ```
342
+ """
343
+ ),
344
+ ] = None,
345
+ click_type: Annotated[
346
+ click.ParamType | None,
347
+ Doc(
348
+ """
349
+ Define this parameter to use a [custom Click type](https://click.palletsprojects.com/en/stable/parameters/#implementing-custom-types) in your Typer applications.
350
+
351
+ **Example**
352
+
353
+ ```python
354
+ class MyClass:
355
+ def __init__(self, value: str):
356
+ self.value = value
357
+
358
+ def __str__(self):
359
+ return f"<MyClass: value={self.value}>"
360
+
361
+ class MyParser(click.ParamType):
362
+ name = "MyClass"
363
+
364
+ def convert(self, value, param, ctx):
365
+ return MyClass(value * 3)
366
+
367
+ @app.command()
368
+ def main(opt: Annotated[MyClass, typer.Option(click_type=MyParser())] = "Foo"):
369
+ print(f"--opt is {opt}")
370
+ ```
371
+ """
372
+ ),
373
+ ] = None,
374
+ # Option
375
+ show_default: Annotated[
376
+ bool | str,
377
+ Doc(
378
+ """
379
+ When set to `False`, don't show the default value of this CLI Option in the [help text](https://typer.tiangolo.com/tutorial/options/help/).
380
+
381
+ **Example**
382
+
383
+ ```python
384
+ @app.command()
385
+ def main(name: Annotated[str, typer.Option(show_default=False)] = "Rick"):
386
+ print(f"Hello {name}")
387
+ ```
388
+ """
389
+ ),
390
+ ] = True,
391
+ prompt: Annotated[
392
+ bool | str,
393
+ Doc(
394
+ """
395
+ When set to `True`, a prompt will appear to ask for the value of this CLI Option if it was not provided:
396
+
397
+ **Example**
398
+
399
+ ```python
400
+ @app.command()
401
+ def main(name: str, lastname: Annotated[str, typer.Option(prompt=True)]):
402
+ print(f"Hello {name} {lastname}")
403
+ ```
404
+ """
405
+ ),
406
+ ] = False,
407
+ confirmation_prompt: Annotated[
408
+ bool,
409
+ Doc(
410
+ """
411
+ When set to `True`, a user will need to type a prompted value twice (may be useful for passwords etc.).
412
+
413
+ **Example**
414
+
415
+ ```python
416
+ @app.command()
417
+ def main(project: Annotated[str, typer.Option(prompt=True, confirmation_prompt=True)]):
418
+ print(f"Deleting project {project}")
419
+ ```
420
+ """
421
+ ),
422
+ ] = False,
423
+ prompt_required: Annotated[
424
+ bool,
425
+ Doc(
426
+ """
427
+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
428
+
429
+ ---
430
+
431
+ If this is `False` then a prompt is only shown if the option's flag is given without a value.
432
+ """
433
+ ),
434
+ ] = True,
435
+ hide_input: Annotated[
436
+ bool,
437
+ Doc(
438
+ """
439
+ When you've configured a prompt, for instance for [querying a password](https://typer.tiangolo.com/tutorial/options/password/),
440
+ don't show anything on the screen while the user is typing the value.
441
+
442
+ **Example**
443
+
444
+ ```python
445
+ @app.command()
446
+ def login(
447
+ name: str,
448
+ password: Annotated[str, typer.Option(prompt=True, hide_input=True)],
449
+ ):
450
+ print(f"Hello {name}. Doing something very secure with password.")
451
+ ```
452
+ """
453
+ ),
454
+ ] = False,
455
+ # TODO: remove is_flag and flag_value in a future release
456
+ is_flag: Annotated[
457
+ bool | None,
458
+ Doc(
459
+ """
460
+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
461
+ It is however not fully functional, and will likely be removed in future versions.
462
+ """
463
+ ),
464
+ ] = None,
465
+ flag_value: Annotated[
466
+ Any | None,
467
+ Doc(
468
+ """
469
+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
470
+ It is however not fully functional, and will likely be removed in future versions.
471
+ """
472
+ ),
473
+ ] = None,
474
+ count: Annotated[
475
+ bool,
476
+ Doc(
477
+ """
478
+ Make a CLI Option work as a [counter](https://typer.tiangolo.com/tutorial/parameter-types/number/#counter-cli-options).
479
+ The CLI option will have the `int` value representing the number of times the option was used on the command line.
480
+
481
+ **Example**
482
+
483
+ ```python
484
+ @app.command()
485
+ def main(verbose: Annotated[int, typer.Option("--verbose", "-v", count=True)] = 0):
486
+ print(f"Verbose level is {verbose}")
487
+ ```
488
+ """
489
+ ),
490
+ ] = False,
491
+ allow_from_autoenv: Annotated[
492
+ bool,
493
+ Doc(
494
+ """
495
+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
496
+
497
+ ---
498
+
499
+ If this is enabled then the value of this parameter will be pulled from an environment variable in case a prefix is defined on the context.
500
+ """
501
+ ),
502
+ ] = True,
503
+ help: Annotated[
504
+ str | None,
505
+ Doc(
506
+ """
507
+ Help text for this CLI Option.
508
+ See [the tutorial about CLI Options with help](https://typer.tiangolo.com/tutorial/options/help/) for more dedails.
509
+
510
+ **Example**
511
+
512
+ ```python
513
+ @app.command()
514
+ def greet(name: Annotated[str, typer.Option(help="Person to greet")] = "Deadpool"):
515
+ print(f"Hello {name}")
516
+ ```
517
+ """
518
+ ),
519
+ ] = None,
520
+ hidden: Annotated[
521
+ bool,
522
+ Doc(
523
+ """
524
+ Hide this CLI Option from [help outputs](https://typer.tiangolo.com/tutorial/options/help). `False` by default.
525
+
526
+ **Example**
527
+
528
+ ```python
529
+ @app.command()
530
+ def greet(name: Annotated[str, typer.Option(hidden=True)] = "Deadpool"):
531
+ print(f"Hello {name}")
532
+ ```
533
+ """
534
+ ),
535
+ ] = False,
536
+ show_choices: Annotated[
537
+ bool,
538
+ Doc(
539
+ """
540
+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
541
+
542
+ ---
543
+
544
+ When set to `False`, this suppresses choices from being displayed inline when `prompt` is used.
545
+ """
546
+ ),
547
+ ] = True,
548
+ show_envvar: Annotated[
549
+ bool,
550
+ Doc(
551
+ """
552
+ When an ["envvar"](https://typer.tiangolo.com/tutorial/arguments/envvar) is defined, prevent it from showing up in the help text:
553
+
554
+ **Example**
555
+
556
+ ```python
557
+ @app.command()
558
+ def main(user: Annotated[str, typer.Option(envvar="ME", show_envvar=False)]):
559
+ print(f"Hello {user}")
560
+ ```
561
+ """
562
+ ),
563
+ ] = True,
564
+ # Choice
565
+ case_sensitive: Annotated[
566
+ bool,
567
+ Doc(
568
+ """
569
+ For a CLI Option representing an [Enum (choice)](https://typer.tiangolo.com/tutorial/parameter-types/enum),
570
+ you can allow case-insensitive matching with this parameter:
571
+
572
+ **Example**
573
+
574
+ ```python
575
+ from enum import Enum
576
+
577
+ class NeuralNetwork(str, Enum):
578
+ simple = "simple"
579
+ conv = "conv"
580
+ lstm = "lstm"
581
+
582
+ @app.command()
583
+ def main(
584
+ network: Annotated[NeuralNetwork, typer.Option(case_sensitive=False)]):
585
+ print(f"Training neural network of type: {network.value}")
586
+ ```
587
+
588
+ With this setting, "LSTM" or "lstm" will both be valid values that will be resolved to `NeuralNetwork.lstm`.
589
+ """
590
+ ),
591
+ ] = True,
592
+ # Numbers
593
+ min: Annotated[
594
+ int | float | None,
595
+ Doc(
596
+ """
597
+ For a CLI Option representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`),
598
+ you can define numeric validations with `min` and `max` values:
599
+
600
+ **Example**
601
+
602
+ ```python
603
+ @app.command()
604
+ def main(
605
+ user: Annotated[str, typer.Argument()],
606
+ user_id: Annotated[int, typer.Option(min=1, max=1000)],
607
+ ):
608
+ print(f"ID for {user} is {user_id}")
609
+ ```
610
+
611
+ If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid.
612
+ """
613
+ ),
614
+ ] = None,
615
+ max: Annotated[
616
+ int | float | None,
617
+ Doc(
618
+ """
619
+ For a CLI Option representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`),
620
+ you can define numeric validations with `min` and `max` values:
621
+
622
+ **Example**
623
+
624
+ ```python
625
+ @app.command()
626
+ def main(
627
+ user: Annotated[str, typer.Argument()],
628
+ user_id: Annotated[int, typer.Option(min=1, max=1000)],
629
+ ):
630
+ print(f"ID for {user} is {user_id}")
631
+ ```
632
+
633
+ If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid.
634
+ """
635
+ ),
636
+ ] = None,
637
+ clamp: Annotated[
638
+ bool,
639
+ Doc(
640
+ """
641
+ For a CLI Option representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) and that is bounded by using `min` and/or `max`,
642
+ you can opt to use the closest minimum or maximum value instead of raising an error when the value is out of bounds. This is done by setting `clamp` to `True`.
643
+
644
+ **Example**
645
+
646
+ ```python
647
+ @app.command()
648
+ def main(
649
+ user: Annotated[str, typer.Argument()],
650
+ user_id: Annotated[int, typer.Option(min=1, max=1000, clamp=True)],
651
+ ):
652
+ print(f"ID for {user} is {user_id}")
653
+ ```
654
+
655
+ If the user attempts to input 3420 for `user_id`, this will internally be converted to `1000`.
656
+ """
657
+ ),
658
+ ] = False,
659
+ # DateTime
660
+ formats: Annotated[
661
+ list[str] | None,
662
+ Doc(
663
+ """
664
+ For a CLI Option representing a [DateTime object](https://typer.tiangolo.com/tutorial/parameter-types/datetime),
665
+ you can customize the formats that can be parsed automatically:
666
+
667
+ **Example**
668
+
669
+ ```python
670
+ from datetime import datetime
671
+
672
+ @app.command()
673
+ def main(
674
+ birthday: Annotated[
675
+ datetime,
676
+ typer.Option(
677
+ formats=["%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%m/%d/%Y"]
678
+ ),
679
+ ],
680
+ ):
681
+ print(f"Birthday defined at: {birthday}")
682
+ ```
683
+ """
684
+ ),
685
+ ] = None,
686
+ # File
687
+ mode: Annotated[
688
+ str | None,
689
+ Doc(
690
+ """
691
+ For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),
692
+ you can customize the mode to open the file with. If unset, Typer will set a [sensible value by default](https://typer.tiangolo.com/tutorial/parameter-types/file/#advanced-mode).
693
+
694
+ **Example**
695
+
696
+ ```python
697
+ @app.command()
698
+ def main(config: Annotated[typer.FileText, typer.Option(mode="a")]):
699
+ config.write("This is a single line\\n")
700
+ print("Config line written")
701
+ ```
702
+ """
703
+ ),
704
+ ] = None,
705
+ encoding: Annotated[
706
+ str | None,
707
+ Doc(
708
+ """
709
+ Customize the encoding of this CLI Option represented by a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/).
710
+
711
+ **Example**
712
+
713
+ ```python
714
+ @app.command()
715
+ def main(config: Annotated[typer.FileText, typer.Option(encoding="utf-8")]):
716
+ config.write("All the text gets written\\n")
717
+ ```
718
+ """
719
+ ),
720
+ ] = None,
721
+ errors: Annotated[
722
+ str | None,
723
+ Doc(
724
+ """
725
+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
726
+
727
+ ---
728
+
729
+ The error handling mode.
730
+ """
731
+ ),
732
+ ] = "strict",
733
+ lazy: Annotated[
734
+ bool | None,
735
+ Doc(
736
+ """
737
+ For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),
738
+ by default the file will not be created until you actually start writing to it.
739
+ You can change this behaviour by setting this parameter.
740
+ By default, it's set to `True` for writing and to `False` for reading.
741
+
742
+ **Example**
743
+
744
+ ```python
745
+ @app.command()
746
+ def main(config: Annotated[typer.FileText, typer.Option(mode="a", lazy=False)]):
747
+ config.write("This is a single line\\n")
748
+ print("Config line written")
749
+ ```
750
+ """
751
+ ),
752
+ ] = None,
753
+ atomic: Annotated[
754
+ bool,
755
+ Doc(
756
+ """
757
+ For a CLI Option representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),
758
+ you can ensure that all write instructions first go into a temporal file, and are only moved to the final destination after completing
759
+ by setting `atomic` to `True`. This can be useful for files with potential concurrent access.
760
+
761
+ **Example**
762
+
763
+ ```python
764
+ @app.command()
765
+ def main(config: Annotated[typer.FileText, typer.Option(mode="a", atomic=True)]):
766
+ config.write("All the text")
767
+ ```
768
+ """
769
+ ),
770
+ ] = False,
771
+ # Path
772
+ exists: Annotated[
773
+ bool,
774
+ Doc(
775
+ """
776
+ When set to `True` for a [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/),
777
+ additional validation is performed to check that the file or directory exists. If not, the value will be invalid.
778
+
779
+ **Example**
780
+
781
+ ```python
782
+ from pathlib import Path
783
+
784
+ @app.command()
785
+ def main(config: Annotated[Path, typer.Option(exists=True)]):
786
+ text = config.read_text()
787
+ print(f"Config file contents: {text}")
788
+ ```
789
+ """
790
+ ),
791
+ ] = False,
792
+ file_okay: Annotated[
793
+ bool,
794
+ Doc(
795
+ """
796
+ Determine whether or not a [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/)
797
+ is allowed to refer to a file. When this is set to `False`, the application will raise a validation error when a path to a file is given.
798
+
799
+ **Example**
800
+
801
+ ```python
802
+ from pathlib import Path
803
+
804
+ @app.command()
805
+ def main(config: Annotated[Path, typer.Option(exists=True, file_okay=False)]):
806
+ print(f"Directory listing: {[x.name for x in config.iterdir()]}")
807
+ ```
808
+ """
809
+ ),
810
+ ] = True,
811
+ dir_okay: Annotated[
812
+ bool,
813
+ Doc(
814
+ """
815
+ Determine whether or not a [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/)
816
+ is allowed to refer to a directory. When this is set to `False`, the application will raise a validation error when a path to a directory is given.
817
+
818
+ **Example**
819
+
820
+ ```python
821
+ from pathlib import Path
822
+
823
+ @app.command()
824
+ def main(config: Annotated[Path, typer.Argument(exists=True, dir_okay=False)]):
825
+ text = config.read_text()
826
+ print(f"Config file contents: {text}")
827
+ ```
828
+ """
829
+ ),
830
+ ] = True,
831
+ writable: Annotated[
832
+ bool,
833
+ Doc(
834
+ """
835
+ Whether or not to perform a writable check for this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/).
836
+
837
+ **Example**
838
+
839
+ ```python
840
+ from pathlib import Path
841
+
842
+ @app.command()
843
+ def main(config: Annotated[Path, typer.Option(writable=True)]):
844
+ config.write_text("All the text")
845
+ ```
846
+ """
847
+ ),
848
+ ] = False,
849
+ readable: Annotated[
850
+ bool,
851
+ Doc(
852
+ """
853
+ Whether or not to perform a readable check for this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/).
854
+
855
+ **Example**
856
+
857
+ ```python
858
+ from pathlib import Path
859
+
860
+ @app.command()
861
+ def main(config: Annotated[Path, typer.Option(readable=True)]):
862
+ config.read_text("All the text")
863
+ ```
864
+ """
865
+ ),
866
+ ] = True,
867
+ resolve_path: Annotated[
868
+ bool,
869
+ Doc(
870
+ """
871
+ Whether or not to fully resolve the path of this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/),
872
+ meaning that the path becomes absolute and symlinks are resolved.
873
+
874
+ **Example**
875
+
876
+ ```python
877
+ from pathlib import Path
878
+
879
+ @app.command()
880
+ def main(config: Annotated[Path, typer.Option(resolve_path=True)]):
881
+ config.read_text("All the text")
882
+ ```
883
+ """
884
+ ),
885
+ ] = False,
886
+ allow_dash: Annotated[
887
+ bool,
888
+ Doc(
889
+ """
890
+ When set to `True`, a single dash for this [`Path` CLI Option](https://typer.tiangolo.com/tutorial/parameter-types/path/)
891
+ would be a valid value, indicating standard streams. This is a more advanced use-case.
892
+ """
893
+ ),
894
+ ] = False,
895
+ path_type: Annotated[
896
+ None | type[str] | type[bytes],
897
+ Doc(
898
+ """
899
+ A string type that will be used to represent this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/).
900
+ The default is `None` which means the return value will be either bytes or unicode, depending on what makes most sense given the input data.
901
+ This is a more advanced use-case.
902
+ """
903
+ ),
904
+ ] = None,
905
+ # Rich settings
906
+ rich_help_panel: Annotated[
907
+ str | None,
908
+ Doc(
909
+ """
910
+ Set the panel name where you want this CLI Option to be shown in the [help text](https://typer.tiangolo.com/tutorial/arguments/help).
911
+
912
+ **Example**
913
+
914
+ ```python
915
+ @app.command()
916
+ def main(
917
+ name: Annotated[str, typer.Argument(help="Who to greet")],
918
+ age: Annotated[str, typer.Option(help="Their age", rich_help_panel="Data")],
919
+ ):
920
+ print(f"Hello {name} of age {age}")
921
+ ```
922
+ """
923
+ ),
924
+ ] = None,
925
+ ) -> Any:
926
+ """
927
+ A [CLI Option](https://typer.tiangolo.com/tutorial/options) is a parameter to your command line application that is called with a single or double dash, something like `--verbose` or `-v`.
928
+
929
+ Often, CLI Options are optional, meaning that users can omit them from the command. However, you can set them to be required by using `Annotated`
930
+ and omitting a default value.
931
+
932
+ ## Example
933
+
934
+ ```python
935
+ @app.command()
936
+ def register(
937
+ user: Annotated[str, typer.Argument()],
938
+ age: Annotated[int, typer.Option(min=18)],
939
+ ):
940
+ print(f"User is {user}")
941
+ print(f"--age is {age}")
942
+ ```
943
+
944
+ Note how in this example, `--age` is a required CLI Option.
945
+ """
946
+ return OptionInfo(
947
+ # Parameter
948
+ default=default,
949
+ param_decls=param_decls,
950
+ callback=callback,
951
+ metavar=metavar,
952
+ expose_value=expose_value,
953
+ is_eager=is_eager,
954
+ envvar=envvar,
955
+ shell_complete=shell_complete,
956
+ autocompletion=autocompletion,
957
+ default_factory=default_factory,
958
+ # Custom type
959
+ parser=parser,
960
+ click_type=click_type,
961
+ # Option
962
+ show_default=show_default,
963
+ prompt=prompt,
964
+ confirmation_prompt=confirmation_prompt,
965
+ prompt_required=prompt_required,
966
+ hide_input=hide_input,
967
+ is_flag=is_flag,
968
+ flag_value=flag_value,
969
+ count=count,
970
+ allow_from_autoenv=allow_from_autoenv,
971
+ help=help,
972
+ hidden=hidden,
973
+ show_choices=show_choices,
974
+ show_envvar=show_envvar,
975
+ # Choice
976
+ case_sensitive=case_sensitive,
977
+ # Numbers
978
+ min=min,
979
+ max=max,
980
+ clamp=clamp,
981
+ # DateTime
982
+ formats=formats,
983
+ # File
984
+ mode=mode,
985
+ encoding=encoding,
986
+ errors=errors,
987
+ lazy=lazy,
988
+ atomic=atomic,
989
+ # Path
990
+ exists=exists,
991
+ file_okay=file_okay,
992
+ dir_okay=dir_okay,
993
+ writable=writable,
994
+ readable=readable,
995
+ resolve_path=resolve_path,
996
+ allow_dash=allow_dash,
997
+ path_type=path_type,
998
+ # Rich settings
999
+ rich_help_panel=rich_help_panel,
1000
+ )
1001
+
1002
+
1003
+ # Overload for Argument created with custom type 'parser'
1004
+ @overload
1005
+ def Argument(
1006
+ # Parameter
1007
+ default: Any | None = ...,
1008
+ *,
1009
+ callback: Callable[..., Any] | None = None,
1010
+ metavar: str | None = None,
1011
+ expose_value: bool = True,
1012
+ is_eager: bool = False,
1013
+ envvar: str | list[str] | None = None,
1014
+ # Note that shell_complete is not fully supported and will be removed in future versions
1015
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
1016
+ shell_complete: Callable[
1017
+ [click.Context, click.Parameter, str],
1018
+ list["click.shell_completion.CompletionItem"] | list[str],
1019
+ ]
1020
+ | None = None,
1021
+ autocompletion: Callable[..., Any] | None = None,
1022
+ default_factory: Callable[[], Any] | None = None,
1023
+ # Custom type
1024
+ parser: Callable[[str], Any] | None = None,
1025
+ # TyperArgument
1026
+ show_default: bool | str = True,
1027
+ show_choices: bool = True,
1028
+ show_envvar: bool = True,
1029
+ help: str | None = None,
1030
+ hidden: bool = False,
1031
+ # Choice
1032
+ case_sensitive: bool = True,
1033
+ # Numbers
1034
+ min: int | float | None = None,
1035
+ max: int | float | None = None,
1036
+ clamp: bool = False,
1037
+ # DateTime
1038
+ formats: list[str] | None = None,
1039
+ # File
1040
+ mode: str | None = None,
1041
+ encoding: str | None = None,
1042
+ errors: str | None = "strict",
1043
+ lazy: bool | None = None,
1044
+ atomic: bool = False,
1045
+ # Path
1046
+ exists: bool = False,
1047
+ file_okay: bool = True,
1048
+ dir_okay: bool = True,
1049
+ writable: bool = False,
1050
+ readable: bool = True,
1051
+ resolve_path: bool = False,
1052
+ allow_dash: bool = False,
1053
+ path_type: None | type[str] | type[bytes] = None,
1054
+ # Rich settings
1055
+ rich_help_panel: str | None = None,
1056
+ ) -> Any: ...
1057
+
1058
+
1059
+ # Overload for Argument created with custom type 'click_type'
1060
+ @overload
1061
+ def Argument(
1062
+ # Parameter
1063
+ default: Any | None = ...,
1064
+ *,
1065
+ callback: Callable[..., Any] | None = None,
1066
+ metavar: str | None = None,
1067
+ expose_value: bool = True,
1068
+ is_eager: bool = False,
1069
+ envvar: str | list[str] | None = None,
1070
+ # Note that shell_complete is not fully supported and will be removed in future versions
1071
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
1072
+ shell_complete: Callable[
1073
+ [click.Context, click.Parameter, str],
1074
+ list["click.shell_completion.CompletionItem"] | list[str],
1075
+ ]
1076
+ | None = None,
1077
+ autocompletion: Callable[..., Any] | None = None,
1078
+ default_factory: Callable[[], Any] | None = None,
1079
+ # Custom type
1080
+ click_type: click.ParamType | None = None,
1081
+ # TyperArgument
1082
+ show_default: bool | str = True,
1083
+ show_choices: bool = True,
1084
+ show_envvar: bool = True,
1085
+ help: str | None = None,
1086
+ hidden: bool = False,
1087
+ # Choice
1088
+ case_sensitive: bool = True,
1089
+ # Numbers
1090
+ min: int | float | None = None,
1091
+ max: int | float | None = None,
1092
+ clamp: bool = False,
1093
+ # DateTime
1094
+ formats: list[str] | None = None,
1095
+ # File
1096
+ mode: str | None = None,
1097
+ encoding: str | None = None,
1098
+ errors: str | None = "strict",
1099
+ lazy: bool | None = None,
1100
+ atomic: bool = False,
1101
+ # Path
1102
+ exists: bool = False,
1103
+ file_okay: bool = True,
1104
+ dir_okay: bool = True,
1105
+ writable: bool = False,
1106
+ readable: bool = True,
1107
+ resolve_path: bool = False,
1108
+ allow_dash: bool = False,
1109
+ path_type: None | type[str] | type[bytes] = None,
1110
+ # Rich settings
1111
+ rich_help_panel: str | None = None,
1112
+ ) -> Any: ...
1113
+
1114
+
1115
+ def Argument(
1116
+ # Parameter
1117
+ default: Annotated[
1118
+ Any | None,
1119
+ Doc(
1120
+ """
1121
+ By default, CLI arguments are required. However, by giving them a default value they become [optional](https://typer.tiangolo.com/tutorial/arguments/optional):
1122
+
1123
+ **Example**
1124
+
1125
+ ```python
1126
+ @app.command()
1127
+ def main(name: str = typer.Argument("World")):
1128
+ print(f"Hello {name}!")
1129
+ ```
1130
+
1131
+ Note that this usage is deprecated, and we recommend to use `Annotated` instead:
1132
+ ```python
1133
+ @app.command()
1134
+ def main(name: Annotated[str, typer.Argument()] = "World"):
1135
+ print(f"Hello {name}!")
1136
+ ```
1137
+ """
1138
+ ),
1139
+ ] = ...,
1140
+ *,
1141
+ callback: Annotated[
1142
+ Callable[..., Any] | None,
1143
+ Doc(
1144
+ """
1145
+ Add a callback to this CLI Argument, to execute additional logic with the value received from the terminal.
1146
+ See [the tutorial about callbacks](https://typer.tiangolo.com/tutorial/options/callback-and-context/) for more details.
1147
+
1148
+ **Example**
1149
+
1150
+ ```python
1151
+ def name_callback(value: str):
1152
+ if value != "Deadpool":
1153
+ raise typer.BadParameter("Only Deadpool is allowed")
1154
+ return value
1155
+
1156
+ @app.command()
1157
+ def main(name: Annotated[str, typer.Argument(callback=name_callback)]):
1158
+ print(f"Hello {name}")
1159
+ ```
1160
+ """
1161
+ ),
1162
+ ] = None,
1163
+ metavar: Annotated[
1164
+ str | None,
1165
+ Doc(
1166
+ """
1167
+ Customize the name displayed in the help text to represent this CLI Argument.
1168
+ By default, it will be the same name you declared, in uppercase.
1169
+ See [the tutorial about CLI Arguments with Help](https://typer.tiangolo.com/tutorial/arguments/help/#custom-help-name-metavar) for more details.
1170
+
1171
+ **Example**
1172
+
1173
+ ```python
1174
+ @app.command()
1175
+ def main(name: Annotated[str, typer.Argument(metavar="✨username✨")]):
1176
+ print(f"Hello {name}")
1177
+ ```
1178
+ """
1179
+ ),
1180
+ ] = None,
1181
+ expose_value: Annotated[
1182
+ bool,
1183
+ Doc(
1184
+ """
1185
+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
1186
+
1187
+ ---
1188
+
1189
+ If this is `True` then the value is passed onwards to the command callback and stored on the context, otherwise it’s skipped.
1190
+ """
1191
+ ),
1192
+ ] = True,
1193
+ is_eager: Annotated[
1194
+ bool,
1195
+ Doc(
1196
+ """
1197
+ Set an argument to "eager" to ensure it gets processed before other CLI parameters. This could be relevant when there are other parameters with callbacks that could exit the program early.
1198
+ For more information and an extended example, see the documentation [here](https://typer.tiangolo.com/tutorial/options/version/#fix-with-is_eager).
1199
+ """
1200
+ ),
1201
+ ] = False,
1202
+ envvar: Annotated[
1203
+ str | list[str] | None,
1204
+ Doc(
1205
+ """
1206
+ Configure an argument to read a value from an environment variable if it is not provided in the command line as a CLI argument.
1207
+ For more information, see the [documentation on Environment Variables](https://typer.tiangolo.com/tutorial/arguments/envvar/).
1208
+
1209
+ **Example**
1210
+
1211
+ ```python
1212
+ @app.command()
1213
+ def main(name: Annotated[str, typer.Argument(envvar="ME")]):
1214
+ print(f"Hello Mr. {name}")
1215
+ ```
1216
+ """
1217
+ ),
1218
+ ] = None,
1219
+ # TODO: Remove shell_complete in a future version (after 0.16.0)
1220
+ shell_complete: Annotated[
1221
+ Callable[
1222
+ [click.Context, click.Parameter, str],
1223
+ list["click.shell_completion.CompletionItem"] | list[str],
1224
+ ]
1225
+ | None,
1226
+ Doc(
1227
+ """
1228
+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
1229
+ It is however not fully functional, and will likely be removed in future versions.
1230
+ """
1231
+ ),
1232
+ ] = None,
1233
+ autocompletion: Annotated[
1234
+ Callable[..., Any] | None,
1235
+ Doc(
1236
+ """
1237
+ Provide a custom function that helps to autocomplete the values of this CLI Argument.
1238
+ See [the tutorial on parameter autocompletion](https://typer.tiangolo.com/tutorial/options-autocompletion) for more details.
1239
+
1240
+ **Example**
1241
+
1242
+ ```python
1243
+ def complete():
1244
+ return ["Me", "Myself", "I"]
1245
+
1246
+ @app.command()
1247
+ def main(name: Annotated[str, typer.Argument(autocompletion=complete)]):
1248
+ print(f"Hello {name}")
1249
+ ```
1250
+ """
1251
+ ),
1252
+ ] = None,
1253
+ default_factory: Annotated[
1254
+ Callable[[], Any] | None,
1255
+ Doc(
1256
+ """
1257
+ Provide a custom function that dynamically generates a [default](https://typer.tiangolo.com/tutorial/arguments/default) for this CLI Argument.
1258
+
1259
+ **Example**
1260
+
1261
+ ```python
1262
+ def get_name():
1263
+ return random.choice(["Me", "Myself", "I"])
1264
+
1265
+ @app.command()
1266
+ def main(name: Annotated[str, typer.Argument(default_factory=get_name)]):
1267
+ print(f"Hello {name}")
1268
+ ```
1269
+ """
1270
+ ),
1271
+ ] = None,
1272
+ # Custom type
1273
+ parser: Annotated[
1274
+ Callable[[str], Any] | None,
1275
+ Doc(
1276
+ """
1277
+ Use your own custom types in Typer applications by defining a `parser` function that parses input into your own types:
1278
+
1279
+ **Example**
1280
+
1281
+ ```python
1282
+ class CustomClass:
1283
+ def __init__(self, value: str):
1284
+ self.value = value
1285
+
1286
+ def __str__(self):
1287
+ return f"<CustomClass: value={self.value}>"
1288
+
1289
+ def my_parser(value: str):
1290
+ return CustomClass(value * 2)
1291
+
1292
+ @app.command()
1293
+ def main(arg: Annotated[CustomClass, typer.Argument(parser=my_parser):
1294
+ print(f"arg is {arg}")
1295
+ ```
1296
+ """
1297
+ ),
1298
+ ] = None,
1299
+ click_type: Annotated[
1300
+ click.ParamType | None,
1301
+ Doc(
1302
+ """
1303
+ Define this parameter to use a [custom Click type](https://click.palletsprojects.com/en/stable/parameters/#implementing-custom-types) in your Typer applications.
1304
+
1305
+ **Example**
1306
+
1307
+ ```python
1308
+ class MyClass:
1309
+ def __init__(self, value: str):
1310
+ self.value = value
1311
+
1312
+ def __str__(self):
1313
+ return f"<MyClass: value={self.value}>"
1314
+
1315
+ class MyParser(click.ParamType):
1316
+ name = "MyClass"
1317
+
1318
+ def convert(self, value, param, ctx):
1319
+ return MyClass(value * 3)
1320
+
1321
+ @app.command()
1322
+ def main(arg: Annotated[MyClass, typer.Argument(click_type=MyParser())]):
1323
+ print(f"arg is {arg}")
1324
+ ```
1325
+ """
1326
+ ),
1327
+ ] = None,
1328
+ # TyperArgument
1329
+ show_default: Annotated[
1330
+ bool | str,
1331
+ Doc(
1332
+ """
1333
+ When set to `False`, don't show the default value of this CLI Argument in the [help text](https://typer.tiangolo.com/tutorial/arguments/help/).
1334
+
1335
+ **Example**
1336
+
1337
+ ```python
1338
+ @app.command()
1339
+ def main(name: Annotated[str, typer.Argument(show_default=False)] = "Rick"):
1340
+ print(f"Hello {name}")
1341
+ ```
1342
+ """
1343
+ ),
1344
+ ] = True,
1345
+ show_choices: Annotated[
1346
+ bool,
1347
+ Doc(
1348
+ """
1349
+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
1350
+
1351
+ ---
1352
+
1353
+ When set to `False`, this suppresses choices from being displayed inline when `prompt` is used.
1354
+ """
1355
+ ),
1356
+ ] = True,
1357
+ show_envvar: Annotated[
1358
+ bool,
1359
+ Doc(
1360
+ """
1361
+ When an ["envvar"](https://typer.tiangolo.com/tutorial/arguments/envvar) is defined, prevent it from showing up in the help text:
1362
+
1363
+ **Example**
1364
+
1365
+ ```python
1366
+ @app.command()
1367
+ def main(name: Annotated[str, typer.Argument(envvar="ME", show_envvar=False)]):
1368
+ print(f"Hello Mr. {name}")
1369
+ ```
1370
+ """
1371
+ ),
1372
+ ] = True,
1373
+ help: Annotated[
1374
+ str | None,
1375
+ Doc(
1376
+ """
1377
+ Help text for this CLI Argument.
1378
+ See [the tutorial about CLI Arguments with help](https://typer.tiangolo.com/tutorial/arguments/help/) for more dedails.
1379
+
1380
+ **Example**
1381
+
1382
+ ```python
1383
+ @app.command()
1384
+ def greet(name: Annotated[str, typer.Argument(help="Person to greet")]):
1385
+ print(f"Hello {name}")
1386
+ ```
1387
+ """
1388
+ ),
1389
+ ] = None,
1390
+ hidden: Annotated[
1391
+ bool,
1392
+ Doc(
1393
+ """
1394
+ Hide this CLI Argument from [help outputs](https://typer.tiangolo.com/tutorial/arguments/help). `False` by default.
1395
+
1396
+ **Example**
1397
+
1398
+ ```python
1399
+ @app.command()
1400
+ def main(name: Annotated[str, typer.Argument(hidden=True)] = "World"):
1401
+ print(f"Hello {name}")
1402
+ ```
1403
+ """
1404
+ ),
1405
+ ] = False,
1406
+ # Choice
1407
+ case_sensitive: Annotated[
1408
+ bool,
1409
+ Doc(
1410
+ """
1411
+ For a CLI Argument representing an [Enum (choice)](https://typer.tiangolo.com/tutorial/parameter-types/enum),
1412
+ you can allow case-insensitive matching with this parameter:
1413
+
1414
+ **Example**
1415
+
1416
+ ```python
1417
+ from enum import Enum
1418
+
1419
+ class NeuralNetwork(str, Enum):
1420
+ simple = "simple"
1421
+ conv = "conv"
1422
+ lstm = "lstm"
1423
+
1424
+ @app.command()
1425
+ def main(
1426
+ network: Annotated[NeuralNetwork, typer.Argument(case_sensitive=False)]):
1427
+ print(f"Training neural network of type: {network.value}")
1428
+ ```
1429
+
1430
+ With this setting, "LSTM" or "lstm" will both be valid values that will be resolved to `NeuralNetwork.lstm`.
1431
+ """
1432
+ ),
1433
+ ] = True,
1434
+ # Numbers
1435
+ min: Annotated[
1436
+ int | float | None,
1437
+ Doc(
1438
+ """
1439
+ For a CLI Argument representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`),
1440
+ you can define numeric validations with `min` and `max` values:
1441
+
1442
+ **Example**
1443
+
1444
+ ```python
1445
+ @app.command()
1446
+ def main(
1447
+ user: Annotated[str, typer.Argument()],
1448
+ user_id: Annotated[int, typer.Argument(min=1, max=1000)],
1449
+ ):
1450
+ print(f"ID for {user} is {user_id}")
1451
+ ```
1452
+
1453
+ If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid.
1454
+ """
1455
+ ),
1456
+ ] = None,
1457
+ max: Annotated[
1458
+ int | float | None,
1459
+ Doc(
1460
+ """
1461
+ For a CLI Argument representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) (`int` or `float`),
1462
+ you can define numeric validations with `min` and `max` values:
1463
+
1464
+ **Example**
1465
+
1466
+ ```python
1467
+ @app.command()
1468
+ def main(
1469
+ user: Annotated[str, typer.Argument()],
1470
+ user_id: Annotated[int, typer.Argument(min=1, max=1000)],
1471
+ ):
1472
+ print(f"ID for {user} is {user_id}")
1473
+ ```
1474
+
1475
+ If the user attempts to input an invalid number, an error will be shown, explaining why the value is invalid.
1476
+ """
1477
+ ),
1478
+ ] = None,
1479
+ clamp: Annotated[
1480
+ bool,
1481
+ Doc(
1482
+ """
1483
+ For a CLI Argument representing a [number](https://typer.tiangolo.com/tutorial/parameter-types/number/) and that is bounded by using `min` and/or `max`,
1484
+ you can opt to use the closest minimum or maximum value instead of raising an error. This is done by setting `clamp` to `True`.
1485
+
1486
+ **Example**
1487
+
1488
+ ```python
1489
+ @app.command()
1490
+ def main(
1491
+ user: Annotated[str, typer.Argument()],
1492
+ user_id: Annotated[int, typer.Argument(min=1, max=1000, clamp=True)],
1493
+ ):
1494
+ print(f"ID for {user} is {user_id}")
1495
+ ```
1496
+
1497
+ If the user attempts to input 3420 for `user_id`, this will internally be converted to `1000`.
1498
+ """
1499
+ ),
1500
+ ] = False,
1501
+ # DateTime
1502
+ formats: Annotated[
1503
+ list[str] | None,
1504
+ Doc(
1505
+ """
1506
+ For a CLI Argument representing a [DateTime object](https://typer.tiangolo.com/tutorial/parameter-types/datetime),
1507
+ you can customize the formats that can be parsed automatically:
1508
+
1509
+ **Example**
1510
+
1511
+ ```python
1512
+ from datetime import datetime
1513
+
1514
+ @app.command()
1515
+ def main(
1516
+ birthday: Annotated[
1517
+ datetime,
1518
+ typer.Argument(
1519
+ formats=["%Y-%m-%d", "%Y-%m-%d %H:%M:%S", "%m/%d/%Y"]
1520
+ ),
1521
+ ],
1522
+ ):
1523
+ print(f"Birthday defined at: {birthday}")
1524
+ ```
1525
+ """
1526
+ ),
1527
+ ] = None,
1528
+ # File
1529
+ mode: Annotated[
1530
+ str | None,
1531
+ Doc(
1532
+ """
1533
+ For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),
1534
+ you can customize the mode to open the file with. If unset, Typer will set a [sensible value by default](https://typer.tiangolo.com/tutorial/parameter-types/file/#advanced-mode).
1535
+
1536
+ **Example**
1537
+
1538
+ ```python
1539
+ @app.command()
1540
+ def main(config: Annotated[typer.FileText, typer.Argument(mode="a")]):
1541
+ config.write("This is a single line\\n")
1542
+ print("Config line written")
1543
+ ```
1544
+ """
1545
+ ),
1546
+ ] = None,
1547
+ encoding: Annotated[
1548
+ str | None,
1549
+ Doc(
1550
+ """
1551
+ Customize the encoding of this CLI Argument represented by a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/).
1552
+
1553
+ **Example**
1554
+
1555
+ ```python
1556
+ @app.command()
1557
+ def main(config: Annotated[typer.FileText, typer.Argument(encoding="utf-8")]):
1558
+ config.write("All the text gets written\\n")
1559
+ ```
1560
+ """
1561
+ ),
1562
+ ] = None,
1563
+ errors: Annotated[
1564
+ str | None,
1565
+ Doc(
1566
+ """
1567
+ **Note**: you probably shouldn't use this parameter, it is inherited from Click and supported for compatibility.
1568
+
1569
+ ---
1570
+
1571
+ The error handling mode.
1572
+ """
1573
+ ),
1574
+ ] = "strict",
1575
+ lazy: Annotated[
1576
+ bool | None,
1577
+ Doc(
1578
+ """
1579
+ For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),
1580
+ by default the file will not be created until you actually start writing to it.
1581
+ You can change this behaviour by setting this parameter.
1582
+ By default, it's set to `True` for writing and to `False` for reading.
1583
+
1584
+ **Example**
1585
+
1586
+ ```python
1587
+ @app.command()
1588
+ def main(config: Annotated[typer.FileText, typer.Argument(mode="a", lazy=False)]):
1589
+ config.write("This is a single line\\n")
1590
+ print("Config line written")
1591
+ ```
1592
+ """
1593
+ ),
1594
+ ] = None,
1595
+ atomic: Annotated[
1596
+ bool,
1597
+ Doc(
1598
+ """
1599
+ For a CLI Argument representing a [File object](https://typer.tiangolo.com/tutorial/parameter-types/file/),
1600
+ you can ensure that all write instructions first go into a temporal file, and are only moved to the final destination after completing
1601
+ by setting `atomic` to `True`. This can be useful for files with potential concurrent access.
1602
+
1603
+ **Example**
1604
+
1605
+ ```python
1606
+ @app.command()
1607
+ def main(config: Annotated[typer.FileText, typer.Argument(mode="a", atomic=True)]):
1608
+ config.write("All the text")
1609
+ ```
1610
+ """
1611
+ ),
1612
+ ] = False,
1613
+ # Path
1614
+ exists: Annotated[
1615
+ bool,
1616
+ Doc(
1617
+ """
1618
+ When set to `True` for a [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/),
1619
+ additional validation is performed to check that the file or directory exists. If not, the value will be invalid.
1620
+
1621
+ **Example**
1622
+
1623
+ ```python
1624
+ from pathlib import Path
1625
+
1626
+ @app.command()
1627
+ def main(config: Annotated[Path, typer.Argument(exists=True)]):
1628
+ text = config.read_text()
1629
+ print(f"Config file contents: {text}")
1630
+ ```
1631
+ """
1632
+ ),
1633
+ ] = False,
1634
+ file_okay: Annotated[
1635
+ bool,
1636
+ Doc(
1637
+ """
1638
+ Determine whether or not a [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/)
1639
+ is allowed to refer to a file. When this is set to `False`, the application will raise a validation error when a path to a file is given.
1640
+
1641
+ **Example**
1642
+
1643
+ ```python
1644
+ from pathlib import Path
1645
+
1646
+ @app.command()
1647
+ def main(config: Annotated[Path, typer.Argument(exists=True, file_okay=False)]):
1648
+ print(f"Directory listing: {[x.name for x in config.iterdir()]}")
1649
+ ```
1650
+ """
1651
+ ),
1652
+ ] = True,
1653
+ dir_okay: Annotated[
1654
+ bool,
1655
+ Doc(
1656
+ """
1657
+ Determine whether or not a [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/)
1658
+ is allowed to refer to a directory. When this is set to `False`, the application will raise a validation error when a path to a directory is given.
1659
+
1660
+ **Example**
1661
+
1662
+ ```python
1663
+ from pathlib import Path
1664
+
1665
+ @app.command()
1666
+ def main(config: Annotated[Path, typer.Argument(exists=True, dir_okay=False)]):
1667
+ text = config.read_text()
1668
+ print(f"Config file contents: {text}")
1669
+ ```
1670
+ """
1671
+ ),
1672
+ ] = True,
1673
+ writable: Annotated[
1674
+ bool,
1675
+ Doc(
1676
+ """
1677
+ Whether or not to perform a writable check for this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/).
1678
+
1679
+ **Example**
1680
+
1681
+ ```python
1682
+ from pathlib import Path
1683
+
1684
+ @app.command()
1685
+ def main(config: Annotated[Path, typer.Argument(writable=True)]):
1686
+ config.write_text("All the text")
1687
+ ```
1688
+ """
1689
+ ),
1690
+ ] = False,
1691
+ readable: Annotated[
1692
+ bool,
1693
+ Doc(
1694
+ """
1695
+ Whether or not to perform a readable check for this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/).
1696
+
1697
+ **Example**
1698
+
1699
+ ```python
1700
+ from pathlib import Path
1701
+
1702
+ @app.command()
1703
+ def main(config: Annotated[Path, typer.Argument(readable=True)]):
1704
+ config.read_text("All the text")
1705
+ ```
1706
+ """
1707
+ ),
1708
+ ] = True,
1709
+ resolve_path: Annotated[
1710
+ bool,
1711
+ Doc(
1712
+ """
1713
+ Whether or not to fully resolve the path of this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/),
1714
+ meaning that the path becomes absolute and symlinks are resolved.
1715
+
1716
+ **Example**
1717
+
1718
+ ```python
1719
+ from pathlib import Path
1720
+
1721
+ @app.command()
1722
+ def main(config: Annotated[Path, typer.Argument(resolve_path=True)]):
1723
+ config.read_text("All the text")
1724
+ ```
1725
+ """
1726
+ ),
1727
+ ] = False,
1728
+ allow_dash: Annotated[
1729
+ bool,
1730
+ Doc(
1731
+ """
1732
+ When set to `True`, a single dash for this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/)
1733
+ would be a valid value, indicating standard streams. This is a more advanced use-case.
1734
+ """
1735
+ ),
1736
+ ] = False,
1737
+ path_type: Annotated[
1738
+ None | type[str] | type[bytes],
1739
+ Doc(
1740
+ """
1741
+ A string type that will be used to represent this [`Path` argument](https://typer.tiangolo.com/tutorial/parameter-types/path/).
1742
+ The default is `None` which means the return value will be either bytes or unicode, depending on what makes most sense given the input data.
1743
+ This is a more advanced use-case.
1744
+ """
1745
+ ),
1746
+ ] = None,
1747
+ # Rich settings
1748
+ rich_help_panel: Annotated[
1749
+ str | None,
1750
+ Doc(
1751
+ """
1752
+ Set the panel name where you want this CLI Argument to be shown in the [help text](https://typer.tiangolo.com/tutorial/arguments/help).
1753
+
1754
+ **Example**
1755
+
1756
+ ```python
1757
+ @app.command()
1758
+ def main(
1759
+ name: Annotated[str, typer.Argument(help="Who to greet")],
1760
+ age: Annotated[str, typer.Option(help="Their age", rich_help_panel="Data")],
1761
+ ):
1762
+ print(f"Hello {name} of age {age}")
1763
+ ```
1764
+ """
1765
+ ),
1766
+ ] = None,
1767
+ ) -> Any:
1768
+ """
1769
+ A [CLI Argument](https://typer.tiangolo.com/tutorial/arguments) is a positional parameter to your command line application.
1770
+
1771
+ Often, CLI Arguments are required, meaning that users have to specify them. However, you can set them to be optional by defining a default value:
1772
+
1773
+ ## Example
1774
+
1775
+ ```python
1776
+ @app.command()
1777
+ def main(name: Annotated[str, typer.Argument()] = "World"):
1778
+ print(f"Hello {name}!")
1779
+ ```
1780
+
1781
+ Note how in this example, if `name` is not specified on the command line, the application will still execute normally and print "Hello World!".
1782
+ """
1783
+ return ArgumentInfo(
1784
+ # Parameter
1785
+ default=default,
1786
+ # Arguments can only have one param declaration
1787
+ # it will be generated from the param name
1788
+ param_decls=None,
1789
+ callback=callback,
1790
+ metavar=metavar,
1791
+ expose_value=expose_value,
1792
+ is_eager=is_eager,
1793
+ envvar=envvar,
1794
+ shell_complete=shell_complete,
1795
+ autocompletion=autocompletion,
1796
+ default_factory=default_factory,
1797
+ # Custom type
1798
+ parser=parser,
1799
+ click_type=click_type,
1800
+ # TyperArgument
1801
+ show_default=show_default,
1802
+ show_choices=show_choices,
1803
+ show_envvar=show_envvar,
1804
+ help=help,
1805
+ hidden=hidden,
1806
+ # Choice
1807
+ case_sensitive=case_sensitive,
1808
+ # Numbers
1809
+ min=min,
1810
+ max=max,
1811
+ clamp=clamp,
1812
+ # DateTime
1813
+ formats=formats,
1814
+ # File
1815
+ mode=mode,
1816
+ encoding=encoding,
1817
+ errors=errors,
1818
+ lazy=lazy,
1819
+ atomic=atomic,
1820
+ # Path
1821
+ exists=exists,
1822
+ file_okay=file_okay,
1823
+ dir_okay=dir_okay,
1824
+ writable=writable,
1825
+ readable=readable,
1826
+ resolve_path=resolve_path,
1827
+ allow_dash=allow_dash,
1828
+ path_type=path_type,
1829
+ # Rich settings
1830
+ rich_help_panel=rich_help_panel,
1831
+ )
loan-advisor-agent/.venv/Lib/site-packages/typer/py.typed ADDED
File without changes
loan-advisor-agent/.venv/Lib/site-packages/typer/rich_utils.py ADDED
@@ -0,0 +1,753 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Extracted and modified from https://github.com/ewels/rich-click
2
+
3
+ import inspect
4
+ import io
5
+ from collections import defaultdict
6
+ from collections.abc import Iterable
7
+ from gettext import gettext as _
8
+ from os import getenv
9
+ from typing import Any, Literal
10
+
11
+ import click
12
+ from rich import box
13
+ from rich.align import Align
14
+ from rich.columns import Columns
15
+ from rich.console import Console, RenderableType, group
16
+ from rich.emoji import Emoji
17
+ from rich.highlighter import RegexHighlighter
18
+ from rich.markdown import Markdown
19
+ from rich.markup import escape
20
+ from rich.padding import Padding
21
+ from rich.panel import Panel
22
+ from rich.table import Table
23
+ from rich.text import Text
24
+ from rich.theme import Theme
25
+ from rich.traceback import Traceback
26
+ from typer.models import DeveloperExceptionConfig
27
+
28
+ # Default styles
29
+ STYLE_OPTION = "bold cyan"
30
+ STYLE_SWITCH = "bold green"
31
+ STYLE_NEGATIVE_OPTION = "bold magenta"
32
+ STYLE_NEGATIVE_SWITCH = "bold red"
33
+ STYLE_METAVAR = "bold yellow"
34
+ STYLE_METAVAR_SEPARATOR = "dim"
35
+ STYLE_USAGE = "yellow"
36
+ STYLE_USAGE_COMMAND = "bold"
37
+ STYLE_DEPRECATED = "red"
38
+ STYLE_DEPRECATED_COMMAND = "dim"
39
+ STYLE_HELPTEXT_FIRST_LINE = ""
40
+ STYLE_HELPTEXT = "dim"
41
+ STYLE_OPTION_HELP = ""
42
+ STYLE_OPTION_DEFAULT = "dim"
43
+ STYLE_OPTION_ENVVAR = "dim yellow"
44
+ STYLE_REQUIRED_SHORT = "red"
45
+ STYLE_REQUIRED_LONG = "dim red"
46
+ STYLE_OPTIONS_PANEL_BORDER = "dim"
47
+ ALIGN_OPTIONS_PANEL: Literal["left", "center", "right"] = "left"
48
+ STYLE_OPTIONS_TABLE_SHOW_LINES = False
49
+ STYLE_OPTIONS_TABLE_LEADING = 0
50
+ STYLE_OPTIONS_TABLE_PAD_EDGE = False
51
+ STYLE_OPTIONS_TABLE_PADDING = (0, 1)
52
+ STYLE_OPTIONS_TABLE_BOX = ""
53
+ STYLE_OPTIONS_TABLE_ROW_STYLES = None
54
+ STYLE_OPTIONS_TABLE_BORDER_STYLE = None
55
+ STYLE_COMMANDS_PANEL_BORDER = "dim"
56
+ ALIGN_COMMANDS_PANEL: Literal["left", "center", "right"] = "left"
57
+ STYLE_COMMANDS_TABLE_SHOW_LINES = False
58
+ STYLE_COMMANDS_TABLE_LEADING = 0
59
+ STYLE_COMMANDS_TABLE_PAD_EDGE = False
60
+ STYLE_COMMANDS_TABLE_PADDING = (0, 1)
61
+ STYLE_COMMANDS_TABLE_BOX = ""
62
+ STYLE_COMMANDS_TABLE_ROW_STYLES = None
63
+ STYLE_COMMANDS_TABLE_BORDER_STYLE = None
64
+ STYLE_COMMANDS_TABLE_FIRST_COLUMN = "bold cyan"
65
+ STYLE_ERRORS_PANEL_BORDER = "red"
66
+ ALIGN_ERRORS_PANEL: Literal["left", "center", "right"] = "left"
67
+ STYLE_ERRORS_SUGGESTION = "dim"
68
+ STYLE_ABORTED = "red"
69
+ _TERMINAL_WIDTH = getenv("TERMINAL_WIDTH")
70
+ MAX_WIDTH = int(_TERMINAL_WIDTH) if _TERMINAL_WIDTH else None
71
+ COLOR_SYSTEM: Literal["auto", "standard", "256", "truecolor", "windows"] | None = (
72
+ "auto" # Set to None to disable colors
73
+ )
74
+ _TYPER_FORCE_DISABLE_TERMINAL = getenv("_TYPER_FORCE_DISABLE_TERMINAL")
75
+ FORCE_TERMINAL = (
76
+ True
77
+ if getenv("GITHUB_ACTIONS") or getenv("FORCE_COLOR") or getenv("PY_COLORS")
78
+ else None
79
+ )
80
+ if _TYPER_FORCE_DISABLE_TERMINAL:
81
+ FORCE_TERMINAL = False
82
+
83
+ # Fixed strings
84
+ DEPRECATED_STRING = _("(deprecated) ")
85
+ DEFAULT_STRING = _("[default: {}]")
86
+ ENVVAR_STRING = _("[env var: {}]")
87
+ REQUIRED_SHORT_STRING = "*"
88
+ REQUIRED_LONG_STRING = _("[required]")
89
+ RANGE_STRING = " [{}]"
90
+ ARGUMENTS_PANEL_TITLE = _("Arguments")
91
+ OPTIONS_PANEL_TITLE = _("Options")
92
+ COMMANDS_PANEL_TITLE = _("Commands")
93
+ ERRORS_PANEL_TITLE = _("Error")
94
+ ABORTED_TEXT = _("Aborted.")
95
+ RICH_HELP = _("Try [blue]'{command_path} {help_option}'[/] for help.")
96
+
97
+ MARKUP_MODE_MARKDOWN = "markdown"
98
+ MARKUP_MODE_RICH = "rich"
99
+ _RICH_HELP_PANEL_NAME = "rich_help_panel"
100
+ ANSI_PREFIX = "\033["
101
+
102
+ MarkupModeStrict = Literal["markdown", "rich"]
103
+
104
+
105
+ # Rich regex highlighter
106
+ class OptionHighlighter(RegexHighlighter):
107
+ """Highlights our special options."""
108
+
109
+ highlights = [
110
+ r"(^|\W)(?P<switch>\-\w+)(?![a-zA-Z0-9])",
111
+ r"(^|\W)(?P<option>\-\-[\w\-]+)(?![a-zA-Z0-9])",
112
+ r"(?P<metavar>\<[^\>]+\>)",
113
+ r"(?P<usage>Usage: )",
114
+ ]
115
+
116
+
117
+ class NegativeOptionHighlighter(RegexHighlighter):
118
+ highlights = [
119
+ r"(^|\W)(?P<negative_switch>\-\w+)(?![a-zA-Z0-9])",
120
+ r"(^|\W)(?P<negative_option>\-\-[\w\-]+)(?![a-zA-Z0-9])",
121
+ ]
122
+
123
+
124
+ # Highlighter to make [ | ] and <> dim
125
+ class MetavarHighlighter(RegexHighlighter):
126
+ highlights = [
127
+ r"^(?P<metavar_sep>(\[|<))",
128
+ r"(?P<metavar_sep>\|)",
129
+ r"(?P<metavar_sep>(\]|>))(\.\.\.)?$",
130
+ ]
131
+
132
+
133
+ highlighter = OptionHighlighter()
134
+ negative_highlighter = NegativeOptionHighlighter()
135
+ metavar_highlighter = MetavarHighlighter()
136
+
137
+
138
+ def _has_ansi_character(text: str) -> bool:
139
+ return ANSI_PREFIX in text
140
+
141
+
142
+ def _get_rich_console(stderr: bool = False) -> Console:
143
+ return Console(
144
+ theme=Theme(
145
+ {
146
+ "option": STYLE_OPTION,
147
+ "switch": STYLE_SWITCH,
148
+ "negative_option": STYLE_NEGATIVE_OPTION,
149
+ "negative_switch": STYLE_NEGATIVE_SWITCH,
150
+ "metavar": STYLE_METAVAR,
151
+ "metavar_sep": STYLE_METAVAR_SEPARATOR,
152
+ "usage": STYLE_USAGE,
153
+ },
154
+ ),
155
+ highlighter=highlighter,
156
+ color_system=COLOR_SYSTEM,
157
+ force_terminal=FORCE_TERMINAL,
158
+ width=MAX_WIDTH,
159
+ stderr=stderr,
160
+ )
161
+
162
+
163
+ def _make_rich_text(
164
+ *, text: str, style: str = "", markup_mode: MarkupModeStrict
165
+ ) -> Markdown | Text:
166
+ """Take a string, remove indentations, and return styled text.
167
+
168
+ If `markup_mode` is `"rich"`, the text is parsed for Rich markup strings.
169
+ If `markup_mode` is `"markdown"`, parse as Markdown.
170
+ """
171
+ # Remove indentations from input text
172
+ text = inspect.cleandoc(text)
173
+ if markup_mode == MARKUP_MODE_MARKDOWN:
174
+ text = Emoji.replace(text)
175
+ return Markdown(text, style=style)
176
+ else:
177
+ assert markup_mode == MARKUP_MODE_RICH
178
+ if _has_ansi_character(text):
179
+ return highlighter(Text.from_ansi(text, style=style))
180
+ else:
181
+ return highlighter(Text.from_markup(text, style=style))
182
+
183
+
184
+ @group()
185
+ def _get_help_text(
186
+ *,
187
+ obj: click.Command | click.Group,
188
+ markup_mode: MarkupModeStrict,
189
+ ) -> Iterable[Markdown | Text]:
190
+ """Build primary help text for a click command or group.
191
+
192
+ Returns the prose help text for a command or group, rendered either as a
193
+ Rich Text object or as Markdown.
194
+ If the command is marked as deprecated, the deprecated string will be prepended.
195
+ """
196
+ # Prepend deprecated status
197
+ if obj.deprecated:
198
+ yield Text(DEPRECATED_STRING, style=STYLE_DEPRECATED)
199
+
200
+ # Fetch and dedent the help text
201
+ help_text = inspect.cleandoc(obj.help or "")
202
+
203
+ # Trim off anything that comes after \f on its own line
204
+ help_text = help_text.partition("\f")[0]
205
+
206
+ # Get the first paragraph
207
+ first_line, *remaining_paragraphs = help_text.split("\n\n")
208
+
209
+ # Remove single linebreaks
210
+ if markup_mode != MARKUP_MODE_MARKDOWN and not first_line.startswith("\b"):
211
+ first_line = first_line.replace("\n", " ")
212
+ yield _make_rich_text(
213
+ text=first_line.strip(),
214
+ style=STYLE_HELPTEXT_FIRST_LINE,
215
+ markup_mode=markup_mode,
216
+ )
217
+
218
+ # Get remaining lines, remove single line breaks and format as dim
219
+ if remaining_paragraphs:
220
+ # Add a newline inbetween the header and the remaining paragraphs
221
+ yield Text("")
222
+ # Join with double linebreaks for markdown and Rich markup
223
+ remaining_lines = "\n\n".join(remaining_paragraphs)
224
+
225
+ yield _make_rich_text(
226
+ text=remaining_lines,
227
+ style=STYLE_HELPTEXT,
228
+ markup_mode=markup_mode,
229
+ )
230
+
231
+
232
+ def _get_parameter_help(
233
+ *,
234
+ param: click.Option | click.Argument | click.Parameter,
235
+ ctx: click.Context,
236
+ markup_mode: MarkupModeStrict,
237
+ ) -> Columns:
238
+ """Build primary help text for a click option or argument.
239
+
240
+ Returns the prose help text for an option or argument, rendered either
241
+ as a Rich Text object or as Markdown.
242
+ Additional elements are appended to show the default and required status if
243
+ applicable.
244
+ """
245
+ # import here to avoid cyclic imports
246
+ from .core import TyperArgument, TyperOption
247
+
248
+ items: list[Text | Markdown] = []
249
+
250
+ # Get the environment variable first
251
+
252
+ envvar = getattr(param, "envvar", None)
253
+ var_str = ""
254
+ # https://github.com/pallets/click/blob/0aec1168ac591e159baf6f61026d6ae322c53aaf/src/click/core.py#L2720-L2726
255
+ if envvar is None:
256
+ if (
257
+ getattr(param, "allow_from_autoenv", None)
258
+ and getattr(ctx, "auto_envvar_prefix", None) is not None
259
+ and param.name is not None
260
+ ):
261
+ envvar = f"{ctx.auto_envvar_prefix}_{param.name.upper()}"
262
+ if envvar is not None:
263
+ var_str = (
264
+ envvar if isinstance(envvar, str) else ", ".join(str(d) for d in envvar)
265
+ )
266
+
267
+ # Main help text
268
+ help_value: str | None = getattr(param, "help", None)
269
+ if help_value:
270
+ paragraphs = help_value.split("\n\n")
271
+ # Remove single linebreaks
272
+ if markup_mode != MARKUP_MODE_MARKDOWN:
273
+ paragraphs = [
274
+ x.replace("\n", " ").strip()
275
+ if not x.startswith("\b")
276
+ else "{}\n".format(x.strip("\b\n"))
277
+ for x in paragraphs
278
+ ]
279
+ items.append(
280
+ _make_rich_text(
281
+ text="\n".join(paragraphs).strip(),
282
+ style=STYLE_OPTION_HELP,
283
+ markup_mode=markup_mode,
284
+ )
285
+ )
286
+
287
+ # Environment variable AFTER help text
288
+ if envvar and getattr(param, "show_envvar", None):
289
+ items.append(Text(ENVVAR_STRING.format(var_str), style=STYLE_OPTION_ENVVAR))
290
+
291
+ # Default value
292
+ # This uses Typer's specific param._get_default_string
293
+ if isinstance(param, (TyperOption, TyperArgument)):
294
+ default_value = param._extract_default_help_str(ctx=ctx)
295
+ show_default_is_str = isinstance(param.show_default, str)
296
+ if show_default_is_str or (
297
+ default_value is not None and (param.show_default or ctx.show_default)
298
+ ):
299
+ default_str = param._get_default_string(
300
+ ctx=ctx,
301
+ show_default_is_str=show_default_is_str,
302
+ default_value=default_value,
303
+ )
304
+ if default_str:
305
+ items.append(
306
+ Text(
307
+ DEFAULT_STRING.format(default_str),
308
+ style=STYLE_OPTION_DEFAULT,
309
+ )
310
+ )
311
+
312
+ # Required?
313
+ if param.required:
314
+ items.append(Text(REQUIRED_LONG_STRING, style=STYLE_REQUIRED_LONG))
315
+
316
+ # Use Columns - this allows us to group different renderable types
317
+ # (Text, Markdown) onto a single line.
318
+ return Columns(items)
319
+
320
+
321
+ def _make_command_help(
322
+ *,
323
+ help_text: str,
324
+ markup_mode: MarkupModeStrict,
325
+ ) -> Text | Markdown:
326
+ """Build cli help text for a click group command.
327
+
328
+ That is, when calling help on groups with multiple subcommands
329
+ (not the main help text when calling the subcommand help).
330
+
331
+ Returns the first paragraph of help text for a command, rendered either as a
332
+ Rich Text object or as Markdown.
333
+ Ignores single newlines as paragraph markers, looks for double only.
334
+ """
335
+ paragraphs = inspect.cleandoc(help_text).split("\n\n")
336
+ # Remove single linebreaks
337
+ if markup_mode != MARKUP_MODE_RICH and not paragraphs[0].startswith("\b"):
338
+ paragraphs[0] = paragraphs[0].replace("\n", " ")
339
+ elif paragraphs[0].startswith("\b"):
340
+ paragraphs[0] = paragraphs[0].replace("\b\n", "")
341
+ return _make_rich_text(
342
+ text=paragraphs[0].strip(),
343
+ style=STYLE_OPTION_HELP,
344
+ markup_mode=markup_mode,
345
+ )
346
+
347
+
348
+ def _print_options_panel(
349
+ *,
350
+ name: str,
351
+ params: list[click.Option] | list[click.Argument],
352
+ ctx: click.Context,
353
+ markup_mode: MarkupModeStrict,
354
+ console: Console,
355
+ ) -> None:
356
+ options_rows: list[list[RenderableType]] = []
357
+ required_rows: list[str | Text] = []
358
+ for param in params:
359
+ # Short and long form
360
+ opt_long_strs = []
361
+ opt_short_strs = []
362
+ secondary_opt_long_strs = []
363
+ secondary_opt_short_strs = []
364
+ for opt_str in param.opts:
365
+ if "--" in opt_str:
366
+ opt_long_strs.append(opt_str)
367
+ else:
368
+ opt_short_strs.append(opt_str)
369
+ for opt_str in param.secondary_opts:
370
+ if "--" in opt_str:
371
+ secondary_opt_long_strs.append(opt_str)
372
+ else:
373
+ secondary_opt_short_strs.append(opt_str)
374
+
375
+ # Column for a metavar, if we have one
376
+ metavar = Text(style=STYLE_METAVAR, overflow="fold")
377
+ metavar_str = param.make_metavar(ctx=ctx)
378
+ # Do it ourselves if this is a positional argument
379
+ if (
380
+ isinstance(param, click.Argument)
381
+ and param.name
382
+ and metavar_str == param.name.upper()
383
+ ):
384
+ metavar_str = param.type.name.upper()
385
+
386
+ # Skip booleans and choices (handled above)
387
+ if metavar_str != "BOOLEAN":
388
+ metavar.append(metavar_str)
389
+
390
+ # Range - from
391
+ # https://github.com/pallets/click/blob/c63c70dabd3f86ca68678b4f00951f78f52d0270/src/click/core.py#L2698-L2706 # noqa: E501
392
+ # skip count with default range type
393
+ if (
394
+ isinstance(param.type, click.types._NumberRangeBase)
395
+ and isinstance(param, click.Option)
396
+ and not (param.count and param.type.min == 0 and param.type.max is None)
397
+ ):
398
+ range_str = param.type._describe_range()
399
+ if range_str:
400
+ metavar.append(RANGE_STRING.format(range_str))
401
+
402
+ # Required asterisk
403
+ required: str | Text = ""
404
+ if param.required:
405
+ required = Text(REQUIRED_SHORT_STRING, style=STYLE_REQUIRED_SHORT)
406
+
407
+ required_rows.append(required)
408
+ options_rows.append(
409
+ [
410
+ highlighter(",".join(opt_long_strs)),
411
+ highlighter(",".join(opt_short_strs)),
412
+ negative_highlighter(",".join(secondary_opt_long_strs)),
413
+ negative_highlighter(",".join(secondary_opt_short_strs)),
414
+ metavar_highlighter(metavar),
415
+ _get_parameter_help(
416
+ param=param,
417
+ ctx=ctx,
418
+ markup_mode=markup_mode,
419
+ ),
420
+ ]
421
+ )
422
+ rows_with_required: list[list[RenderableType]] = []
423
+ if any(required_rows):
424
+ for required, row in zip(required_rows, options_rows, strict=True):
425
+ rows_with_required.append([required, *row])
426
+ else:
427
+ rows_with_required = options_rows
428
+ if options_rows:
429
+ t_styles: dict[str, Any] = {
430
+ "show_lines": STYLE_OPTIONS_TABLE_SHOW_LINES,
431
+ "leading": STYLE_OPTIONS_TABLE_LEADING,
432
+ "box": STYLE_OPTIONS_TABLE_BOX,
433
+ "border_style": STYLE_OPTIONS_TABLE_BORDER_STYLE,
434
+ "row_styles": STYLE_OPTIONS_TABLE_ROW_STYLES,
435
+ "pad_edge": STYLE_OPTIONS_TABLE_PAD_EDGE,
436
+ "padding": STYLE_OPTIONS_TABLE_PADDING,
437
+ }
438
+ box_style = getattr(box, t_styles.pop("box"), None)
439
+
440
+ options_table = Table(
441
+ highlight=True,
442
+ show_header=False,
443
+ expand=True,
444
+ box=box_style,
445
+ **t_styles,
446
+ )
447
+ for row in rows_with_required:
448
+ options_table.add_row(*row)
449
+ console.print(
450
+ Panel(
451
+ options_table,
452
+ border_style=STYLE_OPTIONS_PANEL_BORDER,
453
+ title=name,
454
+ title_align=ALIGN_OPTIONS_PANEL,
455
+ )
456
+ )
457
+
458
+
459
+ def _print_commands_panel(
460
+ *,
461
+ name: str,
462
+ commands: list[click.Command],
463
+ markup_mode: MarkupModeStrict,
464
+ console: Console,
465
+ cmd_len: int,
466
+ ) -> None:
467
+ t_styles: dict[str, Any] = {
468
+ "show_lines": STYLE_COMMANDS_TABLE_SHOW_LINES,
469
+ "leading": STYLE_COMMANDS_TABLE_LEADING,
470
+ "box": STYLE_COMMANDS_TABLE_BOX,
471
+ "border_style": STYLE_COMMANDS_TABLE_BORDER_STYLE,
472
+ "row_styles": STYLE_COMMANDS_TABLE_ROW_STYLES,
473
+ "pad_edge": STYLE_COMMANDS_TABLE_PAD_EDGE,
474
+ "padding": STYLE_COMMANDS_TABLE_PADDING,
475
+ }
476
+ box_style = getattr(box, t_styles.pop("box"), None)
477
+
478
+ commands_table = Table(
479
+ highlight=False,
480
+ show_header=False,
481
+ expand=True,
482
+ box=box_style,
483
+ **t_styles,
484
+ )
485
+ # Define formatting in first column, as commands don't match highlighter
486
+ # regex
487
+ commands_table.add_column(
488
+ style=STYLE_COMMANDS_TABLE_FIRST_COLUMN,
489
+ no_wrap=True,
490
+ width=cmd_len,
491
+ )
492
+
493
+ # A big ratio makes the description column be greedy and take all the space
494
+ # available instead of allowing the command column to grow and misalign with
495
+ # other panels.
496
+ commands_table.add_column("Description", justify="left", no_wrap=False, ratio=10)
497
+ rows: list[list[RenderableType | None]] = []
498
+ deprecated_rows: list[RenderableType | None] = []
499
+ for command in commands:
500
+ helptext = command.short_help or command.help or ""
501
+ command_name = command.name or ""
502
+ if command.deprecated:
503
+ command_name_text = Text(f"{command_name}", style=STYLE_DEPRECATED_COMMAND)
504
+ deprecated_rows.append(Text(DEPRECATED_STRING, style=STYLE_DEPRECATED))
505
+ else:
506
+ command_name_text = Text(command_name)
507
+ deprecated_rows.append(None)
508
+ rows.append(
509
+ [
510
+ command_name_text,
511
+ _make_command_help(
512
+ help_text=helptext,
513
+ markup_mode=markup_mode,
514
+ ),
515
+ ]
516
+ )
517
+ rows_with_deprecated = rows
518
+ if any(deprecated_rows):
519
+ rows_with_deprecated = []
520
+ for row, deprecated_text in zip(rows, deprecated_rows, strict=True):
521
+ rows_with_deprecated.append([*row, deprecated_text])
522
+ for row in rows_with_deprecated:
523
+ commands_table.add_row(*row)
524
+ if commands_table.row_count:
525
+ console.print(
526
+ Panel(
527
+ commands_table,
528
+ border_style=STYLE_COMMANDS_PANEL_BORDER,
529
+ title=name,
530
+ title_align=ALIGN_COMMANDS_PANEL,
531
+ )
532
+ )
533
+
534
+
535
+ def rich_format_help(
536
+ *,
537
+ obj: click.Command | click.Group,
538
+ ctx: click.Context,
539
+ markup_mode: MarkupModeStrict,
540
+ ) -> None:
541
+ """Print nicely formatted help text using rich.
542
+
543
+ Based on original code from rich-cli, by @willmcgugan.
544
+ https://github.com/Textualize/rich-cli/blob/8a2767c7a340715fc6fbf4930ace717b9b2fc5e5/src/rich_cli/__main__.py#L162-L236
545
+
546
+ Replacement for the click function format_help().
547
+ Takes a command or group and builds the help text output.
548
+ """
549
+ console = _get_rich_console()
550
+
551
+ # Print usage
552
+ console.print(
553
+ Padding(highlighter(obj.get_usage(ctx)), 1), style=STYLE_USAGE_COMMAND
554
+ )
555
+
556
+ # Print command / group help if we have some
557
+ if obj.help:
558
+ # Print with some padding
559
+ console.print(
560
+ Padding(
561
+ Align(
562
+ _get_help_text(
563
+ obj=obj,
564
+ markup_mode=markup_mode,
565
+ ),
566
+ pad=False,
567
+ ),
568
+ (0, 1, 1, 1),
569
+ )
570
+ )
571
+ panel_to_arguments: defaultdict[str, list[click.Argument]] = defaultdict(list)
572
+ panel_to_options: defaultdict[str, list[click.Option]] = defaultdict(list)
573
+ for param in obj.get_params(ctx):
574
+ # Skip if option is hidden
575
+ if getattr(param, "hidden", False):
576
+ continue
577
+ if isinstance(param, click.Argument):
578
+ panel_name = (
579
+ getattr(param, _RICH_HELP_PANEL_NAME, None) or ARGUMENTS_PANEL_TITLE
580
+ )
581
+ panel_to_arguments[panel_name].append(param)
582
+ elif isinstance(param, click.Option):
583
+ panel_name = (
584
+ getattr(param, _RICH_HELP_PANEL_NAME, None) or OPTIONS_PANEL_TITLE
585
+ )
586
+ panel_to_options[panel_name].append(param)
587
+ default_arguments = panel_to_arguments.get(ARGUMENTS_PANEL_TITLE, [])
588
+ _print_options_panel(
589
+ name=ARGUMENTS_PANEL_TITLE,
590
+ params=default_arguments,
591
+ ctx=ctx,
592
+ markup_mode=markup_mode,
593
+ console=console,
594
+ )
595
+ for panel_name, arguments in panel_to_arguments.items():
596
+ if panel_name == ARGUMENTS_PANEL_TITLE:
597
+ # Already printed above
598
+ continue
599
+ _print_options_panel(
600
+ name=panel_name,
601
+ params=arguments,
602
+ ctx=ctx,
603
+ markup_mode=markup_mode,
604
+ console=console,
605
+ )
606
+ default_options = panel_to_options.get(OPTIONS_PANEL_TITLE, [])
607
+ _print_options_panel(
608
+ name=OPTIONS_PANEL_TITLE,
609
+ params=default_options,
610
+ ctx=ctx,
611
+ markup_mode=markup_mode,
612
+ console=console,
613
+ )
614
+ for panel_name, options in panel_to_options.items():
615
+ if panel_name == OPTIONS_PANEL_TITLE:
616
+ # Already printed above
617
+ continue
618
+ _print_options_panel(
619
+ name=panel_name,
620
+ params=options,
621
+ ctx=ctx,
622
+ markup_mode=markup_mode,
623
+ console=console,
624
+ )
625
+
626
+ if isinstance(obj, click.Group):
627
+ panel_to_commands: defaultdict[str, list[click.Command]] = defaultdict(list)
628
+ for command_name in obj.list_commands(ctx):
629
+ command = obj.get_command(ctx, command_name)
630
+ if command and not command.hidden:
631
+ panel_name = (
632
+ getattr(command, _RICH_HELP_PANEL_NAME, None)
633
+ or COMMANDS_PANEL_TITLE
634
+ )
635
+ panel_to_commands[panel_name].append(command)
636
+
637
+ # Identify the longest command name in all panels
638
+ max_cmd_len = max(
639
+ [
640
+ len(command.name or "")
641
+ for commands in panel_to_commands.values()
642
+ for command in commands
643
+ ],
644
+ default=0,
645
+ )
646
+
647
+ # Print each command group panel
648
+ default_commands = panel_to_commands.get(COMMANDS_PANEL_TITLE, [])
649
+ _print_commands_panel(
650
+ name=COMMANDS_PANEL_TITLE,
651
+ commands=default_commands,
652
+ markup_mode=markup_mode,
653
+ console=console,
654
+ cmd_len=max_cmd_len,
655
+ )
656
+ for panel_name, commands in panel_to_commands.items():
657
+ if panel_name == COMMANDS_PANEL_TITLE:
658
+ # Already printed above
659
+ continue
660
+ _print_commands_panel(
661
+ name=panel_name,
662
+ commands=commands,
663
+ markup_mode=markup_mode,
664
+ console=console,
665
+ cmd_len=max_cmd_len,
666
+ )
667
+
668
+ # Epilogue if we have it
669
+ if obj.epilog:
670
+ # Remove single linebreaks, replace double with single
671
+ lines = obj.epilog.split("\n\n")
672
+ epilogue = "\n".join([x.replace("\n", " ").strip() for x in lines])
673
+ epilogue_text = _make_rich_text(text=epilogue, markup_mode=markup_mode)
674
+ console.print(Padding(Align(epilogue_text, pad=False), 1))
675
+
676
+
677
+ def rich_format_error(self: click.ClickException) -> None:
678
+ """Print richly formatted click errors.
679
+
680
+ Called by custom exception handler to print richly formatted click errors.
681
+ Mimics original click.ClickException.echo() function but with rich formatting.
682
+ """
683
+ # Don't do anything when it's a NoArgsIsHelpError (without importing it, cf. #1278)
684
+ if self.__class__.__name__ == "NoArgsIsHelpError":
685
+ return
686
+
687
+ console = _get_rich_console(stderr=True)
688
+ ctx: click.Context | None = getattr(self, "ctx", None)
689
+ if ctx is not None:
690
+ console.print(ctx.get_usage())
691
+
692
+ if ctx is not None and ctx.command.get_help_option(ctx) is not None:
693
+ console.print(
694
+ RICH_HELP.format(
695
+ command_path=ctx.command_path, help_option=ctx.help_option_names[0]
696
+ ),
697
+ style=STYLE_ERRORS_SUGGESTION,
698
+ )
699
+
700
+ console.print(
701
+ Panel(
702
+ highlighter(self.format_message()),
703
+ border_style=STYLE_ERRORS_PANEL_BORDER,
704
+ title=ERRORS_PANEL_TITLE,
705
+ title_align=ALIGN_ERRORS_PANEL,
706
+ )
707
+ )
708
+
709
+
710
+ def rich_abort_error() -> None:
711
+ """Print richly formatted abort error."""
712
+ console = _get_rich_console(stderr=True)
713
+ console.print(ABORTED_TEXT, style=STYLE_ABORTED)
714
+
715
+
716
+ def escape_before_html_export(input_text: str) -> str:
717
+ """Ensure that the input string can be used for HTML export."""
718
+ return escape(input_text).strip()
719
+
720
+
721
+ def rich_to_html(input_text: str) -> str:
722
+ """Print the HTML version of a rich-formatted input string.
723
+
724
+ This function does not provide a full HTML page, but can be used to insert
725
+ HTML-formatted text spans into a markdown file.
726
+ """
727
+ console = Console(record=True, highlight=False, file=io.StringIO())
728
+
729
+ console.print(input_text, overflow="ignore", crop=False)
730
+
731
+ return console.export_html(inline_styles=True, code_format="{code}").strip()
732
+
733
+
734
+ def rich_render_text(text: str) -> str:
735
+ """Remove rich tags and render a pure text representation"""
736
+ console = _get_rich_console()
737
+ return "".join(segment.text for segment in console.render(text)).rstrip("\n")
738
+
739
+
740
+ def get_traceback(
741
+ exc: BaseException,
742
+ exception_config: DeveloperExceptionConfig,
743
+ internal_dir_names: list[str],
744
+ ) -> Traceback:
745
+ rich_tb = Traceback.from_exception(
746
+ type(exc),
747
+ exc,
748
+ exc.__traceback__,
749
+ show_locals=exception_config.pretty_exceptions_show_locals,
750
+ suppress=internal_dir_names,
751
+ width=MAX_WIDTH,
752
+ )
753
+ return rich_tb
loan-advisor-agent/.venv/Lib/site-packages/typer/testing.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Mapping, Sequence
2
+ from typing import IO, Any
3
+
4
+ from click.testing import CliRunner as ClickCliRunner # noqa
5
+ from click.testing import Result
6
+ from typer.main import Typer
7
+ from typer.main import get_command as _get_command
8
+
9
+
10
+ class CliRunner(ClickCliRunner):
11
+ def invoke( # type: ignore
12
+ self,
13
+ app: Typer,
14
+ args: str | Sequence[str] | None = None,
15
+ input: bytes | str | IO[Any] | None = None,
16
+ env: Mapping[str, str | None] | None = None,
17
+ catch_exceptions: bool = True,
18
+ color: bool = False,
19
+ **extra: Any,
20
+ ) -> Result:
21
+ use_cli = _get_command(app)
22
+ return super().invoke(
23
+ use_cli,
24
+ args=args,
25
+ input=input,
26
+ env=env,
27
+ catch_exceptions=catch_exceptions,
28
+ color=color,
29
+ **extra,
30
+ )
loan-advisor-agent/.venv/Lib/site-packages/typer/utils.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from collections.abc import Callable
3
+ from copy import copy
4
+ from typing import Any, cast
5
+
6
+ from ._typing import Annotated, get_args, get_origin, get_type_hints
7
+ from .models import ArgumentInfo, OptionInfo, ParameterInfo, ParamMeta
8
+
9
+
10
+ def _param_type_to_user_string(param_type: type[ParameterInfo]) -> str:
11
+ # Render a `ParameterInfo` subclass for use in error messages.
12
+ # User code doesn't call `*Info` directly, so errors should present the classes how
13
+ # they were (probably) defined in the user code.
14
+ if param_type is OptionInfo:
15
+ return "`Option`"
16
+ elif param_type is ArgumentInfo:
17
+ return "`Argument`"
18
+ # This line shouldn't be reachable during normal use.
19
+ return f"`{param_type.__name__}`" # pragma: no cover
20
+
21
+
22
+ class AnnotatedParamWithDefaultValueError(Exception):
23
+ argument_name: str
24
+ param_type: type[ParameterInfo]
25
+
26
+ def __init__(self, argument_name: str, param_type: type[ParameterInfo]):
27
+ self.argument_name = argument_name
28
+ self.param_type = param_type
29
+
30
+ def __str__(self) -> str:
31
+ param_type_str = _param_type_to_user_string(self.param_type)
32
+ return (
33
+ f"{param_type_str} default value cannot be set in `Annotated`"
34
+ f" for {self.argument_name!r}. Set the default value with `=` instead."
35
+ )
36
+
37
+
38
+ class MixedAnnotatedAndDefaultStyleError(Exception):
39
+ argument_name: str
40
+ annotated_param_type: type[ParameterInfo]
41
+ default_param_type: type[ParameterInfo]
42
+
43
+ def __init__(
44
+ self,
45
+ argument_name: str,
46
+ annotated_param_type: type[ParameterInfo],
47
+ default_param_type: type[ParameterInfo],
48
+ ):
49
+ self.argument_name = argument_name
50
+ self.annotated_param_type = annotated_param_type
51
+ self.default_param_type = default_param_type
52
+
53
+ def __str__(self) -> str:
54
+ annotated_param_type_str = _param_type_to_user_string(self.annotated_param_type)
55
+ default_param_type_str = _param_type_to_user_string(self.default_param_type)
56
+ msg = f"Cannot specify {annotated_param_type_str} in `Annotated` and"
57
+ if self.annotated_param_type is self.default_param_type:
58
+ msg += " default value"
59
+ else:
60
+ msg += f" {default_param_type_str} as a default value"
61
+ msg += f" together for {self.argument_name!r}"
62
+ return msg
63
+
64
+
65
+ class MultipleTyperAnnotationsError(Exception):
66
+ argument_name: str
67
+
68
+ def __init__(self, argument_name: str):
69
+ self.argument_name = argument_name
70
+
71
+ def __str__(self) -> str:
72
+ return (
73
+ "Cannot specify multiple `Annotated` Typer arguments"
74
+ f" for {self.argument_name!r}"
75
+ )
76
+
77
+
78
+ class DefaultFactoryAndDefaultValueError(Exception):
79
+ argument_name: str
80
+ param_type: type[ParameterInfo]
81
+
82
+ def __init__(self, argument_name: str, param_type: type[ParameterInfo]):
83
+ self.argument_name = argument_name
84
+ self.param_type = param_type
85
+
86
+ def __str__(self) -> str:
87
+ param_type_str = _param_type_to_user_string(self.param_type)
88
+ return (
89
+ "Cannot specify `default_factory` and a default value together"
90
+ f" for {param_type_str}"
91
+ )
92
+
93
+
94
+ def _split_annotation_from_typer_annotations(
95
+ base_annotation: type[Any],
96
+ ) -> tuple[type[Any], list[ParameterInfo]]:
97
+ if get_origin(base_annotation) is not Annotated:
98
+ return base_annotation, []
99
+ base_annotation, *maybe_typer_annotations = get_args(base_annotation)
100
+ return base_annotation, [
101
+ annotation
102
+ for annotation in maybe_typer_annotations
103
+ if isinstance(annotation, ParameterInfo)
104
+ ]
105
+
106
+
107
+ def get_params_from_function(func: Callable[..., Any]) -> dict[str, ParamMeta]:
108
+ signature = inspect.signature(func, eval_str=True)
109
+ type_hints = get_type_hints(func)
110
+ params = {}
111
+ for param in signature.parameters.values():
112
+ annotation, typer_annotations = _split_annotation_from_typer_annotations(
113
+ param.annotation,
114
+ )
115
+ if len(typer_annotations) > 1:
116
+ raise MultipleTyperAnnotationsError(param.name)
117
+
118
+ default = param.default
119
+ if typer_annotations:
120
+ # It's something like `my_param: Annotated[str, Argument()]`
121
+ [parameter_info] = typer_annotations
122
+
123
+ # Forbid `my_param: Annotated[str, Argument()] = Argument("...")`
124
+ if isinstance(param.default, ParameterInfo):
125
+ raise MixedAnnotatedAndDefaultStyleError(
126
+ argument_name=param.name,
127
+ annotated_param_type=type(parameter_info),
128
+ default_param_type=type(param.default),
129
+ )
130
+
131
+ parameter_info = copy(parameter_info)
132
+
133
+ # When used as a default, `Option` takes a default value and option names
134
+ # as positional arguments:
135
+ # `Option(some_value, "--some-argument", "-s")`
136
+ # When used in `Annotated` (ie, what this is handling), `Option` just takes
137
+ # option names as positional arguments:
138
+ # `Option("--some-argument", "-s")`
139
+ # In this case, the `default` attribute of `parameter_info` is actually
140
+ # meant to be the first item of `param_decls`.
141
+ if (
142
+ isinstance(parameter_info, OptionInfo)
143
+ and parameter_info.default is not ...
144
+ ):
145
+ parameter_info.param_decls = (
146
+ cast(str, parameter_info.default),
147
+ *(parameter_info.param_decls or ()),
148
+ )
149
+ parameter_info.default = ...
150
+
151
+ # Forbid `my_param: Annotated[str, Argument('some-default')]`
152
+ if parameter_info.default is not ...:
153
+ raise AnnotatedParamWithDefaultValueError(
154
+ param_type=type(parameter_info),
155
+ argument_name=param.name,
156
+ )
157
+ if param.default is not param.empty:
158
+ # Put the parameter's default (set by `=`) into `parameter_info`, where
159
+ # typer can find it.
160
+ parameter_info.default = param.default
161
+
162
+ default = parameter_info
163
+ elif param.name in type_hints:
164
+ # Resolve forward references.
165
+ annotation = type_hints[param.name]
166
+
167
+ if isinstance(default, ParameterInfo):
168
+ parameter_info = copy(default)
169
+ # Click supports `default` as either
170
+ # - an actual value; or
171
+ # - a factory function (returning a default value.)
172
+ # The two are not interchangeable for static typing, so typer allows
173
+ # specifying `default_factory`. Move the `default_factory` into `default`
174
+ # so click can find it.
175
+ if parameter_info.default is ... and parameter_info.default_factory:
176
+ parameter_info.default = parameter_info.default_factory
177
+ elif parameter_info.default_factory:
178
+ raise DefaultFactoryAndDefaultValueError(
179
+ argument_name=param.name, param_type=type(parameter_info)
180
+ )
181
+ default = parameter_info
182
+
183
+ params[param.name] = ParamMeta(
184
+ name=param.name, default=default, annotation=annotation
185
+ )
186
+ return params
187
+
188
+
189
+ def parse_boolean_env_var(env_var_value: str | None, default: bool) -> bool:
190
+ if env_var_value is None:
191
+ return default
192
+ value = env_var_value.lower()
193
+ if value in ("y", "yes", "t", "true", "on", "1"):
194
+ return True
195
+ if value in ("n", "no", "f", "false", "off", "0"):
196
+ return False
197
+ return default