aboutsummaryrefslogtreecommitdiffstats
path: root/Library/Homebrew/cask/lib/hbc/dsl/gpg.rb
blob: 99b39d43fd3f67499f27a5fe5e99a8cf1b12fc47 (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
module Hbc
  class DSL
    class Gpg
      KEY_PARAMETERS = Set.new [
        :key_id,
        :key_url,
      ]

      VALID_PARAMETERS = Set.new []
      VALID_PARAMETERS.merge KEY_PARAMETERS

      attr_accessor(*VALID_PARAMETERS)
      attr_accessor :signature

      def initialize(signature, parameters = {})
        @parameters = parameters
        @signature = URI(signature)
        parameters.each do |hkey, hvalue|
          raise "invalid 'gpg' parameter: '#{hkey.inspect}'" unless VALID_PARAMETERS.include?(hkey)
          writer_method = "#{hkey}=".to_sym
          hvalue = URI(hvalue) if hkey == :key_url
          valid_id?(hvalue) if hkey == :key_id
          send(writer_method, hvalue)
        end
        return if KEY_PARAMETERS.intersection(parameters.keys).length == 1
        raise "'gpg' stanza must include exactly one of: '#{KEY_PARAMETERS.to_a}'"
      end

      def valid_id?(id)
        legal_lengths = Set.new [8, 16, 40]
        is_valid = id.is_a?(String) && legal_lengths.include?(id.length) && id[/^[0-9a-f]+$/i]
        raise "invalid ':key_id' value: '#{id.inspect}'" unless is_valid

        is_valid
      end

      def to_yaml
        # bug, :key_url value is not represented as an instance of URI
        [@signature, @parameters].to_yaml
      end

      def to_s
        @signature.to_s
      end
    end
  end
end