Skip to content

fix: refactor to avoid adding duplicate entries #2359

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

Merged
merged 3 commits into from
May 19, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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
45 changes: 25 additions & 20 deletions src/Microsoft.OpenApi/Models/OpenApiDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@
{
return;
}
_tags = value is HashSet<OpenApiTag> tags && tags.Comparer is OpenApiTagComparer ?

Check warning on line 92 in src/Microsoft.OpenApi/Models/OpenApiDocument.cs

View workflow job for this annotation

GitHub Actions / Build

Change this condition so that it does not always evaluate to 'True'. (https://rules.sonarsource.com/csharp/RSPEC-2589)

Check warning on line 92 in src/Microsoft.OpenApi/Models/OpenApiDocument.cs

View workflow job for this annotation

GitHub Actions / Build

Change this condition so that it does not always evaluate to 'True'. (https://rules.sonarsource.com/csharp/RSPEC-2589)
tags :
new HashSet<OpenApiTag>(value, OpenApiTagComparer.Instance);
}
Expand Down Expand Up @@ -265,7 +265,7 @@
/// <summary>
/// Serialize <see cref="OpenApiDocument"/> to OpenAPI object V2.0.
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)

Check warning on line 268 in src/Microsoft.OpenApi/Models/OpenApiDocument.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 31 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)

Check warning on line 268 in src/Microsoft.OpenApi/Models/OpenApiDocument.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 31 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
Utils.CheckArgumentNull(writer);

Expand Down Expand Up @@ -414,7 +414,7 @@
return server.ReplaceServerUrlVariables([]);
}

private static void WriteHostInfoV2(IOpenApiWriter writer, List<OpenApiServer>? servers)

Check warning on line 417 in src/Microsoft.OpenApi/Models/OpenApiDocument.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 21 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)

Check warning on line 417 in src/Microsoft.OpenApi/Models/OpenApiDocument.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 21 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
if (servers == null || !servers.Any())
{
Expand Down Expand Up @@ -483,7 +483,7 @@
// schemes
writer.WriteOptionalCollection(OpenApiConstants.Schemes, schemes, (w, s) =>
{
if(!string.IsNullOrEmpty(s) && s is not null)

Check warning on line 486 in src/Microsoft.OpenApi/Models/OpenApiDocument.cs

View workflow job for this annotation

GitHub Actions / Build

Change this condition so that it does not always evaluate to 'True'. (https://rules.sonarsource.com/csharp/RSPEC-2589)
{
w.WriteValue(s);
}
Expand Down Expand Up @@ -537,14 +537,14 @@

await WriteDocumentAsync(streamWriter, cancellationToken).ConfigureAwait(false);

cryptoStream.FlushFinalBlock();

Check warning on line 540 in src/Microsoft.OpenApi/Models/OpenApiDocument.cs

View workflow job for this annotation

GitHub Actions / Build

Await FlushFinalBlockAsync instead. (https://rules.sonarsource.com/csharp/RSPEC-6966)

var hash = sha.Hash;
#endif

return ConvertByteArrayToString(hash ?? []);

async Task WriteDocumentAsync(TextWriter writer, CancellationToken token)

Check warning on line 547 in src/Microsoft.OpenApi/Models/OpenApiDocument.cs

View workflow job for this annotation

GitHub Actions / Build

Remove this unused method parameter 'token'. (https://rules.sonarsource.com/csharp/RSPEC-1172)

Check warning on line 547 in src/Microsoft.OpenApi/Models/OpenApiDocument.cs

View workflow job for this annotation

GitHub Actions / Build

Remove this unused method parameter 'token'. (https://rules.sonarsource.com/csharp/RSPEC-1172)
{
var openApiJsonWriter = new OpenApiJsonWriter(writer, new() { Terse = true });
SerializeAsV31(openApiJsonWriter);
Expand Down Expand Up @@ -665,47 +665,52 @@
Utils.CheckArgumentNull(componentToRegister);
Utils.CheckArgumentNullOrEmpty(id);
Components ??= new();

static Dictionary<string, TValue> AddToDictionary<TValue>(Dictionary<string, TValue>? dict, string key, TValue value)
{
dict ??= new Dictionary<string, TValue>();
#if NET5_0_OR_GREATER
dict.TryAdd(key, value);
#else
if (!dict.ContainsKey(key))
{
dict.Add(key, value);
}
#endif
return dict;
}

switch (componentToRegister)
{
case IOpenApiSchema openApiSchema:
Components.Schemas ??= [];
Components.Schemas.Add(id, openApiSchema);
Components.Schemas = AddToDictionary(Components.Schemas, id, openApiSchema);
break;
case IOpenApiParameter openApiParameter:
Components.Parameters ??= [];
Components.Parameters.Add(id, openApiParameter);
Components.Parameters = AddToDictionary(Components.Parameters, id, openApiParameter);
break;
case IOpenApiResponse openApiResponse:
Components.Responses ??= [];
Components.Responses.Add(id, openApiResponse);
Components.Responses = AddToDictionary(Components.Responses, id, openApiResponse);
break;
case IOpenApiRequestBody openApiRequestBody:
Components.RequestBodies ??= [];
Components.RequestBodies.Add(id, openApiRequestBody);
Components.RequestBodies = AddToDictionary(Components.RequestBodies, id, openApiRequestBody);
break;
case IOpenApiLink openApiLink:
Components.Links ??= [];
Components.Links.Add(id, openApiLink);
Components.Links = AddToDictionary(Components.Links, id, openApiLink);
break;
case IOpenApiCallback openApiCallback:
Components.Callbacks ??= [];
Components.Callbacks.Add(id, openApiCallback);
Components.Callbacks = AddToDictionary(Components.Callbacks, id, openApiCallback);
break;
case IOpenApiPathItem openApiPathItem:
Components.PathItems ??= [];
Components.PathItems.Add(id, openApiPathItem);
Components.PathItems = AddToDictionary(Components.PathItems, id, openApiPathItem);
break;
case IOpenApiExample openApiExample:
Components.Examples ??= [];
Components.Examples.Add(id, openApiExample);
Components.Examples = AddToDictionary(Components.Examples, id, openApiExample);
break;
case IOpenApiHeader openApiHeader:
Components.Headers ??= [];
Components.Headers.Add(id, openApiHeader);
Components.Headers = AddToDictionary(Components.Headers, id, openApiHeader);
break;
case IOpenApiSecurityScheme openApiSecurityScheme:
Components.SecuritySchemes ??= [];
Components.SecuritySchemes.Add(id, openApiSecurityScheme);
Components.SecuritySchemes = AddToDictionary(Components.SecuritySchemes, id, openApiSecurityScheme);
break;
default:
throw new ArgumentException($"Component type {componentToRegister!.GetType().Name} is not supported.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1270,6 +1270,7 @@ public async Task SerializesDoubleHopeReferences()
Description = "A reference to a pet"
};
document.AddComponent("PetReference", petSchemaReference);
document.AddComponent("Pet", petSchema); // does not add duplicate keys
document.Paths.Add("/pets", new OpenApiPathItem
{
Operations = new()
Expand Down