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 in a given text.

Instance Method Summary collapse

Constructor Details

#initialize(text, source_project, _current_user) ⇒ UploadsRewriter

Returns a new instance of UploadsRewriter


11
12
13
14
15
# File 'lib/gitlab/gfm/uploads_rewriter.rb', line 11

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

Instance Method Details

#filesObject


34
35
36
37
38
39
40
# File 'lib/gitlab/gfm/uploads_rewriter.rb', line 34

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

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

#needs_rewrite?Boolean

Returns:

  • (Boolean)

30
31
32
# File 'lib/gitlab/gfm/uploads_rewriter.rb', line 30

def needs_rewrite?
  files.any?
end

#rewrite(target_project) ⇒ Object


17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/gitlab/gfm/uploads_rewriter.rb', line 17

def rewrite(target_project)
  return @text unless needs_rewrite?

  @text.gsub(@pattern) do |markdown|
    file = find_file(@source_project, $~[:secret], $~[:file])
    return markdown unless file.try(:exists?)

    new_uploader = FileUploader.new(target_project)
    new_uploader.store!(file)
    new_uploader.to_markdown
  end
end