Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions dashscope/cli/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -492,11 +492,17 @@ def _click_passthrough() -> Tuple[type[BaseException], ...]:
the real click ones, so listing only ``click`` lets a missing argument
(``typer._click.exceptions.MissingParameter``) slip past the
``except`` below into the generic branch and come out mislabelled
``server``.
``server``. Real click is optional: newer typer vendors it and does
not install it, so a missing ``click`` must not break CLI import.
"""
import click # pylint: disable=import-outside-toplevel
try:
import click # pylint: disable=import-outside-toplevel
except ImportError: # typer>=0.26 ships its own click; none installed
click = None

classes = [click.exceptions.Exit, click.UsageError, click.Abort]
classes = []
if click is not None:
classes = [click.exceptions.Exit, click.UsageError, click.Abort]
# typer.Exit subclasses click.exceptions.Exit on modern typer; keep
# both spellings so an older typer still passes usage errors through.
typer_exit = getattr(typer, "Exit", None)
Expand Down
14 changes: 7 additions & 7 deletions dashscope/cli/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
Rich.** Rich wraps text at the terminal width, which silently corrupts
JSON for any consumer downstream -- a long ``--output json`` payload
would arrive with newlines inserted mid-string. So json/yaml/NDJSON go
out through ``click.echo`` untouched and only the human ``table`` format
out through ``typer.echo`` untouched and only the human ``table`` format
gets Rich styling.

That also means a piped ``dashscope ... --output json | jq`` needs no
Expand All @@ -20,7 +20,7 @@
import sys
from typing import Any, Optional, Sequence

import click
import typer
from rich.console import Console
from rich.table import Table

Expand Down Expand Up @@ -108,7 +108,7 @@ def __init__(

def echo(self, text: str = "") -> None:
"""Plain stdout: no markup, no wrapping. Use for payload text."""
click.echo(text)
typer.echo(text)

def write(self, text: str) -> None:
"""Unbuffered stdout write for incremental streaming."""
Expand Down Expand Up @@ -145,12 +145,12 @@ def err_console(self) -> Console:

def print_json(self, obj: Any) -> None:
payload = to_serializable(obj, verbose=self.verbose)
click.echo(json.dumps(payload, ensure_ascii=False, indent=2))
typer.echo(json.dumps(payload, ensure_ascii=False, indent=2))

def print_ndjson(self, obj: Any) -> None:
"""One compact, valid JSON object per line (jq-consumable)."""
payload = to_serializable(obj, verbose=self.verbose)
click.echo(
typer.echo(
json.dumps(payload, ensure_ascii=False, separators=(",", ":")),
)

Expand All @@ -160,7 +160,7 @@ def print_yaml(self, obj: Any) -> None:
import yaml # pylint: disable=import-outside-toplevel

payload = to_serializable(obj, verbose=self.verbose)
click.echo(
typer.echo(
yaml.safe_dump(
payload,
allow_unicode=True,
Expand Down Expand Up @@ -222,7 +222,7 @@ def _print_fields(
) -> None:
data = to_serializable(obj, verbose=self.verbose)
if not isinstance(data, dict):
click.echo(data)
typer.echo(data)
return
keys = list(columns) if columns else list(data)
table = Table(show_header=False, box=None, pad_edge=False)
Expand Down
83 changes: 83 additions & 0 deletions tests/cli/test_clickless_import.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# -*- coding: utf-8 -*-
# Copyright (c) Alibaba, Inc. and its affiliates.

"""The CLI must import and render without the real ``click`` package.

typer>=0.26 vendors click as ``typer._click`` and no longer depends on
the real package, and ``click`` is not a declared dashscope dependency
(it used to arrive transitively via uvicorn). A fresh install therefore
may have no click at all; a module-level ``import click`` then crashes
every CLI invocation before any command runs.

Each case runs in a fresh interpreter: typer is imported first (older
typer needs click itself), then new ``import click`` statements are made
to fail -- mirroring a click-less environment where typer still works.
A subprocess keeps the block from leaking into the rest of the suite.
"""

import json
import subprocess
import sys
import textwrap

_BLOCK_CLICK = """\
import sys
import typer # noqa: F401 (older typer imports click; load it first)


class _BlockClick:
def find_spec(self, fullname, path=None, target=None):
if fullname == "click" or fullname.startswith("click."):
raise ModuleNotFoundError(f"No module named {fullname!r}")
return None


for _name in [n for n in sys.modules if n == "click" or n.startswith("click.")]:
del sys.modules[_name]
sys.meta_path.insert(0, _BlockClick())
"""


def _run_clickless(body: str) -> subprocess.CompletedProcess:
return subprocess.run(
[sys.executable, "-c", _BLOCK_CLICK + textwrap.dedent(body)],
capture_output=True,
text=True,
timeout=60,
check=False,
)


def test_cli_errors_imports_without_click():
result = _run_clickless(
"""
import typer
from dashscope.cli import errors

assert errors._CLICK_PASSTHROUGH
assert typer.Exit in errors._CLICK_PASSTHROUGH
""",
)
assert result.returncode == 0, result.stderr


def test_cli_output_imports_without_click():
result = _run_clickless(
"""
from dashscope.cli import output
""",
)
assert result.returncode == 0, result.stderr


def test_json_output_works_without_click():
result = _run_clickless(
"""
from dashscope.cli import output

renderer = output.Renderer(fmt=output.JSON)
renderer.print_json({"model": "qwen-plus", "ok": True})
""",
)
assert result.returncode == 0, result.stderr
assert json.loads(result.stdout) == {"model": "qwen-plus", "ok": True}
Loading