Read about our upcoming Code of Conduct on this issue

This instance will be upgraded to Heptapod 0.28.1 on 2022-01-26 at 16:00 UTC+1 (a few minutes of down time)

abstract_reference_filter.rb 9.36 KB
Newer Older
1
2
module Banzai
  module Filter
3
    # Issues, Merge Requests, Snippets, Commits and Commit Ranges share
Douwe Maan's avatar
Douwe Maan committed
4
    # similar functionality in reference filtering.
5
6
7
8
9
10
11
12
13
    class AbstractReferenceFilter < ReferenceFilter
      include CrossProjectReference

      def self.object_class
        # Implement in child class
        # Example: MergeRequest
      end

      def self.object_name
14
        @object_name ||= object_class.name.underscore
15
16
17
      end

      def self.object_sym
18
        @object_sym ||= object_name.to_sym
19
20
21
22
      end

      # Public: Find references in text (like `!123` for merge requests)
      #
Douwe Maan's avatar
Douwe Maan committed
23
24
25
      #   AnyReferenceFilter.references_in(text) do |match, id, project_ref, matches|
      #     object = find_object(project_ref, id)
      #     "<a href=...>#{object.to_reference}</a>"
26
27
28
29
      #   end
      #
      # text - String text to search.
      #
Douwe Maan's avatar
Douwe Maan committed
30
31
      # Yields the String match, the Integer referenced object ID, an optional String
      # of the external project reference, and all of the matchdata.
32
33
      #
      # Returns a String replaced with the return of the block.
34
35
      def self.references_in(text, pattern = object_class.reference_pattern)
        text.gsub(pattern) do |match|
36
          yield match, $~[object_sym].to_i, $~[:project], $~[:namespace], $~
37
38
39
        end
      end

40
41
42
43
44
45
46
47
48
49
50
      def object_class
        self.class.object_class
      end

      def object_sym
        self.class.object_sym
      end

      def references_in(*args, &block)
        self.class.references_in(*args, &block)
      end
51
52
53
54
55
56

      def find_object(project, id)
        # Implement in child class
        # Example: project.merge_requests.find
      end

57
58
59
60
      def find_object_cached(project, id)
        if RequestStore.active?
          cache = find_objects_cache[object_class][project.id]

61
          get_or_set_cache(cache, id) { find_object(project, id) }
62
63
64
65
66
        else
          find_object(project, id)
        end
      end

67
      def project_from_ref_cached(ref)
68
69
70
        if RequestStore.active?
          cache = project_refs_cache

71
          get_or_set_cache(cache, ref) { project_from_ref(ref) }
72
73
74
75
76
        else
          project_from_ref(ref)
        end
      end

77
78
79
80
81
      def url_for_object(object, project)
        # Implement in child class
        # Example: project_merge_request_url
      end

82
83
84
85
      def url_for_object_cached(object, project)
        if RequestStore.active?
          cache = url_for_object_cache[object_class][project.id]

86
          get_or_set_cache(cache, object) { url_for_object(object, project) }
87
88
89
90
91
        else
          url_for_object(object, project)
        end
      end

92
      def call
93
        return doc if project.nil?
94

95
96
        ref_pattern = object_class.reference_pattern
        link_pattern = object_class.link_reference_pattern
97

98
        nodes.each do |node|
99
100
101
102
103
104
          if text_node?(node) && ref_pattern
            replace_text_when_pattern_matches(node, ref_pattern) do |content|
              object_link_filter(content, ref_pattern)
            end

          elsif element_node?(node)
105
            yield_valid_link(node) do |link, inner_html|
106
              if ref_pattern && link =~ /\A#{ref_pattern}\z/
107
                replace_link_node_with_href(node, link) do
108
                  object_link_filter(link, ref_pattern, link_content: inner_html)
109
110
111
112
113
114
115
                end

                next
              end

              next unless link_pattern

116
              if link == inner_html && inner_html =~ /\A#{link_pattern}/
117
                replace_link_node_with_text(node, link) do
118
                  object_link_filter(inner_html, link_pattern)
119
120
121
122
123
124
125
                end

                next
              end

              if link =~ /\A#{link_pattern}\z/
                replace_link_node_with_href(node, link) do
126
                  object_link_filter(link, link_pattern, link_content: inner_html)
127
                end
128

129
130
131
                next
              end
            end
132
          end
133
        end
134
135

        doc
136
137
138
139
140
141
      end

      # Replace references (like `!123` for merge requests) in text with links
      # to the referenced object's details page.
      #
      # text - String text to replace references in.
Douwe Maan's avatar
Douwe Maan committed
142
      # pattern - Reference pattern to match against.
143
      # link_content - Original content of the link being replaced.
144
145
146
      #
      # Returns a String with references replaced with links. All links
      # have `gfm` and `gfm-OBJECT_NAME` class names attached for styling.
147
      def object_link_filter(text, pattern, link_content: nil)
148
149
150
        references_in(text, pattern) do |match, id, project_ref, namespace_ref, matches|
          project_path = full_project_path(namespace_ref, project_ref)
          project = project_from_ref_cached(project_path)
151

152
          if project && object = find_object_cached(project, id)
Douwe Maan's avatar
Douwe Maan committed
153
            title = object_link_title(object)
154
            klass = reference_class(object_sym)
Douwe Maan's avatar
Douwe Maan committed
155

156
            data = data_attributes_for(link_content || match, project, object)
157

158
159
160
161
162
            if matches.names.include?("url") && matches[:url]
              url = matches[:url]
            else
              url = url_for_object_cached(object, project)
            end
163

164
            content = link_content || object_link_text(object, matches)
165
166

            %(<a href="#{url}" #{data}
Douwe Maan's avatar
Douwe Maan committed
167
                 title="#{escape_once(title)}"
168
                 class="#{klass}">#{content}</a>)
169
170
171
172
173
174
          else
            match
          end
        end
      end

175
176
177
178
179
180
181
182
      def data_attributes_for(text, project, object)
        data_attribute(
          original:     text,
          project:      project.id,
          object_sym => object.id
        )
      end

183
184
185
      def object_link_text_extras(object, matches)
        extras = []

186
        if matches.names.include?("anchor") && matches[:anchor] && matches[:anchor] =~ /\A\#note_(\d+)\z/
187
188
189
190
191
192
193
          extras << "comment #{$1}"
        end

        extras
      end

      def object_link_title(object)
194
        object.title
195
      end
Douwe Maan's avatar
Douwe Maan committed
196
197
198
199
200
201
202
203
204

      def object_link_text(object, matches)
        text = object.reference_link_text(context[:project])

        extras = object_link_text_extras(object, matches)
        text += " (#{extras.join(", ")})" if extras.any?

        text
      end
205

206
207
208
209
210
211
      # Returns a Hash containing all object references (e.g. issue IDs) per the
      # project they belong to.
      def references_per_project
        @references_per_project ||= begin
          refs = Hash.new { |hash, key| hash[key] = Set.new }

212
213
214
215
216
217
          regex =
            if uses_reference_pattern?
              Regexp.union(object_class.reference_pattern, object_class.link_reference_pattern)
            else
              object_class.link_reference_pattern
            end
218
219
220

          nodes.each do |node|
            node.to_html.scan(regex) do
221
              project_path = full_project_path($~[:namespace], $~[:project])
222
              symbol = $~[object_sym]
223
              refs[project_path] << symbol if object_class.reference_valid?(symbol)
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
            end
          end

          refs
        end
      end

      # Returns a Hash containing referenced projects grouped per their full
      # path.
      def projects_per_reference
        @projects_per_reference ||= begin
          hash = {}
          refs = Set.new

          references_per_project.each do |project_ref, _|
            refs << project_ref
          end

          find_projects_for_paths(refs.to_a).each do |project|
            hash[project.path_with_namespace] = project
          end

          hash
        end
      end

250
      def projects_relation_for_paths(paths)
251
252
253
        Project.where_paths_in(paths).includes(:namespace)
      end

254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
      # Returns projects for the given paths.
      def find_projects_for_paths(paths)
        if RequestStore.active?
          to_query = paths - project_refs_cache.keys

          unless to_query.empty?
            projects_relation_for_paths(to_query).each do |project|
              get_or_set_cache(project_refs_cache, project.path_with_namespace) { project }
            end
          end

          project_refs_cache.slice(*paths).values
        else
          projects_relation_for_paths(paths)
        end
      end

271
272
273
274
      def current_project_path
        @current_project_path ||= project.path_with_namespace
      end

275
276
277
278
      def current_project_namespace_path
        @current_project_namespace_path ||= project.namespace.path
      end

279
280
      private

281
282
283
284
285
286
287
      def full_project_path(namespace, project_ref)
        return current_project_path unless project_ref

        namespace_ref = namespace || current_project_namespace_path
        "#{namespace_ref}/#{project_ref}"
      end

288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
      def project_refs_cache
        RequestStore[:banzai_project_refs] ||= {}
      end

      def find_objects_cache
        RequestStore[:banzai_find_objects_cache] ||= Hash.new do |hash, key|
          hash[key] = Hash.new { |h, k| h[k] = {} }
        end
      end

      def url_for_object_cache
        RequestStore[:banzai_url_for_object] ||= Hash.new do |hash, key|
          hash[key] = Hash.new { |h, k| h[k] = {} }
        end
      end
303
304
305
306
307

      def get_or_set_cache(cache, key)
        if cache.key?(key)
          cache[key]
        else
308
309
310
          value = yield
          cache[key] = value if key.present?
          value
311
312
        end
      end
313
314
315
316
317
318
319
320

      # There might be special cases like filters
      # that should ignore reference pattern
      # eg: IssueReferenceFilter when using a external issues tracker
      # In those cases this method should be overridden on the filter subclass
      def uses_reference_pattern?
        true
      end
321
322
323
    end
  end
end