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

adds support for relative server URL #2325

Merged
merged 3 commits into from
Feb 21, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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 CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added

- Added constructors and query parameter factory methods to request configuration classes and constructors to query parameter classes in PHP.
- Added support for relative server URL. [#2278](https://github.com/microsoft/kiota/issues/2278)

### Changed

Expand Down
60 changes: 47 additions & 13 deletions src/Kiota.Builder/KiotaBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ private void CleanOutputDirectory()
sw.Start();
if (originalDocument == null)
{
openApiDocument = CreateOpenApiDocument(input, generating);
openApiDocument = await CreateOpenApiDocumentAsync(input, generating, cancellationToken);
if (openApiDocument != null)
originalDocument = new OpenApiDocument(openApiDocument);
}
Expand Down Expand Up @@ -243,9 +243,27 @@ public static void FilterPathsByPatterns(OpenApiDocument doc, List<Glob> include
.ToList()
.ForEach(x => doc.Paths.Remove(x));
}
private void SetApiRootUrl()
internal void SetApiRootUrl()
{
config.ApiRootUrl = openApiDocument?.Servers.FirstOrDefault()?.Url.TrimEnd('/');
var candidateUrl = openApiDocument?.Servers.FirstOrDefault()?.Url;
if (string.IsNullOrEmpty(candidateUrl))
{
logger.LogWarning("No server url found in the OpenAPI document. The base url will need to be set when using the client.");
return;
}
else if (!candidateUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase) && config.OpenAPIFilePath.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
try
{
candidateUrl = new Uri(new Uri(config.OpenAPIFilePath), candidateUrl).ToString();
}
catch
{
logger.LogWarning("Could not resolve the server url from the OpenAPI document. The base url will need to be set when using the client.");
return;
}
}
config.ApiRootUrl = candidateUrl.TrimEnd(ForwardSlash);
}
private void StopLogAndReset(Stopwatch sw, string prefix)
{
Expand Down Expand Up @@ -298,7 +316,8 @@ ex is SecurityException ||
return input;
}

public OpenApiDocument? CreateOpenApiDocument(Stream input, bool generating = false)
private static readonly char ForwardSlash = '/';
public async Task<OpenApiDocument?> CreateOpenApiDocumentAsync(Stream input, bool generating = false, CancellationToken cancellationToken = default)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
Expand All @@ -308,7 +327,7 @@ ex is SecurityException ||
ValidationRuleSet.GetDefaultRuleSet(); //workaround since validation rule set doesn't support clearing rules
if (generating)
ruleSet.AddKiotaValidationRules(config);
var reader = new OpenApiStreamReader(new OpenApiReaderSettings
var settings = new OpenApiReaderSettings
{
ExtensionParsers = new()
{
Expand All @@ -326,26 +345,41 @@ ex is SecurityException ||
},
},
RuleSet = ruleSet,
});
var doc = reader.Read(input, out var diag);
};
try
{
var rawUri = config.OpenAPIFilePath.TrimEnd(ForwardSlash);
var lastSlashIndex = rawUri.LastIndexOf(ForwardSlash);
if (lastSlashIndex < 0)
lastSlashIndex = rawUri.Length - 1;
var documentUri = new Uri(rawUri[..lastSlashIndex]);
settings.BaseUrl = documentUri;
settings.LoadExternalRefs = true;
}
catch
{
// couldn't parse the URL, it's probably a local file
}
var reader = new OpenApiStreamReader(settings);
var readResult = await reader.ReadAsync(input); //TODO pass the cancellation token when the library patch is out
stopwatch.Stop();
if (generating)
foreach (var warning in diag.Warnings)
foreach (var warning in readResult.OpenApiDiagnostic.Warnings)
logger.LogWarning("OpenAPI warning: {pointer} - {warning}", warning.Pointer, warning.Message);
if (diag.Errors.Any())
if (readResult.OpenApiDiagnostic.Errors.Any())
{
logger.LogTrace("{timestamp}ms: Parsed OpenAPI with errors. {count} paths found.", stopwatch.ElapsedMilliseconds, doc?.Paths?.Count ?? 0);
foreach (var parsingError in diag.Errors)
logger.LogTrace("{timestamp}ms: Parsed OpenAPI with errors. {count} paths found.", stopwatch.ElapsedMilliseconds, readResult.OpenApiDocument?.Paths?.Count ?? 0);
foreach (var parsingError in readResult.OpenApiDiagnostic.Errors)
{
logger.LogError("OpenAPI error: {pointer} - {message}", parsingError.Pointer, parsingError.Message);
}
}
else
{
logger.LogTrace("{timestamp}ms: Parsed OpenAPI successfully. {count} paths found.", stopwatch.ElapsedMilliseconds, doc?.Paths?.Count ?? 0);
logger.LogTrace("{timestamp}ms: Parsed OpenAPI successfully. {count} paths found.", stopwatch.ElapsedMilliseconds, readResult.OpenApiDocument?.Paths?.Count ?? 0);
}

return doc;
return readResult.OpenApiDocument;
}
public static string GetDeeperMostCommonNamespaceNameForModels(OpenApiDocument document)
{
Expand Down
51 changes: 45 additions & 6 deletions tests/Kiota.Builder.Tests/KiotaBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,45 @@ public void Dispose()
_httpClient.Dispose();
GC.SuppressFinalize(this);
}
[InlineData("https://graph.microsoft.com/description.yaml", "/v1.0", "https://graph.microsoft.com/v1.0")]
[InlineData("/home/vsts/a/s/1", "/v1.0", "/v1.0")]
[InlineData("https://graph.microsoft.com/docs/description.yaml", "../v1.0", "https://graph.microsoft.com/v1.0")]
[InlineData("https://graph.microsoft.com/description.yaml", "https://graph.microsoft.com/v1.0", "https://graph.microsoft.com/v1.0")]
[Theory]
public async Task SupportsRelativeServerUrl(string descriptionUrl, string serverRelativeUrl, string expexted)
{
var tempFilePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
await File.WriteAllTextAsync(tempFilePath, @$"openapi: 3.0.1
info:
title: OData Service for namespace microsoft.graph
description: This OData service is located at https://graph.microsoft.com/v1.0
version: 1.0.1
servers:
- url: {serverRelativeUrl}
paths:
/enumeration:
get:
responses:
'200':
content:
application/json:
schema:
type: string");
var mockLogger = new Mock<ILogger<KiotaBuilder>>();
var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration { ClientClassName = "Graph", OpenAPIFilePath = descriptionUrl }, _httpClient);
await using var fs = new FileStream(tempFilePath, FileMode.Open);
var document = await builder.CreateOpenApiDocumentAsync(fs);
var node = builder.CreateUriSpace(document);
builder.SetApiRootUrl();
var codeModel = builder.CreateSourceModel(node);
var rootNS = codeModel.FindNamespaceByName("ApiSdk");
Assert.NotNull(rootNS);
var clientBuilder = rootNS.FindChildByName<CodeClass>("Graph", false);
Assert.NotNull(clientBuilder);
var constructor = clientBuilder.Methods.FirstOrDefault(static x => x.IsOfKind(CodeMethodKind.ClientConstructor));
Assert.NotNull(constructor);
Assert.Equal(expexted, constructor.BaseUrl);
}
private readonly HttpClient _httpClient = new();
[Fact]
public async Task ParsesEnumDescriptions()
Expand Down Expand Up @@ -81,7 +120,7 @@ await File.WriteAllTextAsync(tempFilePath, @"openapi: 3.0.1
var mockLogger = new Mock<ILogger<KiotaBuilder>>();
var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration { ClientClassName = "Graph", OpenAPIFilePath = tempFilePath }, _httpClient);
await using var fs = new FileStream(tempFilePath, FileMode.Open);
var document = builder.CreateOpenApiDocument(fs);
var document = await builder.CreateOpenApiDocumentAsync(fs);
var node = builder.CreateUriSpace(document);
var codeModel = builder.CreateSourceModel(node);
var modelsNS = codeModel.FindNamespaceByName("ApiSdk.models");
Expand Down Expand Up @@ -117,7 +156,7 @@ await File.WriteAllTextAsync(tempFilePath, @"openapi: 3.0.1
var mockLogger = new Mock<ILogger<KiotaBuilder>>();
var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration { ClientClassName = "Graph", OpenAPIFilePath = tempFilePath }, _httpClient);
await using var fs = new FileStream(tempFilePath, FileMode.Open);
var document = builder.CreateOpenApiDocument(fs);
var document = await builder.CreateOpenApiDocumentAsync(fs);
var node = builder.CreateUriSpace(document);
var extensionResult = await builder.GetLanguagesInformationAsync(new CancellationToken());
Assert.NotNull(extensionResult);
Expand Down Expand Up @@ -179,7 +218,7 @@ await File.WriteAllTextAsync(tempFilePath, @"openapi: 3.0.1
var mockLogger = new Mock<ILogger<KiotaBuilder>>();
var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration { ClientClassName = "Graph", OpenAPIFilePath = tempFilePath }, _httpClient);
await using var fs = new FileStream(tempFilePath, FileMode.Open);
var document = builder.CreateOpenApiDocument(fs);
var document = await builder.CreateOpenApiDocumentAsync(fs);
var node = builder.CreateUriSpace(document);
var extensionResult = await builder.GetLanguagesInformationAsync(new CancellationToken());
Assert.Null(extensionResult);
Expand Down Expand Up @@ -4961,7 +5000,7 @@ await File.WriteAllTextAsync(tempFilePath, @"openapi: 3.0.0
var mockLogger = new Mock<ILogger<KiotaBuilder>>();
var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration { ClientClassName = "Graph", OpenAPIFilePath = tempFilePath }, _httpClient);
await using var fs = new FileStream(tempFilePath, FileMode.Open);
var document = builder.CreateOpenApiDocument(fs);
var document = await builder.CreateOpenApiDocumentAsync(fs);
var node = builder.CreateUriSpace(document);
var codeModel = builder.CreateSourceModel(node);
var requestBuilderNS = codeModel.FindNamespaceByName("ApiSdk.me");
Expand Down Expand Up @@ -5014,7 +5053,7 @@ await File.WriteAllTextAsync(tempFilePath, @"openapi: 3.0.0
var mockLogger = new Mock<ILogger<KiotaBuilder>>();
var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration { ClientClassName = "Graph", OpenAPIFilePath = tempFilePath }, _httpClient);
await using var fs = new FileStream(tempFilePath, FileMode.Open);
var document = builder.CreateOpenApiDocument(fs);
var document = await builder.CreateOpenApiDocumentAsync(fs);
var node = builder.CreateUriSpace(document);
var codeModel = builder.CreateSourceModel(node);
var requestBuilderNS = codeModel.FindNamespaceByName("ApiSdk.me");
Expand Down Expand Up @@ -5058,7 +5097,7 @@ await File.WriteAllTextAsync(tempFilePath, @"openapi: 3.0.0
var mockLogger = new Mock<ILogger<KiotaBuilder>>();
var builder = new KiotaBuilder(mockLogger.Object, new GenerationConfiguration { ClientClassName = "Graph", OpenAPIFilePath = tempFilePath }, _httpClient);
await using var fs = new FileStream(tempFilePath, FileMode.Open);
var document = builder.CreateOpenApiDocument(fs);
var document = await builder.CreateOpenApiDocumentAsync(fs);
var node = builder.CreateUriSpace(document!);
var codeModel = builder.CreateSourceModel(node);
var collectionRequestBuilderNamespace = codeModel.FindNamespaceByName("ApiSdk.me.posts");
Expand Down