livecheck: Include Content-Length header for POST

Some servers will return an error response if a `Content-Length`
header isn't included in a `POST` request, so this adds it to the
`post_args` array when `post_form` or `post_json` are used.
This commit is contained in:
Sam Ford 2025-03-07 20:31:00 -05:00
parent 9096a111d7
commit 8ba1b4400a
No known key found for this signature in database
GPG Key ID: 7AF5CBEE1DD6F76D
2 changed files with 16 additions and 4 deletions

View File

@ -178,7 +178,7 @@ module Homebrew
).returns(T::Array[String]) ).returns(T::Array[String])
} }
def self.post_args(post_form: nil, post_json: nil) def self.post_args(post_form: nil, post_json: nil)
if post_form.present? args = if post_form.present?
require "uri" require "uri"
["--data", URI.encode_www_form(post_form)] ["--data", URI.encode_www_form(post_form)]
elsif post_json.present? elsif post_json.present?
@ -187,6 +187,12 @@ module Homebrew
else else
[] []
end end
if (content_length = args[1]&.length)
args << "--header" << "Content-Length: #{content_length}"
end
args
end end
# Collects HTTP response headers, starting with the provided URL. # Collects HTTP response headers, starting with the provided URL.

View File

@ -144,16 +144,22 @@ RSpec.describe Homebrew::Livecheck::Strategy do
end end
describe "::post_args" do describe "::post_args" do
let(:form_string_content_length) { "Content-Length: #{form_string.length}" }
let(:json_string_content_length) { "Content-Length: #{json_string.length}" }
it "returns an array including `--data` and an encoded form data string" do it "returns an array including `--data` and an encoded form data string" do
expect(strategy.post_args(post_form: post_hash)).to eq(["--data", form_string]) expect(strategy.post_args(post_form: post_hash))
.to eq(["--data", form_string, "--header", form_string_content_length])
# If both `post_form` and `post_json` are present, only `post_form` will # If both `post_form` and `post_json` are present, only `post_form` will
# be used. # be used.
expect(strategy.post_args(post_form: post_hash, post_json: post_hash)).to eq(["--data", form_string]) expect(strategy.post_args(post_form: post_hash, post_json: post_hash))
.to eq(["--data", form_string, "--header", form_string_content_length])
end end
it "returns an array including `--json` and a JSON string" do it "returns an array including `--json` and a JSON string" do
expect(strategy.post_args(post_json: post_hash)).to eq(["--json", json_string]) expect(strategy.post_args(post_json: post_hash))
.to eq(["--json", json_string, "--header", json_string_content_length])
end end
it "returns an empty array if `post_form` value is blank" do it "returns an empty array if `post_form` value is blank" do