Skip to content

Commit d1e7621

Browse files
author
Matteo La Cognata
committed
Update annotate_models.rb
Add Sorbet comment matcher
1 parent ae0b79c commit d1e7621

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

lib/annotate/annotate_models.rb

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ module AnnotateModels
4040
}.freeze
4141

4242
MAGIC_COMMENT_MATCHER = Regexp.new(/(^#\s*encoding:.*(?:\n|r\n))|(^# coding:.*(?:\n|\r\n))|(^# -\*- coding:.*(?:\n|\r\n))|(^# -\*- encoding\s?:.*(?:\n|\r\n))|(^#\s*frozen_string_literal:.+(?:\n|\r\n))|(^# -\*- frozen_string_literal\s*:.+-\*-(?:\n|\r\n))/).freeze
43+
SORBET_COMMENT_MATCHER = Regexp.new(/(^#\s*typed:.*(?:\n|r\n))/).freeze
4344

4445
class << self
4546
def annotate_pattern(options = {})
@@ -394,15 +395,17 @@ def annotate_one_file(file_name, info_block, position, options = {})
394395
# need to insert it in correct position
395396
if old_annotation.empty? || options[:force]
396397
magic_comments_block = magic_comments_as_string(old_content)
398+
sorbet_comments_block = sorbet_comments_as_string(old_content)
397399
old_content.gsub!(MAGIC_COMMENT_MATCHER, '')
400+
old_content.gsub!(SORBET_COMMENT_MATCHER, '')
398401
old_content.sub!(annotate_pattern(options), '')
399402

400403
new_content = if %w(after bottom).include?(options[position].to_s)
401-
magic_comments_block + (old_content.rstrip + "\n\n" + wrapped_info_block)
402-
elsif magic_comments_block.empty?
403-
magic_comments_block + wrapped_info_block + old_content.lstrip
404+
magic_comments_block + sorbet_comments_block + (old_content.rstrip + "\n\n" + wrapped_info_block)
405+
elsif magic_comments_block.blank?
406+
sorbet_comments_block + (sorbet_comments_block.blank? ? '' : "\n") + wrapped_info_block + old_content.lstrip
404407
else
405-
magic_comments_block + "\n" + wrapped_info_block + old_content.lstrip
408+
magic_comments_block + sorbet_comments_block + "\n" + wrapped_info_block + old_content.lstrip
406409
end
407410
else
408411
# replace the old annotation with the new one
@@ -428,6 +431,16 @@ def magic_comments_as_string(content)
428431
end
429432
end
430433

434+
def sorbet_comments_as_string(content)
435+
sorbet_comments = content.scan(SORBET_COMMENT_MATCHER).flatten.compact
436+
437+
if sorbet_comments.any?
438+
sorbet_comments.join
439+
else
440+
''
441+
end
442+
end
443+
431444
def remove_annotation_of_file(file_name, options = {})
432445
if File.exist?(file_name)
433446
content = File.read(file_name)

0 commit comments

Comments
 (0)