aboutsummaryrefslogtreecommitdiffstats
path: root/Library/Homebrew/cask/lib/hbc/cask_loader.rb
blob: 3875b30df297b39043706c0c65c93be1df08a9a9 (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
module Hbc
  class CaskLoader
    def self.load_from_file(path)
      raise CaskError, "File '#{path}' does not exist"      unless path.exist?
      raise CaskError, "File '#{path}' is not readable"     unless path.readable?
      raise CaskError, "File '#{path}' is not a plain file" unless path.file?

      token = path.basename(".rb").to_s
      content = IO.read(path).force_encoding("UTF-8")

      new(token, content, path).load
    end

    def self.load_from_string(token, content)
      new(token, content).load
    end

    def load
      instance_eval(@content, __FILE__, __LINE__)
    rescue CaskError, StandardError, ScriptError => e
      e.message.concat(" while loading '#{@token}'")
      e.message.concat(" from '#{@path}'") unless @path.nil?
      raise e, e.message
    end

    private

    def initialize(token, content, path = nil)
      @token = token
      @content = content
      @path = path unless path.nil?
    end

    def cask(header_token, &block)
      @klass = Cask
      build_cask(header_token, &block)
    end

    def test_cask(header_token, &block)
      @klass = TestCask
      build_cask(header_token, &block)
    end

    def build_cask(header_token, &block)
      raise CaskTokenDoesNotMatchError.new(@token, header_token) unless @token == header_token

      if @path.nil?
        @klass.new(@token, &block)
      else
        @klass.new(@token, sourcefile_path: @path, &block)
      end
    end
  end
end