Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
114 commits
Select commit Hold shift + click to select a range
fdbee8f
Update input parameter description
MaggieKimani1 Jan 19, 2022
7f88a35
Add OData conversion libraries
MaggieKimani1 Jan 19, 2022
e0f0ed6
Add necessary usings
MaggieKimani1 Jan 19, 2022
c2ae2dd
Add method for CSDL to OpenAPI conversion
MaggieKimani1 Jan 19, 2022
07169a4
Check input file for .xml extension
MaggieKimani1 Jan 20, 2022
f23b0a9
Merge remote-tracking branch 'origin/vnext' into mk/feature/convert-c…
MaggieKimani1 Jan 24, 2022
581023c
Clean up code
MaggieKimani1 Jan 25, 2022
7606916
Refactor code
MaggieKimani1 Jan 25, 2022
cb8ef3a
Add check for .csdl files
MaggieKimani1 Jan 26, 2022
73339e1
Add a sample csdl file for testing and copy to output directory
MaggieKimani1 Jan 26, 2022
7ec682b
Add csdl conversion tests
MaggieKimani1 Jan 26, 2022
b13c3ad
Add xml documentation
MaggieKimani1 Jan 26, 2022
695eb05
Merge branch 'mk/align-hidi-params-with-kiota' into mk/feature/conver…
MaggieKimani1 Jan 27, 2022
66c06b6
Add --csdl input param for converting csdl files
MaggieKimani1 Jan 27, 2022
1b40298
Refactor code
MaggieKimani1 Jan 27, 2022
ef7640f
Rename test file
MaggieKimani1 Jan 27, 2022
51e85a7
Refactor param to be more implicit
MaggieKimani1 Jan 27, 2022
761088f
Merge branch 'vnext' into mk/feature/convert-csdl-to-openapi
MaggieKimani1 Feb 3, 2022
1d986d1
Resolve merge conflicts
MaggieKimani1 Feb 3, 2022
5550f01
Clean up code
MaggieKimani1 Feb 3, 2022
b8d0d2b
Default to V3 of OpenApi during document serialization
MaggieKimani1 Feb 4, 2022
385e5af
Clean up
MaggieKimani1 Feb 4, 2022
53c4e2c
Update package version
MaggieKimani1 Feb 7, 2022
be80647
Merge pull request #725 from microsoft/release/1.3.1-preview4
darrelmiller Feb 8, 2022
8683e37
Catch any OpenApiExceptions thrown during parsing and continue proces…
MaggieKimani1 Feb 8, 2022
40d0c97
Merge branch 'vnext' into mk/fix-parsing-errors
MaggieKimani1 Feb 8, 2022
528cee2
Merge remote-tracking branch 'origin/vnext' into mk/feature/convert-c…
MaggieKimani1 Feb 8, 2022
36a11bb
Add package icon and description
MaggieKimani1 Feb 8, 2022
707d7b7
Merge pull request #705 from microsoft/mk/feature/convert-csdl-to-ope…
darrelmiller Feb 10, 2022
4092472
Bump Verify from 15.2.1 to 16.1.1
dependabot[bot] Feb 10, 2022
76973e5
Merge pull request #723 from microsoft/dependabot/nuget/Verify-16.1.1
darrelmiller Feb 10, 2022
18abded
Bump System.Text.Json from 6.0.1 to 6.0.2
dependabot[bot] Feb 10, 2022
1b198dc
Merge pull request #728 from microsoft/dependabot/nuget/System.Text.J…
darrelmiller Feb 10, 2022
54bdbbe
Bump Verify.Xunit from 14.14.1 to 16.1.1
dependabot[bot] Feb 10, 2022
96f613a
Merge pull request #724 from microsoft/dependabot/nuget/Verify.Xunit-…
darrelmiller Feb 10, 2022
9f128dc
Fixed ValidateDocument method in hidi
darrelmiller Feb 12, 2022
e48338d
Merge remote-tracking branch 'origin/vnext' into issues/734
darrelmiller Feb 12, 2022
b274162
Fixed validate for Path Parameters so it does not fail for components
darrelmiller Feb 12, 2022
6adac99
Merge pull request #739 from microsoft/issues/733
darrelmiller Feb 15, 2022
34b56de
Merge branch 'vnext' into issues/734
darrelmiller Feb 15, 2022
5984798
Initialize a diagnostics object in the constructor and use it to appe…
MaggieKimani1 Feb 15, 2022
a7b1e1e
Pass the Diagnostic object to the class instances
MaggieKimani1 Feb 15, 2022
00eca6f
Upgrade packages
MaggieKimani1 Feb 15, 2022
4890e0e
Merge branch 'vnext' into mk/fix-parsing-errors
MaggieKimani1 Feb 15, 2022
ceb3ff4
Update TFMs in project and workflow files
MaggieKimani1 Feb 16, 2022
b977607
Update public api text file
MaggieKimani1 Feb 16, 2022
8e9e8cb
Migrate WPF project to .NET6 and delete obsolete App.config
MaggieKimani1 Feb 16, 2022
2937f02
Merge pull request #738 from microsoft/issues/734
darrelmiller Feb 16, 2022
c53bbe9
Merge branch 'vnext' into mk/fix/dependabot-updates
darrelmiller Feb 16, 2022
25b7357
Remove package and its reference
MaggieKimani1 Feb 16, 2022
4ac479a
Merge branch 'vnext' into mk/fix-migrate-to-net6
MaggieKimani1 Feb 16, 2022
7b2821e
Add enums to cater for multiple scheme and bearer formats
MaggieKimani1 Feb 16, 2022
8af1c19
Get the display name from the enum
MaggieKimani1 Feb 16, 2022
fc6f461
Refactor code
MaggieKimani1 Feb 16, 2022
5dc4d8a
Fix test
MaggieKimani1 Feb 16, 2022
80498c9
Bump Microsoft.NET.Test.Sdk from 17.0.0 to 17.1.0
dependabot[bot] Feb 16, 2022
a636ec2
Merge pull request #746 from microsoft/dependabot/nuget/Microsoft.NET…
darrelmiller Feb 17, 2022
6929114
Merge branch 'vnext' into mk/fix/dependabot-updates
darrelmiller Feb 17, 2022
4d84210
Merge branch 'vnext' into mk/feature/add-constants
MaggieKimani1 Feb 17, 2022
8e04fd1
Merge pull request #743 from microsoft/mk/fix/dependabot-updates
darrelmiller Feb 18, 2022
39ce0e9
Merge branch 'vnext' into mk/fix-parsing-errors
darrelmiller Feb 18, 2022
9720987
Add Jwt and Bearer constants and revert previous changes
MaggieKimani1 Feb 21, 2022
0390a81
Merge remote-tracking branch 'origin/mk/feature/add-constants' into m…
MaggieKimani1 Feb 21, 2022
15e7cc4
Merge branch 'vnext' into mk/feature/add-constants
MaggieKimani1 Feb 21, 2022
2b2bc25
Remove the OpenIdConnectUrl constant and replace it with the Bearer s…
MaggieKimani1 Feb 22, 2022
ad396b3
Merge remote-tracking branch 'origin/mk/feature/add-constants' into m…
MaggieKimani1 Feb 22, 2022
4fdfd70
Clean up solution file
MaggieKimani1 Feb 22, 2022
0f1350d
Revert
MaggieKimani1 Feb 22, 2022
9ef0a8e
Update target framework monikers
MaggieKimani1 Feb 22, 2022
b440e32
Revert change to the public API interface
MaggieKimani1 Feb 22, 2022
6ddb563
Merge branch 'vnext' into mk/fix-migrate-to-net6
MaggieKimani1 Feb 22, 2022
b1e745c
Address review feedback
MaggieKimani1 Feb 22, 2022
fd3dc26
Merge remote-tracking branch 'origin/mk/fix-migrate-to-net6' into mk/…
MaggieKimani1 Feb 22, 2022
ad36f92
Merge pull request #745 from microsoft/mk/feature/add-constants
darrelmiller Feb 22, 2022
b67be2a
Merge branch 'vnext' into mk/fix-migrate-to-net6
darrelmiller Feb 22, 2022
b98a4cb
removed support for net462
darrelmiller Feb 23, 2022
9551e33
Merge pull request #744 from microsoft/mk/fix-migrate-to-net6
darrelmiller Feb 23, 2022
1eeb31a
Update ci-build.yml for Azure Pipelines
MaggieKimani1 Feb 24, 2022
da6a4d1
Update ci-build.yml for Azure Pipelines
MaggieKimani1 Feb 27, 2022
fecd0fe
- upgrades odata conversion lib reference in hidi
baywet Feb 28, 2022
cd100d5
- fixes conversion tests and makes method async
baywet Feb 28, 2022
ee063b7
- fixes outdated unit test data
baywet Feb 28, 2022
de4ea22
Merge pull request #753 from microsoft/feature/conversion-lib-upgrade
baywet Feb 28, 2022
a79aae8
Merge remote-tracking branch 'origin/vnext' into mk/feature/publish-h…
MaggieKimani1 Feb 28, 2022
92a9eb1
- fixes an issue where hidi would not process async
baywet Feb 28, 2022
eca9137
- updates vs code configuration files to be able to debug hidi
baywet Feb 28, 2022
7bd8c36
Merge pull request #750 from microsoft/mk/feature/publish-hidi-as-exe
darrelmiller Feb 28, 2022
28ced82
Merge branch 'vnext' into bugfix/hidi-async
darrelmiller Feb 28, 2022
f9b8375
Merge pull request #756 from microsoft/bugfix/hidi-async
darrelmiller Feb 28, 2022
fa45d12
Merge branch 'vnext' into mk/fix-parsing-errors
darrelmiller Feb 28, 2022
d551f87
Merge pull request #727 from microsoft/mk/fix-parsing-errors
darrelmiller Feb 28, 2022
23e3b32
Updated versions to preview5
darrelmiller Mar 1, 2022
05bbf41
Merge pull request #760 from microsoft/release/1.3.1-preview5
darrelmiller Mar 1, 2022
8b2d347
Bump Moq from 4.16.1 to 4.17.1
dependabot[bot] Mar 1, 2022
1acfec6
Merge branch 'master' into release/1.3.1-preview5
baywet Mar 1, 2022
b48025e
Merge pull request #758 from microsoft/dependabot/nuget/Moq-4.17.1
baywet Mar 1, 2022
656697e
Bump actions/setup-dotnet from 1 to 2
dependabot[bot] Mar 1, 2022
be7861d
Bump Verify from 16.1.2 to 16.3.2
dependabot[bot] Mar 1, 2022
6d251f1
Merge pull request #757 from microsoft/dependabot/github_actions/acti…
baywet Mar 1, 2022
c8430ce
Merge pull request #755 from microsoft/dependabot/nuget/Verify-16.3.2
baywet Mar 1, 2022
93d7915
Bump Verify.Xunit from 16.1.2 to 16.3.2
dependabot[bot] Mar 1, 2022
fc83996
Merge pull request #754 from microsoft/dependabot/nuget/Verify.Xunit-…
baywet Mar 1, 2022
2ecd462
- ADO pipeline updates
baywet Feb 28, 2022
8a0ef11
- removes policheck on inexistant tool directory
baywet Feb 28, 2022
a2e516f
- fixes dll path for binskim analysis
baywet Feb 28, 2022
0db1483
- adds PR trigger for pipeline
baywet Mar 1, 2022
f31d6bc
- moves to separate jobs for each nupkg
baywet Mar 1, 2022
1127aed
- adds a copy task to align folder nams
baywet Mar 1, 2022
8431e6e
- fixes task name
baywet Mar 1, 2022
1752217
- enables trimming for hidi executable
baywet Mar 1, 2022
082f0bd
Merge pull request #752 from microsoft/feature/pipeline-upgrades
baywet Mar 1, 2022
75267c2
- bumps reference to openapi.odata
baywet Mar 3, 2022
b868ffc
Merge pull request #768 from microsoft/feature/odata-bump
baywet Mar 3, 2022
cbbf608
Merge pull request #769 from microsoft/vnext
baywet Mar 3, 2022
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
459 changes: 339 additions & 120 deletions .azure-pipelines/ci-build.yml

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions .github/workflows/ci-cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ jobs:
GITHUB_RUN_NUMBER: ${{ github.run_number }}
steps:
- name: Setup .NET
uses: actions/setup-dotnet@v1
uses: actions/setup-dotnet@v2
with:
dotnet-version: 5.0.x
dotnet-version: 6.0.x

- name: Data gatherer
id: data_gatherer
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/codeql-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ jobs:
uses: actions/checkout@v2

- name: Setup .NET
uses: actions/setup-dotnet@v1
uses: actions/setup-dotnet@v2
with:
dotnet-version: 5.0.x
dotnet-version: 6.0.x

- name: Initialize CodeQL
id: init_codeql
Expand Down
2 changes: 1 addition & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/src/Microsoft.OpenApi.Hidi/bin/Debug/netcoreapp3.1/Microsoft.OpenApi.Hidi.dll",
"program": "${workspaceFolder}/src/Microsoft.OpenApi.Hidi/bin/Debug/net6.0/Microsoft.OpenApi.Hidi.dll",
"args": [],
"cwd": "${workspaceFolder}/src/Microsoft.OpenApi.Hidi",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
Expand Down
39 changes: 33 additions & 6 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,43 @@
"tasks": [
{
"label": "build",
"type": "shell",
"command": "msbuild",
"command": "dotnet",
"type": "process",
"group": "build",
"args": [
"build",
"${workspaceFolder}/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "test",
"command": "dotnet",
"type": "process",
"group": "test",
"args": [
"test",
"${workspaceFolder}/Microsoft.OpenApi.sln",
"/property:GenerateFullPaths=true",
"/t:build"
"/consoleloggerparameters:NoSummary",
"--collect:\"XPlat Code Coverage\""
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"group": "build",
"presentation": {
"reveal": "silent"
},
"args": [
"watch",
"run",
"${workspaceFolder}/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
Expand Down
6 changes: 3 additions & 3 deletions Microsoft.OpenApi.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29613.14
# Visual Studio Version 17
VisualStudioVersion = 17.1.32210.238
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.OpenApi", "src\Microsoft.OpenApi\Microsoft.OpenApi.csproj", "{A8E50143-69B2-472A-9D45-3F9A05D13202}"
EndProject
Expand All @@ -12,7 +12,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
readme.md = readme.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.OpenApi.Workbench", "src\Microsoft.OpenApi.Workbench\Microsoft.OpenApi.Workbench.csproj", "{6A5E91E5-0441-46EE-AEB9-8334981B7F08}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.OpenApi.Workbench", "src\Microsoft.OpenApi.Workbench\Microsoft.OpenApi.Workbench.csproj", "{6A5E91E5-0441-46EE-AEB9-8334981B7F08}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.OpenApi.Readers", "src\Microsoft.OpenApi.Readers\Microsoft.OpenApi.Readers.csproj", "{79933258-0126-4382-8755-D50820ECC483}"
EndProject
Expand Down
11 changes: 8 additions & 3 deletions src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>9.0</LangVersion>
<PackAsTool>true</PackAsTool>
<PackageIconUrl>http://go.microsoft.com/fwlink/?LinkID=288890</PackageIconUrl>
<PackageProjectUrl>https://github.com/Microsoft/OpenAPI.NET</PackageProjectUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
Expand All @@ -14,12 +15,14 @@
<PackageId>Microsoft.OpenApi.Hidi</PackageId>
<ToolCommandName>hidi</ToolCommandName>
<PackageOutputPath>./../../artifacts</PackageOutputPath>
<Version>0.5.0-preview4</Version>
<Version>0.5.0-preview5</Version>
<Description>OpenAPI.NET CLI tool for slicing OpenAPI documents</Description>
<Copyright>© Microsoft Corporation. All rights reserved.</Copyright>
<PackageTags>OpenAPI .NET</PackageTags>
<RepositoryUrl>https://github.com/Microsoft/OpenAPI.NET</RepositoryUrl>
<PackageReleaseNotes>
- Publish symbols.
- Upgrades Microsoft.OpenApi.OData to 1.0.10-preview1
- Fixes an issue where hidi would not process async operations
</PackageReleaseNotes>
<AssemblyName>Microsoft.OpenApi.Hidi</AssemblyName>
<RootNamespace>Microsoft.OpenApi.Hidi</RootNamespace>
Expand All @@ -34,6 +37,8 @@
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta2.21617.1" />
<PackageReference Include="Microsoft.OData.Edm" Version="7.10.0" />
<PackageReference Include="Microsoft.OpenApi.OData" Version="1.0.10-preview2" />
</ItemGroup>

<ItemGroup>
Expand Down
140 changes: 107 additions & 33 deletions src/Microsoft.OpenApi.Hidi/OpenApiService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using System.Xml.Linq;
using Microsoft.OData.Edm.Csdl;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.OData;
using Microsoft.OpenApi.Readers;
using Microsoft.OpenApi.Services;
using Microsoft.OpenApi.Validations;
Expand All @@ -24,8 +27,9 @@ namespace Microsoft.OpenApi.Hidi
{
public class OpenApiService
{
public static async void ProcessOpenApiDocument(
public static async Task ProcessOpenApiDocument(
string openapi,
string csdl,
FileInfo output,
OpenApiSpecVersion? version,
OpenApiFormat? format,
Expand All @@ -41,9 +45,9 @@ string filterbycollection

try
{
if (string.IsNullOrEmpty(openapi))
if (string.IsNullOrEmpty(openapi) && string.IsNullOrEmpty(csdl))
{
throw new ArgumentNullException(nameof(openapi));
throw new ArgumentNullException("Please input a file path");
}
}
catch (ArgumentNullException ex)
Expand Down Expand Up @@ -75,36 +79,56 @@ string filterbycollection
logger.LogError(ex.Message);
return;
}

var stream = await GetStream(openapi, logger);

// Parsing OpenAPI file
Stream stream;
OpenApiDocument document;
OpenApiFormat openApiFormat;
var stopwatch = new Stopwatch();
stopwatch.Start();
logger.LogTrace("Parsing OpenApi file");
var result = new OpenApiStreamReader(new OpenApiReaderSettings
{
ReferenceResolution = resolveexternal ? ReferenceResolutionSetting.ResolveAllReferences : ReferenceResolutionSetting.ResolveLocalReferences,
RuleSet = ValidationRuleSet.GetDefaultRuleSet()
}
).ReadAsync(stream).GetAwaiter().GetResult();
var document = result.OpenApiDocument;
stopwatch.Stop();

var context = result.OpenApiDiagnostic;
if (context.Errors.Count > 0)
if (!string.IsNullOrEmpty(csdl))
{
var errorReport = new StringBuilder();
// Default to yaml and OpenApiVersion 3 during csdl to OpenApi conversion
openApiFormat = format ?? GetOpenApiFormat(csdl, logger);
version ??= OpenApiSpecVersion.OpenApi3_0;

foreach (var error in context.Errors)
{
errorReport.AppendLine(error.ToString());
}
logger.LogError($"{stopwatch.ElapsedMilliseconds}ms: OpenApi Parsing errors {string.Join(Environment.NewLine, context.Errors.Select(e => e.Message).ToArray())}");
stream = await GetStream(csdl, logger);
document = await ConvertCsdlToOpenApi(stream);
}
else
{
logger.LogTrace("{timestamp}ms: Parsed OpenApi successfully. {count} paths found.", stopwatch.ElapsedMilliseconds, document.Paths.Count);
stream = await GetStream(openapi, logger);

// Parsing OpenAPI file
stopwatch.Start();
logger.LogTrace("Parsing OpenApi file");
var result = new OpenApiStreamReader(new OpenApiReaderSettings
{
ReferenceResolution = resolveexternal ? ReferenceResolutionSetting.ResolveAllReferences : ReferenceResolutionSetting.ResolveLocalReferences,
RuleSet = ValidationRuleSet.GetDefaultRuleSet()
}
).ReadAsync(stream).GetAwaiter().GetResult();

document = result.OpenApiDocument;
stopwatch.Stop();

var context = result.OpenApiDiagnostic;
if (context.Errors.Count > 0)
{
var errorReport = new StringBuilder();

foreach (var error in context.Errors)
{
errorReport.AppendLine(error.ToString());
}
logger.LogError($"{stopwatch.ElapsedMilliseconds}ms: OpenApi Parsing errors {string.Join(Environment.NewLine, context.Errors.Select(e => e.Message).ToArray())}");
}
else
{
logger.LogTrace("{timestamp}ms: Parsed OpenApi successfully. {count} paths found.", stopwatch.ElapsedMilliseconds, document.Paths.Count);
}

openApiFormat = format ?? GetOpenApiFormat(openapi, logger);
version ??= result.OpenApiDiagnostic.SpecificationVersion;
}

Func<string, OperationType?, OpenApiOperation, bool> predicate;
Expand Down Expand Up @@ -151,8 +175,6 @@ string filterbycollection
ReferenceInline = inline ? ReferenceInlineSetting.InlineLocalReferences : ReferenceInlineSetting.DoNotInlineReferences
};

var openApiFormat = format ?? GetOpenApiFormat(openapi, logger);
var openApiVersion = version ?? result.OpenApiDiagnostic.SpecificationVersion;
IOpenApiWriter writer = openApiFormat switch
{
OpenApiFormat.Json => new OpenApiJsonWriter(textWriter, settings),
Expand All @@ -163,14 +185,66 @@ string filterbycollection
logger.LogTrace("Serializing to OpenApi document using the provided spec version and writer");

stopwatch.Start();
document.Serialize(writer, openApiVersion);
document.Serialize(writer, (OpenApiSpecVersion)version);
stopwatch.Stop();

logger.LogTrace($"Finished serializing in {stopwatch.ElapsedMilliseconds}ms");

textWriter.Flush();
}

/// <summary>
/// Converts CSDL to OpenAPI
/// </summary>
/// <param name="csdl">The CSDL stream.</param>
/// <returns>An OpenAPI document.</returns>
public static async Task<OpenApiDocument> ConvertCsdlToOpenApi(Stream csdl)
{
using var reader = new StreamReader(csdl);
var csdlText = await reader.ReadToEndAsync();
var edmModel = CsdlReader.Parse(XElement.Parse(csdlText).CreateReader());

var settings = new OpenApiConvertSettings()
{
AddSingleQuotesForStringParameters = true,
AddEnumDescriptionExtension = true,
DeclarePathParametersOnPathItem = true,
EnableKeyAsSegment = true,
EnableOperationId = true,
ErrorResponsesAsDefault = false,
PrefixEntityTypeNameBeforeKey = true,
TagDepth = 2,
EnablePagination = true,
EnableDiscriminatorValue = false,
EnableDerivedTypesReferencesForRequestBody = false,
EnableDerivedTypesReferencesForResponses = false,
ShowRootPath = true,
ShowLinks = true
};
OpenApiDocument document = edmModel.ConvertToOpenApi(settings);

document = FixReferences(document);

return document;
}

/// <summary>
/// Fixes the references in the resulting OpenApiDocument.
/// </summary>
/// <param name="document"> The converted OpenApiDocument.</param>
/// <returns> A valid OpenApiDocument instance.</returns>
public static OpenApiDocument FixReferences(OpenApiDocument document)
{
// This method is only needed because the output of ConvertToOpenApi isn't quite a valid OpenApiDocument instance.
// So we write it out, and read it back in again to fix it up.

var sb = new StringBuilder();
document.SerializeAsV3(new OpenApiYamlWriter(new StringWriter(sb)));
var doc = new OpenApiStringReader().Read(sb.ToString(), out _);

return doc;
}

private static async Task<Stream> GetStream(string input, ILogger logger)
{
var stopwatch = new Stopwatch();
Expand All @@ -181,13 +255,13 @@ private static async Task<Stream> GetStream(string input, ILogger logger)
{
try
{
using var httpClientHandler = new HttpClientHandler()
var httpClientHandler = new HttpClientHandler()
{
SslProtocols = System.Security.Authentication.SslProtocols.Tls12,
};
using var httpClient = new HttpClient(httpClientHandler)
{
DefaultRequestVersion = HttpVersion.Version20
DefaultRequestVersion = HttpVersion.Version20
};
stream = await httpClient.GetStreamAsync(input);
}
Expand Down Expand Up @@ -253,7 +327,7 @@ public static Dictionary<string, List<string>> ParseJsonCollectionFile(Stream st
return requestUrls;
}

internal static async void ValidateOpenApiDocument(string openapi, LogLevel loglevel)
internal static async Task ValidateOpenApiDocument(string openapi, LogLevel loglevel)
{
if (string.IsNullOrEmpty(openapi))
{
Expand Down Expand Up @@ -286,10 +360,10 @@ internal static async void ValidateOpenApiDocument(string openapi, LogLevel logl
Console.WriteLine(statsVisitor.GetStatisticsReport());
}

private static OpenApiFormat GetOpenApiFormat(string openapi, ILogger logger)
private static OpenApiFormat GetOpenApiFormat(string input, ILogger logger)
{
logger.LogTrace("Getting the OpenApi format");
return !openapi.StartsWith("http") && Path.GetExtension(openapi) == ".json" ? OpenApiFormat.Json : OpenApiFormat.Yaml;
return !input.StartsWith("http") && Path.GetExtension(input) == ".json" ? OpenApiFormat.Json : OpenApiFormat.Yaml;
}

private static ILogger ConfigureLoggerInstance(LogLevel loglevel)
Expand Down
8 changes: 6 additions & 2 deletions src/Microsoft.OpenApi.Hidi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ static async Task<int> Main(string[] args)
var descriptionOption = new Option<string>("--openapi", "Input OpenAPI description file path or URL");
descriptionOption.AddAlias("-d");

var csdlOption = new Option<string>("--csdl", "Input CSDL file path or URL");
csdlOption.AddAlias("-cs");

var outputOption = new Option<FileInfo>("--output", () => new FileInfo("./output"), "The output directory path for the generated file.") { Arity = ArgumentArity.ZeroOrOne };
outputOption.AddAlias("-o");

Expand Down Expand Up @@ -57,6 +60,7 @@ static async Task<int> Main(string[] args)
var transformCommand = new Command("transform")
{
descriptionOption,
csdlOption,
outputOption,
versionOption,
formatOption,
Expand All @@ -68,8 +72,8 @@ static async Task<int> Main(string[] args)
resolveExternalOption,
};

transformCommand.SetHandler<string, FileInfo, OpenApiSpecVersion?, OpenApiFormat?, LogLevel, bool, bool, string, string, string> (
OpenApiService.ProcessOpenApiDocument, descriptionOption, outputOption, versionOption, formatOption, logLevelOption, inlineOption, resolveExternalOption, filterByOperationIdsOption, filterByTagsOption, filterByCollectionOption);
transformCommand.SetHandler<string, string, FileInfo, OpenApiSpecVersion?, OpenApiFormat?, LogLevel, bool, bool, string, string, string> (
OpenApiService.ProcessOpenApiDocument, descriptionOption, csdlOption, outputOption, versionOption, formatOption, logLevelOption, inlineOption, resolveExternalOption, filterByOperationIdsOption, filterByTagsOption, filterByCollectionOption);

rootCommand.Add(transformCommand);
rootCommand.Add(validateCommand);
Expand Down
Loading