From 5733bdb7c7ccd59f63a3500882d22ebdcf822fe1 Mon Sep 17 00:00:00 2001 From: Robert Speicher Date: Fri, 29 May 2015 01:56:30 -0400 Subject: Fix link_to_gfm with only a reference having the incorrect link Closes #1721 --- app/helpers/gitlab_markdown_helper.rb | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) (limited to 'app/helpers') diff --git a/app/helpers/gitlab_markdown_helper.rb b/app/helpers/gitlab_markdown_helper.rb index d89f7b4a28d..3c207619adf 100644 --- a/app/helpers/gitlab_markdown_helper.rb +++ b/app/helpers/gitlab_markdown_helper.rb @@ -1,3 +1,5 @@ +require 'nokogiri' + module GitlabMarkdownHelper include Gitlab::Markdown @@ -21,11 +23,22 @@ module GitlabMarkdownHelper gfm_body = gfm(escaped_body, {}, html_options) - gfm_body.gsub!(%r{.*?}m) do |match| - "#{match}#{link_to("", url, html_options)[0..-5]}" # "".length +1 + fragment = Nokogiri::XML::DocumentFragment.parse(gfm_body) + if fragment.children.size == 1 && fragment.children[0].name == 'a' + # Fragment has only one node, and it's a link generated by `gfm`. + # Replace it with our requested link. + text = fragment.children[0].text + fragment.children[0].replace(link_to(text, url, html_options)) + else + # Traverse the fragment's first generation of children looking for pure + # text, wrapping anything found in the requested link + fragment.children.each do |node| + next unless node.text? + node.replace(link_to(node.text, url, html_options)) + end end - link_to(gfm_body.html_safe, url, html_options) + fragment.to_html.html_safe end def markdown(text, options={}) -- cgit v1.2.3