Skip to content

Commit

Permalink
Merge pull request #18019 from Homebrew/safe-try-new
Browse files Browse the repository at this point in the history
  • Loading branch information
MikeMcQuaid authored Aug 12, 2024
2 parents fd14dea + c799f5f commit 6b3cac7
Showing 1 changed file with 19 additions and 12 deletions.
31 changes: 19 additions & 12 deletions Library/Homebrew/cask/cask_loader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,22 +51,29 @@ def cask(header_token, **options, &block)

# Loads a cask from a string.
class FromContentLoader < AbstractContentLoader
sig {
params(ref: T.any(Pathname, String, Cask, URI::Generic), warn: T::Boolean)
.returns(T.nilable(T.attached_class))
}
def self.try_new(ref, warn: false)
return false unless ref.respond_to?(:to_str)
case ref
when Cask, URI::Generic
# do nothing
else
content = ref.to_str

# Cache compiled regex
@regex ||= begin
token = /(?:"[^"]*"|'[^']*')/
curly = /\(\s*#{token.source}\s*\)\s*\{.*\}/
do_end = /\s+#{token.source}\s+do(?:\s*;\s*|\s+).*end/
/\A\s*cask(?:#{curly.source}|#{do_end.source})\s*\Z/m
end

content = T.unsafe(ref).to_str
return unless content.match?(@regex)

# Cache compiled regex
@regex ||= begin
token = /(?:"[^"]*"|'[^']*')/
curly = /\(\s*#{token.source}\s*\)\s*\{.*\}/
do_end = /\s+#{token.source}\s+do(?:\s*;\s*|\s+).*end/
/\A\s*cask(?:#{curly.source}|#{do_end.source})\s*\Z/m
new(content)
end

return unless content.match?(@regex)

new(content)
end

sig { params(content: String, tap: Tap).void }
Expand Down

0 comments on commit 6b3cac7

Please sign in to comment.