BigW Consortium Gitlab

reference_extractor.rb 1.88 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
module Gitlab
  # Extract possible GFM references from an arbitrary String for further processing.
  class ReferenceExtractor
    attr_accessor :users, :issues, :merge_requests, :snippets, :commits

    include Markdown

    def initialize
      @users, @issues, @merge_requests, @snippets, @commits = [], [], [], [], []
    end

12 13
    def analyze(string, project)
      parse_references(string.dup, project)
14 15 16 17 18
    end

    # Given a valid project, resolve the extracted identifiers of the requested type to
    # model objects.

19
    def users_for(project)
20 21
      users.map do |entry|
        project.users.where(username: entry[:id]).first
22 23 24
      end.reject(&:nil?)
    end

25 26 27 28 29
    def issues_for(project = nil)
      issues.map do |entry|
        if should_lookup?(project, entry[:project])
          entry[:project].issues.where(iid: entry[:id]).first
        end
30 31 32
      end.reject(&:nil?)
    end

33 34 35 36 37
    def merge_requests_for(project = nil)
      merge_requests.map do |entry|
        if should_lookup?(project, entry[:project])
          entry[:project].merge_requests.where(iid: entry[:id]).first
        end
38 39 40
      end.reject(&:nil?)
    end

41
    def snippets_for(project)
42 43
      snippets.map do |entry|
        project.snippets.where(id: entry[:id]).first
44 45 46
      end.reject(&:nil?)
    end

47 48 49 50 51 52
    def commits_for(project = nil)
      commits.map do |entry|
        repo = entry[:project].repository if entry[:project]
        if should_lookup?(project, entry[:project])
          repo.commit(entry[:id]) if repo
        end
53 54 55 56 57
      end.reject(&:nil?)
    end

    private

58
    def reference_link(type, identifier, project, _)
59
      # Append identifier to the appropriate collection.
60 61 62 63 64 65 66 67 68
      send("#{type}s") << { project: project, id: identifier }
    end

    def should_lookup?(project, entry_project)
      if entry_project.nil?
        false
      else
        project.nil? || project.id == entry_project.id
      end
69 70 71
    end
  end
end