BigW Consortium Gitlab

route_map.rb 1.54 KB
Newer Older
Douwe Maan committed
1 2
module Gitlab
  class RouteMap
3
    FormatError = Class.new(StandardError)
Douwe Maan committed
4 5 6 7 8

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

12
      raise FormatError, 'Route map is not an array' unless entries.is_a?(Array)
Douwe Maan committed
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 }
Douwe Maan committed
19 20
      return unless mapping

21 22 23 24 25
      if mapping[:source].is_a?(String)
        path.sub(mapping[:source], mapping[:public])
      else
        mapping[:source].replace(path, mapping[:public])
      end
Douwe Maan committed
26 27 28 29 30
    end

    private

    def parse_entry(entry)
31
      raise FormatError, 'Route map entry is not a hash' unless entry.is_a?(Hash)
32 33
      raise FormatError, 'Route map entry does not have a source key' unless entry.key?('source')
      raise FormatError, 'Route map entry does not have a public key' unless entry.key?('public')
Douwe Maan committed
34

35
      source_pattern = entry['source']
Douwe Maan committed
36 37
      public_path = entry['public']

38 39
      if source_pattern.start_with?('/') && source_pattern.end_with?('/')
        source_pattern = source_pattern[1...-1].gsub('\/', '/')
Douwe Maan committed
40

41
        begin
42
          source_pattern = Gitlab::UntrustedRegexp.new('\A' + source_pattern + '\z')
43 44 45
        rescue RegexpError => e
          raise FormatError, "Route map entry source is not a valid regular expression: #{e}"
        end
Douwe Maan committed
46 47 48
      end

      {
49
        source: source_pattern,
Douwe Maan committed
50 51 52 53 54
        public: public_path
      }
    end
  end
end