From 0935767bbcbadad9752ad29c5e05581f5f24152e Mon Sep 17 00:00:00 2001 From: r00tkrnl Date: Sat, 28 Nov 2026 08:39:14 +0300 Subject: [PATCH] Sort headers by name without regard to case MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Field names are case insensitive, so `set-cookie` and `Set-Cookie` are the same field and keep their order. The sort also no longer puts every upper case name before every lower case one. Refs #1960 🤖 Generated with Codebuff Co-Authored-By: Codebuff --- httpie/output/formatters/headers.py | 4 +++- tests/test_output.py | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/httpie/output/formatters/headers.py b/httpie/output/formatters/headers.py index 2188193902..4eec4ed301 100644 --- a/httpie/output/formatters/headers.py +++ b/httpie/output/formatters/headers.py @@ -14,5 +14,7 @@ def format_headers(self, headers: str) -> str: """ lines = headers.splitlines() - headers = sorted(lines[1:], key=lambda h: h.split(':')[0]) + # Field names are case insensitive, so compare them that way too. Sorting is + # stable, which keeps repeated fields in their original order. + headers = sorted(lines[1:], key=lambda h: h.split(':')[0].lower()) return '\r\n'.join(lines[:1] + headers) diff --git a/tests/test_output.py b/tests/test_output.py index 2242177dbc..e30fa5f24f 100644 --- a/tests/test_output.py +++ b/tests/test_output.py @@ -392,6 +392,19 @@ def get_headers(sort): assert f'XXX: foo{CRLF}ZZZ: foo' in r_sorted assert f'ZZZ: foo{CRLF}XXX: foo' in r_unsorted + def test_header_sort_ignores_case(self): + """Field names are case insensitive and repeated fields keep their order.""" + r = http( + '--offline', '--print=H', 'example.org', + 'set-cookie:first=1', 'X-Z:last', 'Set-Cookie:second=2', + 'accept:text/plain', + ) + names = [ + line.split(':')[0] for line in r.splitlines()[1:] + if line.split(':')[0].lower() in {'accept', 'set-cookie', 'x-z'} + ] + assert names == ['accept', 'set-cookie', 'Set-Cookie', 'X-Z'] + @pytest.mark.parametrize( 'options, expected_json', [