44from enum import Enum
55from typing import Any
66
7- from ruamel .yaml import YAML , CommentToken , StreamMark
7+ from ruamel .yaml import YAML , CommentedSeq , CommentToken , StreamMark
88from ruamel .yaml .comments import CommentedMap
99
1010from serena .constants import SERENA_FILE_ENCODING
@@ -122,6 +122,20 @@ def trailing_to_leading(comment_entry: Any) -> Any:
122122 first_token .value = first_token .value [1 :]
123123 return token_list
124124
125+ def remove_nested_comments () -> None :
126+ """
127+ Removes nested comments, particularly of sequences, which incorrectly capture comments
128+ that are actually intended for top-level keys.
129+ """
130+ for key in commented_map .keys ():
131+ entry = commented_map [key ]
132+ if isinstance (entry , CommentedSeq ):
133+ items = entry .ca .items
134+ if isinstance (items , dict ):
135+ items_keys = list (items .keys ())
136+ for i in items_keys :
137+ items [i ] = [None ] * 4
138+
125139 match comment_normalisation :
126140 case YamlCommentNormalisation .NONE :
127141 pass
@@ -176,6 +190,9 @@ def trailing_to_leading(comment_entry: Any) -> Any:
176190 preceding_comment [ITEM_COMMENT_INDEX_BEFORE ] = token_list
177191 current_comment [ITEM_COMMENT_INDEX_BEFORE ] = None
178192 preceding_comment = current_comment
193+
194+ # remove nested comments, as we assume that only top-level keys are supposed to be commented
195+ remove_nested_comments ()
179196 case _:
180197 raise ValueError (f"Unhandled comment normalisation: { comment_normalisation } " )
181198
@@ -204,7 +221,7 @@ def yaml_comment_entry_is_empty(comment_entry: Any) -> bool:
204221 return False
205222
206223
207- def transfer_missing_yaml_comments_by_index (
224+ def transfer_yaml_comments_by_index (
208225 source : CommentedMap , target : CommentedMap , indices : list [int ], forced_update_keys : Sequence [str ] = (), force_update_all : bool = False
209226) -> None :
210227 """
@@ -231,7 +248,7 @@ def transfer_missing_yaml_comments_by_index(
231248 target_comment [index ] = source_comment [index ]
232249
233250
234- def transfer_missing_yaml_comments (
251+ def transfer_yaml_comments (
235252 source : CommentedMap ,
236253 target : CommentedMap ,
237254 comment_normalisation : YamlCommentNormalisation ,
@@ -251,7 +268,7 @@ def transfer_missing_yaml_comments(
251268 case YamlCommentNormalisation .NONE :
252269 pass
253270 case YamlCommentNormalisation .LEADING | YamlCommentNormalisation .LEADING_WITH_CONVERSION_FROM_TRAILING :
254- transfer_missing_yaml_comments_by_index (
271+ transfer_yaml_comments_by_index (
255272 source , target , [ITEM_COMMENT_INDEX_BEFORE ], forced_update_keys = forced_update_keys , force_update_all = force_update_all
256273 )
257274 case _:
0 commit comments