debian-mirror-gitlab/lib/gitlab/reference_extractor.rb

74 lines
2 KiB
Ruby
Raw Normal View History

2015-09-25 12:07:36 +05:30
require 'gitlab/markdown'
2014-09-02 18:07:02 +05:30
module Gitlab
# Extract possible GFM references from an arbitrary String for further processing.
class ReferenceExtractor
2015-10-24 18:46:33 +05:30
attr_accessor :project, :current_user, :load_lazy_references
2014-09-02 18:07:02 +05:30
2015-10-24 18:46:33 +05:30
def initialize(project, current_user = nil, load_lazy_references: true)
2015-04-26 12:48:37 +05:30
@project = project
@current_user = current_user
2015-10-24 18:46:33 +05:30
@load_lazy_references = load_lazy_references
2014-09-02 18:07:02 +05:30
end
2015-04-26 12:48:37 +05:30
def analyze(text)
2015-09-11 14:41:01 +05:30
references.clear
2015-09-25 12:07:36 +05:30
@text = Gitlab::Markdown.render_without_gfm(text)
2014-09-02 18:07:02 +05:30
end
2015-09-11 14:41:01 +05:30
%i(user label issue merge_request snippet commit commit_range).each do |type|
define_method("#{type}s") do
references[type]
end
2014-09-02 18:07:02 +05:30
end
2015-09-11 14:41:01 +05:30
private
2014-09-02 18:07:02 +05:30
2015-09-11 14:41:01 +05:30
def references
@references ||= Hash.new do |references, type|
type = type.to_sym
2015-10-24 18:46:33 +05:30
next references[type] if references.has_key?(type)
2014-09-02 18:07:02 +05:30
2015-10-24 18:46:33 +05:30
references[type] = pipeline_result(type)
2015-09-11 14:41:01 +05:30
end
2014-09-02 18:07:02 +05:30
end
2015-09-11 14:41:01 +05:30
# Instantiate and call HTML::Pipeline with a single reference filter type,
# returning the result
#
# filter_type - Symbol reference type (e.g., :commit, :issue, etc.)
#
# Returns the results Array for the requested filter type
def pipeline_result(filter_type)
2015-10-24 18:46:33 +05:30
return [] if @text.blank?
klass = "#{filter_type.to_s.camelize}ReferenceFilter"
2015-09-25 12:07:36 +05:30
filter = Gitlab::Markdown.const_get(klass)
2014-09-02 18:07:02 +05:30
2015-09-11 14:41:01 +05:30
context = {
project: project,
current_user: current_user,
2015-10-24 18:46:33 +05:30
2015-09-11 14:41:01 +05:30
# We don't actually care about the links generated
only_path: true,
2015-10-24 18:46:33 +05:30
ignore_blockquotes: true,
# ReferenceGathererFilter
load_lazy_references: false,
reference_filter: filter
2015-09-11 14:41:01 +05:30
}
2014-09-02 18:07:02 +05:30
2015-10-24 18:46:33 +05:30
pipeline = HTML::Pipeline.new([filter, Gitlab::Markdown::ReferenceGathererFilter], context)
2015-09-11 14:41:01 +05:30
result = pipeline.call(@text)
2014-09-02 18:07:02 +05:30
2015-10-24 18:46:33 +05:30
values = result[:references][filter_type].uniq
if @load_lazy_references
values = Gitlab::Markdown::ReferenceFilter::LazyReference.load(values).uniq
end
values
2014-09-02 18:07:02 +05:30
end
end
end