Skip to content

Commit e530e17

Browse files
committed
Do not delete leading empty lines
Source code may have magic comments. ``` # 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 ``` In this case, the blank line before the annotation should not be erased by `annotate --delete`. Expected: ``` # frozen_string_literal: true class Foo < ActiveRecord::Base end ``` But actual: ``` # frozen_string_literal: true class Foo < ActiveRecord::Base end ``` This change fixes it.
1 parent 9099c62 commit e530e17

File tree

2 files changed

+52
-4
lines changed

2 files changed

+52
-4
lines changed

lib/annotate/annotate_models.rb

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,21 @@ module AnnotateModels
4343

4444
class << self
4545
def annotate_pattern(options = {})
46-
if options[:wrapper_open]
47-
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)*/
48-
end
49-
/^(\n|\r\n)?# (?:#{COMPAT_PREFIX}|#{COMPAT_PREFIX_MD}).*?(\n|\r\n)(#.*(\n|\r\n))*(\n|\r\n)*/
46+
nl = '(?:\n|\r\n)'
47+
wrapper_pattern =
48+
if options[:wrapper_open]
49+
wrapper_open = options[:wrapper_open]
50+
"(?:# (?:#{wrapper_open}).*#{nl}?)?"
51+
else
52+
''
53+
end
54+
annotation_pattern = [
55+
wrapper_pattern,
56+
"# (?:#{COMPAT_PREFIX}|#{COMPAT_PREFIX_MD}).*?#{nl}",
57+
"(?:#.*#{nl})*",
58+
"#{nl}*"
59+
].join('')
60+
/(?:#{annotation_pattern})|(?:^#{nl}?#{annotation_pattern}\z)/
5061
end
5162

5263
def model_dir

spec/lib/annotate/annotate_models_spec.rb

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2439,6 +2439,43 @@ class Foo < ActiveRecord::Base
24392439
expect(file_content_after_removal).to eq expected_result
24402440
end
24412441
end
2442+
2443+
context 'when annotation is before main content and there is a magic comment' do
2444+
let :filename do
2445+
'before_with_extra_comment.rb'
2446+
end
2447+
2448+
let :file_content do
2449+
<<~EOS
2450+
# frozen_string_literal: true
2451+
2452+
# == Schema Information
2453+
#
2454+
# Table name: foo
2455+
#
2456+
# id :integer not null, primary key
2457+
# created_at :datetime
2458+
# updated_at :datetime
2459+
#
2460+
2461+
class Foo < ActiveRecord::Base
2462+
end
2463+
EOS
2464+
end
2465+
2466+
let :expected_result do
2467+
<<~EOS
2468+
# frozen_string_literal: true
2469+
2470+
class Foo < ActiveRecord::Base
2471+
end
2472+
EOS
2473+
end
2474+
2475+
it 'removes annotation but not removes leading empty lines' do
2476+
expect(file_content_after_removal).to eq expected_result
2477+
end
2478+
end
24422479
end
24432480

24442481
describe '.resolve_filename' do

0 commit comments

Comments
 (0)