Json: Allow nil regex block argument

This updates the block-handling logic in `Json::versions_from_content`
to naively pass the regex value when the block has two parameters. Up
to now, we have been ensuring that `regex` is not `nil` and this
makes sense with existing usage (the `Crate` strategy's default
block, formulae/cask `strategy` blocks). However, we need to allow a
`nil` `regex` value to make it possible to add an optional `regex`
parameter in the `Pypi::DEFAULT_BLOCK` Proc. This is necessary to
allow the `Pypi` strategy to work with an optional regex from a
`livecheck` block again [without creating an additional
`DEFAULT_BLOCK` variant with a regex parameter].
This commit is contained in:
Sam Ford 2024-12-08 12:22:57 -05:00
parent 8fa9b72a96
commit 08c927b6a1
No known key found for this signature in database
GPG Key ID: 7AF5CBEE1DD6F76D
2 changed files with 5 additions and 10 deletions

View File

@ -58,8 +58,10 @@ module Homebrew
end
# Parses JSON text and identifies versions using a `strategy` block.
# If a regex is provided, it will be passed as the second argument to
# the `strategy` block (after the parsed JSON data).
# If the block has two parameters, the parsed JSON data will be used as
# the first argument and the regex (if any) will be the second.
# Otherwise, only the parsed JSON data will be passed to the block.
#
# @param content [String] the JSON text to parse and check
# @param regex [Regexp, nil] a regex used for matching versions in the
# content
@ -77,10 +79,8 @@ module Homebrew
json = parse_json(content)
return [] if json.blank?
block_return_value = if regex.present?
block_return_value = if block.arity == 2
yield(json, regex)
elsif block.arity == 2
raise "Two arguments found in `strategy` block but no regex provided."
else
yield(json)
end

View File

@ -107,11 +107,6 @@ RSpec.describe Homebrew::Livecheck::Strategy::Json do
expect(json.versions_from_content(content_simple, regex) { next }).to eq([])
end
it "errors if a block uses two arguments but a regex is not given" do
expect { json.versions_from_content(content_simple) { |json, regex| json["version"][regex, 1] } }
.to raise_error("Two arguments found in `strategy` block but no regex provided.")
end
it "errors on an invalid return type from a block" do
expect { json.versions_from_content(content_simple, regex) { 123 } }
.to raise_error(TypeError, Homebrew::Livecheck::Strategy::INVALID_BLOCK_RETURN_VALUE_MSG)