Skip to content

Commit e84e22d

Browse files
CyborgMasterctran
authored andcommitted
Keep the same whitespace when re-annotating a file (#573)
1 parent f1cae61 commit e84e22d

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

lib/annotate/annotate_models.rb

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -511,8 +511,6 @@ def annotate_one_file(file_name, info_block, position, options = {})
511511
old_columns = old_header && old_header.scan(column_pattern).sort
512512
new_columns = new_header && new_header.scan(column_pattern).sort
513513

514-
magic_comments_block = magic_comments_as_string(old_content)
515-
516514
if old_columns == new_columns && !options[:force]
517515
return false
518516
else
@@ -521,15 +519,12 @@ def annotate_one_file(file_name, info_block, position, options = {})
521519
wrapper_close = options[:wrapper_close] ? "# #{options[:wrapper_close]}\n" : ""
522520
wrapped_info_block = "#{wrapper_open}#{info_block}#{wrapper_close}"
523521

524-
new_content = old_content.sub(annotate_pattern(options), wrapped_info_block + "\n")
525-
526-
if new_content.end_with?(wrapped_info_block + "\n")
527-
new_content = old_content.sub(annotate_pattern(options), "\n" + wrapped_info_block)
528-
end
522+
old_annotation = old_content.match(annotate_pattern(options)).to_s
529523

530-
# if there *was* no old schema info (no substitution happened) or :force was passed,
531-
# we simply need to insert it in correct position
532-
if new_content == old_content || options[:force]
524+
# if there *was* no old schema info or :force was passed, we simply
525+
# need to insert it in correct position
526+
if old_annotation.empty? || options[:force]
527+
magic_comments_block = magic_comments_as_string(old_content)
533528
old_content.gsub!(magic_comment_matcher, '')
534529
old_content.sub!(annotate_pattern(options), '')
535530

@@ -538,6 +533,14 @@ def annotate_one_file(file_name, info_block, position, options = {})
538533
else
539534
magic_comments_block + wrapped_info_block + "\n" + old_content
540535
end
536+
else
537+
# replace the old annotation with the new one
538+
539+
# keep the surrounding whitespace the same
540+
space_match = old_annotation.match(/\A(?<start>\s*).*?\n(?<end>\s*)\z/m)
541+
new_annotation = space_match[:start] + wrapped_info_block + space_match[:end]
542+
543+
new_content = old_content.sub(annotate_pattern(options), new_annotation)
541544
end
542545

543546
File.open(file_name, 'wb') { |f| f.puts new_content }

0 commit comments

Comments
 (0)