route_map.rb 1.4 KB
Newer Older
D
Douwe Maan 已提交
1 2 3 4 5 6 7 8
module Gitlab
  class RouteMap
    class FormatError < StandardError; end

    def initialize(data)
      begin
        entries = YAML.safe_load(data)
      rescue
9
        raise FormatError, 'Route map is not valid YAML'
D
Douwe Maan 已提交
10 11
      end

12
      raise FormatError, 'Route map is not an array' unless entries.is_a?(Array)
D
Douwe Maan 已提交
13 14 15 16 17

      @map = entries.map { |entry| parse_entry(entry) }
    end

    def public_path_for_source_path(path)
18
      mapping = @map.find { |mapping| mapping[:source] === path }
D
Douwe Maan 已提交
19 20 21 22 23 24 25 26
      return unless mapping

      path.sub(mapping[:source], mapping[:public])
    end

    private

    def parse_entry(entry)
27 28 29
      raise FormatError, 'Route map entry is not a hash' unless entry.is_a?(Hash)
      raise FormatError, 'Route map entry does not have a source key' unless entry.has_key?('source')
      raise FormatError, 'Route map entry does not have a public key' unless entry.has_key?('public')
D
Douwe Maan 已提交
30

31
      source_pattern = entry['source']
D
Douwe Maan 已提交
32 33
      public_path = entry['public']

34 35
      if source_pattern.start_with?('/') && source_pattern.end_with?('/')
        source_pattern = source_pattern[1...-1].gsub('\/', '/')
D
Douwe Maan 已提交
36

37 38 39 40 41
        begin
          source_pattern = Regexp.new("^#{source_pattern}$")
        rescue RegexpError => e
          raise FormatError, "Route map entry source is not a valid regular expression: #{e}"
        end
D
Douwe Maan 已提交
42 43 44
      end

      {
45
        source: source_pattern,
D
Douwe Maan 已提交
46 47 48 49 50
        public: public_path
      }
    end
  end
end