Skip to content

Inconsistent comment spacing when dumping YAML with yaml_add_eol_comment #116

@lyz-code

Description

@lyz-code

I'm experiencing inconsistent comment spacing when using yaml_add_eol_comment with ruyaml. Specifically, the issue arises when adding end-of-line comments to YAML keys. Sometimes, the comment is not properly spaced, which can lead to formatting issues.

Steps to Reproduce:

Here's a minimal reproducible example:

from io import StringIO
from ruyaml import YAML
from textwrap import dedent

def check_comment_spacing() -> None:
    """Check for comment spacing issue in ruyaml."""
    print("Starting check for comment spacing issue.")
    yaml = YAML()

    source = dedent(
        """
        parent:
            child1: value1
            child2: value2
            child3: value3
        """
    )

    # Load YAML content
    data = yaml.load(source)

    # Add comments
    data["parent"].yaml_add_eol_comment(key="child3", comment="this is a comment")
    data["parent"].yaml_add_eol_comment(key="child2", comment="this is a comment")
    data["parent"].yaml_add_eol_comment(key="child1", comment="this is a comment")


    # Dump to a string
    string_stream = StringIO()
    yaml.dump(data, string_stream)
    source_code = string_stream.getvalue()
    string_stream.close()

    # Assert that there are two spaces between the value and the comment
    assert "value2  # this is a comment" in source_code, "Comment spacing issue detected!"
    assert "value3  # this is a comment" in source_code, "Comment spacing issue detected!"

    print("Comment spacing check completed.")

if __name__ == "__main__":
    check_comment_spacing()

Expected Behavior:

The output YAML should have two spaces between the value and the comment, like this:

parent:
    child1: value1  # this is a comment
    child2: value2  # this is a comment
    child3: value3  # this is a comment

Actual Behavior:

The second comment only adds one space :S

parent:
    child1: value1  # this is a comment
    child2: value2 # this is a comment
    child3: value3  # this is a comment

Please let me know if you need any additional information or if there's a known workaround for this issue. Thank you for your help!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions