Skip to content
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

Feature/http language support #5778

Open
wants to merge 41 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
8dd143d
initial http genertion support
koros Oct 9, 2024
c7e352a
add http language generation
koros Oct 22, 2024
c2c7443
remove unused code elements from the DOM
koros Nov 13, 2024
3a25dab
merge if statements
koros Nov 14, 2024
9bcac7d
Merge branch 'main' into feature/http-language-support
koros Nov 14, 2024
5154280
remove unused code in the refiner
koros Nov 14, 2024
80d771c
Merge branch 'main' into feature/http-language-support
koros Nov 14, 2024
bac834f
write all properties including ones in the base class
koros Nov 14, 2024
31c3c53
Remove unused code and enhance JSON request body output
koros Nov 15, 2024
0ec5815
decode the parameter names before writing to http snippet files
koros Nov 18, 2024
f033a45
Merge branch 'main' into feature/http-language-support
koros Nov 18, 2024
f2f1c8e
write all the path parameter variables
koros Nov 18, 2024
ec4aea7
Exclude the generic pathParameters variable from being written to the…
koros Nov 18, 2024
da3bf05
add comments and documentation info. to Writers/HTTP/CodeClassDeclara…
koros Nov 18, 2024
69ba9ac
Merge branch 'main' into feature/http-language-support
koros Nov 19, 2024
3852185
Use URL Template to write actual urls
koros Nov 19, 2024
7508ebd
use double curly braces for all variables
koros Nov 21, 2024
0c7e0ee
Merge branch 'main' into feature/http-language-support
koros Nov 21, 2024
41345d5
add unit tests for HttpPathSegmenter
koros Nov 21, 2024
cfabf37
unit tests for CodeEnum writer
koros Nov 21, 2024
cfbbefe
format code
koros Nov 22, 2024
ff4caed
Merge branch 'main' into feature/http-language-support
koros Nov 22, 2024
d9f7584
remove more unnecessary code from the HttpConventionService
koros Nov 25, 2024
69bac1f
rename http namespace to use proper casing
koros Nov 25, 2024
fc39c89
remove unused method
koros Nov 25, 2024
6900e7e
Merge branch 'main' into feature/http-language-support
koros Nov 25, 2024
2ade0bd
Update HTTP Reserved Names Provider with Additional Reserved Keywords
koros Nov 26, 2024
0343d2a
Merge branch 'main' into feature/http-language-support
koros Nov 26, 2024
0fa1c0d
remove reserved names provider; add more unit tests
koros Nov 27, 2024
106cbae
format code
koros Nov 27, 2024
4f2bda2
Merge branch 'main' into feature/http-language-support
koros Nov 27, 2024
41dbd77
reset .vscode/launch.json
koros Nov 27, 2024
7d30713
add more unit tests
koros Nov 27, 2024
4ccc263
address pr comments
koros Dec 3, 2024
d9da636
address pr comments
koros Dec 3, 2024
ef519d1
address pr comments
koros Dec 3, 2024
51c6e25
format code
koros Dec 4, 2024
cfb3024
Merge branch 'main' into feature/http-language-support
koros Dec 4, 2024
fdfabb7
restore formating for nested json objects
koros Dec 4, 2024
407f61a
address pr comments
koros Dec 5, 2024
54c3d8f
Merge branch 'main' into feature/http-language-support
Onokaev Dec 9, 2024
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
3 changes: 2 additions & 1 deletion src/Kiota.Builder/GenerationLanguage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@ public enum GenerationLanguage
Go,
Swift,
Ruby,
CLI
CLI,
HTTP
}
13 changes: 13 additions & 0 deletions src/Kiota.Builder/PathSegmenters/HttpPathSegmenter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Kiota.Builder.CodeDOM;
using Kiota.Builder.Extensions;

namespace Kiota.Builder.PathSegmenters;
public class HttpPathSegmenter(string rootPath, string clientNamespaceName) : CommonPathSegmenter(rootPath, clientNamespaceName)
{
public override string FileSuffix => ".http";
public override string NormalizeNamespaceSegment(string segmentName) => segmentName.ToFirstCharacterUpperCase();
public override string NormalizeFileName(CodeElement currentElement)
{
return GetLastFileNameSegment(currentElement).ToFirstCharacterUpperCase();
}
}
153 changes: 153 additions & 0 deletions src/Kiota.Builder/Refiners/HttpRefiner.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Kiota.Builder.CodeDOM;
using Kiota.Builder.Configuration;
using Kiota.Builder.Extensions;

namespace Kiota.Builder.Refiners;
public class HttpRefiner(GenerationConfiguration configuration) : CommonLanguageRefiner(configuration)
{
public override Task RefineAsync(CodeNamespace generatedCode, CancellationToken cancellationToken)
{
return Task.Run(() =>
{
cancellationToken.ThrowIfCancellationRequested();
CapitalizeNamespacesFirstLetters(generatedCode);
ReplaceIndexersByMethodsWithParameter(
generatedCode,
false,
static x => $"By{x.ToFirstCharacterUpperCase()}",
static x => x.ToFirstCharacterUpperCase(),
GenerationLanguage.HTTP);
cancellationToken.ThrowIfCancellationRequested();
ReplaceReservedNames(
generatedCode,
new HttpReservedNamesProvider(),
x => $"{x}_escaped");
RemoveCancellationParameter(generatedCode);
ConvertUnionTypesToWrapper(
generatedCode,
_configuration.UsesBackingStore,
static s => s
);
cancellationToken.ThrowIfCancellationRequested();
SetBaseUrlForRequestBuilderMethods(generatedCode, GetBaseUrl(generatedCode));
// Remove unused code from the DOM e.g Models, BarrelInitializers, e.t.c
RemoveUnusedCodeElements(generatedCode);
}, cancellationToken);
}

private string? GetBaseUrl(CodeElement element)
{
return element.GetImmediateParentOfType<CodeNamespace>()
.GetRootNamespace()?
.FindChildByName<CodeClass>(_configuration.ClientClassName)?
.Methods?
.FirstOrDefault(static x => x.IsOfKind(CodeMethodKind.ClientConstructor))?
.BaseUrl;
}

private static void CapitalizeNamespacesFirstLetters(CodeElement current)
{
if (current is CodeNamespace currentNamespace)
currentNamespace.Name = currentNamespace.Name.Split('.').Select(static x => x.ToFirstCharacterUpperCase()).Aggregate(static (x, y) => $"{x}.{y}");
CrawlTree(current, CapitalizeNamespacesFirstLetters);
}

private static void SetBaseUrlForRequestBuilderMethods(CodeElement current, string? baseUrl)
{
if (baseUrl is not null && current is CodeClass codeClass && codeClass.IsOfKind(CodeClassKind.RequestBuilder))
{
// Add a new property named BaseUrl and set its value to the baseUrl string
var baseUrlProperty = new CodeProperty
{
Name = "BaseUrl",
Kind = CodePropertyKind.Custom,
Access = AccessModifier.Private,
DefaultValue = baseUrl,
Type = new CodeType { Name = "string", IsExternal = true }
};
codeClass.AddProperty(baseUrlProperty);
}
CrawlTree(current, (element) => SetBaseUrlForRequestBuilderMethods(element, baseUrl));
}

private void RemoveUnusedCodeElements(CodeElement element)
{
if (!IsRequestBuilderClass(element) || IsBaseRequestBuilder(element) || IsRequestBuilderClassWithoutAnyHttpOperations(element))
{
var parentNameSpace = element.GetImmediateParentOfType<CodeNamespace>();
parentNameSpace?.RemoveChildElement(element);
}
else
{
// Add path variables
AddPathParameters(element);
}
CrawlTree(element, RemoveUnusedCodeElements);
}

private static void AddPathParameters(CodeElement element)
{
// Target RequestBuilder Classes only
if (element is not CodeClass codeClass) return;

var parent = element.GetImmediateParentOfType<CodeNamespace>().Parent;
while (parent is not null)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it make sense to call this from the refiner method directly as this would handle the traversal of the tree for you?
My concern here is that if two classes exist in the same namespace, you'll traverse them twice as you will be referencing to the same namespace and select all the children over again.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you give an example of how the traversal would look like?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At the moment, AddPathParameters is currently called from RemoveUnusedCodeElements.
Since RemoveUnusedCodeElements crawls the tree, it will go through each element in the DOM(line 90).

So, if you have two classes in the same namespace, each class may be called as a parameter for AddPathParameters meaning that you will get the same namespace twice(for each time you encounter the class) and enumerate ALL the children. (When you get to the parent of the namespace, I believe you will list all the children which were already listed in a previous iteration as they are part of the child elements of the previous parent)

Instead, you can simply add a method called directly in the RefineAsync (after removing the classes/methods you don't need). The method would simply check if the codeElement is a CodeMethod and the kind is CodeMethodKind.IndexerBackwardCompatibility then add the path parameters. And crawl the tree.

{
var codeIndexer = parent.GetChildElements(false)
.OfType<CodeClass>()
.FirstOrDefault()?
.GetChildElements(false)
.OfType<CodeMethod>()
.FirstOrDefault(static x => x.IsOfKind(CodeMethodKind.IndexerBackwardCompatibility));

if (codeIndexer is not null)
{
// Retrieve all the parameters of kind CodeParameterKind.Custom
var customParameters = codeIndexer.Parameters
.Where(static param => param.IsOfKind(CodeParameterKind.Custom))
.ToList();

// For each parameter:
foreach (var param in customParameters)
{
// Create a new property of kind CodePropertyKind.PathParameters using the parameter and add it to the codeClass
var pathParameterProperty = new CodeProperty
{
Name = param.Name,
Kind = CodePropertyKind.PathParameters,
Type = param.Type,
Access = AccessModifier.Public,
DefaultValue = param.DefaultValue,
SerializationName = param.SerializationName,
Documentation = param.Documentation
};
codeClass.AddProperty(pathParameterProperty);
}
}

parent = parent.Parent?.GetImmediateParentOfType<CodeNamespace>();
}
}

private static bool IsRequestBuilderClass(CodeElement element)
{
return element is CodeClass code && code.IsOfKind(CodeClassKind.RequestBuilder);
}

private bool IsBaseRequestBuilder(CodeElement element)
{
return element is CodeClass codeClass &&
codeClass.Name.Equals(_configuration.ClientClassName, StringComparison.Ordinal);
}

private static bool IsRequestBuilderClassWithoutAnyHttpOperations(CodeElement element)
{
return element is CodeClass codeClass && codeClass.IsOfKind(CodeClassKind.RequestBuilder) &&
!codeClass.Methods.Any(static method => method.IsOfKind(CodeMethodKind.RequestExecutor));
}
}
11 changes: 11 additions & 0 deletions src/Kiota.Builder/Refiners/HttpReservedNamesProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;

namespace Kiota.Builder.Refiners;
public class HttpReservedNamesProvider : IReservedNamesProvider
{
private readonly Lazy<HashSet<string>> _reservedNames = new(() => new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
});
public HashSet<string> ReservedNames => _reservedNames.Value;
}
3 changes: 3 additions & 0 deletions src/Kiota.Builder/Refiners/ILanguageRefiner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ public static async Task RefineAsync(GenerationConfiguration config, CodeNamespa
case GenerationLanguage.Swift:
await new SwiftRefiner(config).RefineAsync(generatedCode, cancellationToken).ConfigureAwait(false);
break;
case GenerationLanguage.HTTP:
await new HttpRefiner(config).RefineAsync(generatedCode, cancellationToken).ConfigureAwait(false);
break;
case GenerationLanguage.Python:
await new PythonRefiner(config).RefineAsync(generatedCode, cancellationToken).ConfigureAwait(false);
break;
Expand Down
12 changes: 12 additions & 0 deletions src/Kiota.Builder/Writers/HTTP/CodeBlockEndWriter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System;
using Kiota.Builder.CodeDOM;

namespace Kiota.Builder.Writers.Http;
public class CodeBlockEndWriter : ICodeElementWriter<BlockEnd>
{
public void WriteCodeElement(BlockEnd codeElement, LanguageWriter writer)
{
ArgumentNullException.ThrowIfNull(codeElement);
ArgumentNullException.ThrowIfNull(writer);
}
}
Loading
Loading