gitlab-org--gitlab-foss/lib/gitlab/dependency_linker/base_linker.rb

70 lines
1.7 KiB
Ruby
Raw Normal View History

2016-07-10 17:13:06 -04:00
module Gitlab
module DependencyLinker
class BaseLinker
2017-05-16 16:25:57 -04:00
URL_REGEX = %r{https?://[^'"]+}.freeze
class_attribute :file_type
def self.support?(blob_name)
Gitlab::FileDetector.type_of(blob_name) == file_type
end
def self.link(*args)
new(*args).link
2016-07-10 17:13:06 -04:00
end
attr_accessor :plain_text, :highlighted_text
def initialize(plain_text, highlighted_text)
@plain_text = plain_text
@highlighted_text = highlighted_text
end
def link
link_dependencies
highlighted_lines.join.html_safe
end
private
def link_dependencies
raise NotImplementedError
end
2017-05-16 16:25:57 -04:00
def license_url(name)
Licensee::License.find(name)&.url
2016-07-10 17:13:06 -04:00
end
2017-05-16 16:25:57 -04:00
def link_tag(name, url)
%{<a href="#{ERB::Util.html_escape_once(url)}" rel="nofollow noreferrer noopener" target="_blank">#{ERB::Util.html_escape_once(name)}</a>}
2016-07-10 17:13:06 -04:00
end
# Links package names based on regex.
#
# Example:
# link_regex(/(github:|:github =>)\s*['"](?<name>[^'"]+)['"]/)
# # Will link `user/repo` in `github: "user/repo"` or `:github => "user/repo"`
2017-05-16 16:25:57 -04:00
def link_regex(regex, &url_proc)
2016-07-10 17:13:06 -04:00
highlighted_lines.map!.with_index do |rich_line, i|
marker = StringRegexMarker.new(plain_lines[i], rich_line.html_safe)
marker.mark(regex, group: :name) do |text, left:, right:|
2017-05-16 16:25:57 -04:00
url = yield(text)
url ? link_tag(text, url) : text
2016-07-10 17:13:06 -04:00
end
end
end
def plain_lines
@plain_lines ||= plain_text.lines
end
def highlighted_lines
@highlighted_lines ||= highlighted_text.lines
end
end
end
end