BigW Consortium Gitlab

reference_extractor.rb 1.44 KB
Newer Older
1 2
module Gitlab
  # Extract possible GFM references from an arbitrary String for further processing.
3
  class ReferenceExtractor < Banzai::ReferenceExtractor
4
    REFERABLES = %i(user issue label milestone merge_request snippet commit commit_range)
5
    attr_accessor :project, :current_user, :author
6

7
    def initialize(project, current_user = nil, author = nil)
8
      @project = project
Douwe Maan committed
9
      @current_user = current_user
10
      @author = author
11

Douwe Maan committed
12
      @references = {}
13 14

      super()
15
    end
16

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

21
    REFERABLES.each do |type|
22
      define_method("#{type}s") do
23
        @references[type] ||= references(type, reference_context)
24
      end
25
    end
Drew Blessing committed
26 27 28

    def issues
      if project && project.jira_tracker?
29
        @references[:external_issue] ||= references(:external_issue, reference_context)
Drew Blessing committed
30
      else
31
        @references[:issue] ||= references(:issue, reference_context)
Drew Blessing committed
32 33
      end
    end
34

35 36 37 38 39
    def all
      REFERABLES.each { |referable| send(referable.to_s.pluralize) }
      @references.values.flatten
    end

40 41 42 43 44 45 46 47 48 49
    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

50 51 52 53 54
    private

    def reference_context
      { project: project, current_user: current_user, author: author }
    end
55 56
  end
end