♻️ Refactor the handling of `shellingham` (#1347)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Nathan McDougall · committed by GitHub · parent b400735 · Browse files · 8 files·+45 added−40 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Diff stats
8 files+45 added−40 removed
- tests:+8 added−19 removed
- other:+37 added−21 removed
Provenance
- Commit
fd4241f- Tree
ac76609- Author
Nathan McDougall <nmcdougall@tonkintaylor.co.nz>- Committer
GitHub <noreply@github.com>- Parent
b400735
8 files changed+45 added−40 removed
modified:tests/test_completion/test_completion_show.py+3 added-4 removed
1 unmodified line2 import subprocess3 import sys4 from unittest import mock5 6-import shellingham6+import typer7+import typer.completion8 from typer.testing import CliRunner9 10 from docs_src.typer_app import tutorial001 as mod11 128 unmodified lines140 )141 142 143 def test_completion_show_invalid_shell():143- with mock.patch.object(144- shellingham, "detect_shell", return_value=("xshell", "/usr/bin/xshell")145- ):144+ with mock.patch.object(typer.completion, "_get_shell_name", return_value="xshell"):145 result = runner.invoke(app, ["--show-completion"])146 assert "Shell xshell not supported" in result.outputmodified:tests/test_others.py+2 added-2 removed
5 unmodified lines6 from unittest import mock7 8 import click9 import pytest10-import shellingham10 import typer11+import typer._completion_shared12 import typer.completion13 from typer.core import _split_opt14 from typer.main import solve_typer_info_defaults, solve_typer_info_help15 from typer.models import ParameterInfo, TyperInfo69 unmodified lines85 def main():86 print("Hello World")87 88 with mock.patch.object(89- shellingham, "detect_shell", return_value=("xshell", "/usr/bin/xshell")89+ typer._completion_shared, "_get_shell_name", return_value="xshell"90 ):91 result = runner.invoke(app, ["--install-completion"])92 assert "Shell xshell is not supported." in result.stdout93 result = runner.invoke(app)230 unmodified linesmodified:tests/utils.py+3 added-13 removed
1 import sys2 from os import getenv3 4 import pytest5+from typer._completion_shared import _get_shell_name6 6-try:7- import shellingham8- from shellingham import ShellDetectionFailure9-10- shell = shellingham.detect_shell()[0]11-except ImportError: # pragma: no cover12- shellingham = None13- shell = None14-except ShellDetectionFailure: # pragma: no cover15- shell = None16-17-7 needs_py310 = pytest.mark.skipif(8 sys.version_info < (3, 10), reason="requires python3.10+"9 )10 11 needs_linux = pytest.mark.skipif(12 not sys.platform.startswith("linux"), reason="Test requires Linux"13 )14 15+shell = _get_shell_name()16 needs_bash = pytest.mark.skipif(27- not shellingham or not shell or "bash" not in shell, reason="Test requires Bash"17+ shell is None or "bash" not in shell, reason="Test requires Bash"18 )19 20 requires_completion_permission = pytest.mark.skipif(21 not getenv("_TYPER_RUN_INSTALL_COMPLETION_TESTS", False),2 unmodified linesmodified:typer/_completion_classes.py-5 removed
22 unmodified lines23 from click.parser import ( # type: ignore[no-redef]24 split_arg_string as click_split_arg_string,25 )26 27-try:28- import shellingham29-except ImportError: # pragma: no cover30- shellingham = None27 32-28 def _sanitize_help_text(text: str) -> str:29 """Sanitizes the help text by removing rich tags"""30 if not importlib.util.find_spec("rich"):31 return text175 unmodified linesmodified:typer/_completion_shared.py+25 added-6 removed
1 unmodified line2 import re3 import subprocess4 from enum import Enum5 from pathlib import Path6-from typing import Optional, Tuple6+from typing import Optional, Tuple, Union7 8 import click9+from typer.core import HAS_SHELLINGHAM10 10-try:11+if HAS_SHELLINGHAM:12 import shellingham12-except ImportError: # pragma: no cover13- shellingham = None13 14 15 class Shells(str, Enum):16 bash = "bash"194 unmodified lines211 assert prog_name212 if complete_var is None:213 complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())214 test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")216- if shell is None and shellingham is not None and not test_disable_detection:217- shell, _ = shellingham.detect_shell()215+ if shell is None and not test_disable_detection:216+ shell = _get_shell_name()217 if shell == "bash":218 installed_path = install_bash(219 prog_name=prog_name, complete_var=complete_var, shell=shell220 )15 unmodified lines236 return shell, installed_path237 else:238 click.echo(f"Shell {shell} is not supported.")239 raise click.exceptions.Exit(1)240+241+242+def _get_shell_name() -> Union[str, None]:243+ """Get the current shell name, if available.244+245+ The name will always be lowercase. If the shell cannot be detected, None is246+ returned.247+ """248+ name: Union[str, None] # N.B. shellingham is untyped249+ if HAS_SHELLINGHAM:250+ try:251+ # N.B. detect_shell returns a tuple of (shell name, shell command).252+ # We only need the name.253+ name, _cmd = shellingham.detect_shell() # noqa: TID251254+ except shellingham.ShellDetectionFailure: # pragma: no cover255+ name = None256+ else:257+ name = None # pragma: no cover258+259+ return namemodified:typer/completion.py+7 added-10 removed
3 unmodified lines4 5 import click6 7 from ._completion_classes import completion_init8-from ._completion_shared import Shells, get_completion_script, install8+from ._completion_shared import Shells, _get_shell_name, get_completion_script, install9+from .core import HAS_SHELLINGHAM10 from .models import ParamMeta11 from .params import Option12 from .utils import get_params_from_function13 13-try:14- import shellingham15-except ImportError: # pragma: no cover16- shellingham = None17-18-14 _click_patched = False15 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")25- if shellingham and not test_disable_detection:20+ if HAS_SHELLINGHAM and 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_function23 unmodified lines48 shell = ""49 test_disable_detection = os.getenv("_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION")50 if isinstance(value, str):51 shell = value57- elif shellingham and not test_disable_detection:58- shell, _ = shellingham.detect_shell()52+ elif not test_disable_detection:53+ detected_shell = _get_shell_name()54+ if detected_shell is not None:55+ shell = detected_shell56 script_content = get_completion_script(57 prog_name=prog_name, complete_var=complete_var, shell=shell58 )59 click.echo(script_content)87 unmodified linesmodified:typer/core.py+1 added
30 unmodified lines31 32 MarkupMode = Literal["markdown", "rich", None]33 34 HAS_RICH = importlib.util.find_spec("rich") is not None35+HAS_SHELLINGHAM = importlib.util.find_spec("shellingham") is not None36 37 if HAS_RICH:38 DEFAULT_MARKUP_MODE: MarkupMode = "rich"39 else: # pragma: no cover791 unmodified linesmodified:pyproject.toml+4 added
213 unmodified lines214 banned-module-level-imports = ["typer.rich_utils"]215 216 [tool.ruff.lint.flake8-tidy-imports.banned-api]217 "rich".msg = "Use 'typer.rich_utils' instead of importing from 'rich' directly."218+"shellingham.detect_shell".msg = """\219+Use 'typer._completion_shared._get_shell_name' instead of using \220+'shellingham.detect_shell' directly.221+"""