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

64 lines
1.9 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
2019-12-04 20:38:33 +05:30
ISSUE_REFERENCE_TYPE = '@data-reference-type="issue"'
2023-07-09 08:55:56 +05:30
WORK_ITEM_REFERENCE_TYPE = '@data-reference-type="work_item"'
2019-12-04 20:38:33 +05:30
MERGE_REQUEST_REFERENCE_TYPE = '@data-reference-type="merge_request"'
2018-12-13 13:39:08 +05:30
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),
2023-07-09 08:55:56 +05:30
Banzai::ReferenceParser::WorkItemParser.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
2023-07-09 08:55:56 +05:30
[ISSUE_REFERENCE_TYPE, WORK_ITEM_REFERENCE_TYPE, MERGE_REQUEST_REFERENCE_TYPE]
2017-08-17 22:00:37 +05:30
end
end
end
2020-04-22 19:07:51 +05:30
2021-06-08 01:23:25 +05:30
Banzai::IssuableExtractor.prepend_mod_with('Banzai::IssuableExtractor')