markdown.rb 6.6 KB
Newer Older
1
module Gitlab
2
  # Custom parser for GitLab-flavored Markdown
3
  #
4
  # It replaces references in the text with links to the appropriate items in
5
  # GitLab.
6 7 8 9
  #
  # Supported reference formats are:
  #   * @foo for team members
  #   * #123 for issues
10
  #   * #JIRA-123 for Jira issues
11 12 13
  #   * !123 for merge requests
  #   * $123 for snippets
  #   * 123456 for commits
14
  #
15 16
  # It also parses Emoji codes to insert images. See
  # http://www.emoji-cheat-sheet.com/ for a list of the supported icons.
17
  #
18
  # Examples
19
  #
20
  #   >> gfm("Hey @david, can you fix this?")
M
Martin Bastien 已提交
21
  #   => "Hey <a href="/u/david">@david</a>, can you fix this?"
22
  #
23
  #   >> gfm("Commit 35d5f7c closes #1234")
24
  #   => "Commit <a href="/gitlab/commits/35d5f7c">35d5f7c</a> closes <a href="/gitlab/issues/1234">#1234</a>"
25 26 27 28
  #
  #   >> gfm(":trollface:")
  #   => "<img alt=\":trollface:\" class=\"emoji\" src=\"/images/trollface.png" title=\":trollface:\" />
  module Markdown
29 30
    include IssuesHelper

31 32
    attr_reader :html_options

33 34 35 36 37 38 39 40 41
    # Public: Parse the provided text with GitLab-Flavored Markdown
    #
    # text         - the source text
    # html_options - extra options for the reference links as given to link_to
    #
    # Note: reference links will only be generated if @project is set
    def gfm(text, html_options = {})
      return text if text.nil?

42 43 44 45
      # Duplicate the string so we don't alter the original, then call to_str
      # to cast it back to a String instead of a SafeBuffer. This is required
      # for gsub calls to work as we need them to.
      text = text.dup.to_str
46

47
      @html_options = html_options
48 49 50

      # Extract pre blocks so they are not altered
      # from http://github.github.com/github-flavored-markdown/
51 52 53 54 55
      text.gsub!(%r{<pre>.*?</pre>|<code>.*?</code>}m) { |match| extract_piece(match) }
      # Extract links with probably parsable hrefs
      text.gsub!(%r{<a.*?>.*?</a>}m) { |match| extract_piece(match) }
      # Extract images with probably parsable src
      text.gsub!(%r{<img.*?>}m) { |match| extract_piece(match) }
56 57 58 59 60 61 62

      # TODO: add popups with additional information

      text = parse(text)

      # Insert pre block extractions
      text.gsub!(/\{gfm-extraction-(\h{32})\}/) do
63
        insert_piece($1)
64 65
      end

D
Dmitriy Zaporozhets 已提交
66
      sanitize text.html_safe, attributes: ActionView::Base.sanitized_allowed_attributes + %w(id class), tags: ActionView::Base.sanitized_allowed_tags + %w(table tr td th)
67 68
    end

69 70
    private

71 72 73 74 75 76 77 78 79 80 81 82
    def extract_piece(text)
      @extractions ||= {}

      md5 = Digest::MD5.hexdigest(text)
      @extractions[md5] = text
      "{gfm-extraction-#{md5}}"
    end

    def insert_piece(id)
      @extractions[id]
    end

83 84 85 86
    # Private: Parses text for references and emoji
    #
    # text - Text to parse
    #
87 88
    # Note: reference links will only be generated if @project is set
    #
89
    # Returns parsed text
90
    def parse(text)
91 92 93 94 95 96
      parse_references(text) if @project
      parse_emoji(text)

      text
    end

97
    REFERENCE_PATTERN = %r{
98 99 100
      (?<prefix>\W)?                         # Prefix
      (                                      # Reference
         @(?<user>[a-zA-Z][a-zA-Z0-9_\-\.]*) # User name
101
        |\#(?<issue>([a-zA-Z]+-)?\d+)        # Issue ID
102 103 104
        |!(?<merge_request>\d+)              # MR ID
        |\$(?<snippet>\d+)                   # Snippet ID
        |(?<commit>[\h]{6,40})               # Commit ID
105
        |(?<skip>gfm-extraction-[\h]{6,40})  # Skip gfm extractions. Otherwise will be parsed as commit
106
      )
107
      (?<suffix>\W)?                         # Suffix
108 109
    }x.freeze

110 111
    TYPES = [:user, :issue, :merge_request, :snippet, :commit].freeze

112
    def parse_references(text)
113
      # parse reference links
114
      text.gsub!(REFERENCE_PATTERN) do |match|
C
Cyril 已提交
115 116 117
        prefix     = $~[:prefix]
        suffix     = $~[:suffix]
        type       = TYPES.select{|t| !$~[t].nil?}.first
118

119 120 121 122 123 124 125 126 127 128 129
        if type
          identifier = $~[type]

          # Avoid HTML entities
          if prefix && suffix && prefix[0] == '&' && suffix[-1] == ';'
            match
          elsif ref_link = reference_link(type, identifier)
            "#{prefix}#{ref_link}#{suffix}"
          else
            match
          end
130 131 132
        else
          match
        end
133 134
      end
    end
135

136 137
    EMOJI_PATTERN = %r{(:(\S+):)}.freeze

138
    def parse_emoji(text)
139
      # parse emoji
140
      text.gsub!(EMOJI_PATTERN) do |match|
141
        if valid_emoji?($2)
142
          image_tag(url_to_image("emoji/#{$2}.png"), class: 'emoji', title: $1, alt: $1, size: "20x20")
143 144 145 146
        else
          match
        end
      end
147 148
    end

149 150 151 152 153 154
    # Private: Checks if an emoji icon exists in the image asset directory
    #
    # emoji - Identifier of the emoji as a string (e.g., "+1", "heart")
    #
    # Returns boolean
    def valid_emoji?(emoji)
R
Riyad Preukschas 已提交
155
      Emoji.names.include? emoji
156
    end
157 158 159 160 161 162 163

    # Private: Dispatches to a dedicated processing method based on reference
    #
    # reference  - Object reference ("@1234", "!567", etc.)
    # identifier - Object identifier (Issue ID, SHA hash, etc.)
    #
    # Returns string rendered by the processing method
C
Cyril 已提交
164 165
    def reference_link(type, identifier)
      send("reference_#{type}", identifier)
166 167 168
    end

    def reference_user(identifier)
169
      if member = @project.team_members.find { |user| user.username == identifier }
170
        link_to("@#{identifier}", user_url(identifier), html_options.merge(class: "gfm gfm-team_member #{html_options[:class]}")) if member
171 172 173 174
      end
    end

    def reference_issue(identifier)
175
      if @project.issue_exists? identifier
176 177 178 179
        url = url_for_issue(identifier)
        title = title_for_issue(identifier)

        link_to("##{identifier}", url, html_options.merge(title: "Issue: #{title}", class: "gfm gfm-issue #{html_options[:class]}"))
180 181 182 183
      end
    end

    def reference_merge_request(identifier)
184
      if merge_request = @project.merge_requests.where(iid: identifier).first
185
        link_to("!#{identifier}", project_merge_request_url(@project, merge_request), html_options.merge(title: "Merge Request: #{merge_request.title}", class: "gfm gfm-merge_request #{html_options[:class]}"))
186 187 188 189 190
      end
    end

    def reference_snippet(identifier)
      if snippet = @project.snippets.where(id: identifier).first
191
        link_to("$#{identifier}", project_snippet_url(@project, snippet), html_options.merge(title: "Snippet: #{snippet.title}", class: "gfm gfm-snippet #{html_options[:class]}"))
192 193 194 195
      end
    end

    def reference_commit(identifier)
196
      if @project.valid_repo? && commit = @project.repository.commit(identifier)
197
        link_to(identifier, project_commit_url(@project, commit), html_options.merge(title: commit.link_title, class: "gfm gfm-commit #{html_options[:class]}"))
198 199 200 201
      end
    end
  end
end