preview_markdown_service.rb 1.72 KB
Newer Older
1 2
# frozen_string_literal: true

3 4
class PreviewMarkdownService < BaseService
  def execute
5
    text, commands = explain_quick_actions(params[:text])
6
    users = find_user_references(text)
7
    suggestions = find_suggestions(text)
8 9 10 11

    success(
      text: text,
      users: users,
12
      suggestions: suggestions,
13
      commands: commands.join(' ')
14 15 16 17 18
    )
  end

  private

19
  def explain_quick_actions(text)
Oswaldo Ferreira's avatar
Oswaldo Ferreira committed
20
    return text, [] unless %w(Issue MergeRequest Commit).include?(target_type)
21

22 23
    quick_actions_service = QuickActions::InterpretService.new(project, current_user)
    quick_actions_service.explain(text, find_commands_target)
24 25 26 27 28 29 30 31
  end

  def find_user_references(text)
    extractor = Gitlab::ReferenceExtractor.new(project, current_user)
    extractor.analyze(text, author: current_user)
    extractor.users.map(&:username)
  end

32
  def find_suggestions(text)
Oswaldo Ferreira's avatar
Oswaldo Ferreira committed
33
    return [] unless preview_sugestions?
34

Oswaldo Ferreira's avatar
Oswaldo Ferreira committed
35 36 37 38 39 40 41 42 43 44 45 46 47
    position = Gitlab::Diff::Position.new(new_path: params[:file_path],
                                          new_line: params[:line].to_i,
                                          base_sha: params[:base_sha],
                                          head_sha: params[:head_sha],
                                          start_sha: params[:start_sha])

    Gitlab::Diff::SuggestionsParser.parse(text, position: position, project: project)
  end

  def preview_sugestions?
    params[:preview_suggestions] &&
      target_type == 'MergeRequest' &&
      Ability.allowed?(current_user, :download_code, project)
48 49
  end

50
  def find_commands_target
51
    QuickActions::TargetService
52
      .new(project, current_user)
Oswaldo Ferreira's avatar
Oswaldo Ferreira committed
53
      .execute(target_type, target_id)
54 55
  end

Oswaldo Ferreira's avatar
Oswaldo Ferreira committed
56 57
  def target_type
    params[:target_type]
58 59
  end

Oswaldo Ferreira's avatar
Oswaldo Ferreira committed
60 61
  def target_id
    params[:target_id]
62 63
  end
end