BigW Consortium Gitlab

json_linker.rb 1.18 KB
Newer Older
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
module Gitlab
  module DependencyLinker
    class JsonLinker < BaseLinker
      def link
        return highlighted_text unless json

        super
      end

      private

      # Links package names in a JSON key or values.
      #
      # Example:
      #   link_json('name')
      #   # Will link `package` in `"name": "package"`
      #
      #   link_json('name', 'specific_package')
      #   # Will link `specific_package` in `"name": "specific_package"`
      #
      #   link_json('name', /[^\/]+\/[^\/]+/)
      #   # Will link `user/repo` in `"name": "user/repo"`, but not `"name": "package"`
      #
      #   link_json('specific_package', '1.0.1', link: :key)
      #   # Will link `specific_package` in `"specific_package": "1.0.1"`
      def link_json(key, value = nil, link: :value, &url_proc)
27 28
        key = regexp_for_value(key, default: /[^" ]+/)
        value = regexp_for_value(value, default: /[^" ]+/)
29 30

        if link == :value
31
          value = /(?<name>#{value})/
32
        else
33
          key = /(?<name>#{key})/
34 35 36 37 38 39 40 41 42 43 44
        end

        link_regex(/"#{key}":\s*"#{value}"/, &url_proc)
      end

      def json
        @json ||= JSON.parse(plain_text) rescue nil
      end
    end
  end
end