YamlDotNet icon indicating copy to clipboard operation
YamlDotNet copied to clipboard

Serialization using IndentedTextWriter causes missing indentation

Open ogretmenb opened this issue 11 months ago • 2 comments
trafficstars

Describe the bug

my project was using 12.0.2 version of YamlDotNet package. While upgrading to a newer version I realized an issue introduced in release 12.1.0 via this change https://github.com/aaubry/YamlDotNet/pull/747/files#diff-7df2919371fb7e178ae78e207ac6010f930dae71acf2e99769c373c472ce575bR1922

I am using Serializer.Serialize(TextWriter writer, object graph) and passing an IndentedTextWriter to that method for custom indentation. That single line seems removing configured indentation in IndentedTextWriter object.

setting EmitterSettings.NewLine to TextWriter.NewLine instead of replacing WriteLine with Write seems a better solution and it works fine

I have a PR for the fix of the issue, It also contains a unit test to explain my issue. But I dont have permissions to push my branch. May I ask for push access as well?

adding the test code which creates the issue below

[Fact]
public void SerializeWithTabs()
{
    var tabString = " ";
    using var writer = new StringWriter();
    using var indentedTextWriter = new IndentedTextWriter(writer, tabString) { Indent = 2 };

    //create a dictionary with a list of strings to test the tabbed serialization
    var items = new List<string> { "item 1", "item 2" };
    var list = new Dictionary<string, List<string>> { { "key", items } };

    SerializerBuilder
        .Build()
        .Serialize(indentedTextWriter, list);

    //split serialized output into lines
    var lines = indentedTextWriter.InnerWriter.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None);

    //expected indentation
    var indent = string.Join(string.Empty, Enumerable.Repeat(tabString, indentedTextWriter.Indent).ToList());

    //check that the serialized lines (excluding the first and last) start with the expected indentation
    lines.Skip(1).Take(lines.Length - 2).Where(element => element.StartsWith(indent)).Should().HaveCount(items.Count);
}

ogretmenb avatar Dec 02 '24 18:12 ogretmenb