Skip to content

Commit

Permalink
Merge pull request #1445 from microsoft/vnext
Browse files Browse the repository at this point in the history
Release new versions of OpenAPI.NET libraries
  • Loading branch information
irvinesunday authored Oct 30, 2023
2 parents 2ade929 + 51890ee commit 1bec222
Show file tree
Hide file tree
Showing 285 changed files with 3,066 additions and 4,193 deletions.
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ csharp_prefer_braces = true:silent
csharp_style_deconstructed_variable_declaration = true:suggestion
csharp_prefer_simple_default_expression = true:suggestion
csharp_style_pattern_local_over_anonymous_function = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_inlined_variable_declaration = true:error
###############################
# C# Formatting Rules #
###############################
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.OpenApi.Hidi/Extensions/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public static IList<string> SplitByChar(this string target, char separator)
{
return new List<string>();
}
return target.Split(new char[] { separator }, StringSplitOptions.RemoveEmptyEntries).ToList();
return target.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries).ToList();
}
}
}
8 changes: 4 additions & 4 deletions src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ private static string SingularizeAndDeduplicateOperationId(IList<string> operati
var lastSegmentIndex = segmentsCount - 1;
var singularizedSegments = new List<string>();

for (int x = 0; x < segmentsCount; x++)
for (var x = 0; x < segmentsCount; x++)
{
var segment = operationIdSegments[x].Singularize(inputIsKnownToBePlural: false);

Expand Down Expand Up @@ -163,10 +163,10 @@ private static IList<OpenApiParameter> ResolveFunctionParameters(IList<OpenApiPa
// Replace content with a schema object of type array
// for structured or collection-valued function parameters
parameter.Content = null;
parameter.Schema = new OpenApiSchema
parameter.Schema = new()
{
Type = "array",
Items = new OpenApiSchema
Items = new()
{
Type = "string"
}
Expand All @@ -179,7 +179,7 @@ private void AddAdditionalPropertiesToSchema(OpenApiSchema schema)
{
if (schema != null && !_schemaLoop.Contains(schema) && "object".Equals(schema.Type, StringComparison.OrdinalIgnoreCase))
{
schema.AdditionalProperties = new OpenApiSchema { Type = "object" };
schema.AdditionalProperties = new() { Type = "object" };

/* Because 'additionalProperties' are now being walked,
* we need a way to keep track of visited schemas to avoid
Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.OpenApi.Hidi/Handlers/PluginCommandHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ public int Invoke(InvocationContext context)
}
public async Task<int> InvokeAsync(InvocationContext context)
{
HidiOptions hidiOptions = new HidiOptions(context.ParseResult, CommandOptions);
CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetRequiredService(typeof(CancellationToken));
var hidiOptions = new HidiOptions(context.ParseResult, CommandOptions);
var cancellationToken = (CancellationToken)context.BindingContext.GetRequiredService(typeof(CancellationToken));

using var loggerFactory = Logger.ConfigureLogger(hidiOptions.LogLevel);
var logger = loggerFactory.CreateLogger<PluginCommandHandler>();
Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ public int Invoke(InvocationContext context)
}
public async Task<int> InvokeAsync(InvocationContext context)
{
HidiOptions hidiOptions = new HidiOptions(context.ParseResult, CommandOptions);
CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetRequiredService(typeof(CancellationToken));
var hidiOptions = new HidiOptions(context.ParseResult, CommandOptions);
var cancellationToken = (CancellationToken)context.BindingContext.GetRequiredService(typeof(CancellationToken));

using var loggerFactory = Logger.ConfigureLogger(hidiOptions.LogLevel);
var logger = loggerFactory.CreateLogger<ShowCommandHandler>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ public int Invoke(InvocationContext context)
}
public async Task<int> InvokeAsync(InvocationContext context)
{
HidiOptions hidiOptions = new HidiOptions(context.ParseResult, CommandOptions);
CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetRequiredService(typeof(CancellationToken));
var hidiOptions = new HidiOptions(context.ParseResult, CommandOptions);
var cancellationToken = (CancellationToken)context.BindingContext.GetRequiredService(typeof(CancellationToken));

using var loggerFactory = Logger.ConfigureLogger(hidiOptions.LogLevel);
var logger = loggerFactory.CreateLogger<TransformCommandHandler>();
Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ public int Invoke(InvocationContext context)
}
public async Task<int> InvokeAsync(InvocationContext context)
{
HidiOptions hidiOptions = new HidiOptions(context.ParseResult, CommandOptions);
CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetRequiredService(typeof(CancellationToken));
var hidiOptions = new HidiOptions(context.ParseResult, CommandOptions);
var cancellationToken = (CancellationToken)context.BindingContext.GetRequiredService(typeof(CancellationToken));
using var loggerFactory = Logger.ConfigureLogger(hidiOptions.LogLevel);
var logger = loggerFactory.CreateLogger<ValidateCommandHandler>();
try
Expand Down
5 changes: 1 addition & 4 deletions src/Microsoft.OpenApi.Hidi/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@ public static ILoggerFactory ConfigureLogger(LogLevel logLevel)
return LoggerFactory.Create((builder) =>
{
builder
.AddSimpleConsole(c =>
{
c.IncludeScopes = true;
})
.AddSimpleConsole(c => c.IncludeScopes = true)
#if DEBUG
.AddDebug()
#endif
Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<Nullable>enable</Nullable>
<ToolCommandName>hidi</ToolCommandName>
<PackageOutputPath>./../../artifacts</PackageOutputPath>
<Version>1.3.1</Version>
<Version>1.3.2</Version>
<Description>OpenAPI.NET CLI tool for slicing OpenAPI documents</Description>
<SignAssembly>true</SignAssembly>
<!-- https://github.com/dotnet/sourcelink/blob/main/docs/README.md#embeduntrackedsources -->
Expand All @@ -35,7 +35,7 @@
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="7.0.0" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
<PackageReference Include="Microsoft.OData.Edm" Version="7.18.0" />
<PackageReference Include="Microsoft.OpenApi.OData" Version="1.5.0-preview5" />
<PackageReference Include="Microsoft.OpenApi.OData" Version="1.5.0-preview7" />
<PackageReference Include="Microsoft.OpenApi.ApiManifest" Version="0.5.0-preview" />
<PackageReference Include="System.CommandLine.Hosting" Version="0.4.0-alpha.22272.1" />
</ItemGroup>
Expand Down
34 changes: 17 additions & 17 deletions src/Microsoft.OpenApi.Hidi/OpenApiService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public static async Task TransformOpenApiDocument(HidiOptions options, ILogger l
if (options.Output == null)
{
var inputExtension = GetInputPathExtension(options.OpenApi, options.Csdl);
options.Output = new FileInfo($"./output{inputExtension}");
options.Output = new($"./output{inputExtension}");
};

if (options.CleanOutput && options.Output.Exists)
Expand All @@ -66,8 +66,8 @@ public static async Task TransformOpenApiDocument(HidiOptions options, ILogger l
}

// Default to yaml and OpenApiVersion 3 during csdl to OpenApi conversion
OpenApiFormat openApiFormat = options.OpenApiFormat ?? (!string.IsNullOrEmpty(options.OpenApi) ? GetOpenApiFormat(options.OpenApi, logger) : OpenApiFormat.Yaml);
OpenApiSpecVersion openApiVersion = options.Version != null ? TryParseOpenApiSpecVersion(options.Version) : OpenApiSpecVersion.OpenApi3_0;
var openApiFormat = options.OpenApiFormat ?? (!string.IsNullOrEmpty(options.OpenApi) ? GetOpenApiFormat(options.OpenApi, logger) : OpenApiFormat.Yaml);
var openApiVersion = options.Version != null ? TryParseOpenApiSpecVersion(options.Version) : OpenApiSpecVersion.OpenApi3_0;

// If ApiManifest is provided, set the referenced OpenAPI document
var apiDependency = await FindApiDependency(options.FilterOptions.FilterByApiManifest, logger, cancellationToken).ConfigureAwait(false);
Expand All @@ -85,7 +85,7 @@ public static async Task TransformOpenApiDocument(HidiOptions options, ILogger l
}

// Load OpenAPI document
OpenApiDocument document = await GetOpenApi(options, logger, options.MetadataVersion, cancellationToken).ConfigureAwait(false);
var document = await GetOpenApi(options, logger, options.MetadataVersion, cancellationToken).ConfigureAwait(false);

if (options.FilterOptions != null)
{
Expand Down Expand Up @@ -194,7 +194,7 @@ private static void WriteOpenApi(HidiOptions options, OpenApiFormat openApiForma

IOpenApiWriter writer = openApiFormat switch
{
OpenApiFormat.Json => options.TerseOutput ? new OpenApiJsonWriter(textWriter, settings, options.TerseOutput) : new OpenApiJsonWriter(textWriter, settings, false),
OpenApiFormat.Json => options.TerseOutput ? new(textWriter, settings, options.TerseOutput) : new OpenApiJsonWriter(textWriter, settings, false),
OpenApiFormat.Yaml => new OpenApiYamlWriter(textWriter, settings),
_ => throw new ArgumentException("Unknown format"),
};
Expand Down Expand Up @@ -227,7 +227,7 @@ private static async Task<OpenApiDocument> GetOpenApi(HidiOptions options, ILogg
Stream? filteredStream = null;
if (!string.IsNullOrEmpty(options.CsdlFilter))
{
XslCompiledTransform transform = GetFilterTransform();
var transform = GetFilterTransform();
filteredStream = ApplyFilterToCsdl(stream, options.CsdlFilter, transform);
filteredStream.Position = 0;
await stream.DisposeAsync().ConfigureAwait(false);
Expand Down Expand Up @@ -299,7 +299,7 @@ private static Dictionary<string, List<string>> GetRequestUrlsFromManifest(ApiDe
private static XslCompiledTransform GetFilterTransform()
{
XslCompiledTransform transform = new();
Assembly assembly = typeof(OpenApiService).GetTypeInfo().Assembly;
var assembly = typeof(OpenApiService).GetTypeInfo().Assembly;
using var xslt = assembly.GetManifestResourceStream("Microsoft.OpenApi.Hidi.CsdlFilter.xslt") ?? throw new InvalidOperationException("Could not find the Microsoft.OpenApi.Hidi.CsdlFilter.xslt file in the assembly. Check build configuration.");
using var streamReader = new StreamReader(xslt);
using var textReader = new XmlTextReader(streamReader);
Expand All @@ -310,7 +310,7 @@ private static XslCompiledTransform GetFilterTransform()
private static Stream ApplyFilterToCsdl(Stream csdlStream, string entitySetOrSingleton, XslCompiledTransform transform)
{
using StreamReader inputReader = new(csdlStream, leaveOpen: true);
using XmlReader inputXmlReader = XmlReader.Create(inputReader);
using var inputXmlReader = XmlReader.Create(inputReader);
MemoryStream filteredStream = new();
using StreamWriter writer = new(filteredStream, leaveOpen: true);
XsltArgumentList args = new();
Expand Down Expand Up @@ -363,16 +363,16 @@ public static async Task ValidateOpenApiDocument(
private static async Task<ReadResult> ParseOpenApi(string openApiFile, bool inlineExternal, ILogger logger, Stream stream, CancellationToken cancellationToken = default)
{
ReadResult result;
Stopwatch stopwatch = Stopwatch.StartNew();
var stopwatch = Stopwatch.StartNew();
using (logger.BeginScope("Parsing OpenAPI: {OpenApiFile}", openApiFile))
{
stopwatch.Start();

result = await new OpenApiStreamReader(new OpenApiReaderSettings
{
result = await new OpenApiStreamReader(new()
{
LoadExternalRefs = inlineExternal,
BaseUrl = openApiFile.StartsWith("http", StringComparison.OrdinalIgnoreCase) ?
new Uri(openApiFile) :
new(openApiFile) :
new Uri("file://" + new FileInfo(openApiFile).DirectoryName + Path.DirectorySeparatorChar)
}
).ReadAsync(stream, cancellationToken).ConfigureAwait(false);
Expand All @@ -398,7 +398,7 @@ public static async Task<OpenApiDocument> ConvertCsdlToOpenApi(Stream csdl, stri
var edmModel = CsdlReader.Parse(XElement.Parse(csdlText).CreateReader());
settings ??= SettingsUtilities.GetConfiguration();

OpenApiDocument document = edmModel.ConvertToOpenApi(SettingsUtilities.GetOpenApiConvertSettings(settings, metadataVersion));
var document = edmModel.ConvertToOpenApi(SettingsUtilities.GetOpenApiConvertSettings(settings, metadataVersion));
document = FixReferences(document);

return document;
Expand Down Expand Up @@ -459,7 +459,7 @@ private static Dictionary<string, List<string>> EnumerateJsonDocument(JsonElemen
}
else
{
paths.Add(path, new List<string> {method});
paths.Add(path, new() {method});
}
}
else
Expand Down Expand Up @@ -725,7 +725,7 @@ internal static async Task PluginManifest(HidiOptions options, ILogger logger, C
}

// Load OpenAPI document
OpenApiDocument document = await GetOpenApi(options, logger, options.MetadataVersion, cancellationToken).ConfigureAwait(false);
var document = await GetOpenApi(options, logger, options.MetadataVersion, cancellationToken).ConfigureAwait(false);

cancellationToken.ThrowIfCancellationRequested();

Expand All @@ -741,7 +741,7 @@ internal static async Task PluginManifest(HidiOptions options, ILogger logger, C
outputFolder.Create();
}
// Write OpenAPI to Output folder
options.Output = new FileInfo(Path.Combine(options.OutputFolder, "openapi.json"));
options.Output = new(Path.Combine(options.OutputFolder, "openapi.json"));
options.TerseOutput = true;
WriteOpenApi(options, OpenApiFormat.Json, OpenApiSpecVersion.OpenApi3_0, document, logger);

Expand All @@ -762,7 +762,7 @@ internal static async Task PluginManifest(HidiOptions options, ILogger logger, C
// Write OpenAIPluginManifest to Output folder
var manifestFile = new FileInfo(Path.Combine(options.OutputFolder, "ai-plugin.json"));
using var file = new FileStream(manifestFile.FullName, FileMode.Create);
using var jsonWriter = new Utf8JsonWriter(file, new JsonWriterOptions { Indented = true });
using var jsonWriter = new Utf8JsonWriter(file, new() { Indented = true });
manifest.Write(jsonWriter);
await jsonWriter.FlushAsync(cancellationToken).ConfigureAwait(false);
}
Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.OpenApi.Hidi/OpenApiSpecVersionHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ public static OpenApiSpecVersion TryParseOpenApiSpecVersion(string value)
}
var res = value.Split('.', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault();

if (int.TryParse(res, out int result))
if (int.TryParse(res, out var result))
{
if (result >= 2 && result < 3)
if (result is >= 2 and < 3)
{
return OpenApiSpecVersion.OpenApi2_0;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.OpenApi.Hidi/Options/HidiOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ private void ParseHidiOptions(ParseResult parseResult, CommandOptions options)
LogLevel = parseResult.GetValueForOption(options.LogLevelOption);
InlineLocal = parseResult.GetValueForOption(options.InlineLocalOption);
InlineExternal = parseResult.GetValueForOption(options.InlineExternalOption);
FilterOptions = new FilterOptions
FilterOptions = new()
{
FilterByOperationIds = parseResult.GetValueForOption(options.FilterByOperationIdsOption),
FilterByTags = parseResult.GetValueForOption(options.FilterByTagsOption),
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.OpenApi.Readers/Interface/IStreamLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public interface IStreamLoader
/// Use Uri to locate data and convert into an input object.
/// </summary>
/// <param name="uri">Identifier of some source of an OpenAPI Description</param>
/// <returns>A data objext that can be processed by a reader to generate an <see cref="OpenApiDocument"/></returns>
/// <returns>A data object that can be processed by a reader to generate an <see cref="OpenApiDocument"/></returns>
Task<Stream> LoadAsync(Uri uri);

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>1.6.9</Version>
<Version>1.6.10</Version>
<Description>OpenAPI.NET Readers for JSON and YAML documents</Description>
<SignAssembly>true</SignAssembly>
<!-- https://github.com/dotnet/sourcelink/blob/main/docs/README.md#embeduntrackedsources -->
Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ public void AppendDiagnostic(OpenApiDiagnostic diagnosticToAdd, string fileNameT
foreach (var err in diagnosticToAdd.Errors)
{
var errMsgWithFileName = fileNameIsSupplied ? $"[File: {fileNameToAdd}] {err.Message}" : err.Message;
Errors.Add(new OpenApiError(err.Pointer, errMsgWithFileName));
Errors.Add(new(err.Pointer, errMsgWithFileName));
}
foreach (var warn in diagnosticToAdd.Warnings)
{
var warnMsgWithFileName = fileNameIsSupplied ? $"[File: {fileNameToAdd}] {warn.Message}" : warn.Message;
Warnings.Add(new OpenApiError(warn.Pointer, warnMsgWithFileName));
Warnings.Add(new(warn.Pointer, warnMsgWithFileName));
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public class OpenApiReaderSettings
/// <summary>
/// Dictionary of parsers for converting extensions into strongly typed classes
/// </summary>
public Dictionary<string, Func<IOpenApiAny, OpenApiSpecVersion, IOpenApiExtension>> ExtensionParsers { get; set; } = new Dictionary<string, Func<IOpenApiAny, OpenApiSpecVersion, IOpenApiExtension>>();
public Dictionary<string, Func<IOpenApiAny, OpenApiSpecVersion, IOpenApiExtension>> ExtensionParsers { get; set; } = new();

/// <summary>
/// Rules to use for validating OpenAPI specification. If none are provided a default set of rules are applied.
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public async Task<ReadResult> ReadAsync(Stream input, CancellationToken cancella
{
// Buffer stream so that OpenApiTextReaderReader can process it synchronously
// YamlDocument doesn't support async reading.
bufferedStream = new MemoryStream();
bufferedStream = new();
await input.CopyToAsync(bufferedStream, 81920, cancellationToken);
bufferedStream.Position = 0;
}
Expand Down
Loading

0 comments on commit 1bec222

Please sign in to comment.