Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Process inline comments with DictionaryDeserializer. #865

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
84 changes: 84 additions & 0 deletions YamlDotNet.Samples/DeserializeWithComment.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

using System;
using System.IO;
using Xunit.Abstractions;
using YamlDotNet.Samples.Helpers;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;


namespace YamlDotNet.Samples
{
public class DeserializeWithComment
{
private readonly ITestOutputHelper output;

public DeserializeWithComment(ITestOutputHelper output)
{
this.output = output;
}

[Sample(
DisplayName = "Deserializing with comments",
Description = "Shows how to process comments"
)]
public void Main()
{
var deserializer = new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.Build();
var serializer = new SerializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.JsonCompatible()
.Build();

var content = WithInlineCommentsAndList;

var parser = new Core.Parser(new Core.Scanner(new StringReader(content), false));
var yamlObject = deserializer.Deserialize<object>(parser);

var json = serializer.Serialize(yamlObject);

output.WriteLine(json);
Console.WriteLine(json);

}

private const string WithInlineCommentsAndList =
@"# document starts with comment
valuelist:
- string1 #{1st comment}
- string2
# block comment
- string3 #{2nd comment}
simplevalue: 12
objectlist:
- att1: 12
att2: v1
- att1: 13
att2: v2
- att1: 14 #3rd comment
att2: v3 #4th comment
";
}
}
36 changes: 36 additions & 0 deletions YamlDotNet.Test/Serialization/SerializationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1647,6 +1647,42 @@ public void YamlConvertiblesAreAbleToEmitAndParseComments()
Assert.Equal("The value", parsed.Value);
}

[Fact]
public void ChildrenWithInlineComments()
{
var input = @"# document starts with comment
valuelist:
- string1 #{1st comment}
- string2
# block comment
- string3 #{2nd comment}
simplevalue: 12
objectlist:
- att1: 12
att2: v1
- att1: 13
att2: v2
- att1: 14 #3rd comment
att2: v3 #4th comment
";

var expected = @"{""valuelist"": [{""value"": ""string1"", ""comment"": ""{1st comment}""}, {""value"": ""string2"", ""comment"": """"}, {""value"": ""string3"", ""comment"": ""{2nd comment}""}], ""simplevalue"": {""value"": ""12"", ""comment"": """"}, ""objectlist"": [{""att1"": {""value"": ""12"", ""comment"": """"}, ""att2"": {""value"": ""v1"", ""comment"": """"}}, {""att1"": {""value"": ""13"", ""comment"": """"}, ""att2"": {""value"": ""v2"", ""comment"": """"}}, {""att1"": {""value"": ""14"", ""comment"": ""3rd comment""}, ""att2"": {""value"": ""v3"", ""comment"": ""4th comment""}}]}
";

var deserializer = new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.Build();
var serializer = new SerializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.JsonCompatible()
.Build();
var parser = new Parser(new Scanner(new StringReader(input), false));

var yamlObject = deserializer.Deserialize<object>(parser);
var actual = serializer.Serialize(yamlObject);

Assert.Equal(expected, actual);
}
public class CommentWrapper<T> : IYamlConvertible
{
public string Comment { get; set; }
Expand Down
35 changes: 35 additions & 0 deletions YamlDotNet/Basic/ValueWithComment.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

namespace YamlDotNet.Basic
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lets not create a new namespace, there should be one that exists already that we can put this in.

{
public class ValueWithComment
{
public ValueWithComment(object? value, string comment)
{
this.Value = value;
this.Comment = comment;
}
public object? Value { get; }

public string Comment { get; }
}
}
10 changes: 10 additions & 0 deletions YamlDotNet/Core/IParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,15 @@ public interface IParser
/// </summary>
/// <returns>Returns true if there are more events available, otherwise returns false.</returns>
bool MoveNext();

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm very hesitant with adding additional fields/methods to this interface. It's implemented by other consumers of the library and I really, really badly don't want to break those. That's a major breaking change.

/// <summary>
/// Skips following comment events.
/// </summary>
void SkipFollowingComments();

/// <summary>
/// Gets the SkipComments value from its scanner.
/// </summary>
bool SkipComments { get; }
}
}
5 changes: 5 additions & 0 deletions YamlDotNet/Core/IScanner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,5 +54,10 @@ public interface IScanner
/// Consumes the current token.
/// </summary>
void ConsumeCurrent();

/// <summary>
/// Gets the SkipComments setting.
/// </summary>
bool SkipComments { get; }
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment as in the IParser, I'm very hesitant to modify these core interfaces.

}
}
9 changes: 9 additions & 0 deletions YamlDotNet/Core/MergingParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ public MergingParser(IParser innerParser)

public ParsingEvent? Current => iterator.Current?.Value;

public bool SkipComments => innerParser.SkipComments;

public bool MoveNext()
{
if (!merged)
Expand All @@ -60,6 +62,13 @@ public bool MoveNext()
return iterator.MoveNext();
}

public void SkipFollowingComments()
{
while (this.TryConsume<Comment>(out var _))
{
}
}

private void Merge()
{
while (innerParser.MoveNext())
Expand Down
10 changes: 10 additions & 0 deletions YamlDotNet/Core/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ public class Parser : IParser
{
pendingEvents.Enqueue(new Events.Comment(commentToken.Value, commentToken.IsInline, commentToken.Start, commentToken.End));
scanner.ConsumeCurrent();
currentToken = scanner.Current;
}
else
{
Expand Down Expand Up @@ -87,6 +88,8 @@ public Parser(IScanner scanner)
/// </summary>
public ParsingEvent? Current { get; private set; }

public bool SkipComments => scanner.SkipComments;

private readonly EventQueue pendingEvents = new EventQueue();

/// <summary>
Expand All @@ -111,6 +114,13 @@ public bool MoveNext()
return true;
}

public void SkipFollowingComments()
{
while (this.TryConsume<Events.Comment>(out var _))
{
}
}

private ParsingEvent StateMachine()
{
switch (state)
Expand Down
10 changes: 10 additions & 0 deletions YamlDotNet/Serialization/BufferedDeserialization/ParserBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public class ParserBuffer : IParser
/// <exception cref="ArgumentOutOfRangeException">If parser does not fit within the max depth and length specified.</exception>
public ParserBuffer(IParser parserToBuffer, int maxDepth, int maxLength)
{
SkipComments = parserToBuffer.SkipComments;
buffer = new LinkedList<ParsingEvent>();
buffer.AddLast(parserToBuffer.Consume<MappingStart>());
var depth = 0;
Expand Down Expand Up @@ -71,6 +72,8 @@ public ParserBuffer(IParser parserToBuffer, int maxDepth, int maxLength)
/// </summary>
public ParsingEvent? Current => current?.Value;

public bool SkipComments { get; }
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be true by default, for sure. I'm not sure of what kind of repercussions this could have in places that inherit or use this outside of the library, I'm suspecting it could cause issues if dictionaries suddenly have additional unexpected objects.

I would like it to be disabled through these changes by default, and have to be opted into for it to work.


/// <summary>
/// Moves to the next event.
/// </summary>
Expand All @@ -88,5 +91,12 @@ public void Reset()
{
current = buffer.First;
}

public void SkipFollowingComments()
{
while (this.TryConsume<Comment>(out var _))
{
}
}
}
}
3 changes: 2 additions & 1 deletion YamlDotNet/Serialization/DeserializerBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ public DeserializerBuilder()
{ typeof(DictionaryNodeDeserializer), _ => new DictionaryNodeDeserializer(objectFactory.Value, duplicateKeyChecking) },
{ typeof(CollectionNodeDeserializer), _ => new CollectionNodeDeserializer(objectFactory.Value) },
{ typeof(EnumerableNodeDeserializer), _ => new EnumerableNodeDeserializer() },
{ typeof(ObjectNodeDeserializer), _ => new ObjectNodeDeserializer(objectFactory.Value, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter) }
{ typeof(CommentNodeDeserializer), _ => new CommentNodeDeserializer() },
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be optional and not included by default. You'll also need to add this to the staticdeserializerbuilder for feature parity with the ahead of time compilation abilities of the library.

{ typeof(ObjectNodeDeserializer), _ => new ObjectNodeDeserializer(objectFactory.Value, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter) },
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Theres an extra comma on the end here.

};

nodeTypeResolverFactories = new LazyComponentRegistrationList<Nothing, INodeTypeResolver>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

using System;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;

namespace YamlDotNet.Serialization.NodeDeserializers
{
internal class CommentNodeDeserializer : INodeDeserializer
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be public so people can remove it if needed.

{
public bool Deserialize(IParser parser, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value)
{
value = null;
if (parser.Accept<Comment>(out var _))
{
if (parser.TryConsume<Comment>(out var comment))
{
value = comment;
return true;
}
}

return false;
}
}
}