diff --git a/Library/Homebrew/livecheck/strategy/json.rb b/Library/Homebrew/livecheck/strategy/json.rb index 91a7fbe30f..e02c64367c 100644 --- a/Library/Homebrew/livecheck/strategy/json.rb +++ b/Library/Homebrew/livecheck/strategy/json.rb @@ -46,6 +46,19 @@ module Homebrew URL_MATCH_REGEX.match?(url) end + # Parses JSON text and returns the parsed data. + # @param content [String] the JSON text to parse + sig { params(content: String).returns(T.untyped) } + def self.parse_json(content) + require "json" + + begin + JSON.parse(content) + rescue JSON::ParserError + raise "Content could not be parsed as JSON." + end + 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). @@ -63,12 +76,8 @@ module Homebrew def self.versions_from_content(content, regex = nil, &block) return [] if content.blank? || block.blank? - require "json" - json = begin - JSON.parse(content) - rescue JSON::ParserError - raise "Content could not be parsed as JSON." - end + json = parse_json(content) + return [] if json.blank? block_return_value = if regex.present? yield(json, regex) diff --git a/Library/Homebrew/test/livecheck/strategy/json_spec.rb b/Library/Homebrew/test/livecheck/strategy/json_spec.rb index 79f71925e1..b20de8416e 100644 --- a/Library/Homebrew/test/livecheck/strategy/json_spec.rb +++ b/Library/Homebrew/test/livecheck/strategy/json_spec.rb @@ -74,6 +74,12 @@ describe Homebrew::Livecheck::Strategy::Json do end end + describe "::parse_json" do + it "returns an object when given valid content" do + expect(json.parse_json(content_simple)).to be_an_instance_of(Hash) + end + end + describe "::versions_from_content" do it "returns an empty array when given a block but content is blank" do expect(json.versions_from_content("", regex) { "1.2.3" }).to eq([])