markdown.rb 6.5 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 10 11 12
  #
  # Supported reference formats are:
  #   * @foo for team members
  #   * #123 for issues
  #   * !123 for merge requests
  #   * $123 for snippets
  #   * 123456 for commits
13
  #
14 15
  # It also parses Emoji codes to insert images. See
  # http://www.emoji-cheat-sheet.com/ for a list of the supported icons.
16
  #
17
  # Examples
18
  #
19
  #   >> gfm("Hey @david, can you fix this?")
M
Martin Bastien 已提交
20
  #   => "Hey <a href="/u/david">@david</a>, can you fix this?"
21
  #
22
  #   >> gfm("Commit 35d5f7c closes #1234")
23
  #   => "Commit <a href="/gitlab/commits/35d5f7c">35d5f7c</a> closes <a href="/gitlab/issues/1234">#1234</a>"
24 25 26 27
  #
  #   >> gfm(":trollface:")
  #   => "<img alt=\":trollface:\" class=\"emoji\" src=\"/images/trollface.png" title=\":trollface:\" />
  module Markdown
28 29
    include IssuesHelper

30 31
    attr_reader :html_options

32 33 34 35 36 37 38 39 40
    # 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?

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 58 59 60 61

      # TODO: add popups with additional information

      text = parse(text)

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

      sanitize text.html_safe, attributes: ActionView::Base.sanitized_allowed_attributes + %w(id class)
66 67
    end

68 69
    private

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

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

    def insert_piece(id)
      @extractions[id]
    end

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

      text
    end

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

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

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

        next unless type

C
Cyril 已提交
120
        identifier = $~[type]
121

122
        # Avoid HTML entities
C
Cyril 已提交
123
        if prefix && suffix && prefix[0] == '&' && suffix[-1] == ';'
124
          match
C
Cyril 已提交
125 126
        elsif ref_link = reference_link(type, identifier)
          "#{prefix}#{ref_link}#{suffix}"
127 128 129
        else
          match
        end
130 131
      end
    end
132

133 134
    EMOJI_PATTERN = %r{(:(\S+):)}.freeze

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

146 147 148 149 150 151
    # 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 已提交
152
      Emoji.names.include? emoji
153
    end
154 155 156 157 158 159 160

    # 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 已提交
161 162
    def reference_link(type, identifier)
      send("reference_#{type}", identifier)
163 164 165
    end

    def reference_user(identifier)
C
Cyril 已提交
166
      if member = @project.users_projects.joins(:user).where(users: { username: identifier }).first
M
Martin Bastien 已提交
167
        link_to("@#{identifier}", user_path(identifier), html_options.merge(class: "gfm gfm-team_member #{html_options[:class]}")) if member
168 169 170 171
      end
    end

    def reference_issue(identifier)
172
      if @project.issue_exists? identifier
173 174 175 176
        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]}"))
177 178 179 180 181
      end
    end

    def reference_merge_request(identifier)
      if merge_request = @project.merge_requests.where(id: identifier).first
182
        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]}"))
183 184 185 186 187
      end
    end

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

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