diff --git a/lib/annotate/annotate_models.rb b/lib/annotate/annotate_models.rb index 1b9911ee3..2958abcaa 100644 --- a/lib/annotate/annotate_models.rb +++ b/lib/annotate/annotate_models.rb @@ -43,10 +43,21 @@ module AnnotateModels class << self def annotate_pattern(options = {}) - if options[:wrapper_open] - return /(?:^(\n|\r\n)?# (?:#{options[:wrapper_open]}).*(\n|\r\n)?# (?:#{COMPAT_PREFIX}|#{COMPAT_PREFIX_MD}).*?(\n|\r\n)(#.*(\n|\r\n))*(\n|\r\n)*)|^(\n|\r\n)?# (?:#{COMPAT_PREFIX}|#{COMPAT_PREFIX_MD}).*?(\n|\r\n)(#.*(\n|\r\n))*(\n|\r\n)*/ - end - /^(\n|\r\n)?# (?:#{COMPAT_PREFIX}|#{COMPAT_PREFIX_MD}).*?(\n|\r\n)(#.*(\n|\r\n))*(\n|\r\n)*/ + nl = '(?:\n|\r\n)' + wrapper_pattern = + if options[:wrapper_open] + wrapper_open = options[:wrapper_open] + "(?:# (?:#{wrapper_open}).*#{nl}?)?" + else + '' + end + annotation_pattern = [ + wrapper_pattern, + "# (?:#{COMPAT_PREFIX}|#{COMPAT_PREFIX_MD}).*?#{nl}", + "(?:#.*#{nl})*", + "#{nl}*" + ].join('') + /(?:#{annotation_pattern})|(?:^#{nl}?#{annotation_pattern}\z)/ end def model_dir diff --git a/spec/lib/annotate/annotate_models_spec.rb b/spec/lib/annotate/annotate_models_spec.rb index e2d6f41ab..f9deff594 100644 --- a/spec/lib/annotate/annotate_models_spec.rb +++ b/spec/lib/annotate/annotate_models_spec.rb @@ -2439,6 +2439,43 @@ class Foo < ActiveRecord::Base expect(file_content_after_removal).to eq expected_result end end + + context 'when annotation is before main content and there is a magic comment' do + let :filename do + 'before_with_extra_comment.rb' + end + + let :file_content do + <<~EOS + # frozen_string_literal: true + + # == Schema Information + # + # Table name: foo + # + # id :integer not null, primary key + # created_at :datetime + # updated_at :datetime + # + + class Foo < ActiveRecord::Base + end + EOS + end + + let :expected_result do + <<~EOS + # frozen_string_literal: true + + class Foo < ActiveRecord::Base + end + EOS + end + + it 'removes annotation but not removes leading empty lines' do + expect(file_content_after_removal).to eq expected_result + end + end end describe '.resolve_filename' do