debian-mirror-gitlab/lib/banzai/issuable_extractor.rb

60 lines
1.7 KiB
Ruby
Raw Normal View History

2018-12-13 13:39:08 +05:30
# frozen_string_literal: true
2017-08-17 22:00:37 +05:30
module Banzai
# Extract references to issuables from multiple documents
# This populates RequestStore cache used in Banzai::ReferenceParser::IssueParser
# and Banzai::ReferenceParser::MergeRequestParser
# Populating the cache should happen before processing documents one-by-one
# so we can avoid N+1 queries problem
class IssuableExtractor
2018-05-09 12:01:36 +05:30
attr_reader :context
2017-08-17 22:00:37 +05:30
2018-12-13 13:39:08 +05:30
ISSUE_REFERENCE_TYPE = '@data-reference-type="issue"'.freeze
MERGE_REQUEST_REFERENCE_TYPE = '@data-reference-type="merge_request"'.freeze
2018-05-09 12:01:36 +05:30
# context - An instance of Banzai::RenderContext.
def initialize(context)
@context = context
2017-08-17 22:00:37 +05:30
end
# Returns Hash in the form { node => issuable_instance }
def extract(documents)
nodes = documents.flat_map do |document|
2018-12-13 13:39:08 +05:30
document.xpath(query)
2017-08-17 22:00:37 +05:30
end
2018-12-13 13:39:08 +05:30
# The project or group for the issuable might be pending for deletion!
# Filter them out because we don't care about them.
issuables_for_nodes(nodes).select { |node, issuable| issuable.project || issuable.group }
end
private
2018-05-09 12:01:36 +05:30
2018-12-13 13:39:08 +05:30
def issuables_for_nodes(nodes)
parsers.each_with_object({}) do |parser, result|
result.merge!(parser.records_for_nodes(nodes))
end
end
def parsers
[
Banzai::ReferenceParser::IssueParser.new(context),
2018-05-09 12:01:36 +05:30
Banzai::ReferenceParser::MergeRequestParser.new(context)
2018-12-13 13:39:08 +05:30
]
end
2017-08-17 22:00:37 +05:30
2018-12-13 13:39:08 +05:30
def query
%Q(
descendant-or-self::a[contains(concat(" ", @class, " "), " gfm ")]
[#{reference_types.join(' or ')}]
2017-08-17 22:00:37 +05:30
)
2018-12-13 13:39:08 +05:30
end
2017-08-17 22:00:37 +05:30
2018-12-13 13:39:08 +05:30
def reference_types
[ISSUE_REFERENCE_TYPE, MERGE_REQUEST_REFERENCE_TYPE]
2017-08-17 22:00:37 +05:30
end
end
end