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

Fix nodes merging to update children paths and path parameters #4174

Merged
merged 8 commits into from
Feb 26, 2024
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
1 change: 1 addition & 0 deletions .github/workflows/integration-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ jobs:
- "https://developers.pipedrive.com/docs/api/v1/openapi.yaml"
- "apisguru::twilio.com:api"
- "apisguru::docusign.net"
- "apisguru::github.com:api.github.com"
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
Expand Down
5 changes: 4 additions & 1 deletion it/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@
"./tests/Kiota.Builder.IntegrationTests/GeneratesUritemplateHints.yaml": {
"MockServerITFolder": "query-params"
},
"apisguru::github.com:api.github.com": {
"MockServerITFolder": "gh"
},
"apisguru::notion.com": {
"ExcludePatterns": [
{
Expand Down Expand Up @@ -325,4 +328,4 @@
}
]
}
}
}
74 changes: 74 additions & 0 deletions it/java/gh/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?xml version="1.0"?>
<project
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0">
<modelVersion>4.0.0</modelVersion>
<groupId>io.kiota</groupId>
<artifactId>kiota-gh-api</artifactId>
<version>0.1.0-SNAPSHOT</version>

<properties>
<maven.compiler.release>11</maven.compiler.release>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<kiota-java.version>0.12.1</kiota-java.version>
</properties>

<dependencies>
<dependency>
<groupId>com.microsoft.kiota</groupId>
<artifactId>microsoft-kiota-abstractions</artifactId>
<version>${kiota-java.version}</version>
</dependency>
<dependency>
<groupId>com.microsoft.kiota</groupId>
<artifactId>microsoft-kiota-serialization-json</artifactId>
<version>${kiota-java.version}</version>
</dependency>
<dependency>
<groupId>com.microsoft.kiota</groupId>
<artifactId>microsoft-kiota-serialization-text</artifactId>
<version>${kiota-java.version}</version>
</dependency>
<dependency>
<groupId>com.microsoft.kiota</groupId>
<artifactId>microsoft-kiota-serialization-form</artifactId>
<version>${kiota-java.version}</version>
</dependency>
<dependency>
<groupId>com.microsoft.kiota</groupId>
<artifactId>microsoft-kiota-serialization-multipart</artifactId>
<version>${kiota-java.version}</version>
</dependency>
<dependency>
<groupId>com.microsoft.kiota</groupId>
<artifactId>microsoft-kiota-http-okHttp</artifactId>
<version>${kiota-java.version}</version>
</dependency>
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M9</version>
</plugin>
</plugins>
</build>
</project>
23 changes: 23 additions & 0 deletions it/java/gh/src/test/java/GHAPITest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import apisdk.ApiClient;
import com.microsoft.kiota.ApiException;
import com.microsoft.kiota.authentication.AnonymousAuthenticationProvider;
import com.microsoft.kiota.http.OkHttpRequestAdapter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import java.util.concurrent.TimeUnit;

public class BasicAPITest {

@Test
void basicTest() throws Exception {
var adapter = new OkHttpRequestAdapter(new AnonymousAuthenticationProvider());
adapter.setBaseUrl("http://127.0.0.1:1080");
var client = new ApiClient(adapter);

client.repos().byOrgId("my-owner").byRepoId("my-repo").get();
client.repos().byOrgId("my-owner").byRepoId("my-repo").generate().post(null);
baywet marked this conversation as resolved.
Show resolved Hide resolved
}

}
100 changes: 99 additions & 1 deletion src/Kiota.Builder/Extensions/OpenApiUrlTreeNodeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Linq;
using System.Text.RegularExpressions;
using Kiota.Builder.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.MicrosoftExtensions;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Services;
Expand Down Expand Up @@ -79,7 +80,7 @@ public static IEnumerable<OpenApiParameter> GetPathParametersForCurrentSegment(t
.Where(static x => x.Value.PathItems.ContainsKey(Constants.DefaultOpenApiLabel))
.SelectMany(x => GetParametersForPathItem(x.Value.PathItems[Constants.DefaultOpenApiLabel], node.DeduplicatedSegment()))
.Distinct();
return Enumerable.Empty<OpenApiParameter>();
return [];
}
private const char PathNameSeparator = '\\';
[GeneratedRegex(@"-?id\d?}?$", RegexOptions.Singleline | RegexOptions.IgnoreCase, 500)]
Expand Down Expand Up @@ -268,4 +269,101 @@ public static void AddDeduplicatedSegment(this OpenApiUrlTreeNode openApiUrlTree
ArgumentException.ThrowIfNullOrEmpty(newName);
openApiUrlTreeNode.AdditionalData.Add(DeduplicatedSegmentKey, [newName]);
}
internal static void MergeIndexNodesAtSameLevel(this OpenApiUrlTreeNode node, ILogger logger)
{
var indexNodes = node.Children
.Where(static x => x.Value.IsPathSegmentWithSingleSimpleParameter())
.OrderBy(static x => x.Key, StringComparer.OrdinalIgnoreCase)
.ToArray();
if (indexNodes.Length > 1)
{
var indexNode = indexNodes[0];
node.Children.Remove(indexNode.Key);
var oldSegmentName = indexNode.Value.Segment.Trim('{', '}').CleanupSymbolName();
var segmentIndex = indexNode.Value.Path.Split('\\', StringSplitOptions.RemoveEmptyEntries).ToList().IndexOf(indexNode.Value.Segment);
var newSegmentParameterName = oldSegmentName.EndsWith("-id", StringComparison.OrdinalIgnoreCase) ? oldSegmentName : $"{{{oldSegmentName}-id}}";
indexNode.Value.Path = indexNode.Value.Path.Replace(indexNode.Key, newSegmentParameterName, StringComparison.OrdinalIgnoreCase);
indexNode.Value.AddDeduplicatedSegment(newSegmentParameterName);
node.Children.Add(newSegmentParameterName, indexNode.Value);
CopyNodeIntoOtherNode(indexNode.Value, indexNode.Value, indexNode.Key, newSegmentParameterName, logger);
foreach (var child in indexNodes.Except([indexNode]))
{
node.Children.Remove(child.Key);
CopyNodeIntoOtherNode(child.Value, indexNode.Value, child.Key, newSegmentParameterName, logger);
}
ReplaceParameterInPathForAllChildNodes(indexNode.Value, segmentIndex, newSegmentParameterName);
}

foreach (var child in node.Children.Values)
MergeIndexNodesAtSameLevel(child, logger);
}
private static void ReplaceParameterInPathForAllChildNodes(OpenApiUrlTreeNode node, int parameterIndex, string newParameterName)
{
if (parameterIndex < 0)
return;
foreach (var child in node.Children.Values)
{
var splatPath = child.Path.Split('\\', StringSplitOptions.RemoveEmptyEntries);
if (splatPath.Length > parameterIndex)
{
var oldName = splatPath[parameterIndex];
splatPath[parameterIndex] = newParameterName;
child.Path = "\\" + string.Join('\\', splatPath);
if (node.PathItems.TryGetValue(Constants.DefaultOpenApiLabel, out var pathItem))
{
foreach (var pathParameter in pathItem.Parameters
.Union(pathItem.Operations.SelectMany(static x => x.Value.Parameters))
.Where(x => x.In == ParameterLocation.Path && oldName.Equals(x.Name, StringComparison.Ordinal)))
{
pathParameter.Name = newParameterName;
}
}
}
ReplaceParameterInPathForAllChildNodes(child, parameterIndex, newParameterName);
}
}
private static void CopyNodeIntoOtherNode(OpenApiUrlTreeNode source, OpenApiUrlTreeNode destination, string pathParameterNameToReplace, string pathParameterNameReplacement, ILogger logger)
{
foreach (var child in source.Children)
{
child.Value.Path = child.Value.Path.Replace(pathParameterNameToReplace, pathParameterNameReplacement, StringComparison.OrdinalIgnoreCase);
if (!destination.Children.TryAdd(child.Key, child.Value))
CopyNodeIntoOtherNode(child.Value, destination.Children[child.Key], pathParameterNameToReplace, pathParameterNameReplacement, logger);
}
pathParameterNameToReplace = pathParameterNameToReplace.Trim('{', '}');
pathParameterNameReplacement = pathParameterNameReplacement.Trim('{', '}');
foreach (var pathItem in source.PathItems)
{
foreach (var pathParameter in pathItem
.Value
.Parameters
.Where(x => x.In == ParameterLocation.Path && pathParameterNameToReplace.Equals(x.Name, StringComparison.Ordinal))
.Union(
pathItem
.Value
.Operations
.SelectMany(static x => x.Value.Parameters)
.Where(x => x.In == ParameterLocation.Path && pathParameterNameToReplace.Equals(x.Name, StringComparison.Ordinal))
))
{
pathParameter.Name = pathParameterNameReplacement;
}
if (source != destination && !destination.PathItems.TryAdd(pathItem.Key, pathItem.Value))
{
var destinationPathItem = destination.PathItems[pathItem.Key];
foreach (var operation in pathItem.Value.Operations)
if (!destinationPathItem.Operations.TryAdd(operation.Key, operation.Value))
{
logger.LogWarning("Duplicate operation {Operation} in path {Path}", operation.Key, pathItem.Key);
}
foreach (var pathParameter in pathItem.Value.Parameters)
destinationPathItem.Parameters.Add(pathParameter);
foreach (var extension in pathItem.Value.Extensions)
if (!destinationPathItem.Extensions.TryAdd(extension.Key, extension.Value))
{
logger.LogWarning("Duplicate extension {Extension} in path {Path}", extension.Key, pathItem.Key);
}
}
}
}
}
71 changes: 1 addition & 70 deletions src/Kiota.Builder/KiotaBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -549,80 +549,11 @@ public OpenApiUrlTreeNode CreateUriSpace(OpenApiDocument doc)
var stopwatch = new Stopwatch();
stopwatch.Start();
var node = OpenApiUrlTreeNode.Create(doc, Constants.DefaultOpenApiLabel);
MergeIndexNodesAtSameLevel(node);
node.MergeIndexNodesAtSameLevel(logger);
stopwatch.Stop();
logger.LogTrace("{Timestamp}ms: Created UriSpace tree", stopwatch.ElapsedMilliseconds);
return node;
}
private void MergeIndexNodesAtSameLevel(OpenApiUrlTreeNode node)
{
var indexNodes = node.Children
.Where(static x => x.Value.IsPathSegmentWithSingleSimpleParameter())
.OrderBy(static x => x.Key, StringComparer.OrdinalIgnoreCase)
.ToArray();
if (indexNodes.Length > 1)
{
var indexNode = indexNodes[0];
node.Children.Remove(indexNode.Key);
var newSegmentParameterName = $"{{{node.Segment.CleanupSymbolName()}-id}}";
indexNode.Value.Path = indexNode.Value.Path.Replace(indexNode.Key, newSegmentParameterName, StringComparison.OrdinalIgnoreCase);
indexNode.Value.AddDeduplicatedSegment(newSegmentParameterName);
node.Children.Add(newSegmentParameterName, indexNode.Value);
CopyNodeIntoOtherNode(indexNode.Value, indexNode.Value, indexNode.Key, newSegmentParameterName);
foreach (var child in indexNodes.Except(new[] { indexNode }))
{
node.Children.Remove(child.Key);
CopyNodeIntoOtherNode(child.Value, indexNode.Value, child.Key, newSegmentParameterName);
}
}

foreach (var child in node.Children.Values)
MergeIndexNodesAtSameLevel(child);
}
private void CopyNodeIntoOtherNode(OpenApiUrlTreeNode source, OpenApiUrlTreeNode destination, string pathParameterNameToReplace, string pathParameterNameReplacement)
{
foreach (var child in source.Children)
{
child.Value.Path = child.Value.Path.Replace(pathParameterNameToReplace, pathParameterNameReplacement, StringComparison.OrdinalIgnoreCase);
if (!destination.Children.TryAdd(child.Key, child.Value))
CopyNodeIntoOtherNode(child.Value, destination.Children[child.Key], pathParameterNameToReplace, pathParameterNameReplacement);
}
pathParameterNameToReplace = pathParameterNameToReplace.Trim('{', '}');
pathParameterNameReplacement = pathParameterNameReplacement.Trim('{', '}');
foreach (var pathItem in source.PathItems)
{
foreach (var pathParameter in pathItem
.Value
.Parameters
.Where(x => x.In == ParameterLocation.Path && pathParameterNameToReplace.Equals(x.Name, StringComparison.Ordinal))
.Union(
pathItem
.Value
.Operations
.SelectMany(static x => x.Value.Parameters)
.Where(x => x.In == ParameterLocation.Path && pathParameterNameToReplace.Equals(x.Name, StringComparison.Ordinal))
))
{
pathParameter.Name = pathParameterNameReplacement;
}
if (source != destination && !destination.PathItems.TryAdd(pathItem.Key, pathItem.Value))
{
var destinationPathItem = destination.PathItems[pathItem.Key];
foreach (var operation in pathItem.Value.Operations)
if (!destinationPathItem.Operations.TryAdd(operation.Key, operation.Value))
{
logger.LogWarning("Duplicate operation {Operation} in path {Path}", operation.Key, pathItem.Key);
}
foreach (var pathParameter in pathItem.Value.Parameters)
destinationPathItem.Parameters.Add(pathParameter);
foreach (var extension in pathItem.Value.Extensions)
if (!destinationPathItem.Extensions.TryAdd(extension.Key, extension.Value))
{
logger.LogWarning("Duplicate extension {Extension} in path {Path}", extension.Key, pathItem.Key);
}
}
}
}
private CodeNamespace? rootNamespace;
private CodeNamespace? modelsNamespace;
private string? modelNamespacePrefixToTrim;
Expand Down
Loading
Loading