Skip to content

updated cli tool to be used to generate openapi document #337

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

Closed
wants to merge 9 commits into from
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/bin/Debug/netcoreapp2.1/azfuncopenapi.dll",
"program": "${workspaceFolder}/bin/Debug/net6.0/azfuncopenapi.dll",
"args": [],
"cwd": "${workspaceFolder}",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"type": "process",
"args": [
"build",
"${workspaceFolder}/Aliencube.AzureFunctions.Extensions.OpenApi.CLI.csproj",
"${workspaceFolder}/Microsoft.Azure.WebJobs.Extensions.OpenApi.CLI.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
Expand All @@ -19,7 +19,7 @@
"type": "process",
"args": [
"publish",
"${workspaceFolder}/Aliencube.AzureFunctions.Extensions.OpenApi.CLI.csproj",
"${workspaceFolder}/Microsoft.Azure.WebJobs.Extensions.OpenApi.CLI.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
Expand All @@ -32,7 +32,7 @@
"args": [
"watch",
"run",
"${workspaceFolder}/Aliencube.AzureFunctions.Extensions.OpenApi.CLI.csproj",
"${workspaceFolder}/Microsoft.Azure.WebJobs.Extensions.OpenApi.CLI.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using Microsoft.Azure.WebJobs.Extensions.OpenApi.CLI.Model;

namespace Microsoft.Azure.WebJobs.Extensions.OpenApi.CLI.Abstractions
{
public interface ICustomApiMockCreator
{
ApiMock SetupApi(string projectPath, string configuration, string targetFramework);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Enums;
using Microsoft.OpenApi.Models;

namespace Microsoft.Azure.WebJobs.Extensions.OpenApi.CLI.Abstractions
{
public interface ICustomOpenApiCreator
{
Task<string> CreateOpenApiDocument(
string apiBaseUrl,
string compiledDllPath,
string routePrefix,
OpenApiInfo openApiInfo,
OpenApiVersionType version,
OpenApiFormatType format);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Enums;

namespace Microsoft.Azure.WebJobs.Extensions.OpenApi.CLI.Abstractions
{
public interface ICustomOpenApiWriter
{
Task WriteOpenApiToFile(string openApiDocument, string outputPath, OpenApiFormatType format);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using System.Threading.Tasks;
using Cocona;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.CLI.Abstractions;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.CLI.Extensions;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Enums;

namespace Microsoft.Azure.WebJobs.Extensions.OpenApi.CLI.ConsoleApp
{
public class GenerateSwaggerConsoleApp
{
/// <summary>
/// Generates the OpenAPI document.
/// </summary>
/// <param name="project">Project path.</param>
/// <param name="apibaseurl"></param>
/// <param name="configuration">Compile configuration.</param>
/// <param name="target"></param>
/// <param name="version">OpenAPI version.</param>
/// <param name="format">OpenAPI output format.</param>
/// <param name="output">Output path.</param>
public async Task Run(
[FromService] ICustomApiMockCreator customApiMockCreator,
[FromService] ICustomOpenApiCreator customOpenApiCreator,
[FromService] ICustomOpenApiWriter customOpenApiWriter,
[Option('p', Description = "Api Project path. Default is current directory")]
string project = ".",
[Option('a', Description = "ApiBaseUrl. Default is 'localhost'")]
string apibaseurl = "localhost",
[Option('c', Description = "Configuration. Default is 'Debug'")]
string configuration = "Debug",
[Option('t', Description = "Target framework. Default is 'net6.0'")]
string target = "net6.0",
[Option('v', Description = "OpenAPI spec version. Value can be either 'v2' or 'v3'. Default is 'v2'")]
OpenApiVersionType version = OpenApiVersionType.V2,
[Option('f', Description = "OpenAPI output format. Value can be either 'json' or 'yaml'. Default is 'json'")]
OpenApiFormatType format = OpenApiFormatType.Json,
[Option('o', Description = "Generated OpenAPI output location. Default is 'output'")]
string output = "output")
{
var apiMock = customApiMockCreator.SetupApi(project, configuration, target);

var openApiDocument = await customOpenApiCreator.CreateOpenApiDocument(
apibaseurl,
apiMock.CompiledDllPath,
apiMock.HttpSettings.RoutePrefix,
apiMock.OpenApiInfo,
version,
format);

await customOpenApiWriter.WriteOpenApiToFile(openApiDocument, output.GetOutputPath(apiMock.CompiledPath), format);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;

namespace Microsoft.Azure.WebJobs.Extensions.OpenApi.CLI.Extensions
{
public static class ProjectPathExtensions
{
public static readonly char DirectorySeparator = Path.DirectorySeparatorChar;

public static string TrimProjectPath(this string path)
{
var filePath = !Path.IsPathFullyQualified(path)
? $"{Environment.CurrentDirectory.TrimEnd(DirectorySeparator)}{DirectorySeparator}{path}"
: path;

return new DirectoryInfo(filePath).FullName.TrimEnd(DirectorySeparator);
}

public static string GetCsProjFileName(this string path)
{
var filePath = !Path.IsPathFullyQualified(path)
? $"{Environment.CurrentDirectory.TrimEnd(DirectorySeparator)}{DirectorySeparator}{path}"
: path;

var segments = new DirectoryInfo(filePath).FullName.Split(new[]
{
DirectorySeparator
}, StringSplitOptions.RemoveEmptyEntries);

return $"{segments.Last()}.csproj";
}

public static string GetProjectDllFileName(this string projectPath, string csprojFileName)
{
var doc = new XmlDocument();

doc.Load($"{projectPath}{DirectorySeparator}{csprojFileName}");

var elements = doc.GetElementsByTagName(nameof(AssemblyName));

var dllName = elements?.Cast<XmlNode>()?.FirstOrDefault()?.InnerText;

return string.IsNullOrWhiteSpace(dllName)
? csprojFileName.Replace(".csproj", ".dll")
: $"{dllName}.dll";
}

public static string GetProjectCompiledPath(this string path, string configuration, string targetFramework)
{
return $"{path.TrimEnd(DirectorySeparator)}{DirectorySeparator}bin{DirectorySeparator}{configuration}{DirectorySeparator}{targetFramework}";
}

public static string GetProjectCompiledDllPath(this string compiledPath, string dllFileName)
{
return $"{compiledPath}{DirectorySeparator}{dllFileName}";
}

public static string GetProjectHostJsonPath(this string compiledPath)
{
return $"{compiledPath}{DirectorySeparator}host.json";
}

public static string GetOutputPath(this string output, string compiledPath)
{
return !Path.IsPathFullyQualified(output)
? $"{compiledPath}{DirectorySeparator}{output}"
: output;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System;
using System.Linq;
using System.Reflection;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Configurations.AppSettings.Extensions;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Abstractions;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Configurations;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.OpenApi.Models;

namespace Microsoft.Azure.WebJobs.Extensions.OpenApi.CLI.Extensions
{
public static class SetupHostExtensions
{
public static HttpSettings SetHostSettings(this string hostJsonPath)
{
var host = new ConfigurationBuilder()
.SetBasePath(hostJsonPath.Replace("host.json", ""))
.AddJsonFile("host.json")
.AddEnvironmentVariables()
.Build();

var version = host.GetSection("version").Value;

HttpSettings hostJsonSetting;
if (string.IsNullOrWhiteSpace(version))
hostJsonSetting = host.Get<HttpSettings>("http");
else if (version.Equals("2.0", StringComparison.CurrentCultureIgnoreCase))
hostJsonSetting = host.Get<HttpSettings>("extensions:http");
else
hostJsonSetting = host.Get<HttpSettings>("http");

return hostJsonSetting;
}

public static OpenApiInfo SetOpenApiInfo(this string compiledDllPath)
{
var assembly = Assembly.LoadFrom(compiledDllPath);
var type = assembly.GetLoadableTypes().SingleOrDefault(p => p.GetInterface(nameof(IOpenApiConfigurationOptions), true).IsNullOrDefault() == false);
return !type.IsNullOrDefault() ? (Activator.CreateInstance(type) as IOpenApiConfigurationOptions)?.Info : new DefaultOpenApiConfigurationOptions().Info;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,23 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TargetFrameworks>net5.0;net6.0</TargetFrameworks>
<RuntimeIdentifiers>win-x64;linux-x64;osx-x64</RuntimeIdentifiers>
<AssemblyName>azfuncopenapi</AssemblyName>
<RootNamespace>Microsoft.Azure.WebJobs.Extensions.OpenApi.CLI</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Cocona.Lite" Version="1.4.0" />
<PackageReference Include="Cocona" Version="2.0.3" />
<PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.5" />
<PackageReference Include="Moq" Version="4.14.5" />
<PackageReference Include="Moq" Version="4.16.1" />
<PackageReference Include="System.IO.FileSystem.Primitives" Version="4.3.0" />
<PackageReference Include="System.Runtime.Handles" Version="4.3.0" />
<PackageReference Include="System.Runtime.InteropServices" Version="4.3.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Microsoft.Azure.Functions.Worker.Extensions.OpenApi\Microsoft.Azure.Functions.Worker.Extensions.OpenApi.csproj" />
<ProjectReference Include="..\Microsoft.Azure.WebJobs.Extensions.OpenApi\Microsoft.Azure.WebJobs.Extensions.OpenApi.csproj" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Configurations;
using Microsoft.OpenApi.Models;

namespace Microsoft.Azure.WebJobs.Extensions.OpenApi.CLI.Model
{
public class ApiMock
{
public string CompiledPath { set; get; }
public string CompiledDllPath { set; get; }
public HttpSettings HttpSettings { set; get; }
public OpenApiInfo OpenApiInfo { set; get; }
}
Comment on lines +6 to +12
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we put XML comments on the class and each property?

}
Loading