@@ -511,8 +511,6 @@ def annotate_one_file(file_name, info_block, position, options = {})
511
511
old_columns = old_header && old_header . scan ( column_pattern ) . sort
512
512
new_columns = new_header && new_header . scan ( column_pattern ) . sort
513
513
514
- magic_comments_block = magic_comments_as_string ( old_content )
515
-
516
514
if old_columns == new_columns && !options [ :force ]
517
515
return false
518
516
else
@@ -521,15 +519,12 @@ def annotate_one_file(file_name, info_block, position, options = {})
521
519
wrapper_close = options [ :wrapper_close ] ? "# #{ options [ :wrapper_close ] } \n " : ""
522
520
wrapped_info_block = "#{ wrapper_open } #{ info_block } #{ wrapper_close } "
523
521
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
529
523
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 )
533
528
old_content . gsub! ( magic_comment_matcher , '' )
534
529
old_content . sub! ( annotate_pattern ( options ) , '' )
535
530
@@ -538,6 +533,14 @@ def annotate_one_file(file_name, info_block, position, options = {})
538
533
else
539
534
magic_comments_block + wrapped_info_block + "\n " + old_content
540
535
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 )
541
544
end
542
545
543
546
File . open ( file_name , 'wb' ) { |f | f . puts new_content }
0 commit comments