Menu

#421 Some EOL comments are not preserved

open
nobody
None
minor
bug
2023-05-06
2022-03-07
Jacob Floyd
No

These EOL comments disappear on round-trip (which I found while coming up with some tests for my ruamel.yaml-based re-formatter):

---
string_next_line: # EOL comment before string gets lost
  "this is a string bla bla
  more text"

# this is a comment
folded_block_scalar_with_octothorpe: > # > EOL comment gets lost
  # this is not a comment

# this is a comment
folded_chomp_strip_block_scalar_with_octothorpe: >- # > EOL comment gets lost
  # this is not a comment

# this is a comment
folded_chomp_keep_block_scalar_with_octothorpe: >+ # > EOL comment gets lost
  # this is not a comment

Discussion

  • Anthon van der Neut

    That first one is a known issue: you cannot have a comment between a key and its value.

    The other three I can only explain as that I did forget folded scalar comment handling when I implemented the handling for literal scalar. I am not sure though if I push an extra release for that.

     
  • Anthon van der Neut

    As I expected the last three only require minor changes, available in the handling of literal scalars with minor adjustments. They will be in 0.18 but if you can't wait it only affects two methods in emitter.py:

    --- a/emitter.py
    +++ b/emitter.py
    @@ -874,7 +874,11 @@
             elif self.style == "'":
                 self.write_single_quoted(self.analysis.scalar, split)
             elif self.style == '>':
    -            self.write_folded(self.analysis.scalar)
    +            try:
    +                cmx = self.event.comment[1][0]
    +            except (IndexError, TypeError):
    +                cmx = ""
    +            self.write_folded(self.analysis.scalar, cmx)
                 if (
                     self.event.comment
                     and self.event.comment[0]
    @@ -1440,9 +1444,11 @@
             hints += indicator
             return hints, indent, indicator
    
    -    def write_folded(self, text: Any) -> None:
    +    def write_folded(self, text: Any, comment: Any) -> None:
             hints, _indent, _indicator = self.determine_block_hints(text)
    -        self.write_indicator('>' + hints, True)
    +        if not isinstance(comment, str):
    +            comment = ''
    +        self.write_indicator('>' + hints + comment, True)
             if _indicator == '+':
                 self.open_ended = True
             self.write_line_break()
    
     
    ❤️
    1
  • Anthon van der Neut

    See e.g. 418 for a duplicate of the first issue

     
  • Anthon van der Neut

    The fix for folded scalars should be in 0.17.22+

     

Log in to post a comment.