markdown.rb 7.8 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
    # Public: Parse the provided text with GitLab-Flavored Markdown
    #
    # text         - the source text
S
skv 已提交
36
    # project      - extra options for the reference links as given to link_to
37
    # html_options - extra options for the reference links as given to link_to
S
skv 已提交
38
    def gfm(text, project = @project, html_options = {})
39 40
      return text if text.nil?

41 42 43 44
      # 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
45

46
      @html_options = html_options
47 48 49

      # Extract pre blocks so they are not altered
      # from http://github.github.com/github-flavored-markdown/
50 51 52 53 54
      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) }
55 56 57

      # TODO: add popups with additional information

S
skv 已提交
58
      text = parse(text, project)
59 60 61

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

S
skv 已提交
65 66 67 68 69 70
      allowed_attributes = ActionView::Base.sanitized_allowed_attributes
      allowed_tags = ActionView::Base.sanitized_allowed_tags

      sanitize text.html_safe,
               attributes: allowed_attributes + %w(id class),
               tags: allowed_tags + %w(table tr td th)
71 72
    end

73 74
    private

75 76 77 78 79 80 81 82 83 84 85 86
    def extract_piece(text)
      @extractions ||= {}

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

    def insert_piece(id)
      @extractions[id]
    end

87 88 89 90 91
    # Private: Parses text for references and emoji
    #
    # text - Text to parse
    #
    # Returns parsed text
S
skv 已提交
92 93
    def parse(text, project = @project)
      parse_references(text, project) if project
94 95 96 97 98
      parse_emoji(text)

      text
    end

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

113 114
    TYPES = [:user, :issue, :merge_request, :snippet, :commit].freeze

S
skv 已提交
115
    def parse_references(text, project = @project)
116
      # parse reference links
117
      text.gsub!(REFERENCE_PATTERN) do |match|
C
Cyril 已提交
118 119 120
        prefix     = $~[:prefix]
        suffix     = $~[:suffix]
        type       = TYPES.select{|t| !$~[t].nil?}.first
121

122 123 124 125 126 127
        if type
          identifier = $~[type]

          # Avoid HTML entities
          if prefix && suffix && prefix[0] == '&' && suffix[-1] == ';'
            match
S
skv 已提交
128
          elsif ref_link = reference_link(type, identifier, project)
129 130 131 132
            "#{prefix}#{ref_link}#{suffix}"
          else
            match
          end
133 134 135
        else
          match
        end
136 137
      end
    end
138

139 140
    EMOJI_PATTERN = %r{(:(\S+):)}.freeze

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

152 153 154 155 156 157
    # 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)
S
skv 已提交
158
      Emoji.find_by_name(emoji)
159
    end
160 161 162 163 164 165 166

    # 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
S
skv 已提交
167 168
    def reference_link(type, identifier, project = @project)
      send("reference_#{type}", identifier, project)
169 170
    end

S
skv 已提交
171
    def reference_user(identifier, project = @project)
172
      options = html_options.merge(
173 174
          class: "gfm gfm-team_member #{html_options[:class]}"
        )
175 176

      if identifier == "all"
177 178
        link_to("@all", project_url(project), options)
      elsif user = User.find_by(username: identifier)
S
skv 已提交
179
        link_to("@#{identifier}", user_url(identifier), options)
180 181 182
      end
    end

S
skv 已提交
183 184 185 186
    def reference_issue(identifier, project = @project)
      if project.used_default_issues_tracker? || !external_issues_tracker_enabled?
        if project.issue_exists? identifier
          url = url_for_issue(identifier, project)
187
          title = title_for_issue(identifier)
S
skv 已提交
188 189 190 191
          options = html_options.merge(
            title: "Issue: #{title}",
            class: "gfm gfm-issue #{html_options[:class]}"
          )
192

S
skv 已提交
193
          link_to("##{identifier}", url, options)
194
        end
S
skv 已提交
195 196
      elsif project.issues_tracker == 'jira'
        reference_jira_issue(identifier, project)
197 198 199
      end
    end

S
skv 已提交
200 201 202 203 204 205 206 207
    def reference_merge_request(identifier, project = @project)
      if merge_request = project.merge_requests.find_by(iid: identifier)
        options = html_options.merge(
          title: "Merge Request: #{merge_request.title}",
          class: "gfm gfm-merge_request #{html_options[:class]}"
        )
        url = project_merge_request_url(project, merge_request)
        link_to("!#{identifier}", url, options)
208 209 210
      end
    end

S
skv 已提交
211 212 213 214 215 216 217 218
    def reference_snippet(identifier, project = @project)
      if snippet = project.snippets.find_by(id: identifier)
        options = html_options.merge(
          title: "Snippet: #{snippet.title}",
          class: "gfm gfm-snippet #{html_options[:class]}"
        )
        link_to("$#{identifier}", project_snippet_url(project, snippet),
                options)
219 220 221
      end
    end

S
skv 已提交
222 223 224 225 226 227 228
    def reference_commit(identifier, project = @project)
      if project.valid_repo? && commit = project.repository.commit(identifier)
        options = html_options.merge(
          title: commit.link_title,
          class: "gfm gfm-commit #{html_options[:class]}"
        )
        link_to(identifier, project_commit_url(project, commit), options)
229 230
      end
    end
231

S
skv 已提交
232
    def reference_jira_issue(identifier, project = @project)
233
      url = url_for_issue(identifier)
234
      title = Gitlab.config.issues_tracker[project.issues_tracker]["title"]
235

S
skv 已提交
236 237 238 239 240
      options = html_options.merge(
        title: "Issue in #{title}",
        class: "gfm gfm-issue #{html_options[:class]}"
      )
      link_to("#{identifier}", url, options)
241
    end
242 243
  end
end