Skip to content

Commit

Permalink
Make the naked invocation display a compacted help
Browse files Browse the repository at this point in the history
  • Loading branch information
isidentical committed Feb 8, 2022
1 parent 37ef670 commit d14e054
Show file tree
Hide file tree
Showing 2 changed files with 108 additions and 4 deletions.
47 changes: 43 additions & 4 deletions httpie/cli/argparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,39 @@ def _split_lines(self, text, width):
text = dedent(text).strip() + '\n\n'
return text.splitlines()

def add_usage(self, usage, actions, groups, prefix=None):
# Only display the positional arguments
displayed_actions = [
action
for action in actions
if not action.option_strings
]

_, exception, _ = sys.exc_info()
if (
isinstance(exception, argparse.ArgumentError)
and len(exception.args) >= 1
and isinstance(exception.args[0], argparse.Action)
):
# add_usage path is also taken when you pass an invalid option,
# e.g --style=invalid. If something like that happens, we want
# to include to action that caused to the invalid usage into
# the list of actions we are displaying.
displayed_actions.insert(0, exception.args[0])

super().add_usage(
usage,
displayed_actions,
groups,
prefix="usage:\n "
)


# TODO: refactor and design type-annotated data structures
# for raw args + parsed args and keep things immutable.
class BaseHTTPieArgumentParser(argparse.ArgumentParser):
def __init__(self, *args, formatter_class=HTTPieHelpFormatter, **kwargs):
super().__init__(*args, formatter_class=formatter_class, **kwargs)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.env = None
self.args = None
self.has_stdin_data = False
Expand Down Expand Up @@ -115,9 +142,9 @@ class HTTPieArgumentParser(BaseHTTPieArgumentParser):
"""

def __init__(self, *args, **kwargs):
def __init__(self, *args, formatter_class=HTTPieHelpFormatter, **kwargs):
kwargs.setdefault('add_help', False)
super().__init__(*args, **kwargs)
super().__init__(*args, formatter_class=formatter_class, **kwargs)

# noinspection PyMethodOverriding
def parse_args(
Expand Down Expand Up @@ -512,3 +539,15 @@ def _process_format_options(self):
for options_group in format_options:
parsed_options = parse_format_options(options_group, defaults=parsed_options)
self.args.format_options = parsed_options

def error(self, message):
"""Prints a usage message incorporating the message to stderr and
exits."""
self.print_usage(sys.stderr)
args = {'prog': self.prog, 'message': message}
self.exit(
2,
'\nerror:\n %(message)s\n\n'
'For more information try with --help '
'or visit the https://pie.co/docs' % args
)
65 changes: 65 additions & 0 deletions tests/test_cli_ui.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import pytest
import shutil
import os
from tests.utils import http

NAKED_HELP_MESSAGE = """\
usage:
http [METHOD] URL [REQUEST_ITEM ...]
error:
the following arguments are required: URL
For more information try with --help or visit the https://pie.co/docs
"""

NAKED_HELP_MESSAGE_PRETTY_WITH_NO_ARG = """\
usage:
http [--pretty {all,colors,format,none}] [METHOD] URL [REQUEST_ITEM ...]
error:
argument --pretty: expected one argument
For more information try with --help or visit the https://pie.co/docs
"""

NAKED_HELP_MESSAGE_PRETTY_WITH_INVALID_ARG = """\
usage:
http [--pretty {all,colors,format,none}] [METHOD] URL [REQUEST_ITEM ...]
error:
argument --pretty: invalid choice: '$invalid' (choose from 'all', 'colors', 'format', 'none')
For more information try with --help or visit the https://pie.co/docs
"""


PREDEFINED_TERMINAL_SIZE = (160, 80)


@pytest.fixture(scope="function")
def ignore_terminal_size(monkeypatch):
"""Some tests wrap/crop the output depending on the
size of the executed terminal, which might not be consistent
through all runs.
This fixture ensures every run uses the same exact configuration.
"""

def fake_terminal_size(*args, **kwargs):
return os.terminal_size(PREDEFINED_TERMINAL_SIZE)

monkeypatch.setattr(shutil, "get_terminal_size", fake_terminal_size)


@pytest.mark.parametrize(
"args, expected_msg", [
([], NAKED_HELP_MESSAGE),
(["--pretty"], NAKED_HELP_MESSAGE_PRETTY_WITH_NO_ARG),
(["pie.dev", "--pretty"], NAKED_HELP_MESSAGE_PRETTY_WITH_NO_ARG),
(["--pretty", "$invalid"], NAKED_HELP_MESSAGE_PRETTY_WITH_INVALID_ARG),
]
)
def test_naked_invocation(ignore_terminal_size, args, expected_msg):
result = http(*args, tolerate_error_exit_status=True)
assert result.stderr == expected_msg

0 comments on commit d14e054

Please sign in to comment.