Skip to content

Commit

Permalink
- adds a parameter to exclude backward compatible types
Browse files Browse the repository at this point in the history
  • Loading branch information
baywet committed Sep 27, 2023
1 parent c8513e3 commit 8430caa
Show file tree
Hide file tree
Showing 9 changed files with 79 additions and 39 deletions.
9 changes: 9 additions & 0 deletions src/Kiota.Builder/Configuration/GenerationConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ public bool UsesBackingStore
{
get; set;
}
public bool ExcludeBackwardCompatible
{
get; set;
}
public bool IncludeBackwardCompatible
{
get => !ExcludeBackwardCompatible;
}
public bool IncludeAdditionalData { get; set; } = true;
public HashSet<string> Serializers
{
Expand Down Expand Up @@ -118,6 +126,7 @@ public object Clone()
{
return new GenerationConfiguration
{
ExcludeBackwardCompatible = ExcludeBackwardCompatible,
OpenAPIFilePath = OpenAPIFilePath,
OutputPath = OutputPath,
ClientClassName = ClientClassName,
Expand Down
6 changes: 3 additions & 3 deletions src/Kiota.Builder/KiotaBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1113,7 +1113,7 @@ private CodeIndexer[] CreateIndexer(string childIdentifier, string childType, Co
IndexParameter = parameter,
}};

if (!"string".Equals(parameter.Type.Name, StringComparison.OrdinalIgnoreCase))
if (!"string".Equals(parameter.Type.Name, StringComparison.OrdinalIgnoreCase) && config.IncludeBackwardCompatible)
{ // adding a second indexer for the string version of the parameter so we keep backward compatibility
//TODO remove for v2

Check warning on line 1118 in src/Kiota.Builder/KiotaBuilder.cs

View workflow job for this annotation

GitHub Actions / Build

Complete the task associated to this 'TODO' comment. (https://rules.sonarsource.com/csharp/RSPEC-1135)
var backCompatibleValue = (CodeIndexer)result[0].Clone();
Expand Down Expand Up @@ -1271,7 +1271,7 @@ codeType.TypeDefinition is CodeClass codeClass &&
{
var suffix = $"{operationType}Response";
var modelType = CreateModelDeclarations(currentNode, schema, operation, parentClass, suffix);
if (modelType is not null && config.Language is GenerationLanguage.CSharp or GenerationLanguage.Go && modelType.Name.EndsWith(suffix, StringComparison.Ordinal))
if (modelType is not null && config.IncludeBackwardCompatible && config.Language is GenerationLanguage.CSharp or GenerationLanguage.Go && modelType.Name.EndsWith(suffix, StringComparison.Ordinal))
{ //TODO remove for v2

Check warning on line 1275 in src/Kiota.Builder/KiotaBuilder.cs

View workflow job for this annotation

GitHub Actions / Build

Complete the task associated to this 'TODO' comment. (https://rules.sonarsource.com/csharp/RSPEC-1135)
var obsoleteTypeName = modelType.Name[..^suffix.Length] + "Response";
if (modelType is CodeType codeType &&
Expand Down Expand Up @@ -1393,7 +1393,7 @@ private void CreateOperationMethods(OpenApiUrlTreeNode currentNode, OperationTyp
};
executorMethod.AddParameter(cancellationParam);// Add cancellation token parameter

if (returnTypes.Item2 is not null)
if (returnTypes.Item2 is not null && config.IncludeBackwardCompatible)
{ //TODO remove for v2

Check warning on line 1397 in src/Kiota.Builder/KiotaBuilder.cs

View workflow job for this annotation

GitHub Actions / Build

Complete the task associated to this 'TODO' comment. (https://rules.sonarsource.com/csharp/RSPEC-1135)
var additionalExecutorMethod = (CodeMethod)executorMethod.Clone();
additionalExecutorMethod.ReturnType = returnTypes.Item2;
Expand Down
9 changes: 9 additions & 0 deletions src/Kiota.Builder/Lock/KiotaLock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ public bool UsesBackingStore
get; set;
}
/// <summary>
/// Whether backward compatible code was excluded for this client.
/// </summary>
public bool ExcludeBackwardCompatible
{
get; set;
}
/// <summary>
/// Whether additional data was used for this client.
/// </summary>
public bool IncludeAdditionalData
Expand Down Expand Up @@ -89,6 +96,7 @@ public void UpdateGenerationConfigurationFromLock(GenerationConfiguration config
if (Enum.TryParse<GenerationLanguage>(Language, out var parsedLanguage))
config.Language = parsedLanguage;
config.UsesBackingStore = UsesBackingStore;
config.ExcludeBackwardCompatible = ExcludeBackwardCompatible;
config.IncludeAdditionalData = IncludeAdditionalData;
config.Serializers = Serializers;
config.Deserializers = Deserializers;
Expand All @@ -115,6 +123,7 @@ public KiotaLock(GenerationConfiguration config)
ClientClassName = config.ClientClassName;
ClientNamespaceName = config.ClientNamespaceName;
UsesBackingStore = config.UsesBackingStore;
ExcludeBackwardCompatible = config.ExcludeBackwardCompatible;
IncludeAdditionalData = config.IncludeAdditionalData;
Serializers = config.Serializers;
Deserializers = config.Deserializers;
Expand Down
17 changes: 9 additions & 8 deletions src/Kiota.Builder/Lock/KiotaLockComparer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,15 @@ public int GetHashCode([DisallowNull] KiotaLock obj)
{
if (obj == null) return 0;
return
_stringIEnumerableDeepComparer.GetHashCode(obj.DisabledValidationRules?.Order(StringComparer.OrdinalIgnoreCase) ?? Enumerable.Empty<string>()) * 47 +
obj.KiotaVersion.GetHashCode(StringComparison.OrdinalIgnoreCase) * 43 +
obj.LockFileVersion.GetHashCode(StringComparison.OrdinalIgnoreCase) * 41 +
(string.IsNullOrEmpty(obj.DescriptionLocation) ? 0 : obj.DescriptionLocation.GetHashCode(StringComparison.OrdinalIgnoreCase)) * 37 +
(string.IsNullOrEmpty(obj.DescriptionHash) ? 0 : obj.DescriptionHash.GetHashCode(StringComparison.OrdinalIgnoreCase)) * 31 +
(string.IsNullOrEmpty(obj.ClientClassName) ? 0 : obj.ClientClassName.GetHashCode(StringComparison.OrdinalIgnoreCase)) * 29 +
(string.IsNullOrEmpty(obj.ClientNamespaceName) ? 0 : obj.ClientNamespaceName.GetHashCode(StringComparison.OrdinalIgnoreCase)) * 23 +
(string.IsNullOrEmpty(obj.Language) ? 0 : obj.Language.GetHashCode(StringComparison.OrdinalIgnoreCase)) * 19 +
_stringIEnumerableDeepComparer.GetHashCode(obj.DisabledValidationRules?.Order(StringComparer.OrdinalIgnoreCase) ?? Enumerable.Empty<string>()) * 53 +
obj.KiotaVersion.GetHashCode(StringComparison.OrdinalIgnoreCase) * 47 +
obj.LockFileVersion.GetHashCode(StringComparison.OrdinalIgnoreCase) * 43 +
(string.IsNullOrEmpty(obj.DescriptionLocation) ? 0 : obj.DescriptionLocation.GetHashCode(StringComparison.OrdinalIgnoreCase)) * 41 +
(string.IsNullOrEmpty(obj.DescriptionHash) ? 0 : obj.DescriptionHash.GetHashCode(StringComparison.OrdinalIgnoreCase)) * 37 +
(string.IsNullOrEmpty(obj.ClientClassName) ? 0 : obj.ClientClassName.GetHashCode(StringComparison.OrdinalIgnoreCase)) * 31 +
(string.IsNullOrEmpty(obj.ClientNamespaceName) ? 0 : obj.ClientNamespaceName.GetHashCode(StringComparison.OrdinalIgnoreCase)) * 29 +
(string.IsNullOrEmpty(obj.Language) ? 0 : obj.Language.GetHashCode(StringComparison.OrdinalIgnoreCase)) * 23 +
obj.ExcludeBackwardCompatible.GetHashCode() * 19 +
obj.UsesBackingStore.GetHashCode() * 17 +
obj.IncludeAdditionalData.GetHashCode() * 13 +
_stringIEnumerableDeepComparer.GetHashCode(obj.Serializers?.Order(StringComparer.OrdinalIgnoreCase) ?? Enumerable.Empty<string>()) * 11 +
Expand Down
33 changes: 17 additions & 16 deletions src/Kiota.Builder/Refiners/CSharpRefiner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,22 +31,23 @@ public override Task Refine(CodeNamespace generatedCode, CancellationToken cance
IsExternal = true
}
});
//TODO uncomment on the next major version
// RemoveRequestConfigurationClasses(generatedCode,
// new CodeUsing
// {
// Name = "RequestConfiguration",
// Declaration = new CodeType
// {
// Name = AbstractionsNamespaceName,
// IsExternal = true
// }
// },
// new CodeType
// {
// Name = "DefaultQueryParameters",
// IsExternal = true,
// });
//TODO remove the condition for v2

Check warning on line 34 in src/Kiota.Builder/Refiners/CSharpRefiner.cs

View workflow job for this annotation

GitHub Actions / Build

Complete the task associated to this 'TODO' comment. (https://rules.sonarsource.com/csharp/RSPEC-1135)
if (_configuration.ExcludeBackwardCompatible)
RemoveRequestConfigurationClasses(generatedCode,
new CodeUsing
{
Name = "RequestConfiguration",
Declaration = new CodeType
{
Name = AbstractionsNamespaceName,
IsExternal = true
}
},
new CodeType
{
Name = "DefaultQueryParameters",
IsExternal = true,
});
AddDefaultImports(generatedCode, defaultUsingEvaluators);
MoveClassesWithNamespaceNamesUnderNamespace(generatedCode);
ConvertUnionTypesToWrapper(generatedCode,
Expand Down
2 changes: 1 addition & 1 deletion src/Kiota.Builder/Writers/Go/CodeMethodWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public override void WriteCodeElement(CodeMethod codeElement, LanguageWriter wri
case CodeMethodKind.RequestGenerator when !codeElement.IsOverload:
WriteRequestGeneratorBody(codeElement, requestParams, writer, parentClass);
break;
case CodeMethodKind.RequestExecutor when !codeElement.IsOverload || (codeElement.Deprecation?.IsDeprecated ?? false): //TODO remove deprecration condition for v2
case CodeMethodKind.RequestExecutor when !codeElement.IsOverload || (codeElement.Deprecation?.IsDeprecated ?? false): //TODO remove deprecation condition for v2
WriteRequestExecutorBody(codeElement, requestParams, returnType, parentClass, writer);
break;
case CodeMethodKind.Getter:
Expand Down
7 changes: 7 additions & 0 deletions src/kiota/Handlers/KiotaGenerationCommandHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ public override async Task<int> InvokeAsync(InvocationContext context)
string openapi = context.ParseResult.GetValueForOption(DescriptionOption) ?? string.Empty;
string manifest = context.ParseResult.GetValueForOption(ManifestOption) ?? string.Empty;
bool backingStore = context.ParseResult.GetValueForOption(BackingStoreOption);
bool excludeBackwardCompatible = context.ParseResult.GetValueForOption(ExcludeBackwardCompatibleOption);
bool clearCache = context.ParseResult.GetValueForOption(ClearCacheOption);
bool includeAdditionalData = context.ParseResult.GetValueForOption(AdditionalDataOption);
string className = context.ParseResult.GetValueForOption(ClassOption) ?? string.Empty;
Expand All @@ -89,6 +90,7 @@ public override async Task<int> InvokeAsync(InvocationContext context)
AssignIfNotNullOrEmpty(className, (c, s) => c.ClientClassName = s);
AssignIfNotNullOrEmpty(namespaceName, (c, s) => c.ClientNamespaceName = s);
Configuration.Generation.UsesBackingStore = backingStore;
Configuration.Generation.ExcludeBackwardCompatible = excludeBackwardCompatible;
Configuration.Generation.IncludeAdditionalData = includeAdditionalData;
Configuration.Generation.Language = language;
if (serializer.Any())
Expand Down Expand Up @@ -167,4 +169,9 @@ public required Option<string> ManifestOption
{
get; init;
}
public required Option<bool> ExcludeBackwardCompatibleOption
{
get;
set;
}
}
7 changes: 5 additions & 2 deletions src/kiota/KiotaHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@
using System.CommandLine;
using System.CommandLine.Parsing;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using kiota.Handlers;
using kiota.Rpc;
using Kiota.Builder;
using Kiota.Builder.Configuration;
using Kiota.Builder.Validation;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Validations;

namespace kiota;
public static class KiotaHost
Expand Down Expand Up @@ -344,6 +342,9 @@ private static Command GetGenerateCommand()
var backingStoreOption = new Option<bool>("--backing-store", () => defaultConfiguration.UsesBackingStore, "Enables backing store for models.");
backingStoreOption.AddAlias("-b");

var excludeBackwardCompatible = new Option<bool>("--exclude-backward-compatible", () => defaultConfiguration.ExcludeBackwardCompatible, "Excludes backward compatible and obsolete assets from the generated result. Should be used for new clients.");
excludeBackwardCompatible.AddAlias("--ebc");

var additionalDataOption = new Option<bool>("--additional-data", () => defaultConfiguration.IncludeAdditionalData, "Will include the 'AdditionalData' property for models.");
additionalDataOption.AddAlias("--ad");

Expand Down Expand Up @@ -384,6 +385,7 @@ private static Command GetGenerateCommand()
namespaceOption,
logLevelOption,
backingStoreOption,
excludeBackwardCompatible,
additionalDataOption,
serializerOption,
deserializerOption,
Expand All @@ -404,6 +406,7 @@ private static Command GetGenerateCommand()
NamespaceOption = namespaceOption,
LogLevelOption = logLevelOption,
BackingStoreOption = backingStoreOption,
ExcludeBackwardCompatibleOption = excludeBackwardCompatible,
AdditionalDataOption = additionalDataOption,
SerializerOption = serializerOption,
DeserializerOption = deserializerOption,
Expand Down
28 changes: 19 additions & 9 deletions tests/Kiota.Builder.Tests/KiotaBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4636,8 +4636,10 @@ public void AcceptVendorsTypes(string contentType)
Assert.NotNull(executorMethod);
Assert.Equal("myobject", executorMethod.ReturnType.Name);
}
[Fact]
public void ModelsUseDescriptionWhenAvailable()
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ModelsUseDescriptionWhenAvailable(bool excludeBackwardCompatible)
{
var document = new OpenApiDocument
{
Expand Down Expand Up @@ -4677,7 +4679,7 @@ public void ModelsUseDescriptionWhenAvailable()
}
};
var mockLogger = new Mock<ILogger<KiotaBuilder>>();
var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration { ClientClassName = "TestClient", ClientNamespaceName = "TestSdk", ApiRootUrl = "https://localhost" }, _httpClient);
var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration { ClientClassName = "TestClient", ClientNamespaceName = "TestSdk", ApiRootUrl = "https://localhost", ExcludeBackwardCompatible = excludeBackwardCompatible }, _httpClient);
var node = builder.CreateUriSpace(document);
var codeModel = builder.CreateSourceModel(node);
var modelsSubNS = codeModel.FindNamespaceByName("TestSdk.answer");
Expand All @@ -4687,17 +4689,25 @@ public void ModelsUseDescriptionWhenAvailable()
Assert.Equal("some description", responseClass.Documentation.Description);

var obsoleteResponseClass = modelsSubNS.FindChildByName<CodeClass>("AnswerResponse", false);
Assert.NotNull(obsoleteResponseClass);
Assert.Equal("some description", obsoleteResponseClass.Documentation.Description);
Assert.True(obsoleteResponseClass.Deprecation.IsDeprecated);
if (excludeBackwardCompatible)
Assert.Null(obsoleteResponseClass);
else
{
Assert.NotNull(obsoleteResponseClass);
Assert.Equal("some description", obsoleteResponseClass.Documentation.Description);
Assert.True(obsoleteResponseClass.Deprecation.IsDeprecated);
}

var requestBuilderClass = modelsSubNS.Classes.FirstOrDefault(c => c.IsOfKind(CodeClassKind.RequestBuilder));
var requestBuilderClass = modelsSubNS.Classes.FirstOrDefault(static c => c.IsOfKind(CodeClassKind.RequestBuilder));
Assert.NotNull(requestBuilderClass);
Assert.Equal("some path item description", requestBuilderClass.Documentation.Description);

Assert.Equal(2, requestBuilderClass.Methods.Where(static x => x.Kind is CodeMethodKind.RequestExecutor).Count());
if (excludeBackwardCompatible)
Assert.Single(requestBuilderClass.Methods.Where(static x => x.Kind is CodeMethodKind.RequestExecutor));
else
Assert.Equal(2, requestBuilderClass.Methods.Where(static x => x.Kind is CodeMethodKind.RequestExecutor).Count());

var responseProperty = codeModel.FindNamespaceByName("TestSdk").Classes.SelectMany(c => c.Properties).FirstOrDefault(p => p.Kind == CodePropertyKind.RequestBuilder);
var responseProperty = codeModel.FindNamespaceByName("TestSdk").Classes.SelectMany(c => c.Properties).FirstOrDefault(static p => p.Kind == CodePropertyKind.RequestBuilder);
Assert.NotNull(responseProperty);
Assert.Equal("some path item description", responseProperty.Documentation.Description);
}
Expand Down

0 comments on commit 8430caa

Please sign in to comment.