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

87 lines
2.1 KiB
Ruby
Raw Normal View History

2016-07-10 17:13:06 -04:00
module Gitlab
module DependencyLinker
class BaseLinker
URL_REGEX = %r{https?://[^'" ]+}.freeze
REPO_REGEX = %r{[^/'" ]+/[^/'" ]+}.freeze
2017-05-16 16:25:57 -04:00
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:27:50 -04:00
def github_url(name)
"https://github.com/#{name}"
end
2016-07-10 17:13:06 -04:00
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
2017-05-25 09:55:47 -04:00
def regexp_for_value(value, default: /[^'" ]+/)
2017-05-25 09:55:47 -04:00
case value
when Array
Regexp.union(value.map { |v| regexp_for_value(v, default: default) })
when String
Regexp.escape(value)
when Regexp
value
else
default
end
end
2016-07-10 17:13:06 -04:00
end
end
end