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

Replaces copy constructors with cloning and adds missing param #1463

Merged
merged 2 commits into from
Mar 30, 2023
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
11 changes: 7 additions & 4 deletions GraphWebApi/Controllers/OpenApiController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public async Task<IActionResult> Get([FromQuery] string graphVersion = null,

var graphOpenApi = await _openApiService.GetGraphOpenApiDocumentAsync(graphUri, style, forceRefresh, fileName);
await WriteIndex(Request.Scheme + "://" + Request.Host.Value, styleOptions.GraphVersion, styleOptions.OpenApiVersion, styleOptions.OpenApiFormat,
graphOpenApi, Response.Body, styleOptions.Style, singularizeOperationIds);
graphOpenApi, Response.Body, styleOptions.Style, singularizeOperationIds, fileName);

return new EmptyResult();
}
Expand Down Expand Up @@ -174,7 +174,8 @@ private static async Task WriteIndex(
OpenApiDocument graphOpenApi,
Stream stream,
OpenApiStyle style,
bool singularizeOperationIds)
bool singularizeOperationIds,
string fileName = null)

{
using var sw = new StreamWriter(stream);
Expand All @@ -190,14 +191,16 @@ await sw.WriteAsync("<head>" + Environment.NewLine +
"<b/>" + Environment.NewLine +
"<ul>" + Environment.NewLine);

string fileNameParam = !string.IsNullOrEmpty(fileName) ? "&fileName=" + fileName : null;

foreach (var item in indexSearch.Index)
{
var target = $"{baseUrl}/openapi?tags={item.Key.Name}&openApiVersion={openApiVersion}&graphVersion={graphVersion}&format={format}&style={style}&singularizeOperationIds={singularizeOperationIds}";
var target = $"{baseUrl}/openapi?tags={item.Key.Name}&openApiVersion={openApiVersion}&graphVersion={graphVersion}&format={format}&style={style}&singularizeOperationIds={singularizeOperationIds}{fileNameParam}";
await sw.WriteAsync($"<li>{item.Key.Name} [<a href='{target}'>OpenApi</a>] [<a href='/swagger/index.html#url={target}'>Swagger UI</a>]</li>{Environment.NewLine}<ul>{Environment.NewLine}");
foreach (var op in item.Value)
{
await sw.WriteLineAsync($"<li>{op.OperationId} [<a href='../../openapi?operationIds={op.OperationId}&openApiVersion={openApiVersion}&graphVersion={graphVersion}" +
$"&format={format}&style={style}'>OpenAPI</a>]</li>");
$"&format={format}&style={style}&singularizeOperationIds={singularizeOperationIds}{fileNameParam}'>OpenAPI</a>]</li>");
}
await sw.WriteLineAsync("</ul>");
}
Expand Down
25 changes: 4 additions & 21 deletions OpenAPIService.Test/OpenAPIDocumentCreatorMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,14 @@
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------------------------------------------------------------------------------

using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.Extensions.Configuration;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Readers;
using Microsoft.OpenApi.Writers;
using OpenAPIService.Interfaces;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;

namespace OpenAPIService.Test
{
Expand All @@ -31,7 +25,7 @@ public class OpenApiDocumentCreatorMock
public OpenApiDocumentCreatorMock(IOpenApiService openApiService)
{
_openApiService = openApiService
?? throw new ArgumentNullException(nameof(openApiService), $"{ NullValueError }: { nameof(openApiService) }");
?? throw new ArgumentNullException(nameof(openApiService), $"{NullValueError}: {nameof(openApiService)}");
}

public static IOpenApiService GetOpenApiService(string configFilePath)
Expand All @@ -43,17 +37,6 @@ public static IOpenApiService GetOpenApiService(string configFilePath)
return new OpenApiService(configuration);
}

private static OpenApiDocument CloneOpenApiDocument(OpenApiDocument openApiDocument)
{
using var stream = new MemoryStream();
var writer = new OpenApiYamlWriter(new StreamWriter(stream));
openApiDocument.SerializeAsV3(writer);
writer.Flush();
stream.Position = 0;
var reader = new OpenApiStreamReader();
return reader.Read(stream, out _); ;
}

/// <summary>
/// Gets an OpenAPI document of Microsoft Graph
/// from a dictionary cache or gets a new instance.
Expand Down Expand Up @@ -1008,7 +991,7 @@ private OpenApiDocument CreateOpenApiDocument()
Id = "StringCollectionResponse"
}
}
}
}
}
}
}
Expand Down Expand Up @@ -1056,7 +1039,7 @@ private OpenApiDocument CreateOpenApiDocument()
Name = "identityGovernance.Actions"
}
},
OperationId = "identityGovernance.lifecycleWorkflows.workflows.workflow.activate"
OperationId = "identityGovernance.lifecycleWorkflows.workflows.workflow.activate"
}
}
}
Expand Down Expand Up @@ -1251,7 +1234,7 @@ private OpenApiDocument CreateOpenApiDocument()
}
};

return CloneOpenApiDocument(document);
return _openApiService.CloneOpenApiDocument(document);
}
}
}
2 changes: 2 additions & 0 deletions OpenAPIService/Interfaces/IOpenApiService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,7 @@ Func<OpenApiOperation, bool> CreatePredicate(string operationIds, string tags, s
void ConvertOpenApiUrlTreeNodeToJson(OpenApiUrlTreeNode rootNode, Stream stream);

OpenApiDocument ApplyStyle(OpenApiStyle style, OpenApiDocument subsetOpenApiDocument, bool includeRequestBody = false, bool singularizeOperationIds = false);

OpenApiDocument CloneOpenApiDocument(OpenApiDocument document);
}
}
44 changes: 29 additions & 15 deletions OpenAPIService/OpenApiService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,17 @@
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// -------------------------------------------------------------------------------------------------------------------------------------------------------

using Microsoft.OData.Edm.Csdl;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Readers;
using Microsoft.OpenApi.Services;
using Microsoft.OpenApi.Writers;
using Microsoft.OpenApi.OData;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using OpenAPIService.Common;
Expand Down Expand Up @@ -153,7 +150,7 @@ public OpenApiDocument CreateFilteredDocument(OpenApiDocument source, string tit
SeverityLevel.Information,
_openApiTraceProperties);

return new OpenApiDocument(subset);
return CloneOpenApiDocument(subset);
}

/// <summary>
Expand Down Expand Up @@ -629,42 +626,44 @@ public OpenApiDocument ApplyStyle(
SeverityLevel.Information,
_openApiTraceProperties);

var openApiDoc = CloneOpenApiDocument(subsetOpenApiDocument);

if (style == OpenApiStyle.GEAutocomplete && !includeRequestBody)
{
// The Content property and its schema $refs are unnecessary for autocomplete
RemoveContent(subsetOpenApiDocument);
RemoveContent(openApiDoc);
}
if (style == OpenApiStyle.PowerShell || style == OpenApiStyle.PowerPlatform)
{
// Remove AnyOf and OneOf since AutoREST does not support them. See https://github.com/Azure/autorest/issues/4118.
var anyOfRemover = new AnyOfOneOfRemover();
var walker = new OpenApiWalker(anyOfRemover);
walker.Walk(subsetOpenApiDocument);
walker.Walk(openApiDoc);

if (style == OpenApiStyle.PowerShell)
{
// Format the OperationId for Powershell cmdlet names generation
var powershellFormatter = new PowershellFormatter(singularizeOperationIds);
walker = new OpenApiWalker(powershellFormatter);
walker.Walk(subsetOpenApiDocument);
walker.Walk(openApiDoc);

var version = subsetOpenApiDocument.Info.Version;
var version = openApiDoc.Info.Version;
if (!new Regex("v\\d\\.\\d", RegexOptions.None, TimeSpan.FromSeconds(5)).Match(version).Success)
{
subsetOpenApiDocument.Info.Version = "v1.0-" + version;
openApiDoc.Info.Version = "v1.0-" + version;
}

// Remove the root path to make AutoREST happy
subsetOpenApiDocument.Paths.Remove("/");
openApiDoc.Paths.Remove("/");

// Temp. fix - Escape the # character from description in
// 'microsoft.graph.networkInterface' schema
EscapePoundCharacter(subsetOpenApiDocument.Components);
EscapePoundCharacter(openApiDoc.Components);
}
}

if (subsetOpenApiDocument.Paths == null ||
!subsetOpenApiDocument.Paths.Any())
if (openApiDoc.Paths == null ||
!openApiDoc.Paths.Any())
{
throw new ArgumentException("No paths found for the supplied parameters.");
}
Expand All @@ -673,14 +672,13 @@ public OpenApiDocument ApplyStyle(
SeverityLevel.Information,
_openApiTraceProperties);

return subsetOpenApiDocument;
return openApiDoc;
}

private async Task<OpenApiDocument> GetOpenApiDocumentAsync(Uri openAPIHref)
{
var stopwatch = new Stopwatch();
var httpClient = CreateHttpClient();

stopwatch.Start();
await using Stream stream = await httpClient.GetStreamAsync(openAPIHref.OriginalString);
stopwatch.Stop();
Expand Down Expand Up @@ -802,6 +800,22 @@ private static void RemoveContent(OpenApiDocument target)
walker.Walk(target);
}

/// <summary>
/// Creates a clone of an OpenAPI document
/// </summary>
/// <param name="document">The source document to clone.</param>
/// <returns>A clone of the source document.</returns>
public OpenApiDocument CloneOpenApiDocument(OpenApiDocument document)
{
using var stream = new MemoryStream();
var writer = new OpenApiYamlWriter(new StreamWriter(stream));
document.SerializeAsV3(writer);
writer.Flush();
stream.Position = 0;
var reader = new OpenApiStreamReader();
return reader.Read(stream, out _);
}

/// <summary>
/// Formats path functions, where present, by surrounding placeholder values of string data types
/// with single quotation marks.
Expand Down