Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,12 @@ internal interface IOpenApiVersionService
OpenApiReference ConvertToOpenApiReference(string reference, ReferenceType? type);

/// <summary>
/// Function that converts a MapNode into a Tag object in a version specific way
/// Loads an OpenAPI Element from a document fragment
/// </summary>
Func<MapNode, OpenApiTag> TagLoader { get; }
/// <typeparam name="T">Type of element to load</typeparam>
/// <param name="node">document fragment node</param>
/// <returns>Instance of OpenAPIElement</returns>
T LoadElement<T>(ParseNode node) where T : IOpenApiElement;

/// <summary>
/// Converts a generic RootNode instance into a strongly typed OpenApiDocument
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<Company>Microsoft</Company>
<Title>Microsoft.OpenApi.Readers</Title>
<PackageId>Microsoft.OpenApi.Readers</PackageId>
<Version>1.0.0</Version>
<Version>1.1.0-preview.1</Version>
<Description>OpenAPI.NET Readers for JSON and YAML documents</Description>
<Copyright>© Microsoft Corporation. All rights reserved.</Copyright>
<PackageTags>OpenAPI .NET</PackageTags>
Expand Down
56 changes: 56 additions & 0 deletions src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Linq;
using Microsoft.OpenApi.Exceptions;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Readers.Interface;
using Microsoft.OpenApi.Readers.Services;
Expand Down Expand Up @@ -102,6 +103,61 @@ public OpenApiDocument Read(Stream input, out OpenApiDiagnostic diagnostic)
return document;
}

/// <summary>
/// Reads the stream input and parses the fragment of an OpenAPI description into an Open API Element.
/// </summary>
/// <param name="input">Stream containing OpenAPI description to parse.</param>
/// <param name="version">Version of the OpenAPI specification that the fragment conforms to.</param>
/// <param name="diagnostic">Returns diagnostic object containing errors detected during parsing</param>
/// <returns>Instance of newly created OpenApiDocument</returns>
public T ReadFragment<T>(Stream input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic) where T : IOpenApiElement
{
ParsingContext context;
YamlDocument yamlDocument;
diagnostic = new OpenApiDiagnostic();

// Parse the YAML/JSON
try
{
yamlDocument = LoadYamlDocument(input);
}
catch (SyntaxErrorException ex)
{
diagnostic.Errors.Add(new OpenApiReaderError(ex));
return default(T);
}

context = new ParsingContext
{
ExtensionParsers = _settings.ExtensionParsers
};

IOpenApiElement element = null;

try
{
// Parse the OpenAPI element
element = context.ParseFragment<T>(yamlDocument, version, diagnostic);
}
catch (OpenApiException ex)
{
diagnostic.Errors.Add(new OpenApiError(ex));
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we also validate the fragment after parsing?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

PerthCharern I'm not sure. I didn't think we could because of references, but as they are unresolved that shouldn't be a problem. Now I'm not sure. Will think about it some more.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added it. Seems to be fine.

// Validate the element
if (_settings.RuleSet != null && _settings.RuleSet.Rules.Count > 0)
{
var errors = element.Validate(_settings.RuleSet);
foreach (var item in errors)
{
diagnostic.Errors.Add(item);
}
}

return (T)element;
}


/// <summary>
/// Helper method to turn streams into YamlDocument
/// </summary>
Expand Down
19 changes: 18 additions & 1 deletion src/Microsoft.OpenApi.Readers/OpenApiStringReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT license.

using System.IO;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Readers.Interface;

Expand All @@ -20,7 +21,7 @@ public class OpenApiStringReader : IOpenApiReader<string, OpenApiDiagnostic>
/// <param name="settings"></param>
public OpenApiStringReader(OpenApiReaderSettings settings = null)
{
_settings = settings ?? new OpenApiReaderSettings();
_settings = settings ?? new OpenApiReaderSettings();
}

/// <summary>
Expand All @@ -38,5 +39,21 @@ public OpenApiDocument Read(string input, out OpenApiDiagnostic diagnostic)
return new OpenApiStreamReader(_settings).Read(memoryStream, out diagnostic);
}
}

/// <summary>
/// Reads the string input and parses it into an Open API element.
/// </summary>
public T ReadFragment<T>(string input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic) where T : IOpenApiElement
{
using (var memoryStream = new MemoryStream())
{
var writer = new StreamWriter(memoryStream);
writer.Write(input);
writer.Flush();
memoryStream.Position = 0;

return new OpenApiStreamReader(_settings).ReadFragment<T>(memoryStream, version, out diagnostic);
}
}
}
}
53 changes: 33 additions & 20 deletions src/Microsoft.OpenApi.Readers/ParsingContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ public class ParsingContext
/// <summary>
/// Initiates the parsing process. Not thread safe and should only be called once on a parsing context
/// </summary>
/// <param name="yamlDocument"></param>
/// <param name="diagnostic"></param>
/// <param name="yamlDocument">Yaml document to parse.</param>
/// <param name="diagnostic">Diagnostic object which will return diagnostic results of the operation.</param>
/// <returns>An OpenApiDocument populated based on the passed yamlDocument </returns>
internal OpenApiDocument Parse(YamlDocument yamlDocument, OpenApiDiagnostic diagnostic)
{
Expand All @@ -47,13 +47,13 @@ internal OpenApiDocument Parse(YamlDocument yamlDocument, OpenApiDiagnostic diag
{
case string version when version == "2.0":
VersionService = new OpenApiV2VersionService();
doc = this.VersionService.LoadDocument(this.RootNode);
doc = VersionService.LoadDocument(RootNode);
diagnostic.SpecificationVersion = OpenApiSpecVersion.OpenApi2_0;
break;

case string version when version.StartsWith("3.0"):
this.VersionService = new OpenApiV3VersionService();
doc = this.VersionService.LoadDocument(this.RootNode);
VersionService = new OpenApiV3VersionService();
doc = VersionService.LoadDocument(RootNode);
diagnostic.SpecificationVersion = OpenApiSpecVersion.OpenApi3_0;
break;

Expand All @@ -64,6 +64,34 @@ internal OpenApiDocument Parse(YamlDocument yamlDocument, OpenApiDiagnostic diag
return doc;
}

/// <summary>
/// Initiates the parsing process of a fragment. Not thread safe and should only be called once on a parsing context
/// </summary>
/// <param name="yamlDocument"></param>
/// <param name="version">OpenAPI version of the fragment</param>
/// <param name="diagnostic">Diagnostic object which will return diagnostic results of the operation.</param>
/// <returns>An OpenApiDocument populated based on the passed yamlDocument </returns>
internal T ParseFragment<T>(YamlDocument yamlDocument, OpenApiSpecVersion version, OpenApiDiagnostic diagnostic) where T: IOpenApiElement
{
var node = ParseNode.Create(this, diagnostic, yamlDocument.RootNode);

T element = default(T);

switch (version)
{
case OpenApiSpecVersion.OpenApi2_0:
VersionService = new OpenApiV2VersionService();
element = this.VersionService.LoadElement<T>(node);
break;

case OpenApiSpecVersion.OpenApi3_0:
this.VersionService = new OpenApiV3VersionService();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this. [](start = 20, length = 5)

nit, remove these "this." for consistency.

element = this.VersionService.LoadElement<T>(node);
break;
}

return element;
}

/// <summary>
/// Gets the version of the Open API document.
Expand All @@ -82,20 +110,6 @@ private static string GetVersion(RootNode rootNode)
return versionNode?.GetScalarValue();
}

private void ComputeTags(List<OpenApiTag> tags, Func<MapNode, OpenApiTag> loadTag)
{
// Precompute the tags array so that each tag reference does not require a new deserialization.
var tagListPointer = new JsonPointer("#/tags");

var tagListNode = RootNode.Find(tagListPointer);

if (tagListNode != null && tagListNode is ListNode)
{
var tagListNodeAsListNode = (ListNode)tagListNode;
tags.AddRange(tagListNodeAsListNode.CreateList(loadTag));
}
}

/// <summary>
/// Service providing all Version specific conversion functions
/// </summary>
Expand All @@ -108,7 +122,6 @@ internal IOpenApiVersionService VersionService
set
{
_versionService = value;
ComputeTags(Tags, VersionService.TagLoader);
}
}

Expand Down
113 changes: 101 additions & 12 deletions src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

using System;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Readers.Exceptions;
using Microsoft.OpenApi.Readers.ParseNodes;

namespace Microsoft.OpenApi.Readers.V2
Expand All @@ -22,41 +25,107 @@ internal static partial class OpenApiV2Deserializer
}
},
{
"required", (o, n) =>
"type", (o, n) =>
{
o.Required = bool.Parse(n.GetScalarValue());
GetOrCreateSchema(o).Type = n.GetScalarValue();
}
},
{
"deprecated", (o, n) =>
"format", (o, n) =>
{
o.Deprecated = bool.Parse(n.GetScalarValue());
GetOrCreateSchema(o).Format = n.GetScalarValue();
}
},
{
"allowReserved", (o, n) =>
"items", (o, n) =>
{
o.AllowReserved = bool.Parse(n.GetScalarValue());
GetOrCreateSchema(o).Items = LoadSchema(n);
}
},
{
"style", (o, n) =>
"collectionFormat", (o, n) =>
{
o.Style = n.GetScalarValue().GetEnumFromDisplayName<ParameterStyle>();
LoadStyle(o, n.GetScalarValue());
}
},
{
"type", (o, n) =>
"default", (o, n) =>
{
GetOrCreateSchema(o).Type = n.GetScalarValue();
GetOrCreateSchema(o).Default = n.CreateAny();
}
},
{
"maximum", (o, n) =>
{
GetOrCreateSchema(o).Maximum = decimal.Parse(n.GetScalarValue());
}
},
{
"format", (o, n) =>
"exclusiveMaximum", (o, n) =>
{
GetOrCreateSchema(o).Format = n.GetScalarValue();
GetOrCreateSchema(o).ExclusiveMaximum = bool.Parse(n.GetScalarValue());
}
},
{
"minimum", (o, n) =>
{
GetOrCreateSchema(o).Minimum = decimal.Parse(n.GetScalarValue());
}
},
{
"exclusiveMinimum", (o, n) =>
{
GetOrCreateSchema(o).ExclusiveMinimum = bool.Parse(n.GetScalarValue());
}
},
{
"maxLength", (o, n) =>
{
GetOrCreateSchema(o).MaxLength = int.Parse(n.GetScalarValue());
}
},
{
"minLength", (o, n) =>
{
GetOrCreateSchema(o).MinLength = int.Parse(n.GetScalarValue());
}
},
{
"pattern", (o, n) =>
{
GetOrCreateSchema(o).Pattern = n.GetScalarValue();
}
},
{
"maxItems", (o, n) =>
{
GetOrCreateSchema(o).MaxItems = int.Parse(n.GetScalarValue());
}
},
{
"minItems", (o, n) =>
{
GetOrCreateSchema(o).MinItems = int.Parse(n.GetScalarValue());
}
},
{
"uniqueItems", (o, n) =>
{
GetOrCreateSchema(o).UniqueItems = bool.Parse(n.GetScalarValue());
}
},
{
"multipleOf", (o, n) =>
{
GetOrCreateSchema(o).MultipleOf = decimal.Parse(n.GetScalarValue());
}
},
{
"enum", (o, n) =>
{
GetOrCreateSchema(o).Enum = n.CreateListOfAny();
}
}
};

private static readonly PatternFieldMap<OpenApiHeader> _headerPatternFields = new PatternFieldMap<OpenApiHeader>
Expand All @@ -82,5 +151,25 @@ public static OpenApiHeader LoadHeader(ParseNode node)

return header;
}

private static void LoadStyle(OpenApiHeader header, string style)
{
switch (style)
{
case "csv":
header.Style = ParameterStyle.Simple;
return;
case "ssv":
header.Style = ParameterStyle.SpaceDelimited;
return;
case "pipes":
header.Style = ParameterStyle.PipeDelimited;
return;
case "tsv":
throw new NotSupportedException();
default:
throw new OpenApiReaderException("Unrecognized header style: " + style);
}
}
}
}
Loading