Skip to content

fix/unique tags #2167

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 6 commits into from
Feb 26, 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
21 changes: 19 additions & 2 deletions src/Microsoft.OpenApi/Models/OpenApiDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,27 @@
public IList<OpenApiSecurityRequirement>? SecurityRequirements { get; set; } =
new List<OpenApiSecurityRequirement>();

private HashSet<OpenApiTag>? _tags;
/// <summary>
/// A list of tags used by the specification with additional metadata.
/// </summary>
public IList<OpenApiTag>? Tags { get; set; } = new List<OpenApiTag>();
public ISet<OpenApiTag>? Tags
{
get
{
return _tags;
}
set
{
if (value is null)
{
return;
}
_tags = value is HashSet<OpenApiTag> tags && tags.Comparer is OpenApiTagComparer ?
tags :
new HashSet<OpenApiTag>(value, OpenApiTagComparer.Instance);
}
}

/// <summary>
/// Additional external documentation.
Expand Down Expand Up @@ -123,7 +140,7 @@
Webhooks = document?.Webhooks != null ? new Dictionary<string, IOpenApiPathItem>(document.Webhooks) : null;
Components = document?.Components != null ? new(document?.Components) : null;
SecurityRequirements = document?.SecurityRequirements != null ? new List<OpenApiSecurityRequirement>(document.SecurityRequirements) : null;
Tags = document?.Tags != null ? new List<OpenApiTag>(document.Tags) : null;
Tags = document?.Tags != null ? new HashSet<OpenApiTag>(document.Tags, OpenApiTagComparer.Instance) : null;
ExternalDocs = document?.ExternalDocs != null ? new(document?.ExternalDocs) : null;
Extensions = document?.Extensions != null ? new Dictionary<string, IOpenApiExtension>(document.Extensions) : null;
Annotations = document?.Annotations != null ? new Dictionary<string, object>(document.Annotations) : null;
Expand Down Expand Up @@ -222,7 +239,7 @@
/// <summary>
/// Serialize <see cref="OpenApiDocument"/> to OpenAPI object V2.0.
/// </summary>
public void SerializeAsV2(IOpenApiWriter writer)

Check warning on line 242 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 30 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
Utils.CheckArgumentNull(writer);

Expand Down Expand Up @@ -516,7 +533,7 @@
}
else
{
string relativePath = OpenApiConstants.ComponentsSegment + reference.Type.GetDisplayName() + "/" + reference.Id;

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

View workflow job for this annotation

GitHub Actions / Build

Remove this hardcoded path-delimiter. (https://rules.sonarsource.com/csharp/RSPEC-1075)

uriLocation = useExternal
? Workspace?.GetDocumentId(reference.ExternalResource)?.OriginalString + relativePath
Expand Down
21 changes: 19 additions & 2 deletions src/Microsoft.OpenApi/Models/OpenApiOperation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,28 @@ public class OpenApiOperation : IOpenApiSerializable, IOpenApiExtensible, IOpenA
/// </summary>
public const bool DeprecatedDefault = false;

private HashSet<OpenApiTagReference>? _tags;
/// <summary>
/// A list of tags for API documentation control.
/// Tags can be used for logical grouping of operations by resources or any other qualifier.
/// </summary>
public IList<OpenApiTagReference>? Tags { get; set; } = [];
public ISet<OpenApiTagReference>? Tags
{
get
{
return _tags;
}
set
{
if (value is null)
{
return;
}
_tags = value is HashSet<OpenApiTagReference> tags && tags.Comparer is OpenApiTagComparer ?
tags :
new HashSet<OpenApiTagReference>(value, OpenApiTagComparer.Instance);
}
}

/// <summary>
/// A short summary of what the operation does.
Expand Down Expand Up @@ -123,7 +140,7 @@ public OpenApiOperation() { }
public OpenApiOperation(OpenApiOperation operation)
{
Utils.CheckArgumentNull(operation);
Tags = operation.Tags != null ? new List<OpenApiTagReference>(operation.Tags) : null;
Tags = operation.Tags != null ? new HashSet<OpenApiTagReference>(operation.Tags) : null;
Summary = operation.Summary ?? Summary;
Description = operation.Description ?? Description;
ExternalDocs = operation.ExternalDocs != null ? new(operation.ExternalDocs) : null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public override OpenApiTag Target
{
get
{
return Reference.HostDocument?.Tags.FirstOrDefault(t => StringComparer.Ordinal.Equals(t.Name, Reference.Id));
return Reference.HostDocument?.Tags?.FirstOrDefault(t => OpenApiTagComparer.StringComparer.Equals(t.Name, Reference.Id));
}
}

Expand Down
47 changes: 47 additions & 0 deletions src/Microsoft.OpenApi/OpenApiTagComparer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using Microsoft.OpenApi.Models.Interfaces;

namespace Microsoft.OpenApi;

#nullable enable
/// <summary>
/// This comparer is used to maintain a globally unique list of tags encountered
/// in a particular OpenAPI document.
/// </summary>
internal sealed class OpenApiTagComparer : IEqualityComparer<IOpenApiTag>
{
private static readonly Lazy<OpenApiTagComparer> _lazyInstance = new(() => new OpenApiTagComparer());
/// <summary>
/// Default instance for the comparer.
/// </summary>
internal static OpenApiTagComparer Instance { get => _lazyInstance.Value; }

/// <inheritdoc/>
public bool Equals(IOpenApiTag? x, IOpenApiTag? y)
{
if (x is null && y is null)
{
return true;
}
if (x is null || y is null)
{
return false;
}
if (ReferenceEquals(x, y))
{
return true;
}
return StringComparer.Equals(x.Name, y.Name);
}

// Tag comparisons are case-sensitive by default. Although the OpenAPI specification
// only outlines case sensitivity for property names, we extend this principle to
// property values for tag names as well.
// See https://spec.openapis.org/oas/v3.1.0#format.
internal static readonly StringComparer StringComparer = StringComparer.Ordinal;

/// <inheritdoc/>
public int GetHashCode(IOpenApiTag obj) => string.IsNullOrEmpty(obj?.Name) ? 0 : StringComparer.GetHashCode(obj!.Name);
}
#nullable restore
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ internal static partial class OpenApiV2Deserializer
}
},
{"security", (o, n, _) => o.SecurityRequirements = n.CreateList(LoadSecurityRequirement, o)},
{"tags", (o, n, _) => o.Tags = n.CreateList(LoadTag, o)},
{"tags", (o, n, _) => { if (n.CreateList(LoadTag, o) is {Count:> 0} tags) {o.Tags = new HashSet<OpenApiTag>(tags, OpenApiTagComparer.Instance); } } },
{"externalDocs", (o, n, _) => o.ExternalDocs = LoadExternalDocs(n, o)}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@ internal static partial class OpenApiV2Deserializer
new()
{
{
"tags", (o, n, doc) => o.Tags = n.CreateSimpleList(
(valueNode, doc) =>
LoadTagByReference(
valueNode.GetScalarValue(), doc), doc)
"tags", (o, n, doc) => {
if (n.CreateSimpleList((valueNode, doc) => LoadTagByReference(valueNode.GetScalarValue(), doc), doc) is {Count: > 0} tags)
{
o.Tags = new HashSet<OpenApiTagReference>(tags, OpenApiTagComparer.Instance);
}
}
},
{
"summary",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT license.

using System;
using System.Collections.Generic;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Reader.ParseNodes;
Expand All @@ -26,7 +27,7 @@ internal static partial class OpenApiV3Deserializer
{"servers", (o, n, _) => o.Servers = n.CreateList(LoadServer, o)},
{"paths", (o, n, _) => o.Paths = LoadPaths(n, o)},
{"components", (o, n, _) => o.Components = LoadComponents(n, o)},
{"tags", (o, n, _) => o.Tags = n.CreateList(LoadTag, o) },
{"tags", (o, n, _) => { if (n.CreateList(LoadTag, o) is {Count:> 0} tags) {o.Tags = new HashSet<OpenApiTag>(tags, OpenApiTagComparer.Instance); } } },
{"externalDocs", (o, n, _) => o.ExternalDocs = LoadExternalDocs(n, o)},
{"security", (o, n, _) => o.SecurityRequirements = n.CreateList(LoadSecurityRequirement, o)}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT license.

using System;
using System.Collections.Generic;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Models.References;
Expand All @@ -19,10 +20,12 @@ internal static partial class OpenApiV3Deserializer
new()
{
{
"tags", (o, n, doc) => o.Tags = n.CreateSimpleList(
(valueNode, doc) =>
LoadTagByReference(
valueNode.GetScalarValue(), doc), doc)
"tags", (o, n, doc) => {
if (n.CreateSimpleList((valueNode, doc) => LoadTagByReference(valueNode.GetScalarValue(), doc), doc) is {Count: > 0} tags)
{
o.Tags = new HashSet<OpenApiTagReference>(tags, OpenApiTagComparer.Instance);
}
}
},
{
"summary",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Reader.ParseNodes;
Expand All @@ -24,7 +25,7 @@ internal static partial class OpenApiV31Deserializer
{"paths", (o, n, _) => o.Paths = LoadPaths(n, o)},
{"webhooks", (o, n, _) => o.Webhooks = n.CreateMap(LoadPathItem, o)},
{"components", (o, n, _) => o.Components = LoadComponents(n, o)},
{"tags", (o, n, _) => o.Tags = n.CreateList(LoadTag, o) },
{"tags", (o, n, _) => { if (n.CreateList(LoadTag, o) is {Count:> 0} tags) {o.Tags = new HashSet<OpenApiTag>(tags, OpenApiTagComparer.Instance); } } },
{"externalDocs", (o, n, _) => o.ExternalDocs = LoadExternalDocs(n, o)},
{"security", (o, n, _) => o.SecurityRequirements = n.CreateList(LoadSecurityRequirement, o)}
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Models.References;
Expand All @@ -16,9 +17,12 @@ internal static partial class OpenApiV31Deserializer
new()
{
{
"tags", (o, n, doc) => o.Tags = n.CreateSimpleList(
(valueNode, doc) =>
LoadTagByReference(valueNode.GetScalarValue(), doc), doc)
"tags", (o, n, doc) => {
if (n.CreateSimpleList((valueNode, doc) => LoadTagByReference(valueNode.GetScalarValue(), doc), doc) is {Count: > 0} tags)
{
o.Tags = new HashSet<OpenApiTagReference>(tags, OpenApiTagComparer.Instance);
}
}
},
{
"summary", (o, n, _) =>
Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.OpenApi/Services/OpenApiFilterService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -363,11 +363,11 @@ private static void ValidateFilters(IDictionary<string, List<string>> requestUrl
if (tagsArray.Length == 1)
{
var regex = new Regex(tagsArray[0]);
return (_, _, operation) => operation.Tags.Any(tag => regex.IsMatch(tag.Name));
return (_, _, operation) => operation.Tags?.Any(tag => regex.IsMatch(tag.Name)) ?? false;
}
else
{
return (_, _, operation) => operation.Tags.Any(tag => tagsArray.Contains(tag.Name));
return (_, _, operation) => operation.Tags?.Any(tag => tagsArray.Contains(tag.Name)) ?? false;
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -309,14 +309,14 @@ public virtual void Visit(IOpenApiExample example)
/// <summary>
/// Visits list of <see cref="OpenApiTag"/>
/// </summary>
public virtual void Visit(IList<OpenApiTag> openApiTags)
public virtual void Visit(ISet<OpenApiTag> openApiTags)
{
}

/// <summary>
/// Visits list of <see cref="OpenApiTagReference"/>
/// </summary>
public virtual void Visit(IList<OpenApiTagReference> openApiTags)
public virtual void Visit(ISet<OpenApiTagReference> openApiTags)
{
}

Expand Down
17 changes: 10 additions & 7 deletions src/Microsoft.OpenApi/Services/OpenApiWalker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Nodes;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Extensions;
Expand Down Expand Up @@ -60,7 +61,7 @@
/// <summary>
/// Visits list of <see cref="OpenApiTag"/> and child objects
/// </summary>
internal void Walk(IList<OpenApiTag> tags)
internal void Walk(ISet<OpenApiTag> tags)
{
if (tags == null)
{
Expand All @@ -70,19 +71,20 @@
_visitor.Visit(tags);

// Visit tags
if (tags != null)

Check warning on line 74 in src/Microsoft.OpenApi/Services/OpenApiWalker.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)
{
for (var i = 0; i < tags.Count; i++)
var tagsAsArray = tags.ToArray();
for (var i = 0; i < tagsAsArray.Length; i++)
{
Walk(i.ToString(), () => Walk(tags[i]));
Walk(i.ToString(), () => Walk(tagsAsArray[i]));
}
}
}

/// <summary>
/// Visits list of <see cref="OpenApiTagReference"/> and child objects
/// </summary>
internal void Walk(IList<OpenApiTagReference> tags)
internal void Walk(ISet<OpenApiTagReference> tags)
{
if (tags == null)
{
Expand All @@ -92,11 +94,12 @@
_visitor.Visit(tags);

// Visit tags
if (tags != null)

Check warning on line 97 in src/Microsoft.OpenApi/Services/OpenApiWalker.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)
{
for (var i = 0; i < tags.Count; i++)
var referencesAsArray = tags.ToArray();
for (var i = 0; i < referencesAsArray.Length; i++)
{
Walk(i.ToString(), () => Walk(tags[i]));
Walk(i.ToString(), () => Walk(referencesAsArray[i]));
}
}
}
Expand Down Expand Up @@ -130,7 +133,7 @@
/// <summary>
/// Visits <see cref="OpenApiComponents"/> and child objects
/// </summary>
internal void Walk(OpenApiComponents? components)

Check warning on line 136 in src/Microsoft.OpenApi/Services/OpenApiWalker.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 52 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
if (components == null)
{
Expand Down Expand Up @@ -266,7 +269,7 @@
_visitor.Visit(paths);

// Visit Paths
if (paths != null)

Check warning on line 272 in src/Microsoft.OpenApi/Services/OpenApiWalker.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)
{
foreach (var pathItem in paths)
{
Expand All @@ -291,7 +294,7 @@
_visitor.Visit(webhooks);

// Visit Webhooks
if (webhooks != null)

Check warning on line 297 in src/Microsoft.OpenApi/Services/OpenApiWalker.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)
{
foreach (var pathItem in webhooks)
{
Expand All @@ -299,7 +302,7 @@
Walk(pathItem.Key, () => Walk(pathItem.Value));// JSON Pointer uses ~1 as an escape character for /
_visitor.CurrentKeys.Path = null;
}
};

Check warning on line 305 in src/Microsoft.OpenApi/Services/OpenApiWalker.cs

View workflow job for this annotation

GitHub Actions / Build

Remove this empty statement. (https://rules.sonarsource.com/csharp/RSPEC-1116)
}

/// <summary>
Expand Down Expand Up @@ -423,7 +426,7 @@

_visitor.Visit(callback);

if (callback != null)

Check warning on line 429 in src/Microsoft.OpenApi/Services/OpenApiWalker.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)
{
foreach (var item in callback.PathItems)
{
Expand Down Expand Up @@ -460,7 +463,7 @@
return;
}

if (tag is IOpenApiReferenceHolder openApiReferenceHolder)

Check warning on line 466 in src/Microsoft.OpenApi/Services/OpenApiWalker.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)
{
Walk(openApiReferenceHolder);
}
Expand Down Expand Up @@ -1213,7 +1216,7 @@
case OpenApiServer e: Walk(e); break;
case OpenApiServerVariable e: Walk(e); break;
case OpenApiTag e: Walk(e); break;
case IList<OpenApiTag> e: Walk(e); break;
case ISet<OpenApiTag> e: Walk(e); break;
case IOpenApiExtensible e: Walk(e); break;
case IOpenApiExtension e: Walk(e); break;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -629,7 +629,7 @@ public static OpenApiDocument CreateOpenApiDocument()
}
}
},
Tags = new List<OpenApiTag>
Tags = new HashSet<OpenApiTag>
{
new()
{
Expand Down Expand Up @@ -678,18 +678,18 @@ public static OpenApiDocument CreateOpenApiDocument()
}
}
};
document.Paths[getTeamsActivityByPeriodPath].Operations[OperationType.Get].Tags!.Add(new OpenApiTagReference("reports.Functions", document));
document.Paths[getTeamsActivityByDatePath].Operations[OperationType.Get].Tags!.Add(new OpenApiTagReference("reports.Functions", document));
document.Paths[usersPath].Operations[OperationType.Get].Tags!.Add(new OpenApiTagReference("users.user", document));
document.Paths[usersByIdPath].Operations[OperationType.Get].Tags!.Add(new OpenApiTagReference("users.user", document));
document.Paths[usersByIdPath].Operations[OperationType.Patch].Tags!.Add(new OpenApiTagReference("users.user", document));
document.Paths[messagesByIdPath].Operations[OperationType.Get].Tags!.Add(new OpenApiTagReference("users.message", document));
document.Paths[administrativeUnitRestorePath].Operations[OperationType.Post].Tags!.Add(new OpenApiTagReference("administrativeUnits.Actions", document));
document.Paths[logoPath].Operations[OperationType.Put].Tags!.Add(new OpenApiTagReference("applications.application", document));
document.Paths[securityProfilesPath].Operations[OperationType.Get].Tags!.Add(new OpenApiTagReference("security.hostSecurityProfile", document));
document.Paths[communicationsCallsKeepAlivePath].Operations[OperationType.Post].Tags!.Add(new OpenApiTagReference("communications.Actions", document));
document.Paths[eventsDeltaPath].Operations[OperationType.Get].Tags!.Add(new OpenApiTagReference("groups.Functions", document));
document.Paths[refPath].Operations[OperationType.Get].Tags!.Add(new OpenApiTagReference("applications.directoryObject", document));
document.Paths[getTeamsActivityByPeriodPath].Operations[OperationType.Get].Tags = new HashSet<OpenApiTagReference> {new OpenApiTagReference("reports.Functions", document)};
document.Paths[getTeamsActivityByDatePath].Operations[OperationType.Get].Tags = new HashSet<OpenApiTagReference> {new OpenApiTagReference("reports.Functions", document)};
document.Paths[usersPath].Operations[OperationType.Get].Tags = new HashSet<OpenApiTagReference> {new OpenApiTagReference("users.user", document)};
document.Paths[usersByIdPath].Operations[OperationType.Get].Tags = new HashSet<OpenApiTagReference> {new OpenApiTagReference("users.user", document)};
document.Paths[usersByIdPath].Operations[OperationType.Patch].Tags = new HashSet<OpenApiTagReference> {new OpenApiTagReference("users.user", document)};
document.Paths[messagesByIdPath].Operations[OperationType.Get].Tags = new HashSet<OpenApiTagReference> {new OpenApiTagReference("users.message", document)};
document.Paths[administrativeUnitRestorePath].Operations[OperationType.Post].Tags = new HashSet<OpenApiTagReference> {new OpenApiTagReference("administrativeUnits.Actions", document)};
document.Paths[logoPath].Operations[OperationType.Put].Tags = new HashSet<OpenApiTagReference> {new OpenApiTagReference("applications.application", document)};
document.Paths[securityProfilesPath].Operations[OperationType.Get].Tags = new HashSet<OpenApiTagReference> {new OpenApiTagReference("security.hostSecurityProfile", document)};
document.Paths[communicationsCallsKeepAlivePath].Operations[OperationType.Post].Tags = new HashSet<OpenApiTagReference> {new OpenApiTagReference("communications.Actions", document)};
document.Paths[eventsDeltaPath].Operations[OperationType.Get].Tags = new HashSet<OpenApiTagReference> {new OpenApiTagReference("groups.Functions", document)};
document.Paths[refPath].Operations[OperationType.Get].Tags = new HashSet<OpenApiTagReference> {new OpenApiTagReference("applications.directoryObject", document)};
((OpenApiSchema)document.Paths[usersPath].Operations[OperationType.Get].Responses!["200"].Content[applicationJsonMediaType].Schema!.Properties["value"]).Items = new OpenApiSchemaReference("microsoft.graph.user", document);
document.Paths[usersByIdPath].Operations[OperationType.Get].Responses!["200"].Content[applicationJsonMediaType].Schema = new OpenApiSchemaReference("microsoft.graph.user", document);
document.Paths[messagesByIdPath].Operations[OperationType.Get].Responses!["200"].Content[applicationJsonMediaType].Schema = new OpenApiSchemaReference("microsoft.graph.message", document);
Expand Down
Loading