Class: Gitlab::Gfm::UploadsRewriter

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab/gfm/uploads_rewriter.rb

Overview

Class that rewrites markdown links for uploads

Using a pattern defined in `FileUploader` it copies files to a new project and rewrites all links to uploads in a given text.

Instance Method Summary collapse

Constructor Details

#initialize(text, source_project, _current_user) ⇒ UploadsRewriter

Returns a new instance of UploadsRewriter.


15
16
17
18
19
# File 'lib/gitlab/gfm/uploads_rewriter.rb', line 15

def initialize(text, source_project, _current_user)
  @text = text
  @source_project = source_project
  @pattern = FileUploader::MARKDOWN_PATTERN
end

Instance Method Details

#filesObject


49
50
51
52
53
54
55
# File 'lib/gitlab/gfm/uploads_rewriter.rb', line 49

def files
  referenced_files = @text.scan(@pattern).map do
    find_file($~[:secret], $~[:file])
  end

  referenced_files.compact.select(&:exists?)
end

#find_file(secret, file_name) ⇒ Object


61
62
63
# File 'lib/gitlab/gfm/uploads_rewriter.rb', line 61

def find_file(secret, file_name)
  UploaderFinder.new(@source_project, secret, file_name).execute
end

#needs_rewrite?Boolean

Returns:

  • (Boolean)

45
46
47
# File 'lib/gitlab/gfm/uploads_rewriter.rb', line 45

def needs_rewrite?
  files.any?
end

#rewrite(target_parent) ⇒ Object


21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/gitlab/gfm/uploads_rewriter.rb', line 21

def rewrite(target_parent)
  return @text unless needs_rewrite?

  @text.gsub(@pattern) do |markdown|
    file = find_file($~[:secret], $~[:file])
    # No file will be returned for a path traversal
    next if file.nil?

    break markdown unless file.try(:exists?)

    klass = target_parent.is_a?(Namespace) ? NamespaceFileUploader : FileUploader
    moved = klass.copy_to(file, target_parent)

    moved_markdown = moved.markdown_link

    # Prevents rewrite of plain links as embedded
    if was_embedded?(markdown)
      moved_markdown
    else
      moved_markdown.sub(/\A!/, "")
    end
  end
end

#was_embedded?(markdown) ⇒ Boolean

Returns:

  • (Boolean)

57
58
59
# File 'lib/gitlab/gfm/uploads_rewriter.rb', line 57

def was_embedded?(markdown)
  markdown.starts_with?("!")
end