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 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
40 changes: 29 additions & 11 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)

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 @@ -544,7 +544,7 @@

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,52 +665,70 @@
Utils.CheckArgumentNull(componentToRegister);
Utils.CheckArgumentNullOrEmpty(id);
Components ??= new();

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

bool added = false;
switch (componentToRegister)
{
case IOpenApiSchema openApiSchema:
Components.Schemas ??= [];
Components.Schemas.Add(id, openApiSchema);
added = AddToDictionary(Components.Schemas, id, openApiSchema);
break;
case IOpenApiParameter openApiParameter:
Components.Parameters ??= [];
Components.Parameters.Add(id, openApiParameter);
added = AddToDictionary(Components.Parameters, id, openApiParameter);
break;
case IOpenApiResponse openApiResponse:
Components.Responses ??= [];
Components.Responses.Add(id, openApiResponse);
added = AddToDictionary(Components.Responses, id, openApiResponse);
break;
case IOpenApiRequestBody openApiRequestBody:
Components.RequestBodies ??= [];
Components.RequestBodies.Add(id, openApiRequestBody);
added = AddToDictionary(Components.RequestBodies, id, openApiRequestBody);
break;
case IOpenApiLink openApiLink:
Components.Links ??= [];
Components.Links.Add(id, openApiLink);
added = AddToDictionary(Components.Links, id, openApiLink);
break;
case IOpenApiCallback openApiCallback:
Components.Callbacks ??= [];
Components.Callbacks.Add(id, openApiCallback);
added = AddToDictionary(Components.Callbacks, id, openApiCallback);
break;
case IOpenApiPathItem openApiPathItem:
Components.PathItems ??= [];
Components.PathItems.Add(id, openApiPathItem);
added = AddToDictionary(Components.PathItems, id, openApiPathItem);
break;
case IOpenApiExample openApiExample:
Components.Examples ??= [];
Components.Examples.Add(id, openApiExample);
added = AddToDictionary(Components.Examples, id, openApiExample);
break;
case IOpenApiHeader openApiHeader:
Components.Headers ??= [];
Components.Headers.Add(id, openApiHeader);
added = AddToDictionary(Components.Headers, id, openApiHeader);
break;
case IOpenApiSecurityScheme openApiSecurityScheme:
Components.SecuritySchemes ??= [];
Components.SecuritySchemes.Add(id, openApiSecurityScheme);
added = AddToDictionary(Components.SecuritySchemes, id, openApiSecurityScheme);
break;
default:
throw new ArgumentException($"Component type {componentToRegister!.GetType().Name} is not supported.");
}
return Workspace?.RegisterComponentForDocument(this, componentToRegister, id) ?? false;

// Register only if it was actually added to the collection
return added && (Workspace?.RegisterComponentForDocument(this, componentToRegister, id) ?? false);
}
}

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