Skip to content
Closed
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
This document records all notable changes to [HTTPie](https://httpie.io).
This project adheres to [Semantic Versioning](https://semver.org/).

## [3.3.0-dev](https://github.com/httpie/httpie/compare/3.2.4...master) (unreleased)

- Allow flags to be specified between the positional arguments, e.g. `http post -f example.com`. ([#1433](https://github.com/httpie/httpie/issues/1433))

## [3.2.4](https://github.com/httpie/cli/compare/3.2.3...3.2.4) (2024-11-01)

- Fix default certs loading and unpin `requests`. ([#1596](https://github.com/httpie/cli/issues/1596))
Expand Down
79 changes: 78 additions & 1 deletion httpie/cli/argparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,9 @@ def parse_args(
) -> argparse.Namespace:
self.env = env
self.env.args = namespace = namespace or argparse.Namespace()
self.args, no_options = super().parse_known_args(args, namespace)
self.args, no_options = super().parse_known_args(
self._intermixed_args(args), namespace
)
if self.args.debug:
self.args.traceback = True
self.has_stdin_data = (
Expand Down Expand Up @@ -193,6 +195,81 @@ def parse_args(

return self.args

def _intermixed_args(self, args):
"""Allow flags to be specified between the positional arguments.

`argparse` consumes the positional arguments as a group, so a flag
placed between `METHOD` and `URL` (e.g. `http post -f example.com`)
ends up assigned to `URL`, and the remaining arguments are then
rejected. Since `parse_known_args()` is what powers the
`--no-OPTION` mechanism (see `_apply_no_options()`), we can't simply
switch to `parse_intermixed_args()`. Instead, the arguments are
sorted into optionals and positionals — each group keeping its
original relative order — before being handed over to `argparse`.

Command lines containing the `--` separator are passed through
untouched: older `argparse` versions cannot match positional
arguments that follow an optional and the separator, so reordering
them would break invocations that work today.

"""
if args is None:
args = sys.argv[1:]

if '--' in args:
# Older `argparse` versions cannot match positional arguments
# that follow an optional and the `--` separator, so reordering
# such a command line would break invocations that work today.
return args

optionals = []
positionals = []

index = 0
while index < len(args):
arg = args[index]
index += 1
parsed = self._parse_optional(arg)
if parsed is None:
positionals.append(arg)
continue
# Depending on the Python version, `_parse_optional()` returns
# either a single (action, option_string, explicit_arg) tuple,
# or a list of (action, option_string, sep, explicit_arg)
# tuples — one per interpretation of an abbreviated option.
# Only the action and the explicit argument are needed here.
if isinstance(parsed, list):
parsed = parsed[0]
action, explicit_arg = parsed[0], parsed[-1]
optionals.append(arg)
if explicit_arg is not None or action is None:
# The option carries its own value (`--opt=value`,
# `-ovalue`), or it is unknown to this parser (such as the
# `--no-OPTION` forms handled by `_apply_no_options()`).
continue
# Consume the values that belong to this option, but never an
# argument that `argparse` wouldn't consume as a value itself
# (i.e. one that looks like an optional).
values_left = action.nargs
if values_left is None or values_left == argparse.OPTIONAL:
values_left = 1
while values_left and index < len(args):
if self._is_optional(args[index]):
break
optionals.append(args[index])
index += 1
if isinstance(values_left, int):
values_left -= 1

return positionals + optionals

def _is_optional(self, arg):
"""Whether `argparse` would treat `arg` as an optional rather
than a positional argument.

"""
return self._parse_optional(arg) is not None

def _process_request_type(self):
request_type = self.args.request_type
self.args.json = request_type is RequestType.JSON
Expand Down
3 changes: 2 additions & 1 deletion httpie/cli/definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@
positional_arguments = options.add_group(
'Positional arguments',
description="""
These arguments come after any flags and in the order they are listed here.
These arguments can be intermixed with any flags, and are matched
in the order they are listed here.
Only URL is required.
""",
)
Expand Down
74 changes: 74 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,80 @@ def test_guess_when_method_set_but_invalid_and_item_exists(self):
]


class TestFlagsAfterPositionalArguments:
"""Flags can be specified between the positional arguments.

See <https://github.com/httpie/httpie/issues/1433>.

"""

def parse(self, *args):
return parser.parse_args(args=list(args), env=MockEnvironment())

def test_flag_between_method_and_url(self):
args = self.parse('post', '-f', 'example.com')
assert args.method == 'post'
assert args.url == 'http://example.com'
assert args.request_type is constants.RequestType.FORM
assert args.form

def test_flag_between_method_and_url_with_request_item(self):
args = self.parse('post', '-f', 'example.com', 'name=value')
assert args.method == 'post'
assert args.url == 'http://example.com'
assert [item.orig for item in args.request_items] == ['name=value']
assert args.data == {'name': 'value'}

def test_multiple_flags_between_positionals(self):
args = self.parse('post', '--json', 'example.com', 'x=1', '--verbose')
assert args.method == 'post'
assert args.url == 'http://example.com'
assert args.request_type is constants.RequestType.JSON
assert args.verbose == 1

def test_flags_parse_the_same_wherever_they_are(self):
for args in (
self.parse('-f', 'post', 'example.com'),
self.parse('post', '-f', 'example.com'),
self.parse('post', 'example.com', '-f'),
):
assert args.method == 'post'
assert args.url == 'http://example.com'
assert args.request_type is constants.RequestType.FORM

def test_option_value_is_not_mistaken_for_a_flag(self):
args = self.parse('post', '--timeout', '-1', 'example.com')
assert args.method == 'post'
assert args.url == 'http://example.com'
assert args.timeout == -1

def test_no_option_between_method_and_url(self):
args = self.parse('post', '--verbose', '--no-verbose', 'example.com')
assert args.method == 'post'
assert args.url == 'http://example.com'
assert args.verbose == 0

def test_items_after_double_dash_stay_positional(self):
args = self.parse('post', 'example.com', '--', '-weird=name')
assert args.method == 'post'
assert args.url == 'http://example.com'
assert [item.orig for item in args.request_items] == ['-weird=name']

def test_flags_before_double_dash_keep_working(self):
# Reordering across `--` would break on older `argparse`
# versions, so such command lines are passed through as-is.
args = self.parse('-f', 'post', 'example.com', '--', 'name=value')
assert args.method == 'post'
assert args.url == 'http://example.com'
assert args.request_type is constants.RequestType.FORM
assert [item.orig for item in args.request_items] == ['name=value']

def test_request_with_flag_after_method(self, httpbin):
r = http('post', '-f', httpbin + '/post', 'name=value')
assert HTTP_OK in r
assert r.json['form'] == {'name': 'value'}


class TestNoOptions:

def test_valid_no_options(self, httpbin):
Expand Down
Loading