Skip to content
Myr

♻️ 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

8 files+45 added−40 removed

modified:tests/test_completion/test_completion_show.py+3 added-4 removed
1 unmodified line
2import subprocess3import sys4from unittest import mock56import shellingham6import typer7import typer.completion8from typer.testing import CliRunner910from docs_src.typer_app import tutorial001 as mod11
128 unmodified lines
140 )141142143def 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.output
modified:tests/test_others.py+2 added-2 removed
5 unmodified lines
6from unittest import mock78import click9import pytest10import shellingham10import typer11import typer._completion_shared12import typer.completion13from typer.core import _split_opt14from typer.main import solve_typer_info_defaults, solve_typer_info_help15from typer.models import ParameterInfo, TyperInfo
69 unmodified lines
85 def main():86 print("Hello World")8788 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 lines
modified:tests/utils.py+3 added-13 removed
1import sys2from os import getenv34import pytest5from typer._completion_shared import _get_shell_name66try:7 import shellingham8 from shellingham import ShellDetectionFailure910 shell = shellingham.detect_shell()[0]11except ImportError: # pragma: no cover12 shellingham = None13 shell = None14except ShellDetectionFailure: # pragma: no cover15 shell = None16177needs_py310 = pytest.mark.skipif(8 sys.version_info < (3, 10), reason="requires python3.10+"9)1011needs_linux = pytest.mark.skipif(12 not sys.platform.startswith("linux"), reason="Test requires Linux"13)1415shell = _get_shell_name()16needs_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)1920requires_completion_permission = pytest.mark.skipif(21 not getenv("_TYPER_RUN_INSTALL_COMPLETION_TESTS", False),
2 unmodified lines
modified:typer/_completion_classes.py-5 removed
22 unmodified lines
23 from click.parser import ( # type: ignore[no-redef]24 split_arg_string as click_split_arg_string,25 )2627try:28 import shellingham29except ImportError: # pragma: no cover30 shellingham = None273228def _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 text
175 unmodified lines
modified:typer/_completion_shared.py+25 added-6 removed
1 unmodified line
2import re3import subprocess4from enum import Enum5from pathlib import Path6from typing import Optional, Tuple6from typing import Optional, Tuple, Union78import click9from typer.core import HAS_SHELLINGHAM1010try:11if HAS_SHELLINGHAM:12 import shellingham12except ImportError: # pragma: no cover13 shellingham = None131415class Shells(str, Enum):16 bash = "bash"
194 unmodified lines
211 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 lines
236 return shell, installed_path237 else:238 click.echo(f"Shell {shell} is not supported.")239 raise click.exceptions.Exit(1)240241242def _get_shell_name() -> Union[str, None]:243 """Get the current shell name, if available.244245 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 cover258259 return name
modified:typer/completion.py+7 added-10 removed
3 unmodified lines
45import click67from ._completion_classes import completion_init8from ._completion_shared import Shells, get_completion_script, install8from ._completion_shared import Shells, _get_shell_name, get_completion_script, install9from .core import HAS_SHELLINGHAM10from .models import ParamMeta11from .params import Option12from .utils import get_params_from_function1313try:14 import shellingham15except ImportError: # pragma: no cover16 shellingham = None171814_click_patched = False151617def 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_function
23 unmodified lines
48 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 lines
modified:typer/core.py+1 added
30 unmodified lines
3132MarkupMode = Literal["markdown", "rich", None]3334HAS_RICH = importlib.util.find_spec("rich") is not None35HAS_SHELLINGHAM = importlib.util.find_spec("shellingham") is not None3637if HAS_RICH:38 DEFAULT_MARKUP_MODE: MarkupMode = "rich"39else: # pragma: no cover
791 unmodified lines
modified:pyproject.toml+4 added
213 unmodified lines
214banned-module-level-imports = ["typer.rich_utils"]215216[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 = """\219Use 'typer._completion_shared._get_shell_name' instead of using \220'shellingham.detect_shell' directly.221"""