Skip to content

Commit

Permalink
Improve support for roundtrip comments with model
Browse files Browse the repository at this point in the history
  • Loading branch information
xoofx committed Jan 24, 2022
1 parent 78b028b commit 014e186
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
26 changes: 26 additions & 0 deletions src/Tomlyn.Tests/ModelTests/ReflectionModelTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,32 @@ public void TestReflectionModelWithErrors()
StringAssert.Contains("id3", diag.Message);
}

[Test]
public void TestCommentRoundtripWithModel()
{
var input = @"
# This is comment before
name = 1 # This is a comment
# This is a comment before a table
[table] # a comment after an table
key = 1
# A Comment before a table array
[[array]] # a comment after a table array
key2 = 3
# This is a comment after a key
";
StandardTests.DisplayHeader("input");
Console.WriteLine(input);
var model = Toml.ToModel(input);
var toml2 = Toml.FromModel(model);
StandardTests.DisplayHeader("toml - write back");
Console.WriteLine(toml2);

Assert.AreEqual(input, toml2);
}

public class SimpleModel
{
public SimpleModel()
Expand Down
13 changes: 8 additions & 5 deletions src/Tomlyn/Model/ModelToTomlTransform.cs
Original file line number Diff line number Diff line change
Expand Up @@ -220,8 +220,11 @@ private bool VisitObject(ObjectDynamicAccessor accessor, object currentObject, b
WriteLeadingTrivia(name);
}

WriteKeyValue(name, prop.Value, propToInline);
if (!inline)
var valueAccessor = WriteKeyValue(name, prop.Value, propToInline);

// Special case to not output duplicated new lines that were already handled
// WriteKeyValue
if (!inline && (valueAccessor is PrimitiveDynamicAccessor || propToInline))
{
WriteTrailingTrivia(name);
_writer.WriteLine();
Expand Down Expand Up @@ -277,10 +280,8 @@ private void VisitList(ListDynamicAccessor accessor, object currentObject, bool
}
}

private void WriteKeyValue(string name, object? value, bool inline)
private DynamicAccessor WriteKeyValue(string name, object value, bool inline)
{
if (value is null) return;

var accessor = _context.GetAccessor(value.GetType());

switch (accessor)
Expand Down Expand Up @@ -348,6 +349,8 @@ private void WriteKeyValue(string name, object? value, bool inline)
default:
throw new ArgumentOutOfRangeException(nameof(accessor));
}

return accessor;
}

private TomlPropertyDisplayKind GetDisplayKind(string name)
Expand Down

0 comments on commit 014e186

Please sign in to comment.