Skip to content

Commit

Permalink
- refactors collections between orderedstructuredmimetypes and the no…
Browse files Browse the repository at this point in the history
…n ordered one

Signed-off-by: Vincent Biret <vibiret@microsoft.com>
  • Loading branch information
baywet committed Oct 16, 2023
1 parent 98ea896 commit ce24f70
Show file tree
Hide file tree
Showing 10 changed files with 38 additions and 41 deletions.
10 changes: 3 additions & 7 deletions src/Kiota.Builder/Configuration/GenerationConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ public bool CleanOutput
{
get; set;
}
internal StructuredMimeTypesCollection OrderedStructuredMimeTypes
public StructuredMimeTypesCollection StructuredMimeTypes
{
get; set;
} = new StructuredMimeTypesCollection {
Expand All @@ -114,10 +114,6 @@ internal StructuredMimeTypesCollection OrderedStructuredMimeTypes
"application/x-www-form-urlencoded;q=0.2",
"multipart/form-data;q=0.1",
};
public List<string> StructuredMimeTypes
{
get => OrderedStructuredMimeTypes.ToList(); set => OrderedStructuredMimeTypes = new StructuredMimeTypesCollection(value);
}
public HashSet<string> IncludePatterns { get; set; } = new(0, StringComparer.OrdinalIgnoreCase);
public HashSet<string> ExcludePatterns { get; set; } = new(0, StringComparer.OrdinalIgnoreCase);
public bool ClearCache
Expand All @@ -143,7 +139,7 @@ public object Clone()
Serializers = new(Serializers ?? Enumerable.Empty<string>(), StringComparer.OrdinalIgnoreCase),
Deserializers = new(Deserializers ?? Enumerable.Empty<string>(), StringComparer.OrdinalIgnoreCase),
CleanOutput = CleanOutput,
StructuredMimeTypes = new List<string>(StructuredMimeTypes ?? Enumerable.Empty<string>()),
StructuredMimeTypes = new(StructuredMimeTypes ?? Enumerable.Empty<string>()),
IncludePatterns = new(IncludePatterns ?? Enumerable.Empty<string>(), StringComparer.OrdinalIgnoreCase),
ExcludePatterns = new(ExcludePatterns ?? Enumerable.Empty<string>(), StringComparer.OrdinalIgnoreCase),
ClearCache = ClearCache,
Expand All @@ -168,7 +164,7 @@ internal void UpdateConfigurationFromLanguagesInformation(LanguagesInformation l
if (languageInfo.StructuredMimeTypes.Any() &&
comparer.Equals(StructuredMimeTypes, defaultConfiguration.StructuredMimeTypes) &&
!comparer.Equals(languageInfo.StructuredMimeTypes, StructuredMimeTypes))
StructuredMimeTypes = new List<string>(languageInfo.StructuredMimeTypes);
StructuredMimeTypes = new(languageInfo.StructuredMimeTypes);
}
}
#pragma warning restore CA1056
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

namespace Kiota.Builder.Configuration;

internal partial class StructuredMimeTypesCollection : ICollection<string>
public partial class StructuredMimeTypesCollection : ICollection<string>
{
[GeneratedRegex(@"(?<mime>[^;]+);?q?=?(?<priority>[\d.]+)?", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline, 2000)]
private static partial Regex mimeTypesRegex();
Expand Down Expand Up @@ -48,11 +48,11 @@ IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public bool Contains(string mimeType)
public bool Contains(string item)
{
if (string.IsNullOrEmpty(mimeType))
if (string.IsNullOrEmpty(item))
return false;
return _mimeTypes.ContainsKey(mimeType);
return _mimeTypes.ContainsKey(item);
}
public float? GetPriority(string mimeType)
{
Expand Down
30 changes: 15 additions & 15 deletions src/Kiota.Builder/KiotaBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -700,7 +700,7 @@ private void CreateRequestBuilderClass(CodeNamespace currentNamespace, OpenApiUr
else
{
var targetNS = currentNode.DoesNodeBelongToItemSubnamespace() ? currentNamespace.EnsureItemNamespace() : currentNamespace;
var className = currentNode.DoesNodeBelongToItemSubnamespace() ? currentNode.GetNavigationPropertyName(config.OrderedStructuredMimeTypes, ItemRequestBuilderSuffix) : currentNode.GetNavigationPropertyName(config.OrderedStructuredMimeTypes, RequestBuilderSuffix);
var className = currentNode.DoesNodeBelongToItemSubnamespace() ? currentNode.GetNavigationPropertyName(config.StructuredMimeTypes, ItemRequestBuilderSuffix) : currentNode.GetNavigationPropertyName(config.StructuredMimeTypes, RequestBuilderSuffix);
codeClass = targetNS.AddClass(new CodeClass
{
Name = className.CleanupSymbolName(),
Expand All @@ -717,8 +717,8 @@ private void CreateRequestBuilderClass(CodeNamespace currentNamespace, OpenApiUr
// Add properties for children
foreach (var child in currentNode.Children)
{
var propIdentifier = child.Value.GetNavigationPropertyName(config.OrderedStructuredMimeTypes);
var propType = child.Value.GetNavigationPropertyName(config.OrderedStructuredMimeTypes, child.Value.DoesNodeBelongToItemSubnamespace() ? ItemRequestBuilderSuffix : RequestBuilderSuffix);
var propIdentifier = child.Value.GetNavigationPropertyName(config.StructuredMimeTypes);
var propType = child.Value.GetNavigationPropertyName(config.StructuredMimeTypes, child.Value.DoesNodeBelongToItemSubnamespace() ? ItemRequestBuilderSuffix : RequestBuilderSuffix);

if (child.Value.IsPathSegmentWithSingleSimpleParameter())
{
Expand Down Expand Up @@ -1233,12 +1233,12 @@ private void AddErrorMappingsForExecutorMethod(OpenApiUrlTreeNode currentNode, O
{
foreach (var response in operation.Responses.Where(x => errorStatusCodes.Contains(x.Key)))
{
if (response.Value.GetResponseSchema(config.OrderedStructuredMimeTypes) is { } schema)
if (response.Value.GetResponseSchema(config.StructuredMimeTypes) is { } schema)
{
AddErrorMappingToExecutorMethod(currentNode, operation, executorMethod, schema, response.Value, response.Key.ToUpperInvariant());
}
}
if (operation.Responses.TryGetValue("default", out var defaultResponse) && defaultResponse.GetResponseSchema(config.OrderedStructuredMimeTypes) is { } errorSchema)
if (operation.Responses.TryGetValue("default", out var defaultResponse) && defaultResponse.GetResponseSchema(config.StructuredMimeTypes) is { } errorSchema)
{
if (!executorMethod.HasErrorMappingCode(FourXXError))
AddErrorMappingToExecutorMethod(currentNode, operation, executorMethod, errorSchema, defaultResponse, FourXXError);
Expand Down Expand Up @@ -1343,7 +1343,7 @@ private void CreateOperationMethods(OpenApiUrlTreeNode currentNode, OperationTyp
},
}).First();

var schema = operation.GetResponseSchema(config.OrderedStructuredMimeTypes);
var schema = operation.GetResponseSchema(config.StructuredMimeTypes);
var method = (HttpMethod)Enum.Parse(typeof(HttpMethod), operationType.ToString());
var deprecationInformation = operation.GetDeprecationInformation();
var returnTypes = GetExecutorMethodReturnType(currentNode, schema, operation, parentClass, operationType);
Expand Down Expand Up @@ -1423,7 +1423,7 @@ private void CreateOperationMethods(OpenApiUrlTreeNode currentNode, OperationTyp
var mediaTypes = schema switch
{
null => operation.Responses.Values.SelectMany(static x => x.Content).Select(static x => x.Key),
_ => config.OrderedStructuredMimeTypes.GetAcceptedTypes(operation.Responses.Values.SelectMany(static x => x.Content).Where(x => schemaReferenceComparer.Equals(schema, x.Value.Schema)).Select(static x => x.Key)),
_ => config.StructuredMimeTypes.GetAcceptedTypes(operation.Responses.Values.SelectMany(static x => x.Content).Where(x => schemaReferenceComparer.Equals(schema, x.Value.Schema)).Select(static x => x.Key)),
};
generatorMethod.AddAcceptedResponsesTypes(mediaTypes);
if (config.Language == GenerationLanguage.CLI)
Expand Down Expand Up @@ -1516,10 +1516,10 @@ private static void AddRequestConfigurationProperties(CodeClass? parameterClass,
private readonly ConcurrentDictionary<CodeElement, bool> multipartPropertiesModels = new();
private void AddRequestBuilderMethodParameters(OpenApiUrlTreeNode currentNode, OperationType operationType, OpenApiOperation operation, CodeClass requestConfigClass, CodeMethod method)
{
if (operation.GetRequestSchema(config.OrderedStructuredMimeTypes) is OpenApiSchema requestBodySchema)
if (operation.GetRequestSchema(config.StructuredMimeTypes) is OpenApiSchema requestBodySchema)
{
CodeTypeBase requestBodyType;
if (operation.RequestBody.Content.IsMultipartFormDataSchema(config.OrderedStructuredMimeTypes))
if (operation.RequestBody.Content.IsMultipartFormDataSchema(config.StructuredMimeTypes))
{
requestBodyType = new CodeType
{
Expand All @@ -1529,7 +1529,7 @@ private void AddRequestBuilderMethodParameters(OpenApiUrlTreeNode currentNode, O
var mediaType = operation.RequestBody.Content.First(x => x.Value.Schema == requestBodySchema).Value;
foreach (var encodingEntry in mediaType.Encoding
.Where(x => !string.IsNullOrEmpty(x.Value.ContentType) &&
config.OrderedStructuredMimeTypes.Contains(x.Value.ContentType)))
config.StructuredMimeTypes.Contains(x.Value.ContentType)))
{
if (CreateModelDeclarations(currentNode, requestBodySchema.Properties[encodingEntry.Key], operation, method, $"{operationType}RequestBody", isRequestBody: true) is CodeType propertyType &&
propertyType.TypeDefinition is not null)
Expand All @@ -1553,7 +1553,7 @@ private void AddRequestBuilderMethodParameters(OpenApiUrlTreeNode currentNode, O
},
Deprecation = requestBodySchema.GetDeprecationInformation(),
});
method.RequestBodyContentType = config.OrderedStructuredMimeTypes.GetContentTypes(operation.RequestBody.Content.Where(x => schemaReferenceComparer.Equals(x.Value.Schema, requestBodySchema)).Select(static x => x.Key)).First();
method.RequestBodyContentType = config.StructuredMimeTypes.GetContentTypes(operation.RequestBody.Content.Where(x => schemaReferenceComparer.Equals(x.Value.Schema, requestBodySchema)).Select(static x => x.Key)).First();
}
else if (operation.RequestBody?.Content?.Any() ?? false)
{
Expand Down Expand Up @@ -1618,7 +1618,7 @@ private string GetModelsNamespaceNameFromReferenceId(string? referenceId)
}
private CodeType CreateModelDeclarationAndType(OpenApiUrlTreeNode currentNode, OpenApiSchema schema, OpenApiOperation? operation, CodeNamespace codeNamespace, string classNameSuffix = "", OpenApiResponse? response = default, string typeNameForInlineSchema = "", bool isRequestBody = false)
{
var className = string.IsNullOrEmpty(typeNameForInlineSchema) ? currentNode.GetClassName(config.OrderedStructuredMimeTypes, operation: operation, suffix: classNameSuffix, response: response, schema: schema, requestBody: isRequestBody).CleanupSymbolName() : typeNameForInlineSchema;
var className = string.IsNullOrEmpty(typeNameForInlineSchema) ? currentNode.GetClassName(config.StructuredMimeTypes, operation: operation, suffix: classNameSuffix, response: response, schema: schema, requestBody: isRequestBody).CleanupSymbolName() : typeNameForInlineSchema;
var codeDeclaration = AddModelDeclarationIfDoesntExist(currentNode, schema, className, codeNamespace);
return new CodeType
{
Expand All @@ -1638,7 +1638,7 @@ private CodeTypeBase CreateInheritedModelDeclaration(OpenApiUrlTreeNode currentN
var shortestNamespace = string.IsNullOrEmpty(referenceId) ? codeNamespaceFromParent : rootNamespace?.FindOrAddNamespace(shortestNamespaceName);
className = (currentSchema.GetSchemaName() is string cName && !string.IsNullOrEmpty(cName) ?
cName :
currentNode.GetClassName(config.OrderedStructuredMimeTypes, operation: operation, suffix: classNameSuffix, schema: schema, requestBody: isRequestBody))
currentNode.GetClassName(config.StructuredMimeTypes, operation: operation, suffix: classNameSuffix, schema: schema, requestBody: isRequestBody))
.CleanupSymbolName();
if (shortestNamespace != null)
codeDeclaration = AddModelDeclarationIfDoesntExist(currentNode, currentSchema, className, shortestNamespace, codeDeclaration as CodeClass);
Expand All @@ -1665,7 +1665,7 @@ private CodeTypeBase CreateInheritedModelDeclaration(OpenApiUrlTreeNode currentN
}
private CodeTypeBase CreateComposedModelDeclaration(OpenApiUrlTreeNode currentNode, OpenApiSchema schema, OpenApiOperation? operation, string suffixForInlineSchema, CodeNamespace codeNamespace, bool isRequestBody, string typeNameForInlineSchema)
{
var typeName = string.IsNullOrEmpty(typeNameForInlineSchema) ? currentNode.GetClassName(config.OrderedStructuredMimeTypes, operation: operation, suffix: suffixForInlineSchema, schema: schema, requestBody: isRequestBody).CleanupSymbolName() : typeNameForInlineSchema;
var typeName = string.IsNullOrEmpty(typeNameForInlineSchema) ? currentNode.GetClassName(config.StructuredMimeTypes, operation: operation, suffix: suffixForInlineSchema, schema: schema, requestBody: isRequestBody).CleanupSymbolName() : typeNameForInlineSchema;
var typesCount = schema.AnyOf?.Count ?? schema.OneOf?.Count ?? 0;
if (typesCount == 1 && schema.Nullable && schema.IsInclusiveUnion() || // nullable on the root schema outside of anyOf
typesCount == 2 && (schema.AnyOf?.Any(static x => // nullable on a schema in the anyOf
Expand Down Expand Up @@ -2114,7 +2114,7 @@ internal static void AddDiscriminatorMethod(CodeClass newClass, string discrimin
logger.LogWarning("Discriminator {ComponentKey} not found in the OpenAPI document.", componentKey);
return null;
}
var className = currentNode.GetClassName(config.OrderedStructuredMimeTypes, schema: discriminatorSchema).CleanupSymbolName();
var className = currentNode.GetClassName(config.StructuredMimeTypes, schema: discriminatorSchema).CleanupSymbolName();
var shouldInherit = discriminatorSchema.AllOf.Any(x => currentSchema.Reference?.Id.Equals(x.Reference?.Id, StringComparison.OrdinalIgnoreCase) ?? false);
var codeClass = AddModelDeclarationIfDoesntExist(currentNode, discriminatorSchema, className, GetShortestNamespace(currentNamespace, discriminatorSchema), shouldInherit ? baseClass : null);
return new CodeType
Expand Down
5 changes: 3 additions & 2 deletions src/Kiota.Builder/Lock/KiotaLock.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Kiota.Builder.Configuration;

namespace Kiota.Builder.Lock;
Expand Down Expand Up @@ -102,7 +103,7 @@ public void UpdateGenerationConfigurationFromLock(GenerationConfiguration config
config.IncludeAdditionalData = IncludeAdditionalData;
config.Serializers = Serializers;
config.Deserializers = Deserializers;
config.StructuredMimeTypes = StructuredMimeTypes;
config.StructuredMimeTypes = new(StructuredMimeTypes);
config.IncludePatterns = IncludePatterns;
config.ExcludePatterns = ExcludePatterns;
config.OpenAPIFilePath = DescriptionLocation;
Expand All @@ -129,7 +130,7 @@ public KiotaLock(GenerationConfiguration config)
IncludeAdditionalData = config.IncludeAdditionalData;
Serializers = config.Serializers;
Deserializers = config.Deserializers;
StructuredMimeTypes = config.StructuredMimeTypes;
StructuredMimeTypes = config.StructuredMimeTypes.ToList();
IncludePatterns = config.IncludePatterns;
ExcludePatterns = config.ExcludePatterns;
DescriptionLocation = config.OpenAPIFilePath;
Expand Down
2 changes: 1 addition & 1 deletion src/Kiota.Builder/Validation/DivergentResponseSchema.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class DivergentResponseSchema : ValidationRule<OpenApiOperation>
private static readonly HashSet<string> validStatusCodes = new(OpenApiOperationExtensions.SuccessCodes, StringComparer.OrdinalIgnoreCase);
public DivergentResponseSchema(GenerationConfiguration configuration) : base((context, operation) =>
{
var schemas = operation.GetResponseSchemas(validStatusCodes, configuration.OrderedStructuredMimeTypes);
var schemas = operation.GetResponseSchemas(validStatusCodes, configuration.StructuredMimeTypes);
if (schemas.GroupBy(x => x, schemaComparer).Count() > 1)
context.CreateWarning(nameof(DivergentResponseSchema), "The operation describes multiple response schemas that are divergent. Only the schema of the lowest success status code will be used.");
})
Expand Down
2 changes: 1 addition & 1 deletion src/Kiota.Builder/Validation/MissingDiscriminator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public MissingDiscriminator(GenerationConfiguration configuration) : base((conte
});
var inlineSchemasToValidate = document.Paths
?.SelectMany(static x => x.Value.Operations.Values.Select(y => (x.Key, Operation: y)))
.SelectMany(x => x.Operation.GetResponseSchemas(OpenApiOperationExtensions.SuccessCodes, configuration.OrderedStructuredMimeTypes).Select(y => (x.Key, Schema: y)))
.SelectMany(x => x.Operation.GetResponseSchemas(OpenApiOperationExtensions.SuccessCodes, configuration.StructuredMimeTypes).Select(y => (x.Key, Schema: y)))
.Where(static x => string.IsNullOrEmpty(x.Schema.Reference?.Id))
.ToArray() ?? Array.Empty<(string, OpenApiSchema)>();
Parallel.ForEach(inlineSchemasToValidate, entry =>
Expand Down
10 changes: 5 additions & 5 deletions src/kiota/KiotaConfigurationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,23 +62,23 @@ public static void BindConfiguration(this KiotaConfiguration configObject, IConf
configObject.Generation.ClearCache = bool.TryParse(configuration[$"{nameof(configObject.Generation)}:{nameof(GenerationConfiguration.ClearCache)}"], out var clearCache) && clearCache;
configObject.Generation.ExcludeBackwardCompatible = bool.TryParse(configuration[$"{nameof(configObject.Generation)}:{nameof(GenerationConfiguration.ExcludeBackwardCompatible)}"], out var excludeBackwardCompatible) && excludeBackwardCompatible;
configObject.Generation.MaxDegreeOfParallelism = int.TryParse(configuration[$"{nameof(configObject.Generation)}:{nameof(GenerationConfiguration.MaxDegreeOfParallelism)}"], out var maxDegreeOfParallelism) ? maxDegreeOfParallelism : configObject.Generation.MaxDegreeOfParallelism;
configuration.GetSection($"{nameof(configObject.Generation)}:{nameof(GenerationConfiguration.StructuredMimeTypes)}").LoadList(configObject.Generation.StructuredMimeTypes);
configuration.GetSection($"{nameof(configObject.Generation)}:{nameof(GenerationConfiguration.StructuredMimeTypes)}").LoadCollection(configObject.Generation.StructuredMimeTypes);
configuration.GetSection($"{nameof(configObject.Generation)}:{nameof(GenerationConfiguration.Serializers)}").LoadHashSet(configObject.Generation.Serializers);
configuration.GetSection($"{nameof(configObject.Generation)}:{nameof(GenerationConfiguration.Deserializers)}").LoadHashSet(configObject.Generation.Deserializers);
configuration.GetSection($"{nameof(configObject.Generation)}:{nameof(GenerationConfiguration.IncludePatterns)}").LoadHashSet(configObject.Generation.IncludePatterns);
configuration.GetSection($"{nameof(configObject.Generation)}:{nameof(GenerationConfiguration.ExcludePatterns)}").LoadHashSet(configObject.Generation.ExcludePatterns);
configuration.GetSection($"{nameof(configObject.Generation)}:{nameof(GenerationConfiguration.DisabledValidationRules)}").LoadHashSet(configObject.Generation.DisabledValidationRules);
}
private static void LoadList(this IConfigurationSection section, List<string> list)
private static void LoadCollection(this IConfigurationSection section, ICollection<string> collection)
{
ArgumentNullException.ThrowIfNull(list);
ArgumentNullException.ThrowIfNull(collection);
if (section is null) return;
var children = section.GetChildren();
if (children.Any() && list.Any()) list.Clear();
if (children.Any() && collection.Any()) collection.Clear();
foreach (var item in children)
{
if (section[item.Key] is string value && !string.IsNullOrEmpty(value))
list.Add(value);
collection.Add(value);
}
}
private static void LoadHashSet(this IConfigurationSection section, HashSet<string> hashSet)
Expand Down
Loading

0 comments on commit ce24f70

Please sign in to comment.