Skip to content

Commit cbc9649

Browse files
authored
fix: simplify conditional logic check for libraries (#3016)
* fix: simplify conditional logic check for libraries * fix: correct spelling error in test case as well
1 parent 6bcd4b5 commit cbc9649

File tree

7 files changed

+36
-69
lines changed

7 files changed

+36
-69
lines changed

Diff for: codecov.yml

+4
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,9 @@ coverage:
33
project:
44
default:
55
target: auto
6+
threshold: 0.1%
7+
patch:
8+
default:
9+
target: auto
610
comment:
711
require_changes: true

Diff for: litestar/cli/_utils.py

+14-31
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,13 @@
99
from dataclasses import dataclass
1010
from datetime import datetime, timedelta, timezone
1111
from functools import wraps
12+
from importlib.util import find_spec
1213
from itertools import chain
1314
from os import getenv
1415
from pathlib import Path
1516
from typing import TYPE_CHECKING, Any, Callable, Generator, Iterable, Sequence, TypeVar, cast
1617

18+
from click import ClickException, Command, Context, Group, pass_context
1719
from rich import get_console
1820
from rich.table import Table
1921
from typing_extensions import ParamSpec, get_type_hints
@@ -22,28 +24,21 @@
2224
from litestar.middleware import DefineMiddleware
2325
from litestar.utils import get_name
2426

25-
RICH_CLICK_INSTALLED = False
26-
with contextlib.suppress(ImportError):
27-
import rich_click # noqa: F401
27+
if sys.version_info >= (3, 10):
28+
from importlib.metadata import entry_points
29+
else:
30+
from importlib_metadata import entry_points
2831

29-
RICH_CLICK_INSTALLED = True
30-
UVICORN_INSTALLED = False
31-
with contextlib.suppress(ImportError):
32-
import uvicorn # noqa: F401
3332

34-
UVICORN_INSTALLED = True
35-
JSBEAUTIFIER_INSTALLED = False
36-
with contextlib.suppress(ImportError):
37-
import jsbeautifier # noqa: F401
33+
if TYPE_CHECKING:
34+
from litestar.openapi import OpenAPIConfig
35+
from litestar.routes import ASGIRoute, HTTPRoute, WebSocketRoute
36+
from litestar.types import AnyCallable
3837

39-
JSBEAUTIFIER_INSTALLED = True
4038

41-
if TYPE_CHECKING or not RICH_CLICK_INSTALLED: # pragma: no cover
42-
from click import ClickException, Command, Context, Group, pass_context
43-
else:
44-
from rich_click import ClickException, Context, pass_context
45-
from rich_click.rich_command import RichCommand as Command
46-
from rich_click.rich_command import RichGroup as Group
39+
RICH_CLICK_INSTALLED = find_spec("rich-click") is not None
40+
UVICORN_INSTALLED = find_spec("uvicorn") is not None
41+
JSBEAUTIFIER_INSTALLED = find_spec("jsbeautifier") is not None
4742

4843

4944
__all__ = (
@@ -59,18 +54,6 @@
5954
)
6055

6156

62-
if sys.version_info >= (3, 10):
63-
from importlib.metadata import entry_points
64-
else:
65-
from importlib_metadata import entry_points
66-
67-
68-
if TYPE_CHECKING:
69-
from litestar.openapi import OpenAPIConfig
70-
from litestar.routes import ASGIRoute, HTTPRoute, WebSocketRoute
71-
from litestar.types import AnyCallable
72-
73-
7457
P = ParamSpec("P")
7558
T = TypeVar("T")
7659

@@ -506,7 +489,7 @@ def _generate_self_signed_cert(certfile_path: Path, keyfile_path: Path, common_n
506489
from cryptography.x509.oid import NameOID
507490
except ImportError as err:
508491
raise LitestarCLIException(
509-
"Cryptogpraphy must be installed when using --create-self-signed-cert\nPlease install the litestar[cryptography] extras"
492+
"Cryptography must be installed when using --create-self-signed-cert\nPlease install the litestar[cryptography] extras"
510493
) from err
511494

512495
subject = x509.Name(

Diff for: litestar/cli/commands/core.py

+4-11
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,12 @@
88
from contextlib import AbstractContextManager, ExitStack, contextmanager
99
from typing import TYPE_CHECKING, Any, Iterator
1010

11+
import click
12+
from click import Context, command, option
1113
from rich.tree import Tree
1214

1315
from litestar.app import DEFAULT_OPENAPI_CONFIG
1416
from litestar.cli._utils import (
15-
RICH_CLICK_INSTALLED,
1617
UVICORN_INSTALLED,
1718
LitestarEnv,
1819
console,
@@ -25,16 +26,6 @@
2526
from litestar.routes import ASGIRoute, HTTPRoute, WebSocketRoute
2627
from litestar.utils.helpers import unwrap_partial
2728

28-
if UVICORN_INSTALLED:
29-
import uvicorn
30-
31-
if TYPE_CHECKING or not RICH_CLICK_INSTALLED: # pragma: no cover
32-
import click
33-
from click import Context, command, option
34-
else:
35-
import rich_click as click
36-
from rich_click import Context, command, option
37-
3829
__all__ = ("info_command", "routes_command", "run_command")
3930

4031
if TYPE_CHECKING:
@@ -226,6 +217,8 @@ def run_command(
226217
show_app_info(app)
227218
with _server_lifespan(app):
228219
if workers == 1 and not reload:
220+
import uvicorn
221+
229222
# A guard statement at the beginning of this function prevents uvicorn from being unbound
230223
# See "reportUnboundVariable in:
231224
# https://microsoft.github.io/pyright/#/configuration?id=type-check-diagnostics-settings

Diff for: litestar/cli/commands/schema.py

+10-16
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,17 @@
11
from pathlib import Path
2-
from typing import TYPE_CHECKING
32

43
import msgspec
4+
from click import Path as ClickPath
5+
from click import group, option
56
from yaml import dump as dump_yaml
67

78
from litestar import Litestar
89
from litestar._openapi.typescript_converter.converter import (
910
convert_openapi_to_typescript,
1011
)
11-
from litestar.cli._utils import JSBEAUTIFIER_INSTALLED, RICH_CLICK_INSTALLED, LitestarCLIException, LitestarGroup
12+
from litestar.cli._utils import JSBEAUTIFIER_INSTALLED, LitestarCLIException, LitestarGroup
1213
from litestar.serialization import encode_json, get_serializer
1314

14-
if TYPE_CHECKING or not RICH_CLICK_INSTALLED: # pragma: no cover
15-
from click import Path as ClickPath
16-
from click import group, option
17-
else:
18-
from rich_click import Path as ClickPath
19-
from rich_click import group, option
20-
21-
if JSBEAUTIFIER_INSTALLED: # pragma: no cover
22-
from jsbeautifier import Beautifier
23-
24-
beautifier = Beautifier()
25-
26-
2715
__all__ = ("generate_openapi_schema", "generate_typescript_specs", "schema_group")
2816

2917

@@ -77,11 +65,17 @@ def generate_openapi_schema(app: Litestar, output: Path) -> None:
7765
@option("--namespace", help="namespace to use for the typescript specs", type=str, default="API")
7866
def generate_typescript_specs(app: Litestar, output: Path, namespace: str) -> None:
7967
"""Generate TypeScript specs from the OpenAPI schema."""
68+
if JSBEAUTIFIER_INSTALLED: # pragma: no cover
69+
from jsbeautifier import Beautifier
70+
71+
beautifier = Beautifier()
72+
else:
73+
beautifier = None
8074
try:
8175
specs = convert_openapi_to_typescript(app.openapi_schema, namespace)
8276
# beautifier will be defined if JSBEAUTIFIER_INSTALLED is True
8377
specs_output = (
84-
beautifier.beautify(specs.write()) if JSBEAUTIFIER_INSTALLED else specs.write() # pyright: ignore
78+
beautifier.beautify(specs.write()) if JSBEAUTIFIER_INSTALLED and beautifier else specs.write() # pyright: ignore
8579
)
8680
output.write_text(specs_output)
8781
except OSError as e: # pragma: no cover

Diff for: litestar/cli/commands/sessions.py

+2-9
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,13 @@
1-
from typing import TYPE_CHECKING
2-
1+
from click import argument, group
32
from rich.prompt import Confirm
43

54
from litestar import Litestar
6-
from litestar.cli._utils import RICH_CLICK_INSTALLED, LitestarCLIException, LitestarGroup, console
5+
from litestar.cli._utils import LitestarCLIException, LitestarGroup, console
76
from litestar.middleware import DefineMiddleware
87
from litestar.middleware.session import SessionMiddleware
98
from litestar.middleware.session.server_side import ServerSideSessionBackend
109
from litestar.utils import is_class_and_subclass
1110

12-
if TYPE_CHECKING or not RICH_CLICK_INSTALLED: # pragma: no cover
13-
from click import argument, group
14-
else:
15-
from rich_click import argument, group
16-
17-
1811
__all__ = ("clear_sessions_command", "delete_session_command", "get_session_backend", "sessions_group")
1912

2013

Diff for: litestar/cli/main.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import click
1111
from click import Context, group, option, pass_context
1212
from click import Path as ClickPath
13-
else:
13+
else: # pragma: no cover
1414
import rich_click as click
1515
from rich_click import Context, group, option, pass_context
1616
from rich_click import Path as ClickPath

Diff for: tests/unit/test_cli/test_ssl.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ def test_without_cryptography_installed(
243243

244244
assert isinstance(result.exception, SystemExit)
245245
exc = get_click_exception(result.exception)
246-
assert "Cryptogpraphy must be installed when using --create-self-signed-cert" in exc.message
246+
assert "Cryptography must be installed when using --create-self-signed-cert" in exc.message
247247

248248

249249
@pytest.mark.usefixtures("mock_uvicorn_run")

0 commit comments

Comments
 (0)