brew/Library/Homebrew/cask/lib/hbc/url_checker.rb

78 lines
2.1 KiB
Ruby
Raw Normal View History

2016-08-18 22:11:42 +03:00
require "hbc/checkable"
2016-09-24 13:52:43 +02:00
module Hbc
class UrlChecker
attr_accessor :cask, :response_status, :headers
2016-08-18 22:11:42 +03:00
2016-09-24 13:52:43 +02:00
include Checkable
2016-08-18 22:11:42 +03:00
2016-09-24 13:52:43 +02:00
def initialize(cask, fetcher = Fetcher)
@cask = cask
@fetcher = fetcher
@headers = {}
end
2016-08-18 22:11:42 +03:00
2016-09-24 13:52:43 +02:00
def summary_header
"url check result for #{cask}"
end
2016-08-18 22:11:42 +03:00
2016-09-24 13:52:43 +02:00
def run
_get_data_from_request
return if errors?
_check_response_status
end
2016-08-18 22:11:42 +03:00
2016-09-24 13:52:43 +02:00
HTTP_RESPONSES = [
"HTTP/1.0 200 OK",
"HTTP/1.1 200 OK",
"HTTP/1.1 302 Found",
].freeze
2016-08-18 22:11:42 +03:00
2016-09-24 13:52:43 +02:00
OK_RESPONSES = {
"http" => HTTP_RESPONSES,
"https" => HTTP_RESPONSES,
"ftp" => ["OK"],
}.freeze
2016-08-18 22:11:42 +03:00
2016-09-24 13:52:43 +02:00
def _check_response_status
ok = OK_RESPONSES[cask.url.scheme]
return if ok.include?(@response_status)
add_error "unexpected http response, expecting #{ok.map(&:utf8_inspect).join(" or ")}, got #{@response_status.utf8_inspect}"
end
2016-08-18 22:11:42 +03:00
2016-09-24 13:52:43 +02:00
def _get_data_from_request
response = @fetcher.head(cask.url)
2016-08-18 22:11:42 +03:00
2016-09-24 13:52:43 +02:00
if response.empty?
add_error "timeout while requesting #{cask.url}"
return
end
2016-08-18 22:11:42 +03:00
2016-09-24 13:52:43 +02:00
response_lines = response.split("\n").map(&:chomp)
2016-08-18 22:11:42 +03:00
2016-09-24 13:52:43 +02:00
case cask.url.scheme
when "http", "https" then
@response_status = response_lines.grep(%r{^HTTP}).last
if @response_status.respond_to?(:strip)
@response_status.strip!
unless response_lines.index(@response_status).nil?
http_headers = response_lines[(response_lines.index(@response_status) + 1)..-1]
http_headers.each do |line|
header_name, header_value = line.split(": ")
@headers[header_name] = header_value
end
2016-08-18 22:11:42 +03:00
end
end
2016-09-24 13:52:43 +02:00
when "ftp" then
@response_status = "OK"
response_lines.each do |line|
header_name, header_value = line.split(": ")
@headers[header_name] = header_value
end
else
add_error "unknown scheme for #{cask.url}"
2016-08-18 22:11:42 +03:00
end
end
end
end