Welcome to mirror list, hosted at ThFree Co, Russian Federation.

gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to 'lib/gitlab/github_import/representation/diff_notes/suggestion_formatter.rb')
-rw-r--r--lib/gitlab/github_import/representation/diff_notes/suggestion_formatter.rb66
1 files changed, 66 insertions, 0 deletions
diff --git a/lib/gitlab/github_import/representation/diff_notes/suggestion_formatter.rb b/lib/gitlab/github_import/representation/diff_notes/suggestion_formatter.rb
new file mode 100644
index 00000000000..4e5855ee4cd
--- /dev/null
+++ b/lib/gitlab/github_import/representation/diff_notes/suggestion_formatter.rb
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+# This class replaces Github markdown suggestion tag with
+# a Gitlab suggestion tag. The difference between
+# Github's and Gitlab's suggestion tags is that Gitlab
+# includes the range of the suggestion in the tag, while Github
+# uses other note attributes to position the suggestion.
+module Gitlab
+ module GithubImport
+ module Representation
+ module DiffNotes
+ class SuggestionFormatter
+ # A github suggestion:
+ # - the ```suggestion tag must be the first text of the line
+ # - it might have up to 3 spaces before the ```suggestion tag
+ # - extra text on the ```suggestion tag line will be ignored
+ GITHUB_SUGGESTION = /^\ {,3}(?<suggestion>```suggestion\b).*(?<eol>\R)/.freeze
+
+ def self.formatted_note_for(...)
+ new(...).formatted_note
+ end
+
+ def initialize(note:, start_line: nil, end_line: nil)
+ @note = note
+ @start_line = start_line
+ @end_line = end_line
+ end
+
+ def formatted_note
+ if contains_suggestion?
+ note.gsub(
+ GITHUB_SUGGESTION,
+ "\\k<suggestion>:#{suggestion_range}\\k<eol>"
+ )
+ else
+ note
+ end
+ end
+
+ private
+
+ attr_reader :note, :start_line, :end_line
+
+ def contains_suggestion?
+ note.to_s.match?(GITHUB_SUGGESTION)
+ end
+
+ # Github always saves the comment on the _last_ line of the range.
+ # Therefore, the diff hunk will always be related to lines before
+ # the comment itself.
+ def suggestion_range
+ "-#{line_count}+0"
+ end
+
+ def line_count
+ if start_line.present?
+ end_line - start_line
+ else
+ 0
+ end
+ end
+ end
+ end
+ end
+ end
+end