diff --git a/Library/Homebrew/formulary.rb b/Library/Homebrew/formulary.rb index 1c163805ce..a61d845579 100644 --- a/Library/Homebrew/formulary.rb +++ b/Library/Homebrew/formulary.rb @@ -696,9 +696,20 @@ module Formulary .returns(T.nilable(T.attached_class)) } def self.try_new(ref, from: T.unsafe(nil), warn: false) - ref = ref.to_s + # Cache compiled regex + @uri_regex ||= begin + uri_regex = ::URI::DEFAULT_PARSER.make_regexp + Regexp.new("\\A#{uri_regex.source}\\Z", uri_regex.options) + end - new(ref, from:) if URI(ref).scheme.present? + uri = ref.to_s + return unless uri.match?(@uri_regex) + + uri = URI(uri) + return unless uri.path + return unless uri.scheme.present? + + new(uri, from:) end attr_reader :url diff --git a/Library/Homebrew/test/formulary_spec.rb b/Library/Homebrew/test/formulary_spec.rb index 384fa622f7..907e8c7c43 100644 --- a/Library/Homebrew/test/formulary_spec.rb +++ b/Library/Homebrew/test/formulary_spec.rb @@ -555,6 +555,14 @@ RSpec.describe Formulary do end.not_to raise_error(UnsupportedInstallationMethod) end end + + context "when passed ref with spaces" do + it "raises a FormulaUnavailableError error" do + expect do + described_class.factory("foo bar") + end.to raise_error(FormulaUnavailableError) + end + end end specify "::from_contents" do