From bc755c08da73e8f93e3f87694efac9dcb61a51c2 Mon Sep 17 00:00:00 2001 From: su ru <183260426+Surri757@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:48:44 +0800 Subject: [PATCH] Allow flags to be specified between positional arguments (#1433) `http post -f example.com` used to fail: argparse consumes the positional arguments as a group, so the flag between METHOD and URL made `post` be parsed as the URL and `example.com` was then rejected as an invalid request item. `http example.com --form name=value` even crashed with an AssertionError in _guess_method(). Sort the raw arguments into optionals and positionals (each group keeping its original relative order) before handing them to parse_known_args(), which we still rely on for the --no-OPTION mechanism -- hence not using parse_intermixed_args(). Token classification reuses argparse's own _parse_optional() so that abbreviations, attached short values, --opt=value, negative numbers and the --no-OPTION forms are classified exactly as argparse would. Command lines containing `--` are passed through untouched: older argparse versions cannot match positionals that follow an optional and the separator. --- CHANGELOG.md | 4 ++ httpie/cli/argparser.py | 79 +++++++++++++++++++++++++++++++++++++++- httpie/cli/definition.py | 3 +- tests/test_cli.py | 74 +++++++++++++++++++++++++++++++++++++ 4 files changed, 158 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0497ac3508..0aa42215e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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)) diff --git a/httpie/cli/argparser.py b/httpie/cli/argparser.py index 9bf09b3b73..0ec0e47a00 100644 --- a/httpie/cli/argparser.py +++ b/httpie/cli/argparser.py @@ -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 = ( @@ -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 diff --git a/httpie/cli/definition.py b/httpie/cli/definition.py index 843b29c9cf..1294883a75 100644 --- a/httpie/cli/definition.py +++ b/httpie/cli/definition.py @@ -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. """, ) diff --git a/tests/test_cli.py b/tests/test_cli.py index 2cd27574af..ed1e4e8c18 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -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 . + + """ + + 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):