aboutsummaryrefslogtreecommitdiffstats
path: root/Library/Homebrew/cask/lib/hbc/url_checker.rb
blob: 60a15ca2fe41f6d38c4c3545665d17ab4121a0a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
require "hbc/checkable"
require "hbc/fetcher"

module Hbc
  class UrlChecker
    attr_accessor :cask, :response_status, :headers

    include Checkable

    def initialize(cask, fetcher = Fetcher)
      @cask = cask
      @fetcher = fetcher
      @headers = {}
    end

    def summary_header
      "url check result for #{cask}"
    end

    def run
      _get_data_from_request
      return if errors?
      _check_response_status
    end

    HTTP_RESPONSES = [
      "HTTP/1.0 200 OK",
      "HTTP/1.1 200 OK",
      "HTTP/1.1 302 Found",
    ].freeze

    OK_RESPONSES = {
      "http"  => HTTP_RESPONSES,
      "https" => HTTP_RESPONSES,
      "ftp"   => ["OK"],
    }.freeze

    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

    def _get_data_from_request
      response = @fetcher.head(cask.url)

      if response.empty?
        add_error "timeout while requesting #{cask.url}"
        return
      end

      response_lines = response.split("\n").map(&:chomp)

      case cask.url.scheme
      when "http", "https" then
        @response_status = response_lines.grep(/^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
          end
        end
      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}"
      end
    end
  end
end