summaryrefslogtreecommitdiff
path: root/lib/gitlab/reference_extractor.rb
blob: 11c0b01f0dc06b53f9b94d7a2c443f39ef727a80 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
module Gitlab
  # Extract possible GFM references from an arbitrary String for further processing.
  class ReferenceExtractor < Banzai::ReferenceExtractor
    REFERABLES = %i(user issue label milestone merge_request snippet commit commit_range)
    attr_accessor :project, :current_user, :author

    def initialize(project, current_user = nil)
      @project = project
      @current_user = current_user

      @references = {}

      super()
    end

    def analyze(text, context = {})
      super(text, context.merge(project: project))
    end

    def references(type)
      super(type, project, current_user)
    end

    REFERABLES.each do |type|
      define_method("#{type}s") do
        @references[type] ||= references(type)
      end
    end

    def issues
      if project && project.jira_tracker?
        @references[:external_issue] ||= references(:external_issue)
      else
        @references[:issue] ||= references(:issue)
      end
    end

    def all
      REFERABLES.each { |referable| send(referable.to_s.pluralize) }
      @references.values.flatten
    end

    def self.references_pattern
      return @pattern if @pattern

      patterns = REFERABLES.map do |ref|
        ref.to_s.classify.constantize.try(:reference_pattern)
      end

      @pattern = Regexp.union(patterns.compact)
    end
  end
end