gitlab-org--gitlab-foss/lib/gitlab/reference_extractor.rb

95 lines
2.4 KiB
Ruby
Raw Normal View History

module Gitlab
# Extract possible GFM references from an arbitrary String for further processing.
class ReferenceExtractor
2015-03-27 06:37:45 -04:00
attr_accessor :project, :references
include Markdown
2015-03-27 06:37:45 -04:00
def initialize(project)
@project = project
@references = Hash.new { [] }
end
2015-03-27 06:37:45 -04:00
def analyze(text)
text = text.dup
# Remove preformatted/code blocks so that references are not included
text.gsub!(%r{<pre>.*?</pre>|<code>.*?</code>}m) { |match| '' }
text.gsub!(%r{^```.*?^```}m) { |match| '' }
2015-03-27 06:37:45 -04:00
parse_references(text)
end
# Given a valid project, resolve the extracted identifiers of the requested type to
# model objects.
2015-03-27 06:37:45 -04:00
def users
references[:users].map do |entry|
project.users.where(username: entry[:id]).first
2015-03-27 06:37:45 -04:00
end.compact
end
2015-03-27 06:37:45 -04:00
def labels
references[:labels].map do |entry|
2015-02-07 06:14:55 -05:00
project.labels.where(id: entry[:id]).first
2015-03-27 06:37:45 -04:00
end.compact
2015-02-07 06:14:55 -05:00
end
2015-03-27 06:37:45 -04:00
def issues
references[:issues].map do |entry|
if should_lookup?(entry[:project])
entry[:project].issues.where(iid: entry[:id]).first
end
2015-03-27 06:37:45 -04:00
end.compact
end
2015-03-27 06:37:45 -04:00
def merge_requests
references[:merge_requests].map do |entry|
if should_lookup?(entry[:project])
entry[:project].merge_requests.where(iid: entry[:id]).first
end
2015-03-27 06:37:45 -04:00
end.compact
end
2015-03-27 06:37:45 -04:00
def snippets
references[:snippets].map do |entry|
project.snippets.where(id: entry[:id]).first
2015-03-27 06:37:45 -04:00
end.compact
end
2015-03-27 06:37:45 -04:00
def commits
references[:commits].map do |entry|
repo = entry[:project].repository if entry[:project]
2015-03-27 06:37:45 -04:00
if should_lookup?(entry[:project])
repo.commit(entry[:id]) if repo
end
2015-03-27 06:37:45 -04:00
end.compact
end
2015-03-27 06:37:45 -04:00
def commit_ranges
references[:commit_ranges].map do |entry|
repo = entry[:project].repository if entry[:project]
2015-03-27 06:37:45 -04:00
if repo && should_lookup?(entry[:project])
from_id, to_id = entry[:id].split(/\.{2,3}/, 2)
[repo.commit(from_id), repo.commit(to_id)]
end
2015-03-27 06:37:45 -04:00
end.compact
end
private
def reference_link(type, identifier, project, _)
2015-03-27 06:37:45 -04:00
references[type] << { project: project, id: identifier }
end
2015-03-27 06:37:45 -04:00
def should_lookup?(entry_project)
if entry_project.nil?
false
else
project.nil? || entry_project.default_issues_tracker?
end
end
end
end